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