xref: /openbmc/linux/tools/perf/util/annotate.c (revision 5f32c314)
1 /*
2  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
3  *
4  * Parts came from builtin-annotate.c, see those files for further
5  * copyright notes.
6  *
7  * Released under the GPL v2. (and only v2, not any later version)
8  */
9 
10 #include "util.h"
11 #include "build-id.h"
12 #include "color.h"
13 #include "cache.h"
14 #include "symbol.h"
15 #include "debug.h"
16 #include "annotate.h"
17 #include "evsel.h"
18 #include <pthread.h>
19 #include <linux/bitops.h>
20 
21 const char 	*disassembler_style;
22 const char	*objdump_path;
23 
24 static struct ins *ins__find(const char *name);
25 static int disasm_line__parse(char *line, char **namep, char **rawp);
26 
27 static void ins__delete(struct ins_operands *ops)
28 {
29 	zfree(&ops->source.raw);
30 	zfree(&ops->source.name);
31 	zfree(&ops->target.raw);
32 	zfree(&ops->target.name);
33 }
34 
35 static int ins__raw_scnprintf(struct ins *ins, char *bf, size_t size,
36 			      struct ins_operands *ops)
37 {
38 	return scnprintf(bf, size, "%-6.6s %s", ins->name, ops->raw);
39 }
40 
41 int ins__scnprintf(struct ins *ins, char *bf, size_t size,
42 		  struct ins_operands *ops)
43 {
44 	if (ins->ops->scnprintf)
45 		return ins->ops->scnprintf(ins, bf, size, ops);
46 
47 	return ins__raw_scnprintf(ins, bf, size, ops);
48 }
49 
50 static int call__parse(struct ins_operands *ops)
51 {
52 	char *endptr, *tok, *name;
53 
54 	ops->target.addr = strtoull(ops->raw, &endptr, 16);
55 
56 	name = strchr(endptr, '<');
57 	if (name == NULL)
58 		goto indirect_call;
59 
60 	name++;
61 
62 	tok = strchr(name, '>');
63 	if (tok == NULL)
64 		return -1;
65 
66 	*tok = '\0';
67 	ops->target.name = strdup(name);
68 	*tok = '>';
69 
70 	return ops->target.name == NULL ? -1 : 0;
71 
72 indirect_call:
73 	tok = strchr(endptr, '(');
74 	if (tok != NULL) {
75 		ops->target.addr = 0;
76 		return 0;
77 	}
78 
79 	tok = strchr(endptr, '*');
80 	if (tok == NULL)
81 		return -1;
82 
83 	ops->target.addr = strtoull(tok + 1, NULL, 16);
84 	return 0;
85 }
86 
87 static int call__scnprintf(struct ins *ins, char *bf, size_t size,
88 			   struct ins_operands *ops)
89 {
90 	if (ops->target.name)
91 		return scnprintf(bf, size, "%-6.6s %s", ins->name, ops->target.name);
92 
93 	if (ops->target.addr == 0)
94 		return ins__raw_scnprintf(ins, bf, size, ops);
95 
96 	return scnprintf(bf, size, "%-6.6s *%" PRIx64, ins->name, ops->target.addr);
97 }
98 
99 static struct ins_ops call_ops = {
100 	.parse	   = call__parse,
101 	.scnprintf = call__scnprintf,
102 };
103 
104 bool ins__is_call(const struct ins *ins)
105 {
106 	return ins->ops == &call_ops;
107 }
108 
109 static int jump__parse(struct ins_operands *ops)
110 {
111 	const char *s = strchr(ops->raw, '+');
112 
113 	ops->target.addr = strtoull(ops->raw, NULL, 16);
114 
115 	if (s++ != NULL)
116 		ops->target.offset = strtoull(s, NULL, 16);
117 	else
118 		ops->target.offset = UINT64_MAX;
119 
120 	return 0;
121 }
122 
123 static int jump__scnprintf(struct ins *ins, char *bf, size_t size,
124 			   struct ins_operands *ops)
125 {
126 	return scnprintf(bf, size, "%-6.6s %" PRIx64, ins->name, ops->target.offset);
127 }
128 
129 static struct ins_ops jump_ops = {
130 	.parse	   = jump__parse,
131 	.scnprintf = jump__scnprintf,
132 };
133 
134 bool ins__is_jump(const struct ins *ins)
135 {
136 	return ins->ops == &jump_ops;
137 }
138 
139 static int comment__symbol(char *raw, char *comment, u64 *addrp, char **namep)
140 {
141 	char *endptr, *name, *t;
142 
143 	if (strstr(raw, "(%rip)") == NULL)
144 		return 0;
145 
146 	*addrp = strtoull(comment, &endptr, 16);
147 	name = strchr(endptr, '<');
148 	if (name == NULL)
149 		return -1;
150 
151 	name++;
152 
153 	t = strchr(name, '>');
154 	if (t == NULL)
155 		return 0;
156 
157 	*t = '\0';
158 	*namep = strdup(name);
159 	*t = '>';
160 
161 	return 0;
162 }
163 
164 static int lock__parse(struct ins_operands *ops)
165 {
166 	char *name;
167 
168 	ops->locked.ops = zalloc(sizeof(*ops->locked.ops));
169 	if (ops->locked.ops == NULL)
170 		return 0;
171 
172 	if (disasm_line__parse(ops->raw, &name, &ops->locked.ops->raw) < 0)
173 		goto out_free_ops;
174 
175 	ops->locked.ins = ins__find(name);
176 	if (ops->locked.ins == NULL)
177 		goto out_free_ops;
178 
179 	if (!ops->locked.ins->ops)
180 		return 0;
181 
182 	if (ops->locked.ins->ops->parse)
183 		ops->locked.ins->ops->parse(ops->locked.ops);
184 
185 	return 0;
186 
187 out_free_ops:
188 	zfree(&ops->locked.ops);
189 	return 0;
190 }
191 
192 static int lock__scnprintf(struct ins *ins, char *bf, size_t size,
193 			   struct ins_operands *ops)
194 {
195 	int printed;
196 
197 	if (ops->locked.ins == NULL)
198 		return ins__raw_scnprintf(ins, bf, size, ops);
199 
200 	printed = scnprintf(bf, size, "%-6.6s ", ins->name);
201 	return printed + ins__scnprintf(ops->locked.ins, bf + printed,
202 					size - printed, ops->locked.ops);
203 }
204 
205 static void lock__delete(struct ins_operands *ops)
206 {
207 	zfree(&ops->locked.ops);
208 	zfree(&ops->target.raw);
209 	zfree(&ops->target.name);
210 }
211 
212 static struct ins_ops lock_ops = {
213 	.free	   = lock__delete,
214 	.parse	   = lock__parse,
215 	.scnprintf = lock__scnprintf,
216 };
217 
218 static int mov__parse(struct ins_operands *ops)
219 {
220 	char *s = strchr(ops->raw, ','), *target, *comment, prev;
221 
222 	if (s == NULL)
223 		return -1;
224 
225 	*s = '\0';
226 	ops->source.raw = strdup(ops->raw);
227 	*s = ',';
228 
229 	if (ops->source.raw == NULL)
230 		return -1;
231 
232 	target = ++s;
233 
234 	while (s[0] != '\0' && !isspace(s[0]))
235 		++s;
236 	prev = *s;
237 	*s = '\0';
238 
239 	ops->target.raw = strdup(target);
240 	*s = prev;
241 
242 	if (ops->target.raw == NULL)
243 		goto out_free_source;
244 
245 	comment = strchr(s, '#');
246 	if (comment == NULL)
247 		return 0;
248 
249 	while (comment[0] != '\0' && isspace(comment[0]))
250 		++comment;
251 
252 	comment__symbol(ops->source.raw, comment, &ops->source.addr, &ops->source.name);
253 	comment__symbol(ops->target.raw, comment, &ops->target.addr, &ops->target.name);
254 
255 	return 0;
256 
257 out_free_source:
258 	zfree(&ops->source.raw);
259 	return -1;
260 }
261 
262 static int mov__scnprintf(struct ins *ins, char *bf, size_t size,
263 			   struct ins_operands *ops)
264 {
265 	return scnprintf(bf, size, "%-6.6s %s,%s", ins->name,
266 			 ops->source.name ?: ops->source.raw,
267 			 ops->target.name ?: ops->target.raw);
268 }
269 
270 static struct ins_ops mov_ops = {
271 	.parse	   = mov__parse,
272 	.scnprintf = mov__scnprintf,
273 };
274 
275 static int dec__parse(struct ins_operands *ops)
276 {
277 	char *target, *comment, *s, prev;
278 
279 	target = s = ops->raw;
280 
281 	while (s[0] != '\0' && !isspace(s[0]))
282 		++s;
283 	prev = *s;
284 	*s = '\0';
285 
286 	ops->target.raw = strdup(target);
287 	*s = prev;
288 
289 	if (ops->target.raw == NULL)
290 		return -1;
291 
292 	comment = strchr(s, '#');
293 	if (comment == NULL)
294 		return 0;
295 
296 	while (comment[0] != '\0' && isspace(comment[0]))
297 		++comment;
298 
299 	comment__symbol(ops->target.raw, comment, &ops->target.addr, &ops->target.name);
300 
301 	return 0;
302 }
303 
304 static int dec__scnprintf(struct ins *ins, char *bf, size_t size,
305 			   struct ins_operands *ops)
306 {
307 	return scnprintf(bf, size, "%-6.6s %s", ins->name,
308 			 ops->target.name ?: ops->target.raw);
309 }
310 
311 static struct ins_ops dec_ops = {
312 	.parse	   = dec__parse,
313 	.scnprintf = dec__scnprintf,
314 };
315 
316 static int nop__scnprintf(struct ins *ins __maybe_unused, char *bf, size_t size,
317 			  struct ins_operands *ops __maybe_unused)
318 {
319 	return scnprintf(bf, size, "%-6.6s", "nop");
320 }
321 
322 static struct ins_ops nop_ops = {
323 	.scnprintf = nop__scnprintf,
324 };
325 
326 /*
327  * Must be sorted by name!
328  */
329 static struct ins instructions[] = {
330 	{ .name = "add",   .ops  = &mov_ops, },
331 	{ .name = "addl",  .ops  = &mov_ops, },
332 	{ .name = "addq",  .ops  = &mov_ops, },
333 	{ .name = "addw",  .ops  = &mov_ops, },
334 	{ .name = "and",   .ops  = &mov_ops, },
335 	{ .name = "bts",   .ops  = &mov_ops, },
336 	{ .name = "call",  .ops  = &call_ops, },
337 	{ .name = "callq", .ops  = &call_ops, },
338 	{ .name = "cmp",   .ops  = &mov_ops, },
339 	{ .name = "cmpb",  .ops  = &mov_ops, },
340 	{ .name = "cmpl",  .ops  = &mov_ops, },
341 	{ .name = "cmpq",  .ops  = &mov_ops, },
342 	{ .name = "cmpw",  .ops  = &mov_ops, },
343 	{ .name = "cmpxch", .ops  = &mov_ops, },
344 	{ .name = "dec",   .ops  = &dec_ops, },
345 	{ .name = "decl",  .ops  = &dec_ops, },
346 	{ .name = "imul",  .ops  = &mov_ops, },
347 	{ .name = "inc",   .ops  = &dec_ops, },
348 	{ .name = "incl",  .ops  = &dec_ops, },
349 	{ .name = "ja",	   .ops  = &jump_ops, },
350 	{ .name = "jae",   .ops  = &jump_ops, },
351 	{ .name = "jb",	   .ops  = &jump_ops, },
352 	{ .name = "jbe",   .ops  = &jump_ops, },
353 	{ .name = "jc",	   .ops  = &jump_ops, },
354 	{ .name = "jcxz",  .ops  = &jump_ops, },
355 	{ .name = "je",	   .ops  = &jump_ops, },
356 	{ .name = "jecxz", .ops  = &jump_ops, },
357 	{ .name = "jg",	   .ops  = &jump_ops, },
358 	{ .name = "jge",   .ops  = &jump_ops, },
359 	{ .name = "jl",    .ops  = &jump_ops, },
360 	{ .name = "jle",   .ops  = &jump_ops, },
361 	{ .name = "jmp",   .ops  = &jump_ops, },
362 	{ .name = "jmpq",  .ops  = &jump_ops, },
363 	{ .name = "jna",   .ops  = &jump_ops, },
364 	{ .name = "jnae",  .ops  = &jump_ops, },
365 	{ .name = "jnb",   .ops  = &jump_ops, },
366 	{ .name = "jnbe",  .ops  = &jump_ops, },
367 	{ .name = "jnc",   .ops  = &jump_ops, },
368 	{ .name = "jne",   .ops  = &jump_ops, },
369 	{ .name = "jng",   .ops  = &jump_ops, },
370 	{ .name = "jnge",  .ops  = &jump_ops, },
371 	{ .name = "jnl",   .ops  = &jump_ops, },
372 	{ .name = "jnle",  .ops  = &jump_ops, },
373 	{ .name = "jno",   .ops  = &jump_ops, },
374 	{ .name = "jnp",   .ops  = &jump_ops, },
375 	{ .name = "jns",   .ops  = &jump_ops, },
376 	{ .name = "jnz",   .ops  = &jump_ops, },
377 	{ .name = "jo",	   .ops  = &jump_ops, },
378 	{ .name = "jp",	   .ops  = &jump_ops, },
379 	{ .name = "jpe",   .ops  = &jump_ops, },
380 	{ .name = "jpo",   .ops  = &jump_ops, },
381 	{ .name = "jrcxz", .ops  = &jump_ops, },
382 	{ .name = "js",	   .ops  = &jump_ops, },
383 	{ .name = "jz",	   .ops  = &jump_ops, },
384 	{ .name = "lea",   .ops  = &mov_ops, },
385 	{ .name = "lock",  .ops  = &lock_ops, },
386 	{ .name = "mov",   .ops  = &mov_ops, },
387 	{ .name = "movb",  .ops  = &mov_ops, },
388 	{ .name = "movdqa",.ops  = &mov_ops, },
389 	{ .name = "movl",  .ops  = &mov_ops, },
390 	{ .name = "movq",  .ops  = &mov_ops, },
391 	{ .name = "movslq", .ops  = &mov_ops, },
392 	{ .name = "movzbl", .ops  = &mov_ops, },
393 	{ .name = "movzwl", .ops  = &mov_ops, },
394 	{ .name = "nop",   .ops  = &nop_ops, },
395 	{ .name = "nopl",  .ops  = &nop_ops, },
396 	{ .name = "nopw",  .ops  = &nop_ops, },
397 	{ .name = "or",    .ops  = &mov_ops, },
398 	{ .name = "orl",   .ops  = &mov_ops, },
399 	{ .name = "test",  .ops  = &mov_ops, },
400 	{ .name = "testb", .ops  = &mov_ops, },
401 	{ .name = "testl", .ops  = &mov_ops, },
402 	{ .name = "xadd",  .ops  = &mov_ops, },
403 	{ .name = "xbeginl", .ops  = &jump_ops, },
404 	{ .name = "xbeginq", .ops  = &jump_ops, },
405 };
406 
407 static int ins__cmp(const void *name, const void *insp)
408 {
409 	const struct ins *ins = insp;
410 
411 	return strcmp(name, ins->name);
412 }
413 
414 static struct ins *ins__find(const char *name)
415 {
416 	const int nmemb = ARRAY_SIZE(instructions);
417 
418 	return bsearch(name, instructions, nmemb, sizeof(struct ins), ins__cmp);
419 }
420 
421 int symbol__annotate_init(struct map *map __maybe_unused, struct symbol *sym)
422 {
423 	struct annotation *notes = symbol__annotation(sym);
424 	pthread_mutex_init(&notes->lock, NULL);
425 	return 0;
426 }
427 
428 int symbol__alloc_hist(struct symbol *sym)
429 {
430 	struct annotation *notes = symbol__annotation(sym);
431 	const size_t size = symbol__size(sym);
432 	size_t sizeof_sym_hist;
433 
434 	/* Check for overflow when calculating sizeof_sym_hist */
435 	if (size > (SIZE_MAX - sizeof(struct sym_hist)) / sizeof(u64))
436 		return -1;
437 
438 	sizeof_sym_hist = (sizeof(struct sym_hist) + size * sizeof(u64));
439 
440 	/* Check for overflow in zalloc argument */
441 	if (sizeof_sym_hist > (SIZE_MAX - sizeof(*notes->src))
442 				/ symbol_conf.nr_events)
443 		return -1;
444 
445 	notes->src = zalloc(sizeof(*notes->src) + symbol_conf.nr_events * sizeof_sym_hist);
446 	if (notes->src == NULL)
447 		return -1;
448 	notes->src->sizeof_sym_hist = sizeof_sym_hist;
449 	notes->src->nr_histograms   = symbol_conf.nr_events;
450 	INIT_LIST_HEAD(&notes->src->source);
451 	return 0;
452 }
453 
454 void symbol__annotate_zero_histograms(struct symbol *sym)
455 {
456 	struct annotation *notes = symbol__annotation(sym);
457 
458 	pthread_mutex_lock(&notes->lock);
459 	if (notes->src != NULL)
460 		memset(notes->src->histograms, 0,
461 		       notes->src->nr_histograms * notes->src->sizeof_sym_hist);
462 	pthread_mutex_unlock(&notes->lock);
463 }
464 
465 static int __symbol__inc_addr_samples(struct symbol *sym, struct map *map,
466 				      struct annotation *notes, int evidx, u64 addr)
467 {
468 	unsigned offset;
469 	struct sym_hist *h;
470 
471 	pr_debug3("%s: addr=%#" PRIx64 "\n", __func__, map->unmap_ip(map, addr));
472 
473 	if (addr < sym->start || addr > sym->end)
474 		return -ERANGE;
475 
476 	offset = addr - sym->start;
477 	h = annotation__histogram(notes, evidx);
478 	h->sum++;
479 	h->addr[offset]++;
480 
481 	pr_debug3("%#" PRIx64 " %s: period++ [addr: %#" PRIx64 ", %#" PRIx64
482 		  ", evidx=%d] => %" PRIu64 "\n", sym->start, sym->name,
483 		  addr, addr - sym->start, evidx, h->addr[offset]);
484 	return 0;
485 }
486 
487 static int symbol__inc_addr_samples(struct symbol *sym, struct map *map,
488 				    int evidx, u64 addr)
489 {
490 	struct annotation *notes;
491 
492 	if (sym == NULL || use_browser != 1 || !sort__has_sym)
493 		return 0;
494 
495 	notes = symbol__annotation(sym);
496 	if (notes->src == NULL) {
497 		if (symbol__alloc_hist(sym) < 0)
498 			return -ENOMEM;
499 	}
500 
501 	return __symbol__inc_addr_samples(sym, map, notes, evidx, addr);
502 }
503 
504 int addr_map_symbol__inc_samples(struct addr_map_symbol *ams, int evidx)
505 {
506 	return symbol__inc_addr_samples(ams->sym, ams->map, evidx, ams->al_addr);
507 }
508 
509 int hist_entry__inc_addr_samples(struct hist_entry *he, int evidx, u64 ip)
510 {
511 	return symbol__inc_addr_samples(he->ms.sym, he->ms.map, evidx, ip);
512 }
513 
514 static void disasm_line__init_ins(struct disasm_line *dl)
515 {
516 	dl->ins = ins__find(dl->name);
517 
518 	if (dl->ins == NULL)
519 		return;
520 
521 	if (!dl->ins->ops)
522 		return;
523 
524 	if (dl->ins->ops->parse)
525 		dl->ins->ops->parse(&dl->ops);
526 }
527 
528 static int disasm_line__parse(char *line, char **namep, char **rawp)
529 {
530 	char *name = line, tmp;
531 
532 	while (isspace(name[0]))
533 		++name;
534 
535 	if (name[0] == '\0')
536 		return -1;
537 
538 	*rawp = name + 1;
539 
540 	while ((*rawp)[0] != '\0' && !isspace((*rawp)[0]))
541 		++*rawp;
542 
543 	tmp = (*rawp)[0];
544 	(*rawp)[0] = '\0';
545 	*namep = strdup(name);
546 
547 	if (*namep == NULL)
548 		goto out_free_name;
549 
550 	(*rawp)[0] = tmp;
551 
552 	if ((*rawp)[0] != '\0') {
553 		(*rawp)++;
554 		while (isspace((*rawp)[0]))
555 			++(*rawp);
556 	}
557 
558 	return 0;
559 
560 out_free_name:
561 	zfree(namep);
562 	return -1;
563 }
564 
565 static struct disasm_line *disasm_line__new(s64 offset, char *line, size_t privsize)
566 {
567 	struct disasm_line *dl = zalloc(sizeof(*dl) + privsize);
568 
569 	if (dl != NULL) {
570 		dl->offset = offset;
571 		dl->line = strdup(line);
572 		if (dl->line == NULL)
573 			goto out_delete;
574 
575 		if (offset != -1) {
576 			if (disasm_line__parse(dl->line, &dl->name, &dl->ops.raw) < 0)
577 				goto out_free_line;
578 
579 			disasm_line__init_ins(dl);
580 		}
581 	}
582 
583 	return dl;
584 
585 out_free_line:
586 	zfree(&dl->line);
587 out_delete:
588 	free(dl);
589 	return NULL;
590 }
591 
592 void disasm_line__free(struct disasm_line *dl)
593 {
594 	zfree(&dl->line);
595 	zfree(&dl->name);
596 	if (dl->ins && dl->ins->ops->free)
597 		dl->ins->ops->free(&dl->ops);
598 	else
599 		ins__delete(&dl->ops);
600 	free(dl);
601 }
602 
603 int disasm_line__scnprintf(struct disasm_line *dl, char *bf, size_t size, bool raw)
604 {
605 	if (raw || !dl->ins)
606 		return scnprintf(bf, size, "%-6.6s %s", dl->name, dl->ops.raw);
607 
608 	return ins__scnprintf(dl->ins, bf, size, &dl->ops);
609 }
610 
611 static void disasm__add(struct list_head *head, struct disasm_line *line)
612 {
613 	list_add_tail(&line->node, head);
614 }
615 
616 struct disasm_line *disasm__get_next_ip_line(struct list_head *head, struct disasm_line *pos)
617 {
618 	list_for_each_entry_continue(pos, head, node)
619 		if (pos->offset >= 0)
620 			return pos;
621 
622 	return NULL;
623 }
624 
625 double disasm__calc_percent(struct annotation *notes, int evidx, s64 offset,
626 			    s64 end, const char **path)
627 {
628 	struct source_line *src_line = notes->src->lines;
629 	double percent = 0.0;
630 
631 	if (src_line) {
632 		size_t sizeof_src_line = sizeof(*src_line) +
633 				sizeof(src_line->p) * (src_line->nr_pcnt - 1);
634 
635 		while (offset < end) {
636 			src_line = (void *)notes->src->lines +
637 					(sizeof_src_line * offset);
638 
639 			if (*path == NULL)
640 				*path = src_line->path;
641 
642 			percent += src_line->p[evidx].percent;
643 			offset++;
644 		}
645 	} else {
646 		struct sym_hist *h = annotation__histogram(notes, evidx);
647 		unsigned int hits = 0;
648 
649 		while (offset < end)
650 			hits += h->addr[offset++];
651 
652 		if (h->sum)
653 			percent = 100.0 * hits / h->sum;
654 	}
655 
656 	return percent;
657 }
658 
659 static int disasm_line__print(struct disasm_line *dl, struct symbol *sym, u64 start,
660 		      struct perf_evsel *evsel, u64 len, int min_pcnt, int printed,
661 		      int max_lines, struct disasm_line *queue)
662 {
663 	static const char *prev_line;
664 	static const char *prev_color;
665 
666 	if (dl->offset != -1) {
667 		const char *path = NULL;
668 		double percent, max_percent = 0.0;
669 		double *ppercents = &percent;
670 		int i, nr_percent = 1;
671 		const char *color;
672 		struct annotation *notes = symbol__annotation(sym);
673 		s64 offset = dl->offset;
674 		const u64 addr = start + offset;
675 		struct disasm_line *next;
676 
677 		next = disasm__get_next_ip_line(&notes->src->source, dl);
678 
679 		if (perf_evsel__is_group_event(evsel)) {
680 			nr_percent = evsel->nr_members;
681 			ppercents = calloc(nr_percent, sizeof(double));
682 			if (ppercents == NULL)
683 				return -1;
684 		}
685 
686 		for (i = 0; i < nr_percent; i++) {
687 			percent = disasm__calc_percent(notes,
688 					notes->src->lines ? i : evsel->idx + i,
689 					offset,
690 					next ? next->offset : (s64) len,
691 					&path);
692 
693 			ppercents[i] = percent;
694 			if (percent > max_percent)
695 				max_percent = percent;
696 		}
697 
698 		if (max_percent < min_pcnt)
699 			return -1;
700 
701 		if (max_lines && printed >= max_lines)
702 			return 1;
703 
704 		if (queue != NULL) {
705 			list_for_each_entry_from(queue, &notes->src->source, node) {
706 				if (queue == dl)
707 					break;
708 				disasm_line__print(queue, sym, start, evsel, len,
709 						    0, 0, 1, NULL);
710 			}
711 		}
712 
713 		color = get_percent_color(max_percent);
714 
715 		/*
716 		 * Also color the filename and line if needed, with
717 		 * the same color than the percentage. Don't print it
718 		 * twice for close colored addr with the same filename:line
719 		 */
720 		if (path) {
721 			if (!prev_line || strcmp(prev_line, path)
722 				       || color != prev_color) {
723 				color_fprintf(stdout, color, " %s", path);
724 				prev_line = path;
725 				prev_color = color;
726 			}
727 		}
728 
729 		for (i = 0; i < nr_percent; i++) {
730 			percent = ppercents[i];
731 			color = get_percent_color(percent);
732 			color_fprintf(stdout, color, " %7.2f", percent);
733 		}
734 
735 		printf(" :	");
736 		color_fprintf(stdout, PERF_COLOR_MAGENTA, "  %" PRIx64 ":", addr);
737 		color_fprintf(stdout, PERF_COLOR_BLUE, "%s\n", dl->line);
738 
739 		if (ppercents != &percent)
740 			free(ppercents);
741 
742 	} else if (max_lines && printed >= max_lines)
743 		return 1;
744 	else {
745 		int width = 8;
746 
747 		if (queue)
748 			return -1;
749 
750 		if (perf_evsel__is_group_event(evsel))
751 			width *= evsel->nr_members;
752 
753 		if (!*dl->line)
754 			printf(" %*s:\n", width, " ");
755 		else
756 			printf(" %*s:	%s\n", width, " ", dl->line);
757 	}
758 
759 	return 0;
760 }
761 
762 /*
763  * symbol__parse_objdump_line() parses objdump output (with -d --no-show-raw)
764  * which looks like following
765  *
766  *  0000000000415500 <_init>:
767  *    415500:       sub    $0x8,%rsp
768  *    415504:       mov    0x2f5ad5(%rip),%rax        # 70afe0 <_DYNAMIC+0x2f8>
769  *    41550b:       test   %rax,%rax
770  *    41550e:       je     415515 <_init+0x15>
771  *    415510:       callq  416e70 <__gmon_start__@plt>
772  *    415515:       add    $0x8,%rsp
773  *    415519:       retq
774  *
775  * it will be parsed and saved into struct disasm_line as
776  *  <offset>       <name>  <ops.raw>
777  *
778  * The offset will be a relative offset from the start of the symbol and -1
779  * means that it's not a disassembly line so should be treated differently.
780  * The ops.raw part will be parsed further according to type of the instruction.
781  */
782 static int symbol__parse_objdump_line(struct symbol *sym, struct map *map,
783 				      FILE *file, size_t privsize)
784 {
785 	struct annotation *notes = symbol__annotation(sym);
786 	struct disasm_line *dl;
787 	char *line = NULL, *parsed_line, *tmp, *tmp2, *c;
788 	size_t line_len;
789 	s64 line_ip, offset = -1;
790 
791 	if (getline(&line, &line_len, file) < 0)
792 		return -1;
793 
794 	if (!line)
795 		return -1;
796 
797 	while (line_len != 0 && isspace(line[line_len - 1]))
798 		line[--line_len] = '\0';
799 
800 	c = strchr(line, '\n');
801 	if (c)
802 		*c = 0;
803 
804 	line_ip = -1;
805 	parsed_line = line;
806 
807 	/*
808 	 * Strip leading spaces:
809 	 */
810 	tmp = line;
811 	while (*tmp) {
812 		if (*tmp != ' ')
813 			break;
814 		tmp++;
815 	}
816 
817 	if (*tmp) {
818 		/*
819 		 * Parse hexa addresses followed by ':'
820 		 */
821 		line_ip = strtoull(tmp, &tmp2, 16);
822 		if (*tmp2 != ':' || tmp == tmp2 || tmp2[1] == '\0')
823 			line_ip = -1;
824 	}
825 
826 	if (line_ip != -1) {
827 		u64 start = map__rip_2objdump(map, sym->start),
828 		    end = map__rip_2objdump(map, sym->end);
829 
830 		offset = line_ip - start;
831 		if ((u64)line_ip < start || (u64)line_ip > end)
832 			offset = -1;
833 		else
834 			parsed_line = tmp2 + 1;
835 	}
836 
837 	dl = disasm_line__new(offset, parsed_line, privsize);
838 	free(line);
839 
840 	if (dl == NULL)
841 		return -1;
842 
843 	if (dl->ops.target.offset == UINT64_MAX)
844 		dl->ops.target.offset = dl->ops.target.addr -
845 					map__rip_2objdump(map, sym->start);
846 
847 	/* kcore has no symbols, so add the call target name */
848 	if (dl->ins && ins__is_call(dl->ins) && !dl->ops.target.name) {
849 		struct addr_map_symbol target = {
850 			.map = map,
851 			.addr = dl->ops.target.addr,
852 		};
853 
854 		if (!map_groups__find_ams(&target, NULL) &&
855 		    target.sym->start == target.al_addr)
856 			dl->ops.target.name = strdup(target.sym->name);
857 	}
858 
859 	disasm__add(&notes->src->source, dl);
860 
861 	return 0;
862 }
863 
864 static void delete_last_nop(struct symbol *sym)
865 {
866 	struct annotation *notes = symbol__annotation(sym);
867 	struct list_head *list = &notes->src->source;
868 	struct disasm_line *dl;
869 
870 	while (!list_empty(list)) {
871 		dl = list_entry(list->prev, struct disasm_line, node);
872 
873 		if (dl->ins && dl->ins->ops) {
874 			if (dl->ins->ops != &nop_ops)
875 				return;
876 		} else {
877 			if (!strstr(dl->line, " nop ") &&
878 			    !strstr(dl->line, " nopl ") &&
879 			    !strstr(dl->line, " nopw "))
880 				return;
881 		}
882 
883 		list_del(&dl->node);
884 		disasm_line__free(dl);
885 	}
886 }
887 
888 int symbol__annotate(struct symbol *sym, struct map *map, size_t privsize)
889 {
890 	struct dso *dso = map->dso;
891 	char *filename = dso__build_id_filename(dso, NULL, 0);
892 	bool free_filename = true;
893 	char command[PATH_MAX * 2];
894 	FILE *file;
895 	int err = 0;
896 	char symfs_filename[PATH_MAX];
897 	struct kcore_extract kce;
898 	bool delete_extract = false;
899 
900 	if (filename) {
901 		snprintf(symfs_filename, sizeof(symfs_filename), "%s%s",
902 			 symbol_conf.symfs, filename);
903 	}
904 
905 	if (filename == NULL) {
906 		if (dso->has_build_id) {
907 			pr_err("Can't annotate %s: not enough memory\n",
908 			       sym->name);
909 			return -ENOMEM;
910 		}
911 		goto fallback;
912 	} else if (readlink(symfs_filename, command, sizeof(command)) < 0 ||
913 		   strstr(command, "[kernel.kallsyms]") ||
914 		   access(symfs_filename, R_OK)) {
915 		free(filename);
916 fallback:
917 		/*
918 		 * If we don't have build-ids or the build-id file isn't in the
919 		 * cache, or is just a kallsyms file, well, lets hope that this
920 		 * DSO is the same as when 'perf record' ran.
921 		 */
922 		filename = (char *)dso->long_name;
923 		snprintf(symfs_filename, sizeof(symfs_filename), "%s%s",
924 			 symbol_conf.symfs, filename);
925 		free_filename = false;
926 	}
927 
928 	if (dso->symtab_type == DSO_BINARY_TYPE__KALLSYMS &&
929 	    !dso__is_kcore(dso)) {
930 		char bf[BUILD_ID_SIZE * 2 + 16] = " with build id ";
931 		char *build_id_msg = NULL;
932 
933 		if (dso->annotate_warned)
934 			goto out_free_filename;
935 
936 		if (dso->has_build_id) {
937 			build_id__sprintf(dso->build_id,
938 					  sizeof(dso->build_id), bf + 15);
939 			build_id_msg = bf;
940 		}
941 		err = -ENOENT;
942 		dso->annotate_warned = 1;
943 		pr_err("Can't annotate %s:\n\n"
944 		       "No vmlinux file%s\nwas found in the path.\n\n"
945 		       "Please use:\n\n"
946 		       "  perf buildid-cache -vu vmlinux\n\n"
947 		       "or:\n\n"
948 		       "  --vmlinux vmlinux\n",
949 		       sym->name, build_id_msg ?: "");
950 		goto out_free_filename;
951 	}
952 
953 	pr_debug("%s: filename=%s, sym=%s, start=%#" PRIx64 ", end=%#" PRIx64 "\n", __func__,
954 		 filename, sym->name, map->unmap_ip(map, sym->start),
955 		 map->unmap_ip(map, sym->end));
956 
957 	pr_debug("annotating [%p] %30s : [%p] %30s\n",
958 		 dso, dso->long_name, sym, sym->name);
959 
960 	if (dso__is_kcore(dso)) {
961 		kce.kcore_filename = symfs_filename;
962 		kce.addr = map__rip_2objdump(map, sym->start);
963 		kce.offs = sym->start;
964 		kce.len = sym->end + 1 - sym->start;
965 		if (!kcore_extract__create(&kce)) {
966 			delete_extract = true;
967 			strlcpy(symfs_filename, kce.extract_filename,
968 				sizeof(symfs_filename));
969 			if (free_filename) {
970 				free(filename);
971 				free_filename = false;
972 			}
973 			filename = symfs_filename;
974 		}
975 	}
976 
977 	snprintf(command, sizeof(command),
978 		 "%s %s%s --start-address=0x%016" PRIx64
979 		 " --stop-address=0x%016" PRIx64
980 		 " -d %s %s -C %s 2>/dev/null|grep -v %s|expand",
981 		 objdump_path ? objdump_path : "objdump",
982 		 disassembler_style ? "-M " : "",
983 		 disassembler_style ? disassembler_style : "",
984 		 map__rip_2objdump(map, sym->start),
985 		 map__rip_2objdump(map, sym->end+1),
986 		 symbol_conf.annotate_asm_raw ? "" : "--no-show-raw",
987 		 symbol_conf.annotate_src ? "-S" : "",
988 		 symfs_filename, filename);
989 
990 	pr_debug("Executing: %s\n", command);
991 
992 	file = popen(command, "r");
993 	if (!file)
994 		goto out_free_filename;
995 
996 	while (!feof(file))
997 		if (symbol__parse_objdump_line(sym, map, file, privsize) < 0)
998 			break;
999 
1000 	/*
1001 	 * kallsyms does not have symbol sizes so there may a nop at the end.
1002 	 * Remove it.
1003 	 */
1004 	if (dso__is_kcore(dso))
1005 		delete_last_nop(sym);
1006 
1007 	pclose(file);
1008 out_free_filename:
1009 	if (delete_extract)
1010 		kcore_extract__delete(&kce);
1011 	if (free_filename)
1012 		free(filename);
1013 	return err;
1014 }
1015 
1016 static void insert_source_line(struct rb_root *root, struct source_line *src_line)
1017 {
1018 	struct source_line *iter;
1019 	struct rb_node **p = &root->rb_node;
1020 	struct rb_node *parent = NULL;
1021 	int i, ret;
1022 
1023 	while (*p != NULL) {
1024 		parent = *p;
1025 		iter = rb_entry(parent, struct source_line, node);
1026 
1027 		ret = strcmp(iter->path, src_line->path);
1028 		if (ret == 0) {
1029 			for (i = 0; i < src_line->nr_pcnt; i++)
1030 				iter->p[i].percent_sum += src_line->p[i].percent;
1031 			return;
1032 		}
1033 
1034 		if (ret < 0)
1035 			p = &(*p)->rb_left;
1036 		else
1037 			p = &(*p)->rb_right;
1038 	}
1039 
1040 	for (i = 0; i < src_line->nr_pcnt; i++)
1041 		src_line->p[i].percent_sum = src_line->p[i].percent;
1042 
1043 	rb_link_node(&src_line->node, parent, p);
1044 	rb_insert_color(&src_line->node, root);
1045 }
1046 
1047 static int cmp_source_line(struct source_line *a, struct source_line *b)
1048 {
1049 	int i;
1050 
1051 	for (i = 0; i < a->nr_pcnt; i++) {
1052 		if (a->p[i].percent_sum == b->p[i].percent_sum)
1053 			continue;
1054 		return a->p[i].percent_sum > b->p[i].percent_sum;
1055 	}
1056 
1057 	return 0;
1058 }
1059 
1060 static void __resort_source_line(struct rb_root *root, struct source_line *src_line)
1061 {
1062 	struct source_line *iter;
1063 	struct rb_node **p = &root->rb_node;
1064 	struct rb_node *parent = NULL;
1065 
1066 	while (*p != NULL) {
1067 		parent = *p;
1068 		iter = rb_entry(parent, struct source_line, node);
1069 
1070 		if (cmp_source_line(src_line, iter))
1071 			p = &(*p)->rb_left;
1072 		else
1073 			p = &(*p)->rb_right;
1074 	}
1075 
1076 	rb_link_node(&src_line->node, parent, p);
1077 	rb_insert_color(&src_line->node, root);
1078 }
1079 
1080 static void resort_source_line(struct rb_root *dest_root, struct rb_root *src_root)
1081 {
1082 	struct source_line *src_line;
1083 	struct rb_node *node;
1084 
1085 	node = rb_first(src_root);
1086 	while (node) {
1087 		struct rb_node *next;
1088 
1089 		src_line = rb_entry(node, struct source_line, node);
1090 		next = rb_next(node);
1091 		rb_erase(node, src_root);
1092 
1093 		__resort_source_line(dest_root, src_line);
1094 		node = next;
1095 	}
1096 }
1097 
1098 static void symbol__free_source_line(struct symbol *sym, int len)
1099 {
1100 	struct annotation *notes = symbol__annotation(sym);
1101 	struct source_line *src_line = notes->src->lines;
1102 	size_t sizeof_src_line;
1103 	int i;
1104 
1105 	sizeof_src_line = sizeof(*src_line) +
1106 			  (sizeof(src_line->p) * (src_line->nr_pcnt - 1));
1107 
1108 	for (i = 0; i < len; i++) {
1109 		free_srcline(src_line->path);
1110 		src_line = (void *)src_line + sizeof_src_line;
1111 	}
1112 
1113 	zfree(&notes->src->lines);
1114 }
1115 
1116 /* Get the filename:line for the colored entries */
1117 static int symbol__get_source_line(struct symbol *sym, struct map *map,
1118 				   struct perf_evsel *evsel,
1119 				   struct rb_root *root, int len)
1120 {
1121 	u64 start;
1122 	int i, k;
1123 	int evidx = evsel->idx;
1124 	struct source_line *src_line;
1125 	struct annotation *notes = symbol__annotation(sym);
1126 	struct sym_hist *h = annotation__histogram(notes, evidx);
1127 	struct rb_root tmp_root = RB_ROOT;
1128 	int nr_pcnt = 1;
1129 	u64 h_sum = h->sum;
1130 	size_t sizeof_src_line = sizeof(struct source_line);
1131 
1132 	if (perf_evsel__is_group_event(evsel)) {
1133 		for (i = 1; i < evsel->nr_members; i++) {
1134 			h = annotation__histogram(notes, evidx + i);
1135 			h_sum += h->sum;
1136 		}
1137 		nr_pcnt = evsel->nr_members;
1138 		sizeof_src_line += (nr_pcnt - 1) * sizeof(src_line->p);
1139 	}
1140 
1141 	if (!h_sum)
1142 		return 0;
1143 
1144 	src_line = notes->src->lines = calloc(len, sizeof_src_line);
1145 	if (!notes->src->lines)
1146 		return -1;
1147 
1148 	start = map__rip_2objdump(map, sym->start);
1149 
1150 	for (i = 0; i < len; i++) {
1151 		u64 offset;
1152 		double percent_max = 0.0;
1153 
1154 		src_line->nr_pcnt = nr_pcnt;
1155 
1156 		for (k = 0; k < nr_pcnt; k++) {
1157 			h = annotation__histogram(notes, evidx + k);
1158 			src_line->p[k].percent = 100.0 * h->addr[i] / h->sum;
1159 
1160 			if (src_line->p[k].percent > percent_max)
1161 				percent_max = src_line->p[k].percent;
1162 		}
1163 
1164 		if (percent_max <= 0.5)
1165 			goto next;
1166 
1167 		offset = start + i;
1168 		src_line->path = get_srcline(map->dso, offset);
1169 		insert_source_line(&tmp_root, src_line);
1170 
1171 	next:
1172 		src_line = (void *)src_line + sizeof_src_line;
1173 	}
1174 
1175 	resort_source_line(root, &tmp_root);
1176 	return 0;
1177 }
1178 
1179 static void print_summary(struct rb_root *root, const char *filename)
1180 {
1181 	struct source_line *src_line;
1182 	struct rb_node *node;
1183 
1184 	printf("\nSorted summary for file %s\n", filename);
1185 	printf("----------------------------------------------\n\n");
1186 
1187 	if (RB_EMPTY_ROOT(root)) {
1188 		printf(" Nothing higher than %1.1f%%\n", MIN_GREEN);
1189 		return;
1190 	}
1191 
1192 	node = rb_first(root);
1193 	while (node) {
1194 		double percent, percent_max = 0.0;
1195 		const char *color;
1196 		char *path;
1197 		int i;
1198 
1199 		src_line = rb_entry(node, struct source_line, node);
1200 		for (i = 0; i < src_line->nr_pcnt; i++) {
1201 			percent = src_line->p[i].percent_sum;
1202 			color = get_percent_color(percent);
1203 			color_fprintf(stdout, color, " %7.2f", percent);
1204 
1205 			if (percent > percent_max)
1206 				percent_max = percent;
1207 		}
1208 
1209 		path = src_line->path;
1210 		color = get_percent_color(percent_max);
1211 		color_fprintf(stdout, color, " %s\n", path);
1212 
1213 		node = rb_next(node);
1214 	}
1215 }
1216 
1217 static void symbol__annotate_hits(struct symbol *sym, struct perf_evsel *evsel)
1218 {
1219 	struct annotation *notes = symbol__annotation(sym);
1220 	struct sym_hist *h = annotation__histogram(notes, evsel->idx);
1221 	u64 len = symbol__size(sym), offset;
1222 
1223 	for (offset = 0; offset < len; ++offset)
1224 		if (h->addr[offset] != 0)
1225 			printf("%*" PRIx64 ": %" PRIu64 "\n", BITS_PER_LONG / 2,
1226 			       sym->start + offset, h->addr[offset]);
1227 	printf("%*s: %" PRIu64 "\n", BITS_PER_LONG / 2, "h->sum", h->sum);
1228 }
1229 
1230 int symbol__annotate_printf(struct symbol *sym, struct map *map,
1231 			    struct perf_evsel *evsel, bool full_paths,
1232 			    int min_pcnt, int max_lines, int context)
1233 {
1234 	struct dso *dso = map->dso;
1235 	char *filename;
1236 	const char *d_filename;
1237 	struct annotation *notes = symbol__annotation(sym);
1238 	struct disasm_line *pos, *queue = NULL;
1239 	u64 start = map__rip_2objdump(map, sym->start);
1240 	int printed = 2, queue_len = 0;
1241 	int more = 0;
1242 	u64 len;
1243 	int width = 8;
1244 	int namelen;
1245 
1246 	filename = strdup(dso->long_name);
1247 	if (!filename)
1248 		return -ENOMEM;
1249 
1250 	if (full_paths)
1251 		d_filename = filename;
1252 	else
1253 		d_filename = basename(filename);
1254 
1255 	len = symbol__size(sym);
1256 	namelen = strlen(d_filename);
1257 
1258 	if (perf_evsel__is_group_event(evsel))
1259 		width *= evsel->nr_members;
1260 
1261 	printf(" %-*.*s|	Source code & Disassembly of %s\n",
1262 	       width, width, "Percent", d_filename);
1263 	printf("-%-*.*s-------------------------------------\n",
1264 	       width+namelen, width+namelen, graph_dotted_line);
1265 
1266 	if (verbose)
1267 		symbol__annotate_hits(sym, evsel);
1268 
1269 	list_for_each_entry(pos, &notes->src->source, node) {
1270 		if (context && queue == NULL) {
1271 			queue = pos;
1272 			queue_len = 0;
1273 		}
1274 
1275 		switch (disasm_line__print(pos, sym, start, evsel, len,
1276 					    min_pcnt, printed, max_lines,
1277 					    queue)) {
1278 		case 0:
1279 			++printed;
1280 			if (context) {
1281 				printed += queue_len;
1282 				queue = NULL;
1283 				queue_len = 0;
1284 			}
1285 			break;
1286 		case 1:
1287 			/* filtered by max_lines */
1288 			++more;
1289 			break;
1290 		case -1:
1291 		default:
1292 			/*
1293 			 * Filtered by min_pcnt or non IP lines when
1294 			 * context != 0
1295 			 */
1296 			if (!context)
1297 				break;
1298 			if (queue_len == context)
1299 				queue = list_entry(queue->node.next, typeof(*queue), node);
1300 			else
1301 				++queue_len;
1302 			break;
1303 		}
1304 	}
1305 
1306 	free(filename);
1307 
1308 	return more;
1309 }
1310 
1311 void symbol__annotate_zero_histogram(struct symbol *sym, int evidx)
1312 {
1313 	struct annotation *notes = symbol__annotation(sym);
1314 	struct sym_hist *h = annotation__histogram(notes, evidx);
1315 
1316 	memset(h, 0, notes->src->sizeof_sym_hist);
1317 }
1318 
1319 void symbol__annotate_decay_histogram(struct symbol *sym, int evidx)
1320 {
1321 	struct annotation *notes = symbol__annotation(sym);
1322 	struct sym_hist *h = annotation__histogram(notes, evidx);
1323 	int len = symbol__size(sym), offset;
1324 
1325 	h->sum = 0;
1326 	for (offset = 0; offset < len; ++offset) {
1327 		h->addr[offset] = h->addr[offset] * 7 / 8;
1328 		h->sum += h->addr[offset];
1329 	}
1330 }
1331 
1332 void disasm__purge(struct list_head *head)
1333 {
1334 	struct disasm_line *pos, *n;
1335 
1336 	list_for_each_entry_safe(pos, n, head, node) {
1337 		list_del(&pos->node);
1338 		disasm_line__free(pos);
1339 	}
1340 }
1341 
1342 static size_t disasm_line__fprintf(struct disasm_line *dl, FILE *fp)
1343 {
1344 	size_t printed;
1345 
1346 	if (dl->offset == -1)
1347 		return fprintf(fp, "%s\n", dl->line);
1348 
1349 	printed = fprintf(fp, "%#" PRIx64 " %s", dl->offset, dl->name);
1350 
1351 	if (dl->ops.raw[0] != '\0') {
1352 		printed += fprintf(fp, "%.*s %s\n", 6 - (int)printed, " ",
1353 				   dl->ops.raw);
1354 	}
1355 
1356 	return printed + fprintf(fp, "\n");
1357 }
1358 
1359 size_t disasm__fprintf(struct list_head *head, FILE *fp)
1360 {
1361 	struct disasm_line *pos;
1362 	size_t printed = 0;
1363 
1364 	list_for_each_entry(pos, head, node)
1365 		printed += disasm_line__fprintf(pos, fp);
1366 
1367 	return printed;
1368 }
1369 
1370 int symbol__tty_annotate(struct symbol *sym, struct map *map,
1371 			 struct perf_evsel *evsel, bool print_lines,
1372 			 bool full_paths, int min_pcnt, int max_lines)
1373 {
1374 	struct dso *dso = map->dso;
1375 	struct rb_root source_line = RB_ROOT;
1376 	u64 len;
1377 
1378 	if (symbol__annotate(sym, map, 0) < 0)
1379 		return -1;
1380 
1381 	len = symbol__size(sym);
1382 
1383 	if (print_lines) {
1384 		symbol__get_source_line(sym, map, evsel, &source_line, len);
1385 		print_summary(&source_line, dso->long_name);
1386 	}
1387 
1388 	symbol__annotate_printf(sym, map, evsel, full_paths,
1389 				min_pcnt, max_lines, 0);
1390 	if (print_lines)
1391 		symbol__free_source_line(sym, len);
1392 
1393 	disasm__purge(&symbol__annotation(sym)->src->source);
1394 
1395 	return 0;
1396 }
1397 
1398 int hist_entry__annotate(struct hist_entry *he, size_t privsize)
1399 {
1400 	return symbol__annotate(he->ms.sym, he->ms.map, privsize);
1401 }
1402