code-reading.c 14.6 KB
Newer Older
1
#include <errno.h>
2
#include <linux/kernel.h>
B
Borislav Petkov 已提交
3
#include <linux/types.h>
4
#include <inttypes.h>
5 6 7 8
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
9
#include <sys/param.h>
10 11 12 13 14 15 16 17 18 19 20 21

#include "parse-events.h"
#include "evlist.h"
#include "evsel.h"
#include "thread_map.h"
#include "cpumap.h"
#include "machine.h"
#include "event.h"
#include "thread.h"

#include "tests.h"

22 23
#include "sane_ctype.h"

24 25 26
#define BUFSZ	1024
#define READLEN	128

27 28 29 30 31
struct state {
	u64 done[1024];
	size_t done_cnt;
};

32 33 34 35 36 37 38 39 40
static unsigned int hex(char c)
{
	if (c >= '0' && c <= '9')
		return c - '0';
	if (c >= 'a' && c <= 'f')
		return c - 'a' + 10;
	return c - 'A' + 10;
}

41 42
static size_t read_objdump_chunk(const char **line, unsigned char **buf,
				 size_t *buf_len)
43
{
44 45
	size_t bytes_read = 0;
	unsigned char *chunk_start = *buf;
46 47

	/* Read bytes */
48
	while (*buf_len > 0) {
49 50 51
		char c1, c2;

		/* Get 2 hex digits */
52 53
		c1 = *(*line)++;
		if (!isxdigit(c1))
54
			break;
55 56
		c2 = *(*line)++;
		if (!isxdigit(c2))
57
			break;
58 59 60 61 62 63 64 65 66

		/* Store byte and advance buf */
		**buf = (hex(c1) << 4) | hex(c2);
		(*buf)++;
		(*buf_len)--;
		bytes_read++;

		/* End of chunk? */
		if (isspace(**line))
67 68
			break;
	}
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

	/*
	 * objdump will display raw insn as LE if code endian
	 * is LE and bytes_per_chunk > 1. In that case reverse
	 * the chunk we just read.
	 *
	 * see disassemble_bytes() at binutils/objdump.c for details
	 * how objdump chooses display endian)
	 */
	if (bytes_read > 1 && !bigendian()) {
		unsigned char *chunk_end = chunk_start + bytes_read - 1;
		unsigned char tmp;

		while (chunk_start < chunk_end) {
			tmp = *chunk_start;
			*chunk_start = *chunk_end;
			*chunk_end = tmp;
			chunk_start++;
			chunk_end--;
		}
	}

	return bytes_read;
}

static size_t read_objdump_line(const char *line, unsigned char *buf,
				size_t buf_len)
{
	const char *p;
	size_t ret, bytes_read = 0;

	/* Skip to a colon */
	p = strchr(line, ':');
	if (!p)
		return 0;
	p++;

	/* Skip initial spaces */
	while (*p) {
		if (!isspace(*p))
			break;
		p++;
	}

	do {
		ret = read_objdump_chunk(&p, &buf, &buf_len);
		bytes_read += ret;
		p++;
	} while (ret > 0);

119
	/* return number of successfully read bytes */
120
	return bytes_read;
121 122
}

123
static int read_objdump_output(FILE *f, void *buf, size_t *len, u64 start_addr)
124 125
{
	char *line = NULL;
126
	size_t line_len, off_last = 0;
127 128
	ssize_t ret;
	int err = 0;
129
	u64 addr, last_addr = start_addr;
130 131 132 133

	while (off_last < *len) {
		size_t off, read_bytes, written_bytes;
		unsigned char tmp[BUFSZ];
134 135 136 137 138 139 140 141 142

		ret = getline(&line, &line_len, f);
		if (feof(f))
			break;
		if (ret < 0) {
			pr_debug("getline failed\n");
			err = -1;
			break;
		}
143 144

		/* read objdump data into temporary buffer */
145
		read_bytes = read_objdump_line(line, tmp, sizeof(tmp));
146 147 148 149 150
		if (!read_bytes)
			continue;

		if (sscanf(line, "%"PRIx64, &addr) != 1)
			continue;
151 152 153 154 155
		if (addr < last_addr) {
			pr_debug("addr going backwards, read beyond section?\n");
			break;
		}
		last_addr = addr;
156 157 158 159 160 161 162 163 164

		/* copy it from temporary buffer to 'buf' according
		 * to address on current objdump line */
		off = addr - start_addr;
		if (off >= *len)
			break;
		written_bytes = MIN(read_bytes, *len - off);
		memcpy(buf + off, tmp, written_bytes);
		off_last = off + written_bytes;
165 166
	}

167 168 169
	/* len returns number of bytes that could not be read */
	*len -= off_last;

170 171 172 173 174 175 176 177 178 179 180 181 182
	free(line);

	return err;
}

