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