File Index
Files and directories
Sign in
FILE

annotate.c

File preview with syntax highlighting.

linux-6.19.14/tools/perf/util/annotate.c C
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
   4 *
   5 * Parts came from builtin-annotate.c, see those files for further
   6 * copyright notes.
   7 */
   8
   9#include <errno.h>
  10#include <inttypes.h>
  11#include <libgen.h>
  12#include <stdlib.h>
  13#include "util.h" // hex_width()
  14#include "ui/ui.h"
  15#include "sort.h"
  16#include "build-id.h"
  17#include "color.h"
  18#include "config.h"
  19#include "disasm.h"
  20#include "dso.h"
  21#include "env.h"
  22#include "map.h"
  23#include "maps.h"
  24#include "symbol.h"
  25#include "srcline.h"
  26#include "units.h"
  27#include "debug.h"
  28#include "debuginfo.h"
  29#include "annotate.h"
  30#include "annotate-data.h"
  31#include "evsel.h"
  32#include "evlist.h"
  33#include "bpf-event.h"
  34#include "bpf-utils.h"
  35#include "block-range.h"
  36#include "string2.h"
  37#include "dwarf-regs.h"
  38#include "util/event.h"
  39#include "util/sharded_mutex.h"
  40#include "arch/common.h"
  41#include "namespaces.h"
  42#include "thread.h"
  43#include "hashmap.h"
  44#include "strbuf.h"
  45#include <regex.h>
  46#include <linux/bitops.h>
  47#include <linux/err.h>
  48#include <linux/kernel.h>
  49#include <linux/string.h>
  50#include <linux/zalloc.h>
  51#include <subcmd/parse-options.h>
  52#include <subcmd/run-command.h>
  53#include <math.h>
  54
  55/* FIXME: For the HE_COLORSET */
  56#include "ui/browser.h"
  57
  58/*
  59 * FIXME: Using the same values as slang.h,
  60 * but that header may not be available everywhere
  61 */
  62#define LARROW_CHAR	((unsigned char)',')
  63#define RARROW_CHAR	((unsigned char)'+')
  64#define DARROW_CHAR	((unsigned char)'.')
  65#define UARROW_CHAR	((unsigned char)'-')
  66
  67#include <linux/ctype.h>
  68
  69/* global annotation options */
  70struct annotation_options annotate_opts;
  71
  72/* Data type collection debug statistics */
  73struct annotated_data_stat ann_data_stat;
  74LIST_HEAD(ann_insn_stat);
  75
  76/* Pseudo data types */
  77struct annotated_data_type stackop_type = {
  78	.self = {
  79		.type_name = (char *)"(stack operation)",
  80		.children = LIST_HEAD_INIT(stackop_type.self.children),
  81	},
  82};
  83
  84struct annotated_data_type canary_type = {
  85	.self = {
  86		.type_name = (char *)"(stack canary)",
  87		.children = LIST_HEAD_INIT(canary_type.self.children),
  88	},
  89};
  90
  91#define NO_TYPE ((struct annotated_data_type *)-1UL)
  92
  93/* symbol histogram: key = offset << 16 | evsel->core.idx */
  94static size_t sym_hist_hash(long key, void *ctx __maybe_unused)
  95{
  96	return (key >> 16) + (key & 0xffff);
  97}
  98
  99static bool sym_hist_equal(long key1, long key2, void *ctx __maybe_unused)
 100{
 101	return key1 == key2;
 102}
 103
 104static struct annotated_source *annotated_source__new(void)
 105{
 106	struct annotated_source *src = zalloc(sizeof(*src));
 107
 108	if (src != NULL)
 109		INIT_LIST_HEAD(&src->source);
 110
 111	return src;
 112}
 113
 114static __maybe_unused void annotated_source__delete(struct annotated_source *src)
 115{
 116	struct hashmap_entry *cur;
 117	size_t bkt;
 118
 119	if (src == NULL)
 120		return;
 121
 122	if (src->samples) {
 123		hashmap__for_each_entry(src->samples, cur, bkt)
 124			zfree(&cur->pvalue);
 125		hashmap__free(src->samples);
 126	}
 127	zfree(&src->histograms);
 128	free(src);
 129}
 130
 131static int annotated_source__alloc_histograms(struct annotated_source *src,
 132					      int nr_hists)
 133{
 134	src->nr_histograms   = nr_hists;
 135	src->histograms	     = calloc(nr_hists, sizeof(*src->histograms));
 136
 137	if (src->histograms == NULL)
 138		return -1;
 139
 140	src->samples = hashmap__new(sym_hist_hash, sym_hist_equal, NULL);
 141	if (IS_ERR(src->samples)) {
 142		zfree(&src->histograms);
 143		src->samples = NULL;
 144	}
 145
 146	return src->histograms ? 0 : -1;
 147}
 148
 149void symbol__annotate_zero_histograms(struct symbol *sym)
 150{
 151	struct annotation *notes = symbol__annotation(sym);
 152
 153	annotation__lock(notes);
 154	if (notes->src != NULL) {
 155		memset(notes->src->histograms, 0,
 156		       notes->src->nr_histograms * sizeof(*notes->src->histograms));
 157		hashmap__clear(notes->src->samples);
 158	}
 159	if (notes->branch && notes->branch->cycles_hist) {
 160		memset(notes->branch->cycles_hist, 0,
 161		       symbol__size(sym) * sizeof(struct cyc_hist));
 162	}
 163	annotation__unlock(notes);
 164}
 165
 166static int __symbol__account_cycles(struct cyc_hist *ch,
 167				    u64 start,
 168				    unsigned offset, unsigned cycles,
 169				    unsigned have_start)
 170{
 171	/*
 172	 * For now we can only account one basic block per
 173	 * final jump. But multiple could be overlapping.
 174	 * Always account the longest one. So when
 175	 * a shorter one has been already seen throw it away.
 176	 *
 177	 * We separately always account the full cycles.
 178	 */
 179	ch[offset].num_aggr++;
 180	ch[offset].cycles_aggr += cycles;
 181
 182	if (cycles > ch[offset].cycles_max)
 183		ch[offset].cycles_max = cycles;
 184
 185	if (ch[offset].cycles_min) {
 186		if (cycles && cycles < ch[offset].cycles_min)
 187			ch[offset].cycles_min = cycles;
 188	} else
 189		ch[offset].cycles_min = cycles;
 190
 191	if (!have_start && ch[offset].have_start)
 192		return 0;
 193	if (ch[offset].num) {
 194		if (have_start && (!ch[offset].have_start ||
 195				   ch[offset].start > start)) {
 196			ch[offset].have_start = 0;
 197			ch[offset].cycles = 0;
 198			ch[offset].num = 0;
 199			if (ch[offset].reset < 0xffff)
 200				ch[offset].reset++;
 201		} else if (have_start &&
 202			   ch[offset].start < start)
 203			return 0;
 204	}
 205
 206	if (ch[offset].num < NUM_SPARKS)
 207		ch[offset].cycles_spark[ch[offset].num] = cycles;
 208
 209	ch[offset].have_start = have_start;
 210	ch[offset].start = start;
 211	ch[offset].cycles += cycles;
 212	ch[offset].num++;
 213	return 0;
 214}
 215
 216static int __symbol__inc_addr_samples(struct map_symbol *ms,
 217				      struct annotated_source *src, struct evsel *evsel, u64 addr,
 218				      struct perf_sample *sample)
 219{
 220	struct symbol *sym = ms->sym;
 221	long hash_key;
 222	u64 offset;
 223	struct sym_hist *h;
 224	struct sym_hist_entry *entry;
 225
 226	pr_debug3("%s: addr=%#" PRIx64 "\n", __func__, map__unmap_ip(ms->map, addr));
 227
 228	if ((addr < sym->start || addr >= sym->end) &&
 229	    (addr != sym->end || sym->start != sym->end)) {
 230		pr_debug("%s(%d): ERANGE! sym->name=%s, start=%#" PRIx64 ", addr=%#" PRIx64 ", end=%#" PRIx64 "\n",
 231		       __func__, __LINE__, sym->name, sym->start, addr, sym->end);
 232		return -ERANGE;
 233	}
 234
 235	offset = addr - sym->start;
 236	h = annotated_source__histogram(src, evsel);
 237	if (h == NULL) {
 238		pr_debug("%s(%d): ENOMEM! sym->name=%s, start=%#" PRIx64 ", addr=%#" PRIx64 ", end=%#" PRIx64 ", func: %d\n",
 239			 __func__, __LINE__, sym->name, sym->start, addr, sym->end, sym->type == STT_FUNC);
 240		return -ENOMEM;
 241	}
 242
 243	hash_key = offset << 16 | evsel->core.idx;
 244	if (!hashmap__find(src->samples, hash_key, &entry)) {
 245		entry = zalloc(sizeof(*entry));
 246		if (entry == NULL)
 247			return -ENOMEM;
 248
 249		if (hashmap__add(src->samples, hash_key, entry) < 0)
 250			return -ENOMEM;
 251	}
 252
 253	h->nr_samples++;
 254	h->period += sample->period;
 255	entry->nr_samples++;
 256	entry->period += sample->period;
 257
 258	pr_debug3("%#" PRIx64 " %s: period++ [addr: %#" PRIx64 ", %#" PRIx64
 259		  ", evidx=%d] => nr_samples: %" PRIu64 ", period: %" PRIu64 "\n",
 260		  sym->start, sym->name, addr, addr - sym->start, evsel->core.idx,
 261		  entry->nr_samples, entry->period);
 262	return 0;
 263}
 264
 265struct annotated_branch *annotation__get_branch(struct annotation *notes)
 266{
 267	if (notes == NULL)
 268		return NULL;
 269
 270	if (notes->branch == NULL)
 271		notes->branch = zalloc(sizeof(*notes->branch));
 272
 273	return notes->branch;
 274}
 275
 276static struct annotated_branch *symbol__find_branch_hist(struct symbol *sym,
 277							 unsigned int br_cntr_nr)
 278{
 279	struct annotation *notes = symbol__annotation(sym);
 280	struct annotated_branch *branch;
 281	const size_t size = symbol__size(sym);
 282
 283	branch = annotation__get_branch(notes);
 284	if (branch == NULL)
 285		return NULL;
 286
 287	if (branch->cycles_hist == NULL) {
 288		branch->cycles_hist = calloc(size, sizeof(struct cyc_hist));
 289		if (!branch->cycles_hist)
 290			return NULL;
 291	}
 292
 293	if (br_cntr_nr && branch->br_cntr == NULL) {
 294		branch->br_cntr = calloc(br_cntr_nr * size, sizeof(u64));
 295		if (!branch->br_cntr)
 296			return NULL;
 297	}
 298
 299	return branch;
 300}
 301
 302struct annotated_source *symbol__hists(struct symbol *sym, int nr_hists)
 303{
 304	struct annotation *notes = symbol__annotation(sym);
 305
 306	if (notes->src == NULL) {
 307		notes->src = annotated_source__new();
 308		if (notes->src == NULL)
 309			return NULL;
 310		goto alloc_histograms;
 311	}
 312
 313	if (notes->src->histograms == NULL) {
 314alloc_histograms:
 315		annotated_source__alloc_histograms(notes->src, nr_hists);
 316	}
 317
 318	return notes->src;
 319}
 320
 321static int symbol__inc_addr_samples(struct map_symbol *ms,
 322				    struct evsel *evsel, u64 addr,
 323				    struct perf_sample *sample)
 324{
 325	struct symbol *sym = ms->sym;
 326	struct annotated_source *src;
 327
 328	if (sym == NULL)
 329		return 0;
 330	src = symbol__hists(sym, evsel->evlist->core.nr_entries);
 331	return src ? __symbol__inc_addr_samples(ms, src, evsel, addr, sample) : 0;
 332}
 333
 334static int symbol__account_br_cntr(struct annotated_branch *branch,
 335				   struct evsel *evsel,
 336				   unsigned offset,
 337				   u64 br_cntr)
 338{
 339	unsigned int br_cntr_nr = evsel__leader(evsel)->br_cntr_nr;
 340	unsigned int base = evsel__leader(evsel)->br_cntr_idx;
 341	unsigned int off = offset * evsel->evlist->nr_br_cntr;
 342	u64 *branch_br_cntr = branch->br_cntr;
 343	unsigned int i, mask, width;
 344
 345	if (!br_cntr || !branch_br_cntr)
 346		return 0;
 347
 348	perf_env__find_br_cntr_info(evsel__env(evsel), NULL, &width);
 349	mask = (1L << width) - 1;
 350	for (i = 0; i < br_cntr_nr; i++) {
 351		u64 cntr = (br_cntr >> i * width) & mask;
 352
 353		branch_br_cntr[off + i + base] += cntr;
 354		if (cntr == mask)
 355			branch_br_cntr[off + i + base] |= ANNOTATION__BR_CNTR_SATURATED_FLAG;
 356	}
 357
 358	return 0;
 359}
 360
 361static int symbol__account_cycles(u64 addr, u64 start, struct symbol *sym,
 362				  unsigned cycles, struct evsel *evsel,
 363				  u64 br_cntr)
 364{
 365	struct annotated_branch *branch;
 366	unsigned offset;
 367	int ret;
 368
 369	if (sym == NULL)
 370		return 0;
 371	branch = symbol__find_branch_hist(sym, evsel->evlist->nr_br_cntr);
 372	if (!branch)
 373		return -ENOMEM;
 374	if (addr < sym->start || addr >= sym->end)
 375		return -ERANGE;
 376
 377	if (start) {
 378		if (start < sym->start || start >= sym->end)
 379			return -ERANGE;
 380		if (start >= addr)
 381			start = 0;
 382	}
 383	offset = addr - sym->start;
 384	ret = __symbol__account_cycles(branch->cycles_hist,
 385					start ? start - sym->start : 0,
 386					offset, cycles,
 387					!!start);
 388
 389	if (ret)
 390		return ret;
 391
 392	return symbol__account_br_cntr(branch, evsel, offset, br_cntr);
 393}
 394
 395int addr_map_symbol__account_cycles(struct addr_map_symbol *ams,
 396				    struct addr_map_symbol *start,
 397				    unsigned cycles,
 398				    struct evsel *evsel,
 399				    u64 br_cntr)
 400{
 401	u64 saddr = 0;
 402	int err;
 403
 404	if (!cycles)
 405		return 0;
 406
 407	/*
 408	 * Only set start when IPC can be computed. We can only
 409	 * compute it when the basic block is completely in a single
 410	 * function.
 411	 * Special case the case when the jump is elsewhere, but
 412	 * it starts on the function start.
 413	 */
 414	if (start &&
 415		(start->ms.sym == ams->ms.sym ||
 416		 (ams->ms.sym &&
 417		  start->addr == ams->ms.sym->start + map__start(ams->ms.map))))
 418		saddr = start->al_addr;
 419	if (saddr == 0)
 420		pr_debug2("BB with bad start: addr %"PRIx64" start %"PRIx64" sym %"PRIx64" saddr %"PRIx64"\n",
 421			ams->addr,
 422			start ? start->addr : 0,
 423			ams->ms.sym ? ams->ms.sym->start + map__start(ams->ms.map) : 0,
 424			saddr);
 425	err = symbol__account_cycles(ams->al_addr, saddr, ams->ms.sym, cycles, evsel, br_cntr);
 426	if (err)
 427		pr_debug2("account_cycles failed %d\n", err);
 428	return err;
 429}
 430
 431struct annotation_line *annotated_source__get_line(struct annotated_source *src,
 432						   s64 offset)
 433{
 434	struct annotation_line *al;
 435
 436	list_for_each_entry(al, &src->source, node) {
 437		if (al->offset == offset)
 438			return al;
 439	}
 440	return NULL;
 441}
 442
 443static unsigned annotation__count_insn(struct annotation *notes, u64 start, u64 end)
 444{
 445	struct annotation_line *al;
 446	unsigned n_insn = 0;
 447
 448	al = annotated_source__get_line(notes->src, start);
 449	if (al == NULL)
 450		return 0;
 451
 452	list_for_each_entry_from(al, &notes->src->source, node) {
 453		if (al->offset == -1)
 454			continue;
 455		if ((u64)al->offset > end)
 456			break;
 457		n_insn++;
 458	}
 459	return n_insn;
 460}
 461
 462static void annotated_branch__delete(struct annotated_branch *branch)
 463{
 464	if (branch) {
 465		zfree(&branch->cycles_hist);
 466		free(branch->br_cntr);
 467		free(branch);
 468	}
 469}
 470
 471static void annotation__count_and_fill(struct annotation *notes, u64 start, u64 end, struct cyc_hist *ch)
 472{
 473	unsigned n_insn;
 474	unsigned int cover_insn = 0;
 475
 476	n_insn = annotation__count_insn(notes, start, end);
 477	if (n_insn && ch->num && ch->cycles) {
 478		struct annotation_line *al;
 479		struct annotated_branch *branch;
 480		float ipc = n_insn / ((double)ch->cycles / (double)ch->num);
 481
 482		/* Hide data when there are too many overlaps. */
 483		if (ch->reset >= 0x7fff)
 484			return;
 485
 486		al = annotated_source__get_line(notes->src, start);
 487		if (al == NULL)
 488			return;
 489
 490		list_for_each_entry_from(al, &notes->src->source, node) {
 491			if (al->offset == -1)
 492				continue;
 493			if ((u64)al->offset > end)
 494				break;
 495			if (al->cycles && al->cycles->ipc == 0.0) {
 496				al->cycles->ipc = ipc;
 497				cover_insn++;
 498			}
 499		}
 500
 501		branch = annotation__get_branch(notes);
 502		if (cover_insn && branch) {
 503			branch->hit_cycles += ch->cycles;
 504			branch->hit_insn += n_insn * ch->num;
 505			branch->cover_insn += cover_insn;
 506		}
 507	}
 508}
 509
 510static int annotation__compute_ipc(struct annotation *notes, size_t size,
 511				   struct evsel *evsel)
 512{
 513	unsigned int br_cntr_nr = evsel->evlist->nr_br_cntr;
 514	int err = 0;
 515	s64 offset;
 516
 517	if (!notes->branch || !notes->branch->cycles_hist)
 518		return 0;
 519
 520	notes->branch->total_insn = annotation__count_insn(notes, 0, size - 1);
 521	notes->branch->hit_cycles = 0;
 522	notes->branch->hit_insn = 0;
 523	notes->branch->cover_insn = 0;
 524
 525	annotation__lock(notes);
 526	for (offset = size - 1; offset >= 0; --offset) {
 527		struct cyc_hist *ch;
 528
 529		ch = &notes->branch->cycles_hist[offset];
 530		if (ch && ch->cycles) {
 531			struct annotation_line *al;
 532
 533			al = annotated_source__get_line(notes->src, offset);
 534			if (al && al->cycles == NULL) {
 535				al->cycles = zalloc(sizeof(*al->cycles));
 536				if (al->cycles == NULL) {
 537					err = ENOMEM;
 538					break;
 539				}
 540			}
 541			if (ch->have_start)
 542				annotation__count_and_fill(notes, ch->start, offset, ch);
 543			if (al && ch->num_aggr) {
 544				al->cycles->avg = ch->cycles_aggr / ch->num_aggr;
 545				al->cycles->max = ch->cycles_max;
 546				al->cycles->min = ch->cycles_min;
 547			}
 548			if (al && notes->branch->br_cntr) {
 549				if (!al->br_cntr) {
 550					al->br_cntr = calloc(br_cntr_nr, sizeof(u64));
 551					if (!al->br_cntr) {
 552						err = ENOMEM;
 553						break;
 554					}
 555				}
 556				al->num_aggr = ch->num_aggr;
 557				al->br_cntr_nr = br_cntr_nr;
 558				al->evsel = evsel;
 559				memcpy(al->br_cntr, &notes->branch->br_cntr[offset * br_cntr_nr],
 560				       br_cntr_nr * sizeof(u64));
 561			}
 562		}
 563	}
 564
 565	if (err) {
 566		while (++offset < (s64)size) {
 567			struct cyc_hist *ch = &notes->branch->cycles_hist[offset];
 568
 569			if (ch && ch->cycles) {
 570				struct annotation_line *al;
 571
 572				al = annotated_source__get_line(notes->src, offset);
 573				if (al) {
 574					zfree(&al->cycles);
 575					zfree(&al->br_cntr);
 576				}
 577			}
 578		}
 579	}
 580
 581	annotation__unlock(notes);
 582	return 0;
 583}
 584
 585int addr_map_symbol__inc_samples(struct addr_map_symbol *ams, struct perf_sample *sample,
 586				 struct evsel *evsel)
 587{
 588	return symbol__inc_addr_samples(&ams->ms, evsel, ams->al_addr, sample);
 589}
 590
 591int hist_entry__inc_addr_samples(struct hist_entry *he, struct perf_sample *sample,
 592				 struct evsel *evsel, u64 ip)
 593{
 594	return symbol__inc_addr_samples(&he->ms, evsel, ip, sample);
 595}
 596
 597
 598void annotation__exit(struct annotation *notes)
 599{
 600	annotated_source__delete(notes->src);
 601	annotated_branch__delete(notes->branch);
 602}
 603
 604static struct sharded_mutex *sharded_mutex;
 605
 606static void annotation__init_sharded_mutex(void)
 607{
 608	/* As many mutexes as there are CPUs. */
 609	sharded_mutex = sharded_mutex__new(cpu__max_present_cpu().cpu);
 610}
 611
 612static size_t annotation__hash(const struct annotation *notes)
 613{
 614	return (size_t)notes;
 615}
 616
 617static struct mutex *annotation__get_mutex(const struct annotation *notes)
 618{
 619	static pthread_once_t once = PTHREAD_ONCE_INIT;
 620
 621	pthread_once(&once, annotation__init_sharded_mutex);
 622	if (!sharded_mutex)
 623		return NULL;
 624
 625	return sharded_mutex__get_mutex(sharded_mutex, annotation__hash(notes));
 626}
 627
 628void annotation__lock(struct annotation *notes)
 629	NO_THREAD_SAFETY_ANALYSIS
 630{
 631	struct mutex *mutex = annotation__get_mutex(notes);
 632
 633	if (mutex)
 634		mutex_lock(mutex);
 635}
 636
 637void annotation__unlock(struct annotation *notes)
 638	NO_THREAD_SAFETY_ANALYSIS
 639{
 640	struct mutex *mutex = annotation__get_mutex(notes);
 641
 642	if (mutex)
 643		mutex_unlock(mutex);
 644}
 645
 646bool annotation__trylock(struct annotation *notes)
 647{
 648	struct mutex *mutex = annotation__get_mutex(notes);
 649
 650	if (!mutex)
 651		return false;
 652
 653	return mutex_trylock(mutex);
 654}
 655
 656void annotation_line__add(struct annotation_line *al, struct list_head *head)
 657{
 658	list_add_tail(&al->node, head);
 659}
 660
 661struct annotation_line *
 662annotation_line__next(struct annotation_line *pos, struct list_head *head)
 663{
 664	list_for_each_entry_continue(pos, head, node)
 665		if (pos->offset >= 0)
 666			return pos;
 667
 668	return NULL;
 669}
 670
 671static const char *annotate__address_color(struct block_range *br)
 672{
 673	double cov = block_range__coverage(br);
 674
 675	if (cov >= 0) {
 676		/* mark red for >75% coverage */
 677		if (cov > 0.75)
 678			return PERF_COLOR_RED;
 679
 680		/* mark dull for <1% coverage */
 681		if (cov < 0.01)
 682			return PERF_COLOR_NORMAL;
 683	}
 684
 685	return PERF_COLOR_MAGENTA;
 686}
 687
 688static const char *annotate__asm_color(struct block_range *br)
 689{
 690	double cov = block_range__coverage(br);
 691
 692	if (cov >= 0) {
 693		/* mark dull for <1% coverage */
 694		if (cov < 0.01)
 695			return PERF_COLOR_NORMAL;
 696	}
 697
 698	return PERF_COLOR_BLUE;
 699}
 700
 701static void annotate__branch_printf(struct block_range *br, u64 addr)
 702{
 703	bool emit_comment = true;
 704
 705	if (!br)
 706		return;
 707
 708#if 1
 709	if (br->is_target && br->start == addr) {
 710		struct block_range *branch = br;
 711		double p;
 712
 713		/*
 714		 * Find matching branch to our target.
 715		 */
 716		while (!branch->is_branch)
 717			branch = block_range__next(branch);
 718
 719		p = 100 *(double)br->entry / branch->coverage;
 720
 721		if (p > 0.1) {
 722			if (emit_comment) {
 723				emit_comment = false;
 724				printf("\t#");
 725			}
 726
 727			/*
 728			 * The percentage of coverage joined at this target in relation
 729			 * to the next branch.
 730			 */
 731			printf(" +%.2f%%", p);
 732		}
 733	}
 734#endif
 735	if (br->is_branch && br->end == addr) {
 736		double p = 100*(double)br->taken / br->coverage;
 737
 738		if (p > 0.1) {
 739			if (emit_comment) {
 740				emit_comment = false;
 741				printf("\t#");
 742			}
 743
 744			/*
 745			 * The percentage of coverage leaving at this branch, and
 746			 * its prediction ratio.
 747			 */
 748			printf(" -%.2f%% (p:%.2f%%)", p, 100*(double)br->pred  / br->taken);
 749		}
 750	}
 751}
 752
 753static int disasm_line__print(struct disasm_line *dl, u64 start, int addr_fmt_width)
 754{
 755	s64 offset = dl->al.offset;
 756	const u64 addr = start + offset;
 757	struct block_range *br;
 758
 759	br = block_range__find(addr);
 760	color_fprintf(stdout, annotate__address_color(br), "  %*" PRIx64 ":", addr_fmt_width, addr);
 761	color_fprintf(stdout, annotate__asm_color(br), "%s", dl->al.line);
 762	annotate__branch_printf(br, addr);
 763	return 0;
 764}
 765
 766static struct annotated_data_type *
 767__hist_entry__get_data_type(struct hist_entry *he, struct arch *arch,
 768			    struct debuginfo *dbg, struct disasm_line *dl,
 769			    int *type_offset);
 770
 771static bool needs_type_info(struct annotated_data_type *data_type)
 772{
 773	if (data_type == NULL || data_type == NO_TYPE)
 774		return false;
 775
 776	if (verbose)
 777		return true;
 778
 779	return (data_type != &stackop_type) && (data_type != &canary_type);
 780}
 781
 782static int
 783annotation_line__print(struct annotation_line *al, struct annotation_print_data *apd,
 784		       struct annotation_options *opts, int printed,
 785		       struct annotation_line *queue)
 786{
 787	struct symbol *sym = apd->he->ms.sym;
 788	struct disasm_line *dl = container_of(al, struct disasm_line, al);
 789	struct annotation *notes = symbol__annotation(sym);
 790	static const char *prev_line;
 791	int max_lines = opts->max_lines;
 792	int percent_type = opts->percent_type;
 793
 794	if (al->offset != -1) {
 795		double max_percent = 0.0;
 796		int i, nr_percent = 1;
 797		const char *color;
 798
 799		for (i = 0; i < al->data_nr; i++) {
 800			double percent;
 801
 802			percent = annotation_data__percent(&al->data[i],
 803							   percent_type);
 804
 805			if (percent > max_percent)
 806				max_percent = percent;
 807		}
 808
 809		if (al->data_nr > nr_percent)
 810			nr_percent = al->data_nr;
 811
 812		if (max_percent < opts->min_pcnt)
 813			return -1;
 814
 815		if (max_lines && printed >= max_lines)
 816			return 1;
 817
 818		if (queue != NULL) {
 819			struct annotation_options queue_opts = {
 820				.max_lines = 1,
 821				.percent_type = percent_type,
 822			};
 823
 824			list_for_each_entry_from(queue, &notes->src->source, node) {
 825				if (queue == al)
 826					break;
 827				annotation_line__print(queue, apd, &queue_opts,
 828						       /*printed=*/0, /*queue=*/NULL);
 829			}
 830		}
 831
 832		color = get_percent_color(max_percent);
 833
 834		for (i = 0; i < nr_percent; i++) {
 835			struct annotation_data *data = &al->data[i];
 836			double percent;
 837
 838			percent = annotation_data__percent(data, percent_type);
 839			color = get_percent_color(percent);
 840
 841			if (symbol_conf.show_total_period)
 842				color_fprintf(stdout, color, " %11" PRIu64,
 843					      data->he.period);
 844			else if (symbol_conf.show_nr_samples)
 845				color_fprintf(stdout, color, " %7" PRIu64,
 846					      data->he.nr_samples);
 847			else
 848				color_fprintf(stdout, color, " %7.2f", percent);
 849		}
 850
 851		printf(" : ");
 852
 853		disasm_line__print(dl, notes->src->start, apd->addr_fmt_width);
 854
 855		if (opts->code_with_type && apd->dbg) {
 856			struct annotated_data_type *data_type;
 857			int offset = 0;
 858
 859			data_type = __hist_entry__get_data_type(apd->he, apd->arch,
 860								apd->dbg, dl, &offset);
 861			if (needs_type_info(data_type)) {
 862				char buf[4096];
 863
 864				printf("\t\t# data-type: %s",
 865				       data_type->self.type_name);
 866
 867				if (data_type != &stackop_type &&
 868				    data_type != &canary_type)
 869					printf(" +%#x", offset);
 870
 871				if (annotated_data_type__get_member_name(data_type,
 872									 buf,
 873									 sizeof(buf),
 874									 offset))
 875					printf(" (%s)", buf);
 876			}
 877		}
 878
 879		/*
 880		 * Also color the filename and line if needed, with
 881		 * the same color than the percentage. Don't print it
 882		 * twice for close colored addr with the same filename:line
 883		 */
 884		if (al->path) {
 885			if (!prev_line || strcmp(prev_line, al->path)) {
 886				color_fprintf(stdout, color, " // %s", al->path);
 887				prev_line = al->path;
 888			}
 889		}
 890
 891		printf("\n");
 892	} else if (max_lines && printed >= max_lines)
 893		return 1;
 894	else {
 895		int width = annotation__pcnt_width(notes);
 896
 897		if (queue)
 898			return -1;
 899
 900		if (!*al->line)
 901			printf(" %*s:\n", width, " ");
 902		else
 903			printf(" %*s: %-*d %s\n", width, " ", apd->addr_fmt_width,
 904			       al->line_nr, al->line);
 905	}
 906
 907	return 0;
 908}
 909
 910static void calc_percent(struct annotation *notes,
 911			 struct evsel *evsel,
 912			 struct annotation_data *data,
 913			 s64 offset, s64 end)
 914{
 915	struct hists *hists = evsel__hists(evsel);
 916	struct sym_hist *sym_hist = annotation__histogram(notes, evsel);
 917	unsigned int hits = 0;
 918	u64 period = 0;
 919
 920	while (offset < end) {
 921		struct sym_hist_entry *entry;
 922
 923		entry = annotated_source__hist_entry(notes->src, evsel, offset);
 924		if (entry) {
 925			hits   += entry->nr_samples;
 926			period += entry->period;
 927		}
 928		++offset;
 929	}
 930
 931	if (sym_hist->nr_samples) {
 932		data->he.period     = period;
 933		data->he.nr_samples = hits;
 934		data->percent[PERCENT_HITS_LOCAL] = 100.0 * hits / sym_hist->nr_samples;
 935	}
 936
 937	if (hists->stats.nr_non_filtered_samples)
 938		data->percent[PERCENT_HITS_GLOBAL] = 100.0 * hits / hists->stats.nr_non_filtered_samples;
 939
 940	if (sym_hist->period)
 941		data->percent[PERCENT_PERIOD_LOCAL] = 100.0 * period / sym_hist->period;
 942
 943	if (hists->stats.total_period)
 944		data->percent[PERCENT_PERIOD_GLOBAL] = 100.0 * period / hists->stats.total_period;
 945}
 946
 947static void annotation__calc_percent(struct annotation *notes,
 948				     struct evsel *leader, s64 len)
 949{
 950	struct annotation_line *al, *next;
 951	struct evsel *evsel;
 952
 953	list_for_each_entry(al, &notes->src->source, node) {
 954		s64 end;
 955		int i = 0;
 956
 957		if (al->offset == -1)
 958			continue;
 959
 960		next = annotation_line__next(al, &notes->src->source);
 961		end  = next ? next->offset : len;
 962
 963		for_each_group_evsel(evsel, leader) {
 964			struct annotation_data *data;
 965
 966			BUG_ON(i >= al->data_nr);
 967
 968			if (symbol_conf.skip_empty &&
 969			    evsel__hists(evsel)->stats.nr_samples == 0)
 970				continue;
 971
 972			data = &al->data[i++];
 973
 974			calc_percent(notes, evsel, data, al->offset, end);
 975		}
 976	}
 977}
 978
 979void symbol__calc_percent(struct symbol *sym, struct evsel *evsel)
 980{
 981	struct annotation *notes = symbol__annotation(sym);
 982
 983	annotation__calc_percent(notes, evsel, symbol__size(sym));
 984}
 985
 986int evsel__get_arch(struct evsel *evsel, struct arch **parch)
 987{
 988	struct perf_env *env = evsel__env(evsel);
 989	const char *arch_name = perf_env__arch(env);
 990	struct arch *arch;
 991	int err;
 992
 993	if (!arch_name) {
 994		*parch = NULL;
 995		return errno;
 996	}
 997
 998	*parch = arch = arch__find(arch_name);
 999	if (arch == NULL) {
1000		pr_err("%s: unsupported arch %s\n", __func__, arch_name);
1001		return ENOTSUP;
1002	}
1003
1004	if (arch->init) {
1005		err = arch->init(arch, env ? env->cpuid : NULL);
1006		if (err) {
1007			pr_err("%s: failed to initialize %s arch priv area\n",
1008			       __func__, arch->name);
1009			return err;
1010		}
1011	}
1012	return 0;
1013}
1014
1015int symbol__annotate(struct map_symbol *ms, struct evsel *evsel,
1016		     struct arch **parch)
1017{
1018	struct symbol *sym = ms->sym;
1019	struct annotation *notes = symbol__annotation(sym);
1020	struct annotate_args args = {
1021		.options	= &annotate_opts,
1022	};
1023	struct arch *arch = NULL;
1024	int err, nr;
1025
1026	err = evsel__get_arch(evsel, &arch);
1027	if (err)
1028		return err;
1029
1030	if (parch)
1031		*parch = arch;
1032
1033	if (notes->src && !list_empty(&notes->src->source))
1034		return 0;
1035
1036	args.arch = arch;
1037	args.ms = ms;
1038
1039	if (notes->src == NULL) {
1040		notes->src = annotated_source__new();
1041		if (notes->src == NULL)
1042			return -1;
1043	}
1044
1045	nr = 0;
1046	if (evsel__is_group_event(evsel)) {
1047		struct evsel *pos;
1048
1049		for_each_group_evsel(pos, evsel) {
1050			if (symbol_conf.skip_empty &&
1051			    evsel__hists(pos)->stats.nr_samples == 0)
1052				continue;
1053			nr++;
1054		}
1055	}
1056	notes->src->nr_events = nr ? nr : 1;
1057
1058	if (annotate_opts.full_addr)
1059		notes->src->start = map__objdump_2mem(ms->map, ms->sym->start);
1060	else
1061		notes->src->start = map__rip_2objdump(ms->map, ms->sym->start);
1062
1063	return symbol__disassemble(sym, &args);
1064}
1065
1066static void insert_source_line(struct rb_root *root, struct annotation_line *al)
1067{
1068	struct annotation_line *iter;
1069	struct rb_node **p = &root->rb_node;
1070	struct rb_node *parent = NULL;
1071	unsigned int percent_type = annotate_opts.percent_type;
1072	int i, ret;
1073
1074	while (*p != NULL) {
1075		parent = *p;
1076		iter = rb_entry(parent, struct annotation_line, rb_node);
1077
1078		ret = strcmp(iter->path, al->path);
1079		if (ret == 0) {
1080			for (i = 0; i < al->data_nr; i++) {
1081				iter->data[i].percent_sum += annotation_data__percent(&al->data[i],
1082										      percent_type);
1083			}
1084			return;
1085		}
1086
1087		if (ret < 0)
1088			p = &(*p)->rb_left;
1089		else
1090			p = &(*p)->rb_right;
1091	}
1092
1093	for (i = 0; i < al->data_nr; i++) {
1094		al->data[i].percent_sum = annotation_data__percent(&al->data[i],
1095								   percent_type);
1096	}
1097
1098	rb_link_node(&al->rb_node, parent, p);
1099	rb_insert_color(&al->rb_node, root);
1100}
1101
1102static int cmp_source_line(struct annotation_line *a, struct annotation_line *b)
1103{
1104	int i;
1105
1106	for (i = 0; i < a->data_nr; i++) {
1107		if (a->data[i].percent_sum == b->data[i].percent_sum)
1108			continue;
1109		return a->data[i].percent_sum > b->data[i].percent_sum;
1110	}
1111
1112	return 0;
1113}
1114
1115static void __resort_source_line(struct rb_root *root, struct annotation_line *al)
1116{
1117	struct annotation_line *iter;
1118	struct rb_node **p = &root->rb_node;
1119	struct rb_node *parent = NULL;
1120
1121	while (*p != NULL) {
1122		parent = *p;
1123		iter = rb_entry(parent, struct annotation_line, rb_node);
1124
1125		if (cmp_source_line(al, iter))
1126			p = &(*p)->rb_left;
1127		else
1128			p = &(*p)->rb_right;
1129	}
1130
1131	rb_link_node(&al->rb_node, parent, p);
1132	rb_insert_color(&al->rb_node, root);
1133}
1134
1135static void resort_source_line(struct rb_root *dest_root, struct rb_root *src_root)
1136{
1137	struct annotation_line *al;
1138	struct rb_node *node;
1139
1140	node = rb_first(src_root);
1141	while (node) {
1142		struct rb_node *next;
1143
1144		al = rb_entry(node, struct annotation_line, rb_node);
1145		next = rb_next(node);
1146		rb_erase(node, src_root);
1147
1148		__resort_source_line(dest_root, al);
1149		node = next;
1150	}
1151}
1152
1153static void print_summary(struct rb_root *root, const char *filename)
1154{
1155	struct annotation_line *al;
1156	struct rb_node *node;
1157
1158	printf("\nSorted summary for file %s\n", filename);
1159	printf("----------------------------------------------\n\n");
1160
1161	if (RB_EMPTY_ROOT(root)) {
1162		printf(" Nothing higher than %1.1f%%\n", MIN_GREEN);
1163		return;
1164	}
1165
1166	node = rb_first(root);
1167	while (node) {
1168		double percent, percent_max = 0.0;
1169		const char *color;
1170		char *path;
1171		int i;
1172
1173		al = rb_entry(node, struct annotation_line, rb_node);
1174		for (i = 0; i < al->data_nr; i++) {
1175			percent = al->data[i].percent_sum;
1176			color = get_percent_color(percent);
1177			color_fprintf(stdout, color, " %7.2f", percent);
1178
1179			if (percent > percent_max)
1180				percent_max = percent;
1181		}
1182
1183		path = al->path;
1184		color = get_percent_color(percent_max);
1185		color_fprintf(stdout, color, " %s\n", path);
1186
1187		node = rb_next(node);
1188	}
1189}
1190
1191static void symbol__annotate_hits(struct symbol *sym, struct evsel *evsel)
1192{
1193	struct annotation *notes = symbol__annotation(sym);
1194	struct sym_hist *h = annotation__histogram(notes, evsel);
1195	u64 len = symbol__size(sym), offset;
1196
1197	for (offset = 0; offset < len; ++offset) {
1198		struct sym_hist_entry *entry;
1199
1200		entry = annotated_source__hist_entry(notes->src, evsel, offset);
1201		if (entry && entry->nr_samples != 0)
1202			printf("%*" PRIx64 ": %" PRIu64 "\n", BITS_PER_LONG / 2,
1203			       sym->start + offset, entry->nr_samples);
1204	}
1205	printf("%*s: %" PRIu64 "\n", BITS_PER_LONG / 2, "h->nr_samples", h->nr_samples);
1206}
1207
1208static int annotated_source__addr_fmt_width(struct list_head *lines, u64 start)
1209{
1210	char bf[32];
1211	struct annotation_line *line;
1212
1213	list_for_each_entry_reverse(line, lines, node) {
1214		if (line->offset != -1)
1215			return scnprintf(bf, sizeof(bf), "%" PRIx64, start + line->offset);
1216	}
1217
1218	return 0;
1219}
1220
1221int hist_entry__annotate_printf(struct hist_entry *he, struct evsel *evsel)
1222{
1223	struct map_symbol *ms = &he->ms;
1224	struct map *map = ms->map;
1225	struct symbol *sym = ms->sym;
1226	struct dso *dso = map__dso(map);
1227	char *filename;
1228	const char *d_filename;
1229	const char *evsel_name = evsel__name(evsel);
1230	struct annotation *notes = symbol__annotation(sym);
1231	struct sym_hist *h = annotation__histogram(notes, evsel);
1232	struct annotation_line *pos, *queue = NULL;
1233	struct annotation_options *opts = &annotate_opts;
1234	struct annotation_print_data apd = {
1235		.he = he,
1236		.evsel = evsel,
1237	};
1238	int printed = 2, queue_len = 0;
1239	int more = 0;
1240	bool context = opts->context;
1241	int width = annotation__pcnt_width(notes);
1242	int graph_dotted_len;
1243	char buf[512];
1244
1245	filename = strdup(dso__long_name(dso));
1246	if (!filename)
1247		return -ENOMEM;
1248
1249	if (opts->full_path)
1250		d_filename = filename;
1251	else
1252		d_filename = basename(filename);
1253
1254	if (evsel__is_group_event(evsel)) {
1255		evsel__group_desc(evsel, buf, sizeof(buf));
1256		evsel_name = buf;
1257	}
1258
1259	graph_dotted_len = printf(" %-*.*s|	Source code & Disassembly of %s for %s (%" PRIu64 " samples, "
1260				  "percent: %s)\n",
1261				  width, width, symbol_conf.show_total_period ? "Period" :
1262				  symbol_conf.show_nr_samples ? "Samples" : "Percent",
1263				  d_filename, evsel_name, h->nr_samples,
1264				  percent_type_str(opts->percent_type));
1265
1266	printf("%-*.*s----\n",
1267	       graph_dotted_len, graph_dotted_len, graph_dotted_line);
1268
1269	if (verbose > 0)
1270		symbol__annotate_hits(sym, evsel);
1271
1272	apd.addr_fmt_width = annotated_source__addr_fmt_width(&notes->src->source,
1273							      notes->src->start);
1274	evsel__get_arch(evsel, &apd.arch);
1275	apd.dbg = dso__debuginfo(dso);
1276
1277	list_for_each_entry(pos, &notes->src->source, node) {
1278		int err;
1279
1280		if (context && queue == NULL) {
1281			queue = pos;
1282			queue_len = 0;
1283		}
1284
1285		err = annotation_line__print(pos, &apd, opts, printed, queue);
1286
1287		switch (err) {
1288		case 0:
1289			++printed;
1290			if (context) {
1291				printed += queue_len;
1292				queue = NULL;
1293				queue_len = 0;
1294			}
1295			break;
1296		case 1:
1297			/* filtered by max_lines */
1298			++more;
1299			break;
1300		case -1:
1301		default:
1302			/*
1303			 * Filtered by min_pcnt or non IP lines when
1304			 * context != 0
1305			 */
1306			if (!context)
1307				break;
1308			if (queue_len == context)
1309				queue = list_entry(queue->node.next, typeof(*queue), node);
1310			else
1311				++queue_len;
1312			break;
1313		}
1314	}
1315
1316	debuginfo__delete(apd.dbg);
1317	free(filename);
1318
1319	return more;
1320}
1321
1322static void FILE__set_percent_color(void *fp __maybe_unused,
1323				    double percent __maybe_unused,
1324				    bool current __maybe_unused)
1325{
1326}
1327
1328static int FILE__set_jumps_percent_color(void *fp __maybe_unused,
1329					 int nr __maybe_unused, bool current __maybe_unused)
1330{
1331	return 0;
1332}
1333
1334static int FILE__set_color(void *fp __maybe_unused, int color __maybe_unused)
1335{
1336	return 0;
1337}
1338
1339static void FILE__printf(void *fp, const char *fmt, ...)
1340{
1341	va_list args;
1342
1343	va_start(args, fmt);
1344	vfprintf(fp, fmt, args);
1345	va_end(args);
1346}
1347
1348static void FILE__write_graph(void *fp, int graph)
1349{
1350	const char *s;
1351	switch (graph) {
1352
1353	case DARROW_CHAR: s = "↓"; break;
1354	case UARROW_CHAR: s = "↑"; break;
1355	case LARROW_CHAR: s = "←"; break;
1356	case RARROW_CHAR: s = "→"; break;
1357	default:		s = "?"; break;
1358	}
1359
1360	fputs(s, fp);
1361}
1362
1363static int symbol__annotate_fprintf2(struct symbol *sym, FILE *fp,
1364				     struct annotation_print_data *apd)
1365{
1366	struct annotation *notes = symbol__annotation(sym);
1367	struct annotation_write_ops wops = {
1368		.first_line		 = true,
1369		.obj			 = fp,
1370		.set_color		 = FILE__set_color,
1371		.set_percent_color	 = FILE__set_percent_color,
1372		.set_jumps_percent_color = FILE__set_jumps_percent_color,
1373		.printf			 = FILE__printf,
1374		.write_graph		 = FILE__write_graph,
1375	};
1376	struct annotation_line *al;
1377
1378	if (annotate_opts.code_with_type) {
1379		evsel__get_arch(apd->evsel, &apd->arch);
1380		apd->dbg = dso__debuginfo(map__dso(apd->he->ms.map));
1381	}
1382
1383	list_for_each_entry(al, &notes->src->source, node) {
1384		if (annotation_line__filter(al))
1385			continue;
1386		annotation_line__write(al, notes, &wops, apd);
1387		fputc('\n', fp);
1388		wops.first_line = false;
1389	}
1390
1391	if (annotate_opts.code_with_type)
1392		debuginfo__delete(apd->dbg);
1393
1394	return 0;
1395}
1396
1397int map_symbol__annotation_dump(struct map_symbol *ms, struct evsel *evsel,
1398				struct hist_entry *he)
1399{
1400	const char *ev_name = evsel__name(evsel);
1401	char buf[1024];
1402	char *filename;
1403	int err = -1;
1404	FILE *fp;
1405	struct annotation_print_data apd = {
1406		.he = he,
1407		.evsel = evsel,
1408	};
1409
1410	if (asprintf(&filename, "%s.annotation", ms->sym->name) < 0)
1411		return -1;
1412
1413	fp = fopen(filename, "w");
1414	if (fp == NULL)
1415		goto out_free_filename;
1416
1417	if (evsel__is_group_event(evsel)) {
1418		evsel__group_desc(evsel, buf, sizeof(buf));
1419		ev_name = buf;
1420	}
1421
1422	fprintf(fp, "%s() %s\nEvent: %s\n\n",
1423		ms->sym->name, dso__long_name(map__dso(ms->map)), ev_name);
1424	symbol__annotate_fprintf2(ms->sym, fp, &apd);
1425
1426	fclose(fp);
1427	err = 0;
1428out_free_filename:
1429	free(filename);
1430	return err;
1431}
1432
1433void symbol__annotate_zero_histogram(struct symbol *sym, struct evsel *evsel)
1434{
1435	struct annotation *notes = symbol__annotation(sym);
1436	struct sym_hist *h = annotation__histogram(notes, evsel);
1437
1438	memset(h, 0, sizeof(*notes->src->histograms) * notes->src->nr_histograms);
1439}
1440
1441void symbol__annotate_decay_histogram(struct symbol *sym, struct evsel *evsel)
1442{
1443	struct annotation *notes = symbol__annotation(sym);
1444	struct sym_hist *h = annotation__histogram(notes, evsel);
1445	struct annotation_line *al;
1446
1447	h->nr_samples = 0;
1448	list_for_each_entry(al, &notes->src->source, node) {
1449		struct sym_hist_entry *entry;
1450
1451		if (al->offset == -1)
1452			continue;
1453
1454		entry = annotated_source__hist_entry(notes->src, evsel, al->offset);
1455		if (entry == NULL)
1456			continue;
1457
1458		entry->nr_samples = entry->nr_samples * 7 / 8;
1459		h->nr_samples += entry->nr_samples;
1460	}
1461}
1462
1463void annotated_source__purge(struct annotated_source *as)
1464{
1465	struct annotation_line *al, *n;
1466
1467	list_for_each_entry_safe(al, n, &as->source, node) {
1468		list_del_init(&al->node);
1469		disasm_line__free(disasm_line(al));
1470	}
1471	as->tried_source = false;
1472}
1473
1474static size_t disasm_line__fprintf(struct disasm_line *dl, FILE *fp)
1475{
1476	size_t printed;
1477
1478	if (dl->al.offset == -1)
1479		return fprintf(fp, "%s\n", dl->al.line);
1480
1481	printed = fprintf(fp, "%#" PRIx64 " %s", dl->al.offset, dl->ins.name);
1482
1483	if (dl->ops.raw[0] != '\0') {
1484		printed += fprintf(fp, "%.*s %s\n", 6 - (int)printed, " ",
1485				   dl->ops.raw);
1486	}
1487
1488	return printed + fprintf(fp, "\n");
1489}
1490
1491size_t disasm__fprintf(struct list_head *head, FILE *fp)
1492{
1493	struct disasm_line *pos;
1494	size_t printed = 0;
1495
1496	list_for_each_entry(pos, head, al.node)
1497		printed += disasm_line__fprintf(pos, fp);
1498
1499	return printed;
1500}
1501
1502bool disasm_line__is_valid_local_jump(struct disasm_line *dl, struct symbol *sym)
1503{
1504	if (!dl || !dl->ins.ops || !ins__is_jump(&dl->ins) ||
1505	    !disasm_line__has_local_offset(dl) || dl->ops.target.offset < 0 ||
1506	    dl->ops.target.offset >= (s64)symbol__size(sym))
1507		return false;
1508
1509	return true;
1510}
1511
1512static void
1513annotation__mark_jump_targets(struct annotation *notes, struct symbol *sym)
1514{
1515	struct annotation_line *al;
1516
1517	/* PLT symbols contain external offsets */
1518	if (strstr(sym->name, "@plt"))
1519		return;
1520
1521	list_for_each_entry(al, &notes->src->source, node) {
1522		struct disasm_line *dl;
1523		struct annotation_line *target;
1524
1525		dl = disasm_line(al);
1526
1527		if (!disasm_line__is_valid_local_jump(dl, sym))
1528			continue;
1529
1530		target = annotated_source__get_line(notes->src,
1531						    dl->ops.target.offset);
1532		/*
1533		 * FIXME: Oops, no jump target? Buggy disassembler? Or do we
1534		 * have to adjust to the previous offset?
1535		 */
1536		if (target == NULL)
1537			continue;
1538
1539		if (++target->jump_sources > notes->src->max_jump_sources)
1540			notes->src->max_jump_sources = target->jump_sources;
1541	}
1542}
1543
1544static void annotation__set_index(struct annotation *notes)
1545{
1546	struct annotation_line *al;
1547	struct annotated_source *src = notes->src;
1548
1549	src->widths.max_line_len = 0;
1550	src->nr_entries = 0;
1551	src->nr_asm_entries = 0;
1552
1553	list_for_each_entry(al, &src->source, node) {
1554		size_t line_len = strlen(al->line);
1555
1556		if (src->widths.max_line_len < line_len)
1557			src->widths.max_line_len = line_len;
1558		al->idx = src->nr_entries++;
1559		if (al->offset != -1)
1560			al->idx_asm = src->nr_asm_entries++;
1561		else
1562			al->idx_asm = -1;
1563	}
1564}
1565
1566static inline int width_jumps(int n)
1567{
1568	if (n >= 100)
1569		return 5;
1570	if (n / 10)
1571		return 2;
1572	return 1;
1573}
1574
1575static int annotation__max_ins_name(struct annotation *notes)
1576{
1577	int max_name = 0, len;
1578	struct annotation_line *al;
1579
1580        list_for_each_entry(al, &notes->src->source, node) {
1581		if (al->offset == -1)
1582			continue;
1583
1584		len = strlen(disasm_line(al)->ins.name);
1585		if (max_name < len)
1586			max_name = len;
1587	}
1588
1589	return max_name;
1590}
1591
1592static void
1593annotation__init_column_widths(struct annotation *notes, struct symbol *sym)
1594{
1595	notes->src->widths.addr = notes->src->widths.target =
1596		notes->src->widths.min_addr = hex_width(symbol__size(sym));
1597	notes->src->widths.max_addr = hex_width(sym->end);
1598	notes->src->widths.jumps = width_jumps(notes->src->max_jump_sources);
1599	notes->src->widths.max_ins_name = annotation__max_ins_name(notes);
1600}
1601
1602void annotation__update_column_widths(struct annotation *notes)
1603{
1604	if (annotate_opts.use_offset)
1605		notes->src->widths.target = notes->src->widths.min_addr;
1606	else if (annotate_opts.full_addr)
1607		notes->src->widths.target = BITS_PER_LONG / 4;
1608	else
1609		notes->src->widths.target = notes->src->widths.max_addr;
1610
1611	notes->src->widths.addr = notes->src->widths.target;
1612
1613	if (annotate_opts.show_nr_jumps)
1614		notes->src->widths.addr += notes->src->widths.jumps + 1;
1615}
1616
1617void annotation__toggle_full_addr(struct annotation *notes, struct map_symbol *ms)
1618{
1619	annotate_opts.full_addr = !annotate_opts.full_addr;
1620
1621	if (annotate_opts.full_addr)
1622		notes->src->start = map__objdump_2mem(ms->map, ms->sym->start);
1623	else
1624		notes->src->start = map__rip_2objdump(ms->map, ms->sym->start);
1625
1626	annotation__update_column_widths(notes);
1627}
1628
1629static void annotation__calc_lines(struct annotation *notes, struct map_symbol *ms,
1630				   struct rb_root *root)
1631{
1632	struct annotation_line *al;
1633	struct rb_root tmp_root = RB_ROOT;
1634
1635	list_for_each_entry(al, &notes->src->source, node) {
1636		double percent_max = 0.0;
1637		u64 addr;
1638		int i;
1639
1640		for (i = 0; i < al->data_nr; i++) {
1641			double percent;
1642
1643			percent = annotation_data__percent(&al->data[i],
1644							   annotate_opts.percent_type);
1645
1646			if (percent > percent_max)
1647				percent_max = percent;
1648		}
1649
1650		if (percent_max <= 0.5)
1651			continue;
1652
1653		addr = map__rip_2objdump(ms->map, ms->sym->start);
1654		al->path = get_srcline(map__dso(ms->map), addr + al->offset, NULL,
1655				       false, true, ms->sym->start + al->offset);
1656		insert_source_line(&tmp_root, al);
1657	}
1658
1659	resort_source_line(root, &tmp_root);
1660}
1661
1662static void symbol__calc_lines(struct map_symbol *ms, struct rb_root *root)
1663{
1664	struct annotation *notes = symbol__annotation(ms->sym);
1665
1666	annotation__calc_lines(notes, ms, root);
1667}
1668
1669int hist_entry__tty_annotate2(struct hist_entry *he, struct evsel *evsel)
1670{
1671	struct map_symbol *ms = &he->ms;
1672	struct dso *dso = map__dso(ms->map);
1673	struct symbol *sym = ms->sym;
1674	struct rb_root source_line = RB_ROOT;
1675	struct hists *hists = evsel__hists(evsel);
1676	struct annotation_print_data apd = {
1677		.he = he,
1678		.evsel = evsel,
1679	};
1680	char buf[1024];
1681	int err;
1682
1683	err = symbol__annotate2(ms, evsel, NULL);
1684	if (err) {
1685		char msg[BUFSIZ];
1686
1687		dso__set_annotate_warned(dso);
1688		symbol__strerror_disassemble(ms, err, msg, sizeof(msg));
1689		ui__error("Couldn't annotate %s:\n%s", sym->name, msg);
1690		return -1;
1691	}
1692
1693	if (annotate_opts.print_lines) {
1694		srcline_full_filename = annotate_opts.full_path;
1695		symbol__calc_lines(ms, &source_line);
1696		print_summary(&source_line, dso__long_name(dso));
1697	}
1698
1699	hists__scnprintf_title(hists, buf, sizeof(buf));
1700	fprintf(stdout, "%s, [percent: %s]\n%s() %s\n",
1701		buf, percent_type_str(annotate_opts.percent_type), sym->name, dso__long_name(dso));
1702	symbol__annotate_fprintf2(sym, stdout, &apd);
1703
1704	annotated_source__purge(symbol__annotation(sym)->src);
1705
1706	return 0;
1707}
1708
1709int hist_entry__tty_annotate(struct hist_entry *he, struct evsel *evsel)
1710{
1711	struct map_symbol *ms = &he->ms;
1712	struct dso *dso = map__dso(ms->map);
1713	struct symbol *sym = ms->sym;
1714	struct rb_root source_line = RB_ROOT;
1715	int err;
1716
1717	err = symbol__annotate(ms, evsel, NULL);
1718	if (err) {
1719		char msg[BUFSIZ];
1720
1721		dso__set_annotate_warned(dso);
1722		symbol__strerror_disassemble(ms, err, msg, sizeof(msg));
1723		ui__error("Couldn't annotate %s:\n%s", sym->name, msg);
1724		return -1;
1725	}
1726
1727	symbol__calc_percent(sym, evsel);
1728
1729	if (annotate_opts.print_lines) {
1730		srcline_full_filename = annotate_opts.full_path;
1731		symbol__calc_lines(ms, &source_line);
1732		print_summary(&source_line, dso__long_name(dso));
1733	}
1734
1735	hist_entry__annotate_printf(he, evsel);
1736
1737	annotated_source__purge(symbol__annotation(sym)->src);
1738
1739	return 0;
1740}
1741
1742bool ui__has_annotation(void)
1743{
1744	return use_browser == 1 && perf_hpp_list.sym;
1745}
1746
1747
1748static double annotation_line__max_percent(struct annotation_line *al,
1749					   unsigned int percent_type)
1750{
1751	double percent_max = 0.0;
1752	int i;
1753
1754	for (i = 0; i < al->data_nr; i++) {
1755		double percent;
1756
1757		percent = annotation_data__percent(&al->data[i],
1758						   percent_type);
1759
1760		if (percent > percent_max)
1761			percent_max = percent;
1762	}
1763
1764	return percent_max;
1765}
1766
1767static int disasm_line__write(struct disasm_line *dl, struct annotation *notes,
1768			       void *obj, char *bf, size_t size,
1769			       void (*obj__printf)(void *obj, const char *fmt, ...),
1770			       void (*obj__write_graph)(void *obj, int graph))
1771{
1772	if (dl->ins.ops && dl->ins.ops->scnprintf) {
1773		if (ins__is_jump(&dl->ins)) {
1774			bool fwd;
1775
1776			if (dl->ops.target.outside)
1777				goto call_like;
1778			fwd = dl->ops.target.offset > dl->al.offset;
1779			obj__write_graph(obj, fwd ? DARROW_CHAR : UARROW_CHAR);
1780			obj__printf(obj, " ");
1781		} else if (ins__is_call(&dl->ins)) {
1782call_like:
1783			obj__write_graph(obj, RARROW_CHAR);
1784			obj__printf(obj, " ");
1785		} else if (ins__is_ret(&dl->ins)) {
1786			obj__write_graph(obj, LARROW_CHAR);
1787			obj__printf(obj, " ");
1788		} else {
1789			obj__printf(obj, "  ");
1790		}
1791	} else {
1792		obj__printf(obj, "  ");
1793	}
1794
1795	return disasm_line__scnprintf(dl, bf, size, !annotate_opts.use_offset,
1796				      notes->src->widths.max_ins_name) + 2;
1797}
1798
1799static void ipc_coverage_string(char *bf, int size, struct annotation *notes)
1800{
1801	double ipc = 0.0, coverage = 0.0;
1802	struct annotated_branch *branch = annotation__get_branch(notes);
1803
1804	if (branch && branch->hit_cycles)
1805		ipc = branch->hit_insn / ((double)branch->hit_cycles);
1806
1807	if (branch && branch->total_insn) {
1808		coverage = branch->cover_insn * 100.0 /
1809			((double)branch->total_insn);
1810	}
1811
1812	scnprintf(bf, size, "(Average IPC: %.2f, IPC Coverage: %.1f%%)",
1813		  ipc, coverage);
1814}
1815
1816int annotation_br_cntr_abbr_list(char **str, struct evsel *evsel, bool header)
1817{
1818	struct evsel *pos;
1819	struct strbuf sb;
1820
1821	if (evsel->evlist->nr_br_cntr <= 0)
1822		return -ENOTSUP;
1823
1824	strbuf_init(&sb, /*hint=*/ 0);
1825
1826	if (header && strbuf_addf(&sb, "# Branch counter abbr list:\n"))
1827		goto err;
1828
1829	evlist__for_each_entry(evsel->evlist, pos) {
1830		if (!(pos->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS))
1831			continue;
1832		if (header && strbuf_addf(&sb, "#"))
1833			goto err;
1834
1835		if (strbuf_addf(&sb, " %s = %s\n", pos->name, pos->abbr_name))
1836			goto err;
1837	}
1838
1839	if (header && strbuf_addf(&sb, "#"))
1840		goto err;
1841	if (strbuf_addf(&sb, " '-' No event occurs\n"))
1842		goto err;
1843
1844	if (header && strbuf_addf(&sb, "#"))
1845		goto err;
1846	if (strbuf_addf(&sb, " '+' Event occurrences may be lost due to branch counter saturated\n"))
1847		goto err;
1848
1849	*str = strbuf_detach(&sb, NULL);
1850
1851	return 0;
1852err:
1853	strbuf_release(&sb);
1854	return -ENOMEM;
1855}
1856
1857/* Assume the branch counter saturated at 3 */
1858#define ANNOTATION_BR_CNTR_SATURATION		3
1859
1860int annotation_br_cntr_entry(char **str, int br_cntr_nr,
1861			     u64 *br_cntr, int num_aggr,
1862			     struct evsel *evsel)
1863{
1864	struct evsel *pos = evsel ? evlist__first(evsel->evlist) : NULL;
1865	bool saturated = false;
1866	int i, j, avg, used;
1867	struct strbuf sb;
1868
1869	strbuf_init(&sb, /*hint=*/ 0);
1870	for (i = 0; i < br_cntr_nr; i++) {
1871		used = 0;
1872		avg = ceil((double)(br_cntr[i] & ~ANNOTATION__BR_CNTR_SATURATED_FLAG) /
1873			   (double)num_aggr);
1874
1875		/*
1876		 * A histogram with the abbr name is displayed by default.
1877		 * With -v, the exact number of branch counter is displayed.
1878		 */
1879		if (verbose) {
1880			evlist__for_each_entry_from(evsel->evlist, pos) {
1881				if ((pos->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) &&
1882				    (pos->br_cntr_idx == i))
1883				break;
1884			}
1885			if (strbuf_addstr(&sb, pos->abbr_name))
1886				goto err;
1887
1888			if (!br_cntr[i]) {
1889				if (strbuf_addstr(&sb, "=-"))
1890					goto err;
1891			} else {
1892				if (strbuf_addf(&sb, "=%d", avg))
1893					goto err;
1894			}
1895			if (br_cntr[i] & ANNOTATION__BR_CNTR_SATURATED_FLAG) {
1896				if (strbuf_addch(&sb, '+'))
1897					goto err;
1898			} else {
1899				if (strbuf_addch(&sb, ' '))
1900					goto err;
1901			}
1902
1903			if ((i < br_cntr_nr - 1) && strbuf_addch(&sb, ','))
1904				goto err;
1905			continue;
1906		}
1907
1908		if (strbuf_addch(&sb, '|'))
1909			goto err;
1910
1911		if (!br_cntr[i]) {
1912			if (strbuf_addch(&sb, '-'))
1913				goto err;
1914			used++;
1915		} else {
1916			evlist__for_each_entry_from(evsel->evlist, pos) {
1917				if ((pos->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) &&
1918				    (pos->br_cntr_idx == i))
1919					break;
1920			}
1921			if (br_cntr[i] & ANNOTATION__BR_CNTR_SATURATED_FLAG)
1922				saturated = true;
1923
1924			for (j = 0; j < avg; j++, used++) {
1925				/* Print + if the number of logged events > 3 */
1926				if (j >= ANNOTATION_BR_CNTR_SATURATION) {
1927					saturated = true;
1928					break;
1929				}
1930				if (strbuf_addstr(&sb, pos->abbr_name))
1931					goto err;
1932			}
1933
1934			if (saturated) {
1935				if (strbuf_addch(&sb, '+'))
1936					goto err;
1937				used++;
1938			}
1939			pos = list_next_entry(pos, core.node);
1940		}
1941
1942		for (j = used; j < ANNOTATION_BR_CNTR_SATURATION + 1; j++) {
1943			if (strbuf_addch(&sb, ' '))
1944				goto err;
1945		}
1946	}
1947
1948	if (!verbose && strbuf_addch(&sb, br_cntr_nr ? '|' : ' '))
1949		goto err;
1950
1951	*str = strbuf_detach(&sb, NULL);
1952
1953	return 0;
1954err:
1955	strbuf_release(&sb);
1956	return -ENOMEM;
1957}
1958
1959struct type_hash_entry {
1960	struct annotated_data_type *type;
1961	int offset;
1962};
1963
1964static int disasm_line__snprint_type_info(struct disasm_line *dl,
1965					  char *buf, int len,
1966					  struct annotation_print_data *apd)
1967{
1968	struct annotated_data_type *data_type = NULL;
1969	struct type_hash_entry *entry = NULL;
1970	char member[256];
1971	int offset = 0;
1972	int printed;
1973
1974	scnprintf(buf, len, " ");
1975
1976	if (!annotate_opts.code_with_type || apd->dbg == NULL)
1977		return 1;
1978
1979	if (apd->type_hash) {
1980		hashmap__find(apd->type_hash, dl->al.offset, &entry);
1981		if (entry != NULL) {
1982			data_type = entry->type;
1983			offset = entry->offset;
1984		}
1985	}
1986
1987	if (data_type == NULL)
1988		data_type = __hist_entry__get_data_type(apd->he, apd->arch, apd->dbg, dl, &offset);
1989
1990	if (apd->type_hash && entry == NULL) {
1991		entry = malloc(sizeof(*entry));
1992		if (entry != NULL) {
1993			entry->type = data_type;
1994			entry->offset = offset;
1995			hashmap__add(apd->type_hash, dl->al.offset, entry);
1996		}
1997	}
1998
1999	if (!needs_type_info(data_type))
2000		return 1;
2001
2002	printed = scnprintf(buf, len, "\t\t# data-type: %s", data_type->self.type_name);
2003
2004	if (data_type != &stackop_type && data_type != &canary_type && len > printed)
2005		printed += scnprintf(buf + printed, len - printed, " +%#x", offset);
2006
2007	if (annotated_data_type__get_member_name(data_type, member, sizeof(member), offset) &&
2008	    len > printed) {
2009		printed += scnprintf(buf + printed, len - printed, " (%s)", member);
2010	}
2011	return printed;
2012}
2013
2014void annotation_line__write(struct annotation_line *al, struct annotation *notes,
2015			    const struct annotation_write_ops *wops,
2016			    struct annotation_print_data *apd)
2017{
2018	bool current_entry = wops->current_entry;
2019	bool change_color = wops->change_color;
2020	double percent_max = annotation_line__max_percent(al, annotate_opts.percent_type);
2021	int width = wops->width;
2022	int pcnt_width = annotation__pcnt_width(notes);
2023	int cycles_width = annotation__cycles_width(notes);
2024	bool show_title = false;
2025	char bf[256];
2026	int printed;
2027	void *obj = wops->obj;
2028	int  (*obj__set_color)(void *obj, int color) = wops->set_color;
2029	void (*obj__set_percent_color)(void *obj, double percent, bool current) = wops->set_percent_color;
2030	int  (*obj__set_jumps_percent_color)(void *obj, int nr, bool current) = wops->set_jumps_percent_color;
2031	void (*obj__printf)(void *obj, const char *fmt, ...) = wops->printf;
2032	void (*obj__write_graph)(void *obj, int graph) = wops->write_graph;
2033
2034	if (wops->first_line && (al->offset == -1 || percent_max == 0.0)) {
2035		if (notes->branch && al->cycles) {
2036			if (al->cycles->ipc == 0.0 && al->cycles->avg == 0)
2037				show_title = true;
2038		} else
2039			show_title = true;
2040	}
2041
2042	if (al->offset != -1 && percent_max != 0.0) {
2043		int i;
2044
2045		for (i = 0; i < al->data_nr; i++) {
2046			double percent;
2047
2048			percent = annotation_data__percent(&al->data[i],
2049							   annotate_opts.percent_type);
2050
2051			obj__set_percent_color(obj, percent, current_entry);
2052			if (symbol_conf.show_total_period) {
2053				obj__printf(obj, "%11" PRIu64 " ", al->data[i].he.period);
2054			} else if (symbol_conf.show_nr_samples) {
2055				obj__printf(obj, "%7" PRIu64 " ",
2056						   al->data[i].he.nr_samples);
2057			} else {
2058				obj__printf(obj, "%7.2f ", percent);
2059			}
2060		}
2061	} else {
2062		obj__set_percent_color(obj, 0, current_entry);
2063
2064		if (!show_title)
2065			obj__printf(obj, "%-*s", pcnt_width, " ");
2066		else {
2067			obj__printf(obj, "%-*s", pcnt_width,
2068					   symbol_conf.show_total_period ? "Period" :
2069					   symbol_conf.show_nr_samples ? "Samples" : "Percent");
2070		}
2071	}
2072	width -= pcnt_width;
2073
2074	if (notes->branch) {
2075		if (al->cycles && al->cycles->ipc)
2076			obj__printf(obj, "%*.2f ", ANNOTATION__IPC_WIDTH - 1, al->cycles->ipc);
2077		else if (!show_title)
2078			obj__printf(obj, "%*s", ANNOTATION__IPC_WIDTH, " ");
2079		else
2080			obj__printf(obj, "%*s ", ANNOTATION__IPC_WIDTH - 1, "IPC");
2081
2082		if (!annotate_opts.show_minmax_cycle) {
2083			if (al->cycles && al->cycles->avg)
2084				obj__printf(obj, "%*" PRIu64 " ",
2085					   ANNOTATION__CYCLES_WIDTH - 1, al->cycles->avg);
2086			else if (!show_title)
2087				obj__printf(obj, "%*s",
2088					    ANNOTATION__CYCLES_WIDTH, " ");
2089			else
2090				obj__printf(obj, "%*s ",
2091					    ANNOTATION__CYCLES_WIDTH - 1,
2092					    "Cycle");
2093		} else {
2094			if (al->cycles) {
2095				char str[32];
2096
2097				scnprintf(str, sizeof(str),
2098					"%" PRIu64 "(%" PRIu64 "/%" PRIu64 ")",
2099					al->cycles->avg, al->cycles->min,
2100					al->cycles->max);
2101
2102				obj__printf(obj, "%*s ",
2103					    ANNOTATION__MINMAX_CYCLES_WIDTH - 1,
2104					    str);
2105			} else if (!show_title)
2106				obj__printf(obj, "%*s",
2107					    ANNOTATION__MINMAX_CYCLES_WIDTH,
2108					    " ");
2109			else
2110				obj__printf(obj, "%*s ",
2111					    ANNOTATION__MINMAX_CYCLES_WIDTH - 1,
2112					    "Cycle(min/max)");
2113		}
2114
2115		if (annotate_opts.show_br_cntr) {
2116			if (show_title) {
2117				obj__printf(obj, "%*s ",
2118					    ANNOTATION__BR_CNTR_WIDTH,
2119					    "Branch Counter");
2120			} else {
2121				char *buf;
2122
2123				if (!annotation_br_cntr_entry(&buf, al->br_cntr_nr, al->br_cntr,
2124							      al->num_aggr, al->evsel)) {
2125					obj__printf(obj, "%*s ", ANNOTATION__BR_CNTR_WIDTH, buf);
2126					free(buf);
2127				}
2128			}
2129		}
2130
2131		if (show_title && !*al->line) {
2132			ipc_coverage_string(bf, sizeof(bf), notes);
2133			obj__printf(obj, "%*s", ANNOTATION__AVG_IPC_WIDTH, bf);
2134		}
2135	}
2136	width -= cycles_width;
2137
2138	obj__printf(obj, " ");
2139	width -= 1;
2140
2141	if (!*al->line)
2142		obj__printf(obj, "%-*s", width, " ");
2143	else if (al->offset == -1) {
2144		if (al->line_nr && annotate_opts.show_linenr)
2145			printed = scnprintf(bf, sizeof(bf), "%-*d ",
2146					    notes->src->widths.addr + 1, al->line_nr);
2147		else
2148			printed = scnprintf(bf, sizeof(bf), "%-*s  ",
2149					    notes->src->widths.addr, " ");
2150		obj__printf(obj, bf);
2151		width -= printed;
2152		obj__printf(obj, "%-*s", width, al->line);
2153	} else {
2154		u64 addr = al->offset;
2155		int color = -1;
2156
2157		if (!annotate_opts.use_offset)
2158			addr += notes->src->start;
2159
2160		if (!annotate_opts.use_offset) {
2161			printed = scnprintf(bf, sizeof(bf), "%" PRIx64 ": ", addr);
2162		} else {
2163			if (al->jump_sources &&
2164			    annotate_opts.offset_level >= ANNOTATION__OFFSET_JUMP_TARGETS) {
2165				if (annotate_opts.show_nr_jumps) {
2166					int prev;
2167					printed = scnprintf(bf, sizeof(bf), "%*d ",
2168							    notes->src->widths.jumps,
2169							    al->jump_sources);
2170					prev = obj__set_jumps_percent_color(obj, al->jump_sources,
2171									    current_entry);
2172					obj__printf(obj, bf);
2173					obj__set_color(obj, prev);
2174				}
2175print_addr:
2176				printed = scnprintf(bf, sizeof(bf), "%*" PRIx64 ": ",
2177						    notes->src->widths.target, addr);
2178			} else if (ins__is_call(&disasm_line(al)->ins) &&
2179				   annotate_opts.offset_level >= ANNOTATION__OFFSET_CALL) {
2180				goto print_addr;
2181			} else if (annotate_opts.offset_level == ANNOTATION__MAX_OFFSET_LEVEL) {
2182				goto print_addr;
2183			} else {
2184				printed = scnprintf(bf, sizeof(bf), "%-*s  ",
2185						    notes->src->widths.addr, " ");
2186			}
2187		}
2188
2189		if (change_color)
2190			color = obj__set_color(obj, HE_COLORSET_ADDR);
2191		obj__printf(obj, bf);
2192		if (change_color)
2193			obj__set_color(obj, color);
2194
2195		width -= printed;
2196
2197		printed = disasm_line__write(disasm_line(al), notes, obj, bf, sizeof(bf),
2198					     obj__printf, obj__write_graph);
2199
2200		obj__printf(obj, "%s", bf);
2201		width -= printed;
2202
2203		disasm_line__snprint_type_info(disasm_line(al), bf, sizeof(bf), apd);
2204		obj__printf(obj, "%-*s", width, bf);
2205	}
2206
2207}
2208
2209int symbol__annotate2(struct map_symbol *ms, struct evsel *evsel,
2210		      struct arch **parch)
2211{
2212	struct symbol *sym = ms->sym;
2213	struct annotation *notes = symbol__annotation(sym);
2214	size_t size = symbol__size(sym);
2215	int err;
2216
2217	err = symbol__annotate(ms, evsel, parch);
2218	if (err)
2219		return err;
2220
2221	symbol__calc_percent(sym, evsel);
2222
2223	annotation__set_index(notes);
2224	annotation__mark_jump_targets(notes, sym);
2225
2226	err = annotation__compute_ipc(notes, size, evsel);
2227	if (err)
2228		return err;
2229
2230	annotation__init_column_widths(notes, sym);
2231	annotation__update_column_widths(notes);
2232	sym->annotate2 = 1;
2233
2234	return 0;
2235}
2236
2237const char * const perf_disassembler__strs[] = {
2238	[PERF_DISASM_UNKNOWN]  = "unknown",
2239	[PERF_DISASM_LLVM]     = "llvm",
2240	[PERF_DISASM_CAPSTONE] = "capstone",
2241	[PERF_DISASM_OBJDUMP]  = "objdump",
2242};
2243
2244
2245static void annotation_options__add_disassembler(struct annotation_options *options,
2246						 enum perf_disassembler dis)
2247{
2248	for (u8 i = 0; i < ARRAY_SIZE(options->disassemblers); i++) {
2249		if (options->disassemblers[i] == dis) {
2250			/* Disassembler is already present then don't add again. */
2251			return;
2252		}
2253		if (options->disassemblers[i] == PERF_DISASM_UNKNOWN) {
2254			/* Found a free slot. */
2255			options->disassemblers[i] = dis;
2256			return;
2257		}
2258	}
2259	pr_err("Failed to add disassembler %d\n", dis);
2260}
2261
2262static int annotation_options__add_disassemblers_str(struct annotation_options *options,
2263						const char *str)
2264{
2265	while (str && *str != '\0') {
2266		const char *comma = strchr(str, ',');
2267		int len = comma ? comma - str : (int)strlen(str);
2268		bool match = false;
2269
2270		for (u8 i = 0; i < ARRAY_SIZE(perf_disassembler__strs); i++) {
2271			const char *dis_str = perf_disassembler__strs[i];
2272
2273			if (len == (int)strlen(dis_str) && !strncmp(str, dis_str, len)) {
2274				annotation_options__add_disassembler(options, i);
2275				match = true;
2276				break;
2277			}
2278		}
2279		if (!match) {
2280			pr_err("Invalid disassembler '%.*s'\n", len, str);
2281			return -1;
2282		}
2283		str = comma ? comma + 1 : NULL;
2284	}
2285	return 0;
2286}
2287
2288static int annotation__config(const char *var, const char *value, void *data)
2289{
2290	struct annotation_options *opt = data;
2291
2292	if (!strstarts(var, "annotate."))
2293		return 0;
2294
2295	if (!strcmp(var, "annotate.offset_level")) {
2296		perf_config_u8(&opt->offset_level, "offset_level", value);
2297
2298		if (opt->offset_level > ANNOTATION__MAX_OFFSET_LEVEL)
2299			opt->offset_level = ANNOTATION__MAX_OFFSET_LEVEL;
2300		else if (opt->offset_level < ANNOTATION__MIN_OFFSET_LEVEL)
2301			opt->offset_level = ANNOTATION__MIN_OFFSET_LEVEL;
2302	} else if (!strcmp(var, "annotate.disassemblers")) {
2303		int err = annotation_options__add_disassemblers_str(opt, value);
2304
2305		if (err)
2306			return err;
2307	} else if (!strcmp(var, "annotate.hide_src_code")) {
2308		opt->hide_src_code = perf_config_bool("hide_src_code", value);
2309	} else if (!strcmp(var, "annotate.jump_arrows")) {
2310		opt->jump_arrows = perf_config_bool("jump_arrows", value);
2311	} else if (!strcmp(var, "annotate.show_linenr")) {
2312		opt->show_linenr = perf_config_bool("show_linenr", value);
2313	} else if (!strcmp(var, "annotate.show_nr_jumps")) {
2314		opt->show_nr_jumps = perf_config_bool("show_nr_jumps", value);
2315	} else if (!strcmp(var, "annotate.show_nr_samples")) {
2316		symbol_conf.show_nr_samples = perf_config_bool("show_nr_samples",
2317								value);
2318	} else if (!strcmp(var, "annotate.show_total_period")) {
2319		symbol_conf.show_total_period = perf_config_bool("show_total_period",
2320								value);
2321	} else if (!strcmp(var, "annotate.use_offset")) {
2322		opt->use_offset = perf_config_bool("use_offset", value);
2323	} else if (!strcmp(var, "annotate.disassembler_style")) {
2324		opt->disassembler_style = strdup(value);
2325		if (!opt->disassembler_style) {
2326			pr_err("Not enough memory for annotate.disassembler_style\n");
2327			return -1;
2328		}
2329	} else if (!strcmp(var, "annotate.objdump")) {
2330		opt->objdump_path = strdup(value);
2331		if (!opt->objdump_path) {
2332			pr_err("Not enough memory for annotate.objdump\n");
2333			return -1;
2334		}
2335	} else if (!strcmp(var, "annotate.addr2line")) {
2336		symbol_conf.addr2line_path = strdup(value);
2337		if (!symbol_conf.addr2line_path) {
2338			pr_err("Not enough memory for annotate.addr2line\n");
2339			return -1;
2340		}
2341	} else if (!strcmp(var, "annotate.demangle")) {
2342		symbol_conf.demangle = perf_config_bool("demangle", value);
2343	} else if (!strcmp(var, "annotate.demangle_kernel")) {
2344		symbol_conf.demangle_kernel = perf_config_bool("demangle_kernel", value);
2345	} else {
2346		pr_debug("%s variable unknown, ignoring...", var);
2347	}
2348
2349	return 0;
2350}
2351
2352void annotation_options__init(void)
2353{
2354	struct annotation_options *opt = &annotate_opts;
2355
2356	memset(opt, 0, sizeof(*opt));
2357
2358	/* Default values. */
2359	opt->use_offset = true;
2360	opt->jump_arrows = true;
2361	opt->annotate_src = true;
2362	opt->offset_level = ANNOTATION__OFFSET_JUMP_TARGETS;
2363	opt->percent_type = PERCENT_PERIOD_LOCAL;
2364	opt->hide_src_code = true;
2365	opt->hide_src_code_on_title = true;
2366}
2367
2368void annotation_options__exit(void)
2369{
2370	zfree(&annotate_opts.disassembler_style);
2371	zfree(&annotate_opts.objdump_path);
2372}
2373
2374static void annotation_options__default_init_disassemblers(struct annotation_options *options)
2375{
2376	if (options->disassemblers[0] != PERF_DISASM_UNKNOWN) {
2377		/* Already initialized. */
2378		return;
2379	}
2380#ifdef HAVE_LIBLLVM_SUPPORT
2381	annotation_options__add_disassembler(options, PERF_DISASM_LLVM);
2382#endif
2383#ifdef HAVE_LIBCAPSTONE_SUPPORT
2384	annotation_options__add_disassembler(options, PERF_DISASM_CAPSTONE);
2385#endif
2386	annotation_options__add_disassembler(options, PERF_DISASM_OBJDUMP);
2387}
2388
2389void annotation_config__init(void)
2390{
2391	perf_config(annotation__config, &annotate_opts);
2392	annotation_options__default_init_disassemblers(&annotate_opts);
2393}
2394
2395static unsigned int parse_percent_type(char *str1, char *str2)
2396{
2397	unsigned int type = (unsigned int) -1;
2398
2399	if (!strcmp("period", str1)) {
2400		if (!strcmp("local", str2))
2401			type = PERCENT_PERIOD_LOCAL;
2402		else if (!strcmp("global", str2))
2403			type = PERCENT_PERIOD_GLOBAL;
2404	}
2405
2406	if (!strcmp("hits", str1)) {
2407		if (!strcmp("local", str2))
2408			type = PERCENT_HITS_LOCAL;
2409		else if (!strcmp("global", str2))
2410			type = PERCENT_HITS_GLOBAL;
2411	}
2412
2413	return type;
2414}
2415
2416int annotate_parse_percent_type(const struct option *opt __maybe_unused, const char *_str,
2417				int unset __maybe_unused)
2418{
2419	unsigned int type;
2420	char *str1, *str2;
2421	int err = -1;
2422
2423	str1 = strdup(_str);
2424	if (!str1)
2425		return -ENOMEM;
2426
2427	str2 = strchr(str1, '-');
2428	if (!str2)
2429		goto out;
2430
2431	*str2++ = 0;
2432
2433	type = parse_percent_type(str1, str2);
2434	if (type == (unsigned int) -1)
2435		type = parse_percent_type(str2, str1);
2436	if (type != (unsigned int) -1) {
2437		annotate_opts.percent_type = type;
2438		err = 0;
2439	}
2440
2441out:
2442	free(str1);
2443	return err;
2444}
2445
2446int annotate_check_args(void)
2447{
2448	struct annotation_options *args = &annotate_opts;
2449
2450	if (args->prefix_strip && !args->prefix) {
2451		pr_err("--prefix-strip requires --prefix\n");
2452		return -1;
2453	}
2454	return 0;
2455}
2456
2457/*
2458 * Get register number and access offset from the given instruction.
2459 * It assumes AT&T x86 asm format like OFFSET(REG).  Maybe it needs
2460 * to revisit the format when it handles different architecture.
2461 * Fills @reg and @offset when return 0.
2462 */
2463static int extract_reg_offset(struct arch *arch, const char *str,
2464			      struct annotated_op_loc *op_loc)
2465{
2466	char *p;
2467	char *regname;
2468
2469	if (arch->objdump.register_char == 0)
2470		return -1;
2471
2472	/*
2473	 * It should start from offset, but it's possible to skip 0
2474	 * in the asm.  So 0(%rax) should be same as (%rax).
2475	 *
2476	 * However, it also start with a segment select register like
2477	 * %gs:0x18(%rbx).  In that case it should skip the part.
2478	 */
2479	if (*str == arch->objdump.register_char) {
2480		if (arch__is(arch, "x86")) {
2481			/* FIXME: Handle other segment registers */
2482			if (!strncmp(str, "%gs:", 4))
2483				op_loc->segment = INSN_SEG_X86_GS;
2484		}
2485
2486		while (*str && !isdigit(*str) &&
2487		       *str != arch->objdump.memory_ref_char)
2488			str++;
2489	}
2490
2491	op_loc->offset = strtol(str, &p, 0);
2492
2493	p = strchr(p, arch->objdump.register_char);
2494	if (p == NULL)
2495		return -1;
2496
2497	regname = strdup(p);
2498	if (regname == NULL)
2499		return -1;
2500
2501	op_loc->reg1 = get_dwarf_regnum(regname, arch->e_machine, arch->e_flags);
2502	free(regname);
2503
2504	/* Get the second register */
2505	if (op_loc->multi_regs) {
2506		p = strchr(p + 1, arch->objdump.register_char);
2507		if (p == NULL)
2508			return -1;
2509
2510		regname = strdup(p);
2511		if (regname == NULL)
2512			return -1;
2513
2514		op_loc->reg2 = get_dwarf_regnum(regname, arch->e_machine, arch->e_flags);
2515		free(regname);
2516	}
2517	return 0;
2518}
2519
2520/**
2521 * annotate_get_insn_location - Get location of instruction
2522 * @arch: the architecture info
2523 * @dl: the target instruction
2524 * @loc: a buffer to save the data
2525 *
2526 * Get detailed location info (register and offset) in the instruction.
2527 * It needs both source and target operand and whether it accesses a
2528 * memory location.  The offset field is meaningful only when the
2529 * corresponding mem flag is set.  The reg2 field is meaningful only
2530 * when multi_regs flag is set.
2531 *
2532 * Some examples on x86:
2533 *
2534 *   mov  (%rax), %rcx   # src_reg1 = rax, src_mem = 1, src_offset = 0
2535 *                       # dst_reg1 = rcx, dst_mem = 0
2536 *
2537 *   mov  0x18, %r8      # src_reg1 = -1, src_mem = 0
2538 *                       # dst_reg1 = r8, dst_mem = 0
2539 *
2540 *   mov  %rsi, 8(%rbx,%rcx,4)  # src_reg1 = rsi, src_mem = 0, src_multi_regs = 0
2541 *                              # dst_reg1 = rbx, dst_reg2 = rcx, dst_mem = 1
2542 *                              # dst_multi_regs = 1, dst_offset = 8
2543 */
2544int annotate_get_insn_location(struct arch *arch, struct disasm_line *dl,
2545			       struct annotated_insn_loc *loc)
2546{
2547	struct ins_operands *ops;
2548	struct annotated_op_loc *op_loc;
2549	int i;
2550
2551	if (ins__is_lock(&dl->ins))
2552		ops = dl->ops.locked.ops;
2553	else
2554		ops = &dl->ops;
2555
2556	if (ops == NULL)
2557		return -1;
2558
2559	memset(loc, 0, sizeof(*loc));
2560
2561	for_each_insn_op_loc(loc, i, op_loc) {
2562		const char *insn_str = ops->source.raw;
2563		bool multi_regs = ops->source.multi_regs;
2564		bool mem_ref = ops->source.mem_ref;
2565
2566		if (i == INSN_OP_TARGET) {
2567			insn_str = ops->target.raw;
2568			multi_regs = ops->target.multi_regs;
2569			mem_ref = ops->target.mem_ref;
2570		}
2571
2572		/* Invalidate the register by default */
2573		op_loc->reg1 = -1;
2574		op_loc->reg2 = -1;
2575
2576		if (insn_str == NULL) {
2577			if (!arch__is(arch, "powerpc"))
2578				continue;
2579		}
2580
2581		/*
2582		 * For powerpc, call get_powerpc_regs function which extracts the
2583		 * required fields for op_loc, ie reg1, reg2, offset from the
2584		 * raw instruction.
2585		 */
2586		if (arch__is(arch, "powerpc")) {
2587			op_loc->mem_ref = mem_ref;
2588			op_loc->multi_regs = multi_regs;
2589			get_powerpc_regs(dl->raw.raw_insn, !i, op_loc);
2590		} else if (strchr(insn_str, arch->objdump.memory_ref_char)) {
2591			op_loc->mem_ref = true;
2592			op_loc->multi_regs = multi_regs;
2593			extract_reg_offset(arch, insn_str, op_loc);
2594		} else {
2595			char *s, *p = NULL;
2596
2597			if (arch__is(arch, "x86")) {
2598				/* FIXME: Handle other segment registers */
2599				if (!strncmp(insn_str, "%gs:", 4)) {
2600					op_loc->segment = INSN_SEG_X86_GS;
2601					op_loc->offset = strtol(insn_str + 4,
2602								&p, 0);
2603					if (p && p != insn_str + 4)
2604						op_loc->imm = true;
2605					continue;
2606				}
2607			}
2608
2609			s = strdup(insn_str);
2610			if (s == NULL)
2611				return -1;
2612
2613			if (*s == arch->objdump.register_char)
2614				op_loc->reg1 = get_dwarf_regnum(s, arch->e_machine, arch->e_flags);
2615			else if (*s == arch->objdump.imm_char) {
2616				op_loc->offset = strtol(s + 1, &p, 0);
2617				if (p && p != s + 1)
2618					op_loc->imm = true;
2619			}
2620			free(s);
2621		}
2622	}
2623
2624	return 0;
2625}
2626
2627static struct disasm_line *find_disasm_line(struct symbol *sym, u64 ip,
2628					    bool allow_update)
2629{
2630	struct disasm_line *dl;
2631	struct annotation *notes;
2632
2633	notes = symbol__annotation(sym);
2634
2635	list_for_each_entry(dl, &notes->src->source, al.node) {
2636		if (dl->al.offset == -1)
2637			continue;
2638
2639		if (sym->start + dl->al.offset == ip) {
2640			/*
2641			 * llvm-objdump places "lock" in a separate line and
2642			 * in that case, we want to get the next line.
2643			 */
2644			if (ins__is_lock(&dl->ins) &&
2645			    *dl->ops.raw == '\0' && allow_update) {
2646				ip++;
2647				continue;
2648			}
2649			return dl;
2650		}
2651	}
2652	return NULL;
2653}
2654
2655static struct annotated_item_stat *annotate_data_stat(struct list_head *head,
2656						      const char *name)
2657{
2658	struct annotated_item_stat *istat;
2659
2660	list_for_each_entry(istat, head, list) {
2661		if (!strcmp(istat->name, name))
2662			return istat;
2663	}
2664
2665	istat = zalloc(sizeof(*istat));
2666	if (istat == NULL)
2667		return NULL;
2668
2669	istat->name = strdup(name);
2670	if ((istat->name == NULL) || (!strlen(istat->name))) {
2671		free(istat);
2672		return NULL;
2673	}
2674
2675	list_add_tail(&istat->list, head);
2676	return istat;
2677}
2678
2679static bool is_stack_operation(struct arch *arch, struct disasm_line *dl)
2680{
2681	if (arch__is(arch, "x86")) {
2682		if (!strncmp(dl->ins.name, "push", 4) ||
2683		    !strncmp(dl->ins.name, "pop", 3) ||
2684		    !strncmp(dl->ins.name, "call", 4) ||
2685		    !strncmp(dl->ins.name, "ret", 3))
2686			return true;
2687	}
2688
2689	return false;
2690}
2691
2692static bool is_stack_canary(struct arch *arch, struct annotated_op_loc *loc)
2693{
2694	/* On x86_64, %gs:40 is used for stack canary */
2695	if (arch__is(arch, "x86")) {
2696		if (loc->segment == INSN_SEG_X86_GS && loc->imm &&
2697		    loc->offset == 40)
2698			return true;
2699	}
2700
2701	return false;
2702}
2703
2704/**
2705 * Returns true if the instruction has a memory operand without
2706 * performing a load/store
2707 */
2708static bool is_address_gen_insn(struct arch *arch, struct disasm_line *dl)
2709{
2710	if (arch__is(arch, "x86")) {
2711		if (!strncmp(dl->ins.name, "lea", 3))
2712			return true;
2713	}
2714
2715	return false;
2716}
2717
2718static struct disasm_line *
2719annotation__prev_asm_line(struct annotation *notes, struct disasm_line *curr)
2720{
2721	struct list_head *sources = &notes->src->source;
2722	struct disasm_line *prev;
2723
2724	if (curr == list_first_entry(sources, struct disasm_line, al.node))
2725		return NULL;
2726
2727	prev = list_prev_entry(curr, al.node);
2728	while (prev->al.offset == -1 &&
2729	       prev != list_first_entry(sources, struct disasm_line, al.node))
2730		prev = list_prev_entry(prev, al.node);
2731
2732	if (prev->al.offset == -1)
2733		return NULL;
2734
2735	return prev;
2736}
2737
2738static struct disasm_line *
2739annotation__next_asm_line(struct annotation *notes, struct disasm_line *curr)
2740{
2741	struct list_head *sources = &notes->src->source;
2742	struct disasm_line *next;
2743
2744	if (curr == list_last_entry(sources, struct disasm_line, al.node))
2745		return NULL;
2746
2747	next = list_next_entry(curr, al.node);
2748	while (next->al.offset == -1 &&
2749	       next != list_last_entry(sources, struct disasm_line, al.node))
2750		next = list_next_entry(next, al.node);
2751
2752	if (next->al.offset == -1)
2753		return NULL;
2754
2755	return next;
2756}
2757
2758u64 annotate_calc_pcrel(struct map_symbol *ms, u64 ip, int offset,
2759			struct disasm_line *dl)
2760{
2761	struct annotation *notes;
2762	struct disasm_line *next;
2763	u64 addr;
2764
2765	notes = symbol__annotation(ms->sym);
2766	/*
2767	 * PC-relative addressing starts from the next instruction address
2768	 * But the IP is for the current instruction.  Since disasm_line
2769	 * doesn't have the instruction size, calculate it using the next
2770	 * disasm_line.  If it's the last one, we can use symbol's end
2771	 * address directly.
2772	 */
2773	next = annotation__next_asm_line(notes, dl);
2774	if (next == NULL)
2775		addr = ms->sym->end + offset;
2776	else
2777		addr = ip + (next->al.offset - dl->al.offset) + offset;
2778
2779	return map__rip_2objdump(ms->map, addr);
2780}
2781
2782static struct debuginfo_cache {
2783	struct dso *dso;
2784	struct debuginfo *dbg;
2785} di_cache;
2786
2787void debuginfo_cache__delete(void)
2788{
2789	dso__put(di_cache.dso);
2790	di_cache.dso = NULL;
2791
2792	debuginfo__delete(di_cache.dbg);
2793	di_cache.dbg = NULL;
2794}
2795
2796static struct annotated_data_type *
2797__hist_entry__get_data_type(struct hist_entry *he, struct arch *arch,
2798			    struct debuginfo *dbg, struct disasm_line *dl,
2799			    int *type_offset)
2800{
2801	struct map_symbol *ms = &he->ms;
2802	struct annotated_insn_loc loc;
2803	struct annotated_op_loc *op_loc;
2804	struct annotated_data_type *mem_type;
2805	struct annotated_item_stat *istat;
2806	int i;
2807
2808	istat = annotate_data_stat(&ann_insn_stat, dl->ins.name);
2809	if (istat == NULL) {
2810		ann_data_stat.no_insn++;
2811		return NO_TYPE;
2812	}
2813
2814	if (annotate_get_insn_location(arch, dl, &loc) < 0) {
2815		ann_data_stat.no_insn_ops++;
2816		istat->bad++;
2817		return NO_TYPE;
2818	}
2819
2820	if (is_stack_operation(arch, dl)) {
2821		istat->good++;
2822		*type_offset = 0;
2823		return &stackop_type;
2824	}
2825
2826	if (is_address_gen_insn(arch, dl)) {
2827		istat->bad++;
2828		ann_data_stat.no_mem_ops++;
2829		return NO_TYPE;
2830	}
2831
2832	for_each_insn_op_loc(&loc, i, op_loc) {
2833		struct data_loc_info dloc = {
2834			.arch = arch,
2835			.thread = he->thread,
2836			.ms = ms,
2837			.ip = ms->sym->start + dl->al.offset,
2838			.cpumode = he->cpumode,
2839			.op = op_loc,
2840			.di = dbg,
2841		};
2842
2843		if (!op_loc->mem_ref && op_loc->segment == INSN_SEG_NONE)
2844			continue;
2845
2846		/* PC-relative addressing */
2847		if (op_loc->reg1 == DWARF_REG_PC) {
2848			dloc.var_addr = annotate_calc_pcrel(ms, dloc.ip,
2849							    op_loc->offset, dl);
2850		}
2851
2852		/* This CPU access in kernel - pretend PC-relative addressing */
2853		if (dso__kernel(map__dso(ms->map)) && arch__is(arch, "x86") &&
2854		    op_loc->segment == INSN_SEG_X86_GS && op_loc->imm) {
2855			dloc.var_addr = op_loc->offset;
2856			op_loc->reg1 = DWARF_REG_PC;
2857		}
2858
2859		mem_type = find_data_type(&dloc);
2860
2861		if (mem_type == NULL && is_stack_canary(arch, op_loc)) {
2862			istat->good++;
2863			*type_offset = 0;
2864			return &canary_type;
2865		}
2866
2867		if (mem_type)
2868			istat->good++;
2869		else
2870			istat->bad++;
2871
2872		if (symbol_conf.annotate_data_sample) {
2873			struct evsel *evsel = hists_to_evsel(he->hists);
2874
2875			annotated_data_type__update_samples(mem_type, evsel,
2876							    dloc.type_offset,
2877							    he->stat.nr_events,
2878							    he->stat.period);
2879		}
2880		*type_offset = dloc.type_offset;
2881		return mem_type ?: NO_TYPE;
2882	}
2883
2884	/* retry with a fused instruction */
2885	return NULL;
2886}
2887
2888/**
2889 * hist_entry__get_data_type - find data type for given hist entry
2890 * @he: hist entry
2891 *
2892 * This function first annotates the instruction at @he->ip and extracts
2893 * register and offset info from it.  Then it searches the DWARF debug
2894 * info to get a variable and type information using the address, register,
2895 * and offset.
2896 */
2897struct annotated_data_type *hist_entry__get_data_type(struct hist_entry *he)
2898{
2899	struct map_symbol *ms = &he->ms;
2900	struct evsel *evsel = hists_to_evsel(he->hists);
2901	struct arch *arch;
2902	struct disasm_line *dl;
2903	struct annotated_data_type *mem_type;
2904	struct annotated_item_stat *istat;
2905	u64 ip = he->ip;
2906
2907	ann_data_stat.total++;
2908
2909	if (ms->map == NULL || ms->sym == NULL) {
2910		ann_data_stat.no_sym++;
2911		return NULL;
2912	}
2913
2914	if (!symbol_conf.init_annotation) {
2915		ann_data_stat.no_sym++;
2916		return NULL;
2917	}
2918
2919	/*
2920	 * di_cache holds a pair of values, but code below assumes
2921	 * di_cache.dso can be compared/updated and di_cache.dbg can be
2922	 * read/updated independently from each other. That assumption only
2923	 * holds in single threaded code.
2924	 */
2925	assert(perf_singlethreaded);
2926
2927	if (map__dso(ms->map) != di_cache.dso) {
2928		dso__put(di_cache.dso);
2929		di_cache.dso = dso__get(map__dso(ms->map));
2930
2931		debuginfo__delete(di_cache.dbg);
2932		di_cache.dbg = dso__debuginfo(di_cache.dso);
2933	}
2934
2935	if (di_cache.dbg == NULL) {
2936		ann_data_stat.no_dbginfo++;
2937		return NULL;
2938	}
2939
2940	/* Make sure it has the disasm of the function */
2941	if (symbol__annotate(ms, evsel, &arch) < 0) {
2942		ann_data_stat.no_insn++;
2943		return NULL;
2944	}
2945
2946	/*
2947	 * Get a disasm to extract the location from the insn.
2948	 * This is too slow...
2949	 */
2950	dl = find_disasm_line(ms->sym, ip, /*allow_update=*/true);
2951	if (dl == NULL) {
2952		ann_data_stat.no_insn++;
2953		return NULL;
2954	}
2955
2956retry:
2957	mem_type = __hist_entry__get_data_type(he, arch, di_cache.dbg, dl,
2958					       &he->mem_type_off);
2959	if (mem_type)
2960		return mem_type == NO_TYPE ? NULL : mem_type;
2961
2962	/*
2963	 * Some instructions can be fused and the actual memory access came
2964	 * from the previous instruction.
2965	 */
2966	if (dl->al.offset > 0) {
2967		struct annotation *notes;
2968		struct disasm_line *prev_dl;
2969
2970		notes = symbol__annotation(ms->sym);
2971		prev_dl = annotation__prev_asm_line(notes, dl);
2972
2973		if (prev_dl && ins__is_fused(arch, prev_dl->ins.name, dl->ins.name)) {
2974			dl = prev_dl;
2975			goto retry;
2976		}
2977	}
2978
2979	ann_data_stat.no_mem_ops++;
2980	istat = annotate_data_stat(&ann_insn_stat, dl->ins.name);
2981	if (istat)
2982		istat->bad++;
2983	return NULL;
2984}
2985
2986/* Basic block traversal (BFS) data structure */
2987struct basic_block_data {
2988	struct list_head queue;
2989	struct list_head visited;
2990};
2991
2992/*
2993 * During the traversal, it needs to know the parent block where the current
2994 * block block started from.  Note that single basic block can be parent of
2995 * two child basic blocks (in case of condition jump).
2996 */
2997struct basic_block_link {
2998	struct list_head node;
2999	struct basic_block_link *parent;
3000	struct annotated_basic_block *bb;
3001};
3002
3003/* Check any of basic block in the list already has the offset */
3004static bool basic_block_has_offset(struct list_head *head, s64 offset)
3005{
3006	struct basic_block_link *link;
3007
3008	list_for_each_entry(link, head, node) {
3009		s64 begin_offset = link->bb->begin->al.offset;
3010		s64 end_offset = link->bb->end->al.offset;
3011
3012		if (begin_offset <= offset && offset <= end_offset)
3013			return true;
3014	}
3015	return false;
3016}
3017
3018static bool is_new_basic_block(struct basic_block_data *bb_data,
3019			       struct disasm_line *dl)
3020{
3021	s64 offset = dl->al.offset;
3022
3023	if (basic_block_has_offset(&bb_data->visited, offset))
3024		return false;
3025	if (basic_block_has_offset(&bb_data->queue, offset))
3026		return false;
3027	return true;
3028}
3029
3030/* Add a basic block starting from dl and link it to the parent */
3031static int add_basic_block(struct basic_block_data *bb_data,
3032			   struct basic_block_link *parent,
3033			   struct disasm_line *dl)
3034{
3035	struct annotated_basic_block *bb;
3036	struct basic_block_link *link;
3037
3038	if (dl == NULL)
3039		return -1;
3040
3041	if (!is_new_basic_block(bb_data, dl))
3042		return 0;
3043
3044	bb = zalloc(sizeof(*bb));
3045	if (bb == NULL)
3046		return -1;
3047
3048	bb->begin = dl;
3049	bb->end = dl;
3050	INIT_LIST_HEAD(&bb->list);
3051
3052	link = malloc(sizeof(*link));
3053	if (link == NULL) {
3054		free(bb);
3055		return -1;
3056	}
3057
3058	link->bb = bb;
3059	link->parent = parent;
3060	list_add_tail(&link->node, &bb_data->queue);
3061	return 0;
3062}
3063
3064/* Returns true when it finds the target in the current basic block */
3065static bool process_basic_block(struct basic_block_data *bb_data,
3066				struct basic_block_link *link,
3067				struct symbol *sym, u64 target)
3068{
3069	struct disasm_line *dl, *next_dl, *last_dl;
3070	struct annotation *notes = symbol__annotation(sym);
3071	bool found = false;
3072
3073	dl = link->bb->begin;
3074	/* Check if it's already visited */
3075	if (basic_block_has_offset(&bb_data->visited, dl->al.offset))
3076		return false;
3077
3078	last_dl = list_last_entry(&notes->src->source,
3079				  struct disasm_line, al.node);
3080	if (last_dl->al.offset == -1)
3081		last_dl = annotation__prev_asm_line(notes, last_dl);
3082
3083	if (last_dl == NULL)
3084		return false;
3085
3086	list_for_each_entry_from(dl, &notes->src->source, al.node) {
3087		/* Skip comment or debug info line */
3088		if (dl->al.offset == -1)
3089			continue;
3090		/* Found the target instruction */
3091		if (sym->start + dl->al.offset == target) {
3092			found = true;
3093			break;
3094		}
3095		/* End of the function, finish the block */
3096		if (dl == last_dl)
3097			break;
3098		/* 'return' instruction finishes the block */
3099		if (ins__is_ret(&dl->ins))
3100			break;
3101		/* normal instructions are part of the basic block */
3102		if (!ins__is_jump(&dl->ins))
3103			continue;
3104		/* jump to a different function, tail call or return */
3105		if (dl->ops.target.outside)
3106			break;
3107		/* jump instruction creates new basic block(s) */
3108		next_dl = find_disasm_line(sym, sym->start + dl->ops.target.offset,
3109					   /*allow_update=*/false);
3110		if (next_dl)
3111			add_basic_block(bb_data, link, next_dl);
3112
3113		/*
3114		 * FIXME: determine conditional jumps properly.
3115		 * Conditional jumps create another basic block with the
3116		 * next disasm line.
3117		 */
3118		if (!strstr(dl->ins.name, "jmp")) {
3119			next_dl = annotation__next_asm_line(notes, dl);
3120			if (next_dl)
3121				add_basic_block(bb_data, link, next_dl);
3122		}
3123		break;
3124
3125	}
3126	link->bb->end = dl;
3127	return found;
3128}
3129
3130/*
3131 * It founds a target basic block, build a proper linked list of basic blocks
3132 * by following the link recursively.
3133 */
3134static void link_found_basic_blocks(struct basic_block_link *link,
3135				    struct list_head *head)
3136{
3137	while (link) {
3138		struct basic_block_link *parent = link->parent;
3139
3140		list_move(&link->bb->list, head);
3141		list_del(&link->node);
3142		free(link);
3143
3144		link = parent;
3145	}
3146}
3147
3148static void delete_basic_blocks(struct basic_block_data *bb_data)
3149{
3150	struct basic_block_link *link, *tmp;
3151
3152	list_for_each_entry_safe(link, tmp, &bb_data->queue, node) {
3153		list_del(&link->node);
3154		zfree(&link->bb);
3155		free(link);
3156	}
3157
3158	list_for_each_entry_safe(link, tmp, &bb_data->visited, node) {
3159		list_del(&link->node);
3160		zfree(&link->bb);
3161		free(link);
3162	}
3163}
3164
3165/**
3166 * annotate_get_basic_blocks - Get basic blocks for given address range
3167 * @sym: symbol to annotate
3168 * @src: source address
3169 * @dst: destination address
3170 * @head: list head to save basic blocks
3171 *
3172 * This function traverses disasm_lines from @src to @dst and save them in a
3173 * list of annotated_basic_block to @head.  It uses BFS to find the shortest
3174 * path between two.  The basic_block_link is to maintain parent links so
3175 * that it can build a list of blocks from the start.
3176 */
3177int annotate_get_basic_blocks(struct symbol *sym, s64 src, s64 dst,
3178			      struct list_head *head)
3179{
3180	struct basic_block_data bb_data = {
3181		.queue = LIST_HEAD_INIT(bb_data.queue),
3182		.visited = LIST_HEAD_INIT(bb_data.visited),
3183	};
3184	struct basic_block_link *link;
3185	struct disasm_line *dl;
3186	int ret = -1;
3187
3188	dl = find_disasm_line(sym, src, /*allow_update=*/false);
3189	if (dl == NULL)
3190		return -1;
3191
3192	if (add_basic_block(&bb_data, /*parent=*/NULL, dl) < 0)
3193		return -1;
3194
3195	/* Find shortest path from src to dst using BFS */
3196	while (!list_empty(&bb_data.queue)) {
3197		link = list_first_entry(&bb_data.queue, struct basic_block_link, node);
3198
3199		if (process_basic_block(&bb_data, link, sym, dst)) {
3200			link_found_basic_blocks(link, head);
3201			ret = 0;
3202			break;
3203		}
3204		list_move(&link->node, &bb_data.visited);
3205	}
3206	delete_basic_blocks(&bb_data);
3207	return ret;
3208}
~/ Read-only file preview.