static int read_via_objdump(const char *filename, u64 addr, void *buf,
			    size_t len)
{
	char cmd[PATH_MAX * 2];
	const char *fmt;
	FILE *f;
	int ret;

183
	fmt = "%s -z -d --start-address=0x%"PRIx64" --stop-address=0x%"PRIx64" %s";
184 185 186 187 188 189 190
	ret = snprintf(cmd, sizeof(cmd), fmt, "objdump", addr, addr + len,
		       filename);
	if (ret <= 0 || (size_t)ret >= sizeof(cmd))
		return -1;

	pr_debug("Objdump command is: %s\n", cmd);

191 192 193
	/* Ignore objdump errors */
	strcat(cmd, " 2>/dev/null");

194 195 196 197 198 199
	f = popen(cmd, "r");
	if (!f) {
		pr_debug("popen failed\n");
		return -1;
	}

200
	ret = read_objdump_output(f, buf, &len, addr);
201
	if (len) {
202
		pr_debug("objdump read too few bytes: %zd\n", len);
203 204 205 206 207 208 209 210 211
		if (!ret)
			ret = len;
	}

	pclose(f);

	return ret;
}

212 213 214 215 216 217 218 219 220 221 222 223
static void dump_buf(unsigned char *buf, size_t len)
{
	size_t i;

	for (i = 0; i < len; i++) {
		pr_debug("0x%02x ", buf[i]);
		if (i % 16 == 15)
			pr_debug("\n");
	}
	pr_debug("\n");
}

224
static int read_object_code(u64 addr, size_t len, u8 cpumode,
225
			    struct thread *thread, struct state *state)
