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