xref: /linux-6.15/tools/perf/tests/code-reading.c (revision d2ed5d2b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <errno.h>
3 #include <linux/kernel.h>
4 #include <linux/types.h>
5 #include <inttypes.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <sys/param.h>
11 
12 #include "parse-events.h"
13 #include "evlist.h"
14 #include "evsel.h"
15 #include "thread_map.h"
16 #include "cpumap.h"
17 #include "machine.h"
18 #include "event.h"
19 #include "thread.h"
20 
21 #include "tests.h"
22 
23 #include "sane_ctype.h"
24 
25 #define BUFSZ	1024
26 #define READLEN	128
27 
28 struct state {
29 	u64 done[1024];
30 	size_t done_cnt;
31 };
32 
33 static unsigned int hex(char c)
34 {
35 	if (c >= '0' && c <= '9')
36 		return c - '0';
37 	if (c >= 'a' && c <= 'f')
38 		return c - 'a' + 10;
39 	return c - 'A' + 10;
40 }
41 
42 static size_t read_objdump_chunk(const char **line, unsigned char **buf,
43 				 size_t *buf_len)
44 {
45 	size_t bytes_read = 0;
46 	unsigned char *chunk_start = *buf;
47 
48 	/* Read bytes */
49 	while (*buf_len > 0) {
50 		char c1, c2;
51 
52 		/* Get 2 hex digits */
53 		c1 = *(*line)++;
54 		if (!isxdigit(c1))
55 			break;
56 		c2 = *(*line)++;
57 		if (!isxdigit(c2))
58 			break;
59 
60 		/* Store byte and advance buf */
61 		**buf = (hex(c1) << 4) | hex(c2);
62 		(*buf)++;
63 		(*buf_len)--;
64 		bytes_read++;
65 
66 		/* End of chunk? */
67 		if (isspace(**line))
68 			break;
69 	}
70 
71 	/*
72 	 * objdump will display raw insn as LE if code endian
73 	 * is LE and bytes_per_chunk > 1. In that case reverse
74 	 * the chunk we just read.
75 	 *
76 	 * see disassemble_bytes() at binutils/objdump.c for details
77 	 * how objdump chooses display endian)
78 	 */
79 	if (bytes_read > 1 && !bigendian()) {
80 		unsigned char *chunk_end = chunk_start + bytes_read - 1;
81 		unsigned char tmp;
82 
83 		while (chunk_start < chunk_end) {
84 			tmp = *chunk_start;
85 			*chunk_start = *chunk_end;
86 			*chunk_end = tmp;
87 			chunk_start++;
88 			chunk_end--;
89 		}
90 	}
91 
92 	return bytes_read;
93 }
94 
95 static size_t read_objdump_line(const char *line, unsigned char *buf,
96 				size_t buf_len)
97 {
98 	const char *p;
99 	size_t ret, bytes_read = 0;
100 
101 	/* Skip to a colon */
102 	p = strchr(line, ':');
103 	if (!p)
104 		return 0;
105 	p++;
106 
107 	/* Skip initial spaces */
108 	while (*p) {
109 		if (!isspace(*p))
110 			break;
111 		p++;
112 	}
113 
114 	do {
115 		ret = read_objdump_chunk(&p, &buf, &buf_len);
116 		bytes_read += ret;
117 		p++;
118 	} while (ret > 0);
119 
120 	/* return number of successfully read bytes */
121 	return bytes_read;
122 }
123 
124 static int read_objdump_output(FILE *f, void *buf, size_t *len, u64 start_addr)
125 {
126 	char *line = NULL;
127 	size_t line_len, off_last = 0;
128 	ssize_t ret;
129 	int err = 0;
130 	u64 addr, last_addr = start_addr;
131 
132 	while (off_last < *len) {
133 		size_t off, read_bytes, written_bytes;
134 		unsigned char tmp[BUFSZ];
135 
136 		ret = getline(&line, &line_len, f);
137 		if (feof(f))
138 			break;
139 		if (ret < 0) {
140 			pr_debug("getline failed\n");
141 			err = -1;
142 			break;
143 		}
144 
145 		/* read objdump data into temporary buffer */
146 		read_bytes = read_objdump_line(line, tmp, sizeof(tmp));
147 		if (!read_bytes)
148 			continue;
149 
150 		if (sscanf(line, "%"PRIx64, &addr) != 1)
151 			continue;
152 		if (addr < last_addr) {
153 			pr_debug("addr going backwards, read beyond section?\n");
154 			break;
155 		}
156 		last_addr = addr;
157 
158 		/* copy it from temporary buffer to 'buf' according
159 		 * to address on current objdump line */
160 		off = addr - start_addr;
161 		if (off >= *len)
162 			break;
163 		written_bytes = MIN(read_bytes, *len - off);
164 		memcpy(buf + off, tmp, written_bytes);
165 		off_last = off + written_bytes;
166 	}
167 
168 	/* len returns number of bytes that could not be read */
169 	*len -= off_last;
170 
171 	free(line);
172 
173 	return err;
174 }
175 
176 static int read_via_objdump(const char *filename, u64 addr, void *buf,
177 			    size_t len)
178 {
179 	char cmd[PATH_MAX * 2];
180 	const char *fmt;
181 	FILE *f;
182 	int ret;
183 
184 	fmt = "%s -z -d --start-address=0x%"PRIx64" --stop-address=0x%"PRIx64" %s";
185 	ret = snprintf(cmd, sizeof(cmd), fmt, "objdump", addr, addr + len,
186 		       filename);
187 	if (ret <= 0 || (size_t)ret >= sizeof(cmd))
188 		return -1;
189 
190 	pr_debug("Objdump command is: %s\n", cmd);
191 
192 	/* Ignore objdump errors */
193 	strcat(cmd, " 2>/dev/null");
194 
195 	f = popen(cmd, "r");
196 	if (!f) {
197 		pr_debug("popen failed\n");
198 		return -1;
199 	}
200 
201 	ret = read_objdump_output(f, buf, &len, addr);
202 	if (len) {
203 		pr_debug("objdump read too few bytes: %zd\n", len);
204 		if (!ret)
205 			ret = len;
206 	}
207 
208 	pclose(f);
209 
210 	return ret;
211 }
212 
213 static void dump_buf(unsigned char *buf, size_t len)
214 {
215 	size_t i;
216 
217 	for (i = 0; i < len; i++) {
218 		pr_debug("0x%02x ", buf[i]);
219 		if (i % 16 == 15)
220 			pr_debug("\n");
221 	}
222 	pr_debug("\n");
223 }
224 
225 static int read_object_code(u64 addr, size_t len, u8 cpumode,
226 			    struct thread *thread, struct state *state)
227 {
228 	struct addr_location al;
229 	unsigned char buf1[BUFSZ];
230 	unsigned char buf2[BUFSZ];
231 	size_t ret_len;
232 	u64 objdump_addr;
233 	const char *objdump_name;
234 	char decomp_name[KMOD_DECOMP_LEN];
235 	int ret;
236 
237 	pr_debug("Reading object code for memory address: %#"PRIx64"\n", addr);
238 
239 	thread__find_addr_map(thread, cpumode, MAP__FUNCTION, addr, &al);
240 	if (!al.map || !al.map->dso) {
241 		if (cpumode == PERF_RECORD_MISC_HYPERVISOR) {
242 			pr_debug("Hypervisor address can not be resolved - skipping\n");
243 			return 0;
244 		}
245 
246 		pr_debug("thread__find_addr_map failed\n");
247 		return -1;
248 	}
249 
250 	pr_debug("File is: %s\n", al.map->dso->long_name);
251 
252 	if (al.map->dso->symtab_type == DSO_BINARY_TYPE__KALLSYMS &&
253 	    !dso__is_kcore(al.map->dso)) {
254 		pr_debug("Unexpected kernel address - skipping\n");
255 		return 0;
256 	}
257 
258 	pr_debug("On file address is: %#"PRIx64"\n", al.addr);
259 
260 	if (len > BUFSZ)
261 		len = BUFSZ;
262 
263 	/* Do not go off the map */
264 	if (addr + len > al.map->end)
265 		len = al.map->end - addr;
266 
267 	/* Read the object code using perf */
268 	ret_len = dso__data_read_offset(al.map->dso, thread->mg->machine,
269 					al.addr, buf1, len);
270 	if (ret_len != len) {
271 		pr_debug("dso__data_read_offset failed\n");
272 		return -1;
273 	}
274 
275 	/*
276 	 * Converting addresses for use by objdump requires more information.
277 	 * map__load() does that.  See map__rip_2objdump() for details.
278 	 */
279 	if (map__load(al.map))
280 		return -1;
281 
282 	/* objdump struggles with kcore - try each map only once */
283 	if (dso__is_kcore(al.map->dso)) {
284 		size_t d;
285 
286 		for (d = 0; d < state->done_cnt; d++) {
287 			if (state->done[d] == al.map->start) {
288 				pr_debug("kcore map tested already");
289 				pr_debug(" - skipping\n");
290 				return 0;
291 			}
292 		}
293 		if (state->done_cnt >= ARRAY_SIZE(state->done)) {
294 			pr_debug("Too many kcore maps - skipping\n");
295 			return 0;
296 		}
297 		state->done[state->done_cnt++] = al.map->start;
298 	}
299 
300 	objdump_name = al.map->dso->long_name;
301 	if (dso__needs_decompress(al.map->dso)) {
302 		if (dso__decompress_kmodule_path(al.map->dso, objdump_name,
303 						 decomp_name,
304 						 sizeof(decomp_name)) < 0) {
305 			pr_debug("decompression failed\n");
306 			return -1;
307 		}
308 
309 		objdump_name = decomp_name;
310 	}
311 
312 	/* Read the object code using objdump */
313 	objdump_addr = map__rip_2objdump(al.map, al.addr);
314 	ret = read_via_objdump(objdump_name, objdump_addr, buf2, len);
315 
316 	if (dso__needs_decompress(al.map->dso))
317 		unlink(objdump_name);
318 
319 	if (ret > 0) {
320 		/*
321 		 * The kernel maps are inaccurate - assume objdump is right in
322 		 * that case.
323 		 */
324 		if (cpumode == PERF_RECORD_MISC_KERNEL ||
325 		    cpumode == PERF_RECORD_MISC_GUEST_KERNEL) {
326 			len -= ret;
327 			if (len) {
328 				pr_debug("Reducing len to %zu\n", len);
329 			} else if (dso__is_kcore(al.map->dso)) {
330 				/*
331 				 * objdump cannot handle very large segments
332 				 * that may be found in kcore.
333 				 */
334 				pr_debug("objdump failed for kcore");
335 				pr_debug(" - skipping\n");
336 				return 0;
337 			} else {
338 				return -1;
339 			}
340 		}
341 	}
342 	if (ret < 0) {
343 		pr_debug("read_via_objdump failed\n");
344 		return -1;
345 	}
346 
347 	/* The results should be identical */
348 	if (memcmp(buf1, buf2, len)) {
349 		pr_debug("Bytes read differ from those read by objdump\n");
350 		pr_debug("buf1 (dso):\n");
351 		dump_buf(buf1, len);
352 		pr_debug("buf2 (objdump):\n");
353 		dump_buf(buf2, len);
354 		return -1;
355 	}
356 	pr_debug("Bytes read match those read by objdump\n");
357 
358 	return 0;
359 }
360 
361 static int process_sample_event(struct machine *machine,
362 				struct perf_evlist *evlist,
363 				union perf_event *event, struct state *state)
364 {
365 	struct perf_sample sample;
366 	struct thread *thread;
367 	int ret;
368 
369 	if (perf_evlist__parse_sample(evlist, event, &sample)) {
370 		pr_debug("perf_evlist__parse_sample failed\n");
371 		return -1;
372 	}
373 
374 	thread = machine__findnew_thread(machine, sample.pid, sample.tid);
375 	if (!thread) {
376 		pr_debug("machine__findnew_thread failed\n");
377 		return -1;
378 	}
379 
380 	ret = read_object_code(sample.ip, READLEN, sample.cpumode, thread, state);
381 	thread__put(thread);
382 	return ret;
383 }
384 
385 static int process_event(struct machine *machine, struct perf_evlist *evlist,
386 			 union perf_event *event, struct state *state)
387 {
388 	if (event->header.type == PERF_RECORD_SAMPLE)
389 		return process_sample_event(machine, evlist, event, state);
390 
391 	if (event->header.type == PERF_RECORD_THROTTLE ||
392 	    event->header.type == PERF_RECORD_UNTHROTTLE)
393 		return 0;
394 
395 	if (event->header.type < PERF_RECORD_MAX) {
396 		int ret;
397 
398 		ret = machine__process_event(machine, event, NULL);
399 		if (ret < 0)
400 			pr_debug("machine__process_event failed, event type %u\n",
401 				 event->header.type);
402 		return ret;
403 	}
404 
405 	return 0;
406 }
407 
408 static int process_events(struct machine *machine, struct perf_evlist *evlist,
409 			  struct state *state)
410 {
411 	union perf_event *event;
412 	int i, ret;
413 
414 	for (i = 0; i < evlist->nr_mmaps; i++) {
415 		while ((event = perf_evlist__mmap_read(evlist, i)) != NULL) {
416 			ret = process_event(machine, evlist, event, state);
417 			perf_evlist__mmap_consume(evlist, i);
418 			if (ret < 0)
419 				return ret;
420 		}
421 	}
422 	return 0;
423 }
424 
425 static int comp(const void *a, const void *b)
426 {
427 	return *(int *)a - *(int *)b;
428 }
429 
430 static void do_sort_something(void)
431 {
432 	int buf[40960], i;
433 
434 	for (i = 0; i < (int)ARRAY_SIZE(buf); i++)
435 		buf[i] = ARRAY_SIZE(buf) - i - 1;
436 
437 	qsort(buf, ARRAY_SIZE(buf), sizeof(int), comp);
438 
439 	for (i = 0; i < (int)ARRAY_SIZE(buf); i++) {
440 		if (buf[i] != i) {
441 			pr_debug("qsort failed\n");
442 			break;
443 		}
444 	}
445 }
446 
447 static void sort_something(void)
448 {
449 	int i;
450 
451 	for (i = 0; i < 10; i++)
452 		do_sort_something();
453 }
454 
455 static void syscall_something(void)
456 {
457 	int pipefd[2];
458 	int i;
459 
460 	for (i = 0; i < 1000; i++) {
461 		if (pipe(pipefd) < 0) {
462 			pr_debug("pipe failed\n");
463 			break;
464 		}
465 		close(pipefd[1]);
466 		close(pipefd[0]);
467 	}
468 }
469 
470 static void fs_something(void)
471 {
472 	const char *test_file_name = "temp-perf-code-reading-test-file--";
473 	FILE *f;
474 	int i;
475 
476 	for (i = 0; i < 1000; i++) {
477 		f = fopen(test_file_name, "w+");
478 		if (f) {
479 			fclose(f);
480 			unlink(test_file_name);
481 		}
482 	}
483 }
484 
485 static const char *do_determine_event(bool excl_kernel)
486 {
487 	const char *event = excl_kernel ? "cycles:u" : "cycles";
488 
489 #ifdef __s390x__
490 	char cpuid[128], model[16], model_c[16], cpum_cf_v[16];
491 	unsigned int family;
492 	int ret, cpum_cf_a;
493 
494 	if (get_cpuid(cpuid, sizeof(cpuid)))
495 		goto out_clocks;
496 	ret = sscanf(cpuid, "%*[^,],%u,%[^,],%[^,],%[^,],%x", &family, model_c,
497 		     model, cpum_cf_v, &cpum_cf_a);
498 	if (ret != 5)		 /* Not available */
499 		goto out_clocks;
500 	if (excl_kernel && (cpum_cf_a & 4))
501 		return event;
502 	if (!excl_kernel && (cpum_cf_a & 2))
503 		return event;
504 
505 	/* Fall through: missing authorization */
506 out_clocks:
507 	event = excl_kernel ? "cpu-clock:u" : "cpu-clock";
508 
509 #endif
510 	return event;
511 }
512 
513 static void do_something(void)
514 {
515 	fs_something();
516 
517 	sort_something();
518 
519 	syscall_something();
520 }
521 
522 enum {
523 	TEST_CODE_READING_OK,
524 	TEST_CODE_READING_NO_VMLINUX,
525 	TEST_CODE_READING_NO_KCORE,
526 	TEST_CODE_READING_NO_ACCESS,
527 	TEST_CODE_READING_NO_KERNEL_OBJ,
528 };
529 
530 static int do_test_code_reading(bool try_kcore)
531 {
532 	struct machine *machine;
533 	struct thread *thread;
534 	struct record_opts opts = {
535 		.mmap_pages	     = UINT_MAX,
536 		.user_freq	     = UINT_MAX,
537 		.user_interval	     = ULLONG_MAX,
538 		.freq		     = 500,
539 		.target		     = {
540 			.uses_mmap   = true,
541 		},
542 	};
543 	struct state state = {
544 		.done_cnt = 0,
545 	};
546 	struct thread_map *threads = NULL;
547 	struct cpu_map *cpus = NULL;
548 	struct perf_evlist *evlist = NULL;
549 	struct perf_evsel *evsel = NULL;
550 	int err = -1, ret;
551 	pid_t pid;
552 	struct map *map;
553 	bool have_vmlinux, have_kcore, excl_kernel = false;
554 
555 	pid = getpid();
556 
557 	machine = machine__new_host();
558 
559 	ret = machine__create_kernel_maps(machine);
560 	if (ret < 0) {
561 		pr_debug("machine__create_kernel_maps failed\n");
562 		goto out_err;
563 	}
564 
565 	/* Force the use of kallsyms instead of vmlinux to try kcore */
566 	if (try_kcore)
567 		symbol_conf.kallsyms_name = "/proc/kallsyms";
568 
569 	/* Load kernel map */
570 	map = machine__kernel_map(machine);
571 	ret = map__load(map);
572 	if (ret < 0) {
573 		pr_debug("map__load failed\n");
574 		goto out_err;
575 	}
576 	have_vmlinux = dso__is_vmlinux(map->dso);
577 	have_kcore = dso__is_kcore(map->dso);
578 
579 	/* 2nd time through we just try kcore */
580 	if (try_kcore && !have_kcore)
581 		return TEST_CODE_READING_NO_KCORE;
582 
583 	/* No point getting kernel events if there is no kernel object */
584 	if (!have_vmlinux && !have_kcore)
585 		excl_kernel = true;
586 
587 	threads = thread_map__new_by_tid(pid);
588 	if (!threads) {
589 		pr_debug("thread_map__new_by_tid failed\n");
590 		goto out_err;
591 	}
592 
593 	ret = perf_event__synthesize_thread_map(NULL, threads,
594 						perf_event__process, machine, false, 500);
595 	if (ret < 0) {
596 		pr_debug("perf_event__synthesize_thread_map failed\n");
597 		goto out_err;
598 	}
599 
600 	thread = machine__findnew_thread(machine, pid, pid);
601 	if (!thread) {
602 		pr_debug("machine__findnew_thread failed\n");
603 		goto out_put;
604 	}
605 
606 	cpus = cpu_map__new(NULL);
607 	if (!cpus) {
608 		pr_debug("cpu_map__new failed\n");
609 		goto out_put;
610 	}
611 
612 	while (1) {
613 		const char *str;
614 
615 		evlist = perf_evlist__new();
616 		if (!evlist) {
617 			pr_debug("perf_evlist__new failed\n");
618 			goto out_put;
619 		}
620 
621 		perf_evlist__set_maps(evlist, cpus, threads);
622 
623 		str = do_determine_event(excl_kernel);
624 		pr_debug("Parsing event '%s'\n", str);
625 		ret = parse_events(evlist, str, NULL);
626 		if (ret < 0) {
627 			pr_debug("parse_events failed\n");
628 			goto out_put;
629 		}
630 
631 		perf_evlist__config(evlist, &opts, NULL);
632 
633 		evsel = perf_evlist__first(evlist);
634 
635 		evsel->attr.comm = 1;
636 		evsel->attr.disabled = 1;
637 		evsel->attr.enable_on_exec = 0;
638 
639 		ret = perf_evlist__open(evlist);
640 		if (ret < 0) {
641 			if (!excl_kernel) {
642 				excl_kernel = true;
643 				/*
644 				 * Both cpus and threads are now owned by evlist
645 				 * and will be freed by following perf_evlist__set_maps
646 				 * call. Getting refference to keep them alive.
647 				 */
648 				cpu_map__get(cpus);
649 				thread_map__get(threads);
650 				perf_evlist__set_maps(evlist, NULL, NULL);
651 				perf_evlist__delete(evlist);
652 				evlist = NULL;
653 				continue;
654 			}
655 
656 			if (verbose > 0) {
657 				char errbuf[512];
658 				perf_evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
659 				pr_debug("perf_evlist__open() failed!\n%s\n", errbuf);
660 			}
661 
662 			goto out_put;
663 		}
664 		break;
665 	}
666 
667 	ret = perf_evlist__mmap(evlist, UINT_MAX);
668 	if (ret < 0) {
669 		pr_debug("perf_evlist__mmap failed\n");
670 		goto out_put;
671 	}
672 
673 	perf_evlist__enable(evlist);
674 
675 	do_something();
676 
677 	perf_evlist__disable(evlist);
678 
679 	ret = process_events(machine, evlist, &state);
680 	if (ret < 0)
681 		goto out_put;
682 
683 	if (!have_vmlinux && !have_kcore && !try_kcore)
684 		err = TEST_CODE_READING_NO_KERNEL_OBJ;
685 	else if (!have_vmlinux && !try_kcore)
686 		err = TEST_CODE_READING_NO_VMLINUX;
687 	else if (excl_kernel)
688 		err = TEST_CODE_READING_NO_ACCESS;
689 	else
690 		err = TEST_CODE_READING_OK;
691 out_put:
692 	thread__put(thread);
693 out_err:
694 
695 	if (evlist) {
696 		perf_evlist__delete(evlist);
697 	} else {
698 		cpu_map__put(cpus);
699 		thread_map__put(threads);
700 	}
701 	machine__delete_threads(machine);
702 	machine__delete(machine);
703 
704 	return err;
705 }
706 
707 int test__code_reading(struct test *test __maybe_unused, int subtest __maybe_unused)
708 {
709 	int ret;
710 
711 	ret = do_test_code_reading(false);
712 	if (!ret)
713 		ret = do_test_code_reading(true);
714 
715 	switch (ret) {
716 	case TEST_CODE_READING_OK:
717 		return 0;
718 	case TEST_CODE_READING_NO_VMLINUX:
719 		pr_debug("no vmlinux\n");
720 		return 0;
721 	case TEST_CODE_READING_NO_KCORE:
722 		pr_debug("no kcore\n");
723 		return 0;
724 	case TEST_CODE_READING_NO_ACCESS:
725 		pr_debug("no access\n");
726 		return 0;
727 	case TEST_CODE_READING_NO_KERNEL_OBJ:
728 		pr_debug("no kernel obj\n");
729 		return 0;
730 	default:
731 		return -1;
732 	};
733 }
734