226 227 228 229 230 231
{
	struct addr_location al;
	unsigned char buf1[BUFSZ];
	unsigned char buf2[BUFSZ];
	size_t ret_len;
	u64 objdump_addr;
232 233
	const char *objdump_name;
	char decomp_name[KMOD_DECOMP_LEN];
234 235 236 237
	int ret;

	pr_debug("Reading object code for memory address: %#"PRIx64"\n", addr);

238
	thread__find_addr_map(thread, cpumode, MAP__FUNCTION, addr, &al);
239
	if (!al.map || !al.map->dso) {
240 241 242 243 244
		if (cpumode == PERF_RECORD_MISC_HYPERVISOR) {
			pr_debug("Hypervisor address can not be resolved - skipping\n");
			return 0;
		}

245 246 247 248 249 250
		pr_debug("thread__find_addr_map failed\n");
		return -1;
	}

	pr_debug("File is: %s\n", al.map->dso->long_name);

251 252
	if (al.map->dso->symtab_type == DSO_BINARY_TYPE__KALLSYMS &&
	    !dso__is_kcore(al.map->dso)) {
253 254 255 256 257 258 259 260 261 262 263 264 265 266
		pr_debug("Unexpected kernel address - skipping\n");
		return 0;
	}

	pr_debug("On file address is: %#"PRIx64"\n", al.addr);

	if (len > BUFSZ)
		len = BUFSZ;

	/* Do not go off the map */
	if (addr + len > al.map->end)
		len = al.map->end - addr;

	/* Read the object code using perf */
267 268
	ret_len = dso__data_read_offset(al.map->dso, thread->mg->machine,
					al.addr, buf1, len);
269 270 271 272 273 274 275 276 277
	if (ret_len != len) {
		pr_debug("dso__data_read_offset failed\n");
		return -1;
	}

	/*
	 * Converting addresses for use by objdump requires more information.
	 * map__load() does that.  See map__rip_2objdump() for details.
	 */
278
	if (map__load(al.map))
279 280
		return -1;

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	/* objdump struggles with kcore - try each map only once */
	if (dso__is_kcore(al.map->dso)) {
		size_t d;

		for (d = 0; d < state->done_cnt; d++) {
			if (state->done[d] == al.map->start) {
				pr_debug("kcore map tested already");
				pr_debug(" - skipping\n");
				return 0;
			}
		}
		if (state->done_cnt >= ARRAY_SIZE(state->done)) {
			pr_debug("Too many kcore maps - skipping\n");
			return 0;
		}
		state->done[state->done_cnt++] = al.map->start;
	}

299 300 301 302 303 304 305 306 307 308 309 310
	objdump_name = al.map->dso->long_name;
	if (dso__needs_decompress(al.map->dso)) {
		if (dso__decompress_kmodule_path(al.map->dso, objdump_name,
						 decomp_name,
						 sizeof(decomp_name)) < 0) {
			pr_debug("decompression failed\n");
			return -1;
		}

		objdump_name = decomp_name;
	}

311 312
	/* Read the object code using objdump */
	objdump_addr = map__rip_2objdump(al.map, al.addr);
313 314 315 316 317
	ret = read_via_objdump(objdump_name, objdump_addr, buf2, len);

	if (dso__needs_decompress(al.map->dso))
		unlink(objdump_name);

318 319 320 321 322 323 324 325
	if (ret > 0) {
		/*
		 * The kernel maps are inaccurate - assume objdump is right in
		 * that case.
		 */
		if (cpumode == PERF_RECORD_MISC_KERNEL ||
		    cpumode == PERF_RECORD_MISC_GUEST_KERNEL) {
			len -= ret;
326
			if (len) {
327
				pr_debug("Reducing len to %zu\n", len);
328 329 330 331 332 333 334 335 336
			} else if (dso__is_kcore(al.map->dso)) {
				/*
				 * objdump cannot handle very large segments
				 * that may be found in kcore.
				 */
				pr_debug("objdump failed for kcore");
				pr_debug(" - skipping\n");
				return 0;
			} else {
337
				return -1;
338
			}
339 340 341 342 343 344 345 346 347 348
		}
	}
	if (ret < 0) {
		pr_debug("read_via_objdump failed\n");
		return -1;
	}

	/* The results should be identical */
	if (memcmp(buf1, buf2, len)) {
		pr_debug("Bytes read differ from those read by objdump\n");
349 350 351 352
		pr_debug("buf1 (dso):\n");
		dump_buf(buf1, len);
		pr_debug("buf2 (objdump):\n");
		dump_buf(buf2, len);
353 354 355 356 357 358 359 360 361
		return -1;
	}
	pr_debug("Bytes read match those read by objdump\n");

	return 0;
}

static int process_sample_event(struct machine *machine,
				struct perf_evlist *evlist,
362
				union perf_event *event, struct state *state)
363 364 365
{
	struct perf_sample sample;
	struct thread *thread;
366
	int ret;
367 368 369 370 371 372

	if (perf_evlist__parse_sample(evlist, event, &sample)) {
		pr_debug("perf_evlist__parse_sample failed\n");
		return -1;
	}

373
	thread = machine__findnew_thread(machine, sample.pid, sample.tid);
374 375 376 377 378
	if (!thread) {
		pr_debug("machine__findnew_thread failed\n");
		return -1;
	}

379
	ret = read_object_code(sample.ip, READLEN, sample.cpumode, thread, state);
380 381
	thread__put(thread);
	return ret;
382 383 384
}

static int process_event(struct machine *machine, struct perf_evlist *evlist,
385
			 union perf_event *event, struct state *state)
386 387
{
	if (event->header.type == PERF_RECORD_SAMPLE)
388
		return process_sample_event(machine, evlist, event, state);
389

390 391 392 393 394 395 396 397 398 399 400 401 402
	if (event->header.type == PERF_RECORD_THROTTLE ||
	    event->header.type == PERF_RECORD_UNTHROTTLE)
		return 0;

	if (event->header.type < PERF_RECORD_MAX) {
		int ret;

		ret = machine__process_event(machine, event, NULL);
		if (ret < 0)
			pr_debug("machine__process_event failed, event type %u\n",
				 event->header.type);
		return ret;
	}
403 404 405 406

	return 0;
}

407 408
static int process_events(struct machine *machine, struct perf_evlist *evlist,
			  struct state *state)
409 410 411 412 413 414
{
	union perf_event *event;
	int i, ret;

	for (i = 0; i < evlist->nr_mmaps; i++) {
		while ((event = perf_evlist__mmap_read(evlist, i)) != NULL) {
415
			ret = process_event(machine, evlist, event, state);
416
			perf_evlist__mmap_consume(evlist, i);
417 418 419 420 421 422 423 424 425 426 427 428 429 430
			if (ret < 0)
				return ret;
		}
	}
	return 0;
}

static int comp(const void *a, const void *b)
{
	return *(int *)a - *(int *)b;
}

static void do_sort_something(void)
{
431
	int buf[40960], i;
432

433 434
	for (i = 0; i < (int)ARRAY_SIZE(buf); i++)
		buf[i] = ARRAY_SIZE(buf) - i - 1;
435

436
	qsort(buf, ARRAY_SIZE(buf), sizeof(int), comp);
437

438
	for (i = 0; i < (int)ARRAY_SIZE(buf); i++) {
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
		if (buf[i] != i) {
			pr_debug("qsort failed\n");
			break;
		}
	}
}

static void sort_something(void)
{
	int i;

	for (i = 0; i < 10; i++)
		do_sort_something();
}

static void syscall_something(void)
{
	int pipefd[2];
	int i;

	for (i = 0; i < 1000; i++) {
		if (pipe(pipefd) < 0) {
			pr_debug("pipe failed\n");
			break;
		}
		close(pipefd[1]);
		close(pipefd[0]);
	}
}

static void fs_something(void)
{
	const char *test_file_name = "temp-perf-code-reading-test-file--";
	FILE *f;
	int i;

	for (i = 0; i < 1000; i++) {
		f = fopen(test_file_name, "w+");
		if (f) {
			fclose(f);
			unlink(test_file_name);
		}
	}
}

static void do_something(void)
{
	fs_something();

	sort_something();

	syscall_something();
}

enum {
	TEST_CODE_READING_OK,
	TEST_CODE_READING_NO_VMLINUX,
496
	TEST_CODE_READING_NO_KCORE,
497
	TEST_CODE_READING_NO_ACCESS,
498
	TEST_CODE_READING_NO_KERNEL_OBJ,
499 500
};

501
static int do_test_code_reading(bool try_kcore)
502 503 504
{
	struct machine *machine;
	struct thread *thread;
505
	struct record_opts opts = {
506 507 508
		.mmap_pages	     = UINT_MAX,
		.user_freq	     = UINT_MAX,
		.user_interval	     = ULLONG_MAX,
509
		.freq		     = 500,
510 511 512 513
		.target		     = {
			.uses_mmap   = true,
		},
	};
514 515 516
	struct state state = {
		.done_cnt = 0,
	};
517 518 519 520 521 522 523
	struct thread_map *threads = NULL;
	struct cpu_map *cpus = NULL;
	struct perf_evlist *evlist = NULL;
	struct perf_evsel *evsel = NULL;
	int err = -1, ret;
	pid_t pid;
	struct map *map;
524
	bool have_vmlinux, have_kcore, excl_kernel = false;
525 526 527

	pid = getpid();

528
	machine = machine__new_host();
529 530 531 532 533 534 535

	ret = machine__create_kernel_maps(machine);
	if (ret < 0) {
		pr_debug("machine__create_kernel_maps failed\n");
		goto out_err;
	}

536 537 538 539
	/* Force the use of kallsyms instead of vmlinux to try kcore */
	if (try_kcore)
		symbol_conf.kallsyms_name = "/proc/kallsyms";

540
	/* Load kernel map */
541
	map = machine__kernel_map(machine);
542
	ret = map__load(map);
543 544 545 546
	if (ret < 0) {
		pr_debug("map__load failed\n");
		goto out_err;
	}
547 548 549 550 551 552 553 554 555
	have_vmlinux = dso__is_vmlinux(map->dso);
	have_kcore = dso__is_kcore(map->dso);

	/* 2nd time through we just try kcore */
	if (try_kcore && !have_kcore)
		return TEST_CODE_READING_NO_KCORE;

	/* No point getting kernel events if there is no kernel object */
	if (!have_vmlinux && !have_kcore)
556 557 558 559 560 561 562 563 564
		excl_kernel = true;

	threads = thread_map__new_by_tid(pid);
	if (!threads) {
		pr_debug("thread_map__new_by_tid failed\n");
		goto out_err;
	}

	ret = perf_event__synthesize_thread_map(NULL, threads,
565
						perf_event__process, machine, false, 500);
566 567 568 569 570
	if (ret < 0) {
		pr_debug("perf_event__synthesize_thread_map failed\n");
		goto out_err;
	}

571
	thread = machine__findnew_thread(machine, pid, pid);
572 573
	if (!thread) {
		pr_debug("machine__findnew_thread failed\n");
574
		goto out_put;
575 576 577 578 579
	}

	cpus = cpu_map__new(NULL);
	if (!cpus) {
		pr_debug("cpu_map__new failed\n");
580
		goto out_put;
581 582 583 584 585 586 587 588
	}

	while (1) {
		const char *str;

		evlist = perf_evlist__new();
		if (!evlist) {
			pr_debug("perf_evlist__new failed\n");
589
			goto out_put;
590 591 592 593 594 595 596 597 598
		}

		perf_evlist__set_maps(evlist, cpus, threads);

		if (excl_kernel)
			str = "cycles:u";
		else
			str = "cycles";
		pr_debug("Parsing event '%s'\n", str);
599
		ret = parse_events(evlist, str, NULL);
600 601
		if (ret < 0) {
			pr_debug("parse_events failed\n");
602
			goto out_put;
603 604
		}

605
		perf_evlist__config(evlist, &opts, NULL);
606 607 608 609 610 611 612 613 614 615 616

		evsel = perf_evlist__first(evlist);

		evsel->attr.comm = 1;
		evsel->attr.disabled = 1;
		evsel->attr.enable_on_exec = 0;

		ret = perf_evlist__open(evlist);
		if (ret < 0) {
			if (!excl_kernel) {
				excl_kernel = true;
617 618 619 620 621 622 623
				/*
				 * Both cpus and threads are now owned by evlist
				 * and will be freed by following perf_evlist__set_maps
				 * call. Getting refference to keep them alive.
				 */
				cpu_map__get(cpus);
				thread_map__get(threads);
624
				perf_evlist__set_maps(evlist, NULL, NULL);
625 626 627 628
				perf_evlist__delete(evlist);
				evlist = NULL;
				continue;
			}
629

630
			if (verbose > 0) {
631 632 633 634 635
				char errbuf[512];
				perf_evlist__strerror_open(evlist, errno, errbuf, sizeof(errbuf));
				pr_debug("perf_evlist__open() failed!\n%s\n", errbuf);
			}

636
			goto out_put;
637 638 639 640 641 642 643
		}
		break;
	}

	ret = perf_evlist__mmap(evlist, UINT_MAX, false);
	if (ret < 0) {
		pr_debug("perf_evlist__mmap failed\n");
644
		goto out_put;
645 646 647 648 649 650 651 652
	}

	perf_evlist__enable(evlist);

	do_something();

	perf_evlist__disable(evlist);

653
	ret = process_events(machine, evlist, &state);
654
	if (ret < 0)
655
		goto out_put;
656

657 658 659
	if (!have_vmlinux && !have_kcore && !try_kcore)
		err = TEST_CODE_READING_NO_KERNEL_OBJ;
	else if (!have_vmlinux && !try_kcore)
660 661 662 663 664
		err = TEST_CODE_READING_NO_VMLINUX;
	else if (excl_kernel)
		err = TEST_CODE_READING_NO_ACCESS;
	else
		err = TEST_CODE_READING_OK;
665 666
out_put:
	thread__put(thread);
667
out_err:
668

669 670
	if (evlist) {
		perf_evlist__delete(evlist);
671
	} else {
672
		cpu_map__put(cpus);
673
		thread_map__put(threads);
674
	}
675
	machine__delete_threads(machine);
676
	machine__delete(machine);
677 678 679 680

	return err;
}

681
int test__code_reading(struct test *test __maybe_unused, int subtest __maybe_unused)
682 683 684
{
	int ret;

685 686 687
	ret = do_test_code_reading(false);
	if (!ret)
		ret = do_test_code_reading(true);
688 689 690 691 692

	switch (ret) {
	case TEST_CODE_READING_OK:
		return 0;
	case TEST_CODE_READING_NO_VMLINUX:
693
		pr_debug("no vmlinux\n");
694
		return 0;
695
	case TEST_CODE_READING_NO_KCORE:
696
		pr_debug("no kcore\n");
697
		return 0;
698
	case TEST_CODE_READING_NO_ACCESS:
699
		pr_debug("no access\n");
700
		return 0;
701
	case TEST_CODE_READING_NO_KERNEL_OBJ:
702
		pr_debug("no kernel obj\n");
703
		return 0;
704 705 706 707
	default:
		return -1;
	};
}