newt.c 16.5 KB
Newer Older
1 2 3 4 5 6
#define _GNU_SOURCE
#include <stdio.h>
#undef _GNU_SOURCE

#include <stdlib.h>
#include <newt.h>
7
#include <sys/ttydefaults.h>
8 9 10 11 12 13 14

#include "cache.h"
#include "hist.h"
#include "session.h"
#include "sort.h"
#include "symbol.h"

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
struct ui_progress {
	newtComponent form, scale;
};

struct ui_progress *ui_progress__new(const char *title, u64 total)
{
	struct ui_progress *self = malloc(sizeof(*self));

	if (self != NULL) {
		int cols;
		newtGetScreenSize(&cols, NULL);
		cols -= 4;
		newtCenteredWindow(cols, 1, title);
		self->form  = newtForm(NULL, NULL, 0);
		if (self->form == NULL)
			goto out_free_self;
		self->scale = newtScale(0, 0, cols, total);
		if (self->scale == NULL)
			goto out_free_form;
34
		newtFormAddComponent(self->form, self->scale);
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
		newtRefresh();
	}

	return self;

out_free_form:
	newtFormDestroy(self->form);
out_free_self:
	free(self);
	return NULL;
}

void ui_progress__update(struct ui_progress *self, u64 curr)
{
	newtScaleSet(self->scale, curr);
	newtRefresh();
}

void ui_progress__delete(struct ui_progress *self)
{
	newtFormDestroy(self->form);
	newtPopWindow();
	free(self);
}

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
static void ui_helpline__pop(void)
{
	newtPopHelpLine();
}

static void ui_helpline__push(const char *msg)
{
	newtPushHelpLine(msg);
}

static void ui_helpline__vpush(const char *fmt, va_list ap)
{
	char *s;

	if (vasprintf(&s, fmt, ap) < 0)
		vfprintf(stderr, fmt, ap);
	else {
		ui_helpline__push(s);
		free(s);
	}
}

static void ui_helpline__fpush(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	ui_helpline__vpush(fmt, ap);
	va_end(ap);
}

static void ui_helpline__puts(const char *msg)
{
	ui_helpline__pop();
	ui_helpline__push(msg);
}

97 98 99 100 101 102 103 104 105 106 107 108
static char browser__last_msg[1024];

int browser__show_help(const char *format, va_list ap)
{
	int ret;
	static int backlog;

        ret = vsnprintf(browser__last_msg + backlog,
			sizeof(browser__last_msg) - backlog, format, ap);
	backlog += ret;

	if (browser__last_msg[backlog - 1] == '\n') {
109
		ui_helpline__puts(browser__last_msg);
110 111 112 113 114 115 116
		newtRefresh();
		backlog = 0;
	}

	return ret;
}

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
static void newt_form__set_exit_keys(newtComponent self)
{
	newtFormAddHotKey(self, NEWT_KEY_ESCAPE);
	newtFormAddHotKey(self, 'Q');
	newtFormAddHotKey(self, 'q');
	newtFormAddHotKey(self, CTRL('c'));
}

static newtComponent newt_form__new(void)
{
	newtComponent self = newtForm(NULL, NULL, 0);
	if (self)
		newt_form__set_exit_keys(self);
	return self;
}

133
static int popup_menu(int argc, char * const argv[])
134 135 136 137 138 139 140 141 142 143 144 145
{
	struct newtExitStruct es;
	int i, rc = -1, max_len = 5;
	newtComponent listbox, form = newt_form__new();

	if (form == NULL)
		return -1;

	listbox = newtListbox(0, 0, argc, NEWT_FLAG_RETURNEXIT);
	if (listbox == NULL)
		goto out_destroy_form;

146
	newtFormAddComponent(form, listbox);
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

	for (i = 0; i < argc; ++i) {
		int len = strlen(argv[i]);
		if (len > max_len)
			max_len = len;
		if (newtListboxAddEntry(listbox, argv[i], (void *)(long)i))
			goto out_destroy_form;
	}

	newtCenteredWindow(max_len, argc, NULL);
	newtFormRun(form, &es);
	rc = newtListboxGetCurrent(listbox) - NULL;
	if (es.reason == NEWT_EXIT_HOTKEY)
		rc = -1;
	newtPopWindow();
out_destroy_form:
	newtFormDestroy(form);
	return rc;
}

static bool dialog_yesno(const char *msg)
{
	/* newtWinChoice should really be accepting const char pointers... */
	char yes[] = "Yes", no[] = "No";
171
	return newtWinChoice(NULL, yes, no, (char *)msg) == 1;
172 173
}

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
/*
 * When debugging newt problems it was useful to be able to "unroll"
 * the calls to newtCheckBoxTreeAdd{Array,Item}, so that we can generate
 * a source file with the sequence of calls to these methods, to then
 * tweak the arrays to get the intended results, so I'm keeping this code
 * here, may be useful again in the future.
 */
#undef NEWT_DEBUG

static void newt_checkbox_tree__add(newtComponent tree, const char *str,
				    void *priv, int *indexes)
{
#ifdef NEWT_DEBUG
	/* Print the newtCheckboxTreeAddArray to tinker with its index arrays */
	int i = 0, len = 40 - strlen(str);

	fprintf(stderr,
		"\tnewtCheckboxTreeAddItem(tree, %*.*s\"%s\", (void *)%p, 0, ",
		len, len, " ", str, priv);
	while (indexes[i] != NEWT_ARG_LAST) {
		if (indexes[i] != NEWT_ARG_APPEND)
			fprintf(stderr, " %d,", indexes[i]);
		else
			fprintf(stderr, " %s,", "NEWT_ARG_APPEND");
		++i;
	}
	fprintf(stderr, " %s", " NEWT_ARG_LAST);\n");
	fflush(stderr);
#endif
	newtCheckboxTreeAddArray(tree, str, priv, 0, indexes);
}

static char *callchain_list__sym_name(struct callchain_list *self,
				      char *bf, size_t bfsize)
{
209 210
	if (self->ms.sym)
		return self->ms.sym->name;
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

	snprintf(bf, bfsize, "%#Lx", self->ip);
	return bf;
}

static void __callchain__append_graph_browser(struct callchain_node *self,
					      newtComponent tree, u64 total,
					      int *indexes, int depth)
{
	struct rb_node *node;
	u64 new_total, remaining;
	int idx = 0;

	if (callchain_param.mode == CHAIN_GRAPH_REL)
		new_total = self->children_hit;
	else
		new_total = total;

	remaining = new_total;
	node = rb_first(&self->rb_root);
	while (node) {
		struct callchain_node *child = rb_entry(node, struct callchain_node, rb_node);
		struct rb_node *next = rb_next(node);
		u64 cumul = cumul_hits(child);
		struct callchain_list *chain;
		int first = true, printed = 0;
		int chain_idx = -1;
		remaining -= cumul;

		indexes[depth] = NEWT_ARG_APPEND;
		indexes[depth + 1] = NEWT_ARG_LAST;

		list_for_each_entry(chain, &child->val, list) {
			char ipstr[BITS_PER_LONG / 4 + 1],
			     *alloc_str = NULL;
			const char *str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));

			if (first) {
				double percent = cumul * 100.0 / new_total;

				first = false;
				if (asprintf(&alloc_str, "%2.2f%% %s", percent, str) < 0)
					str = "Not enough memory!";
				else
					str = alloc_str;
			} else {
				indexes[depth] = idx;
				indexes[depth + 1] = NEWT_ARG_APPEND;
				indexes[depth + 2] = NEWT_ARG_LAST;
				++chain_idx;
			}
262
			newt_checkbox_tree__add(tree, str, &chain->ms, indexes);
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
			free(alloc_str);
			++printed;
		}

		indexes[depth] = idx;
		if (chain_idx != -1)
			indexes[depth + 1] = chain_idx;
		if (printed != 0)
			++idx;
		__callchain__append_graph_browser(child, tree, new_total, indexes,
						  depth + (chain_idx != -1 ? 2 : 1));
		node = next;
	}
}

static void callchain__append_graph_browser(struct callchain_node *self,
					    newtComponent tree, u64 total,
					    int *indexes, int parent_idx)
{
	struct callchain_list *chain;
	int i = 0;

	indexes[1] = NEWT_ARG_APPEND;
	indexes[2] = NEWT_ARG_LAST;

	list_for_each_entry(chain, &self->val, list) {
		char ipstr[BITS_PER_LONG / 4 + 1], *str;

		if (chain->ip >= PERF_CONTEXT_MAX)
			continue;

		if (!i++ && sort__first_dimension == SORT_SYM)
			continue;

		str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));
298
		newt_checkbox_tree__add(tree, str, &chain->ms, indexes);
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
	}

	indexes[1] = parent_idx;
	indexes[2] = NEWT_ARG_APPEND;
	indexes[3] = NEWT_ARG_LAST;
	__callchain__append_graph_browser(self, tree, total, indexes, 2);
}

static void hist_entry__append_callchain_browser(struct hist_entry *self,
						 newtComponent tree, u64 total, int parent_idx)
{
	struct rb_node *rb_node;
	int indexes[1024] = { [0] = parent_idx, };
	int idx = 0;
	struct callchain_node *chain;

	rb_node = rb_first(&self->sorted_chain);
	while (rb_node) {
		chain = rb_entry(rb_node, struct callchain_node, rb_node);
		switch (callchain_param.mode) {
		case CHAIN_FLAT:
			break;
		case CHAIN_GRAPH_ABS: /* falldown */
		case CHAIN_GRAPH_REL:
			callchain__append_graph_browser(chain, tree, total, indexes, idx++);
			break;
		case CHAIN_NONE:
		default:
			break;
		}
		rb_node = rb_next(rb_node);
	}
}

333
static size_t hist_entry__append_browser(struct hist_entry *self,
334
					 newtComponent tree, u64 total)
335
{
336 337
	char s[256];
	size_t ret;
338 339 340 341

	if (symbol_conf.exclude_other && !self->parent)
		return 0;

342 343
	ret = hist_entry__snprintf(self, s, sizeof(s), NULL,
				   false, 0, false, total);
344 345 346 347 348
	if (symbol_conf.use_callchain) {
		int indexes[2];

		indexes[0] = NEWT_ARG_APPEND;
		indexes[1] = NEWT_ARG_LAST;
349
		newt_checkbox_tree__add(tree, s, &self->ms, indexes);
350
	} else
351
		newtListboxAppendEntry(tree, s, &self->ms);
352

353
	return ret;
354 355
}

356 357
static void map_symbol__annotate_browser(const struct map_symbol *self,
					 const char *input_name)
358 359
{
	FILE *fp;
360
	int cols, rows;
361
	newtComponent form, tree;
362 363 364 365 366 367
	struct newtExitStruct es;
	char *str;
	size_t line_len, max_line_len = 0;
	size_t max_usable_width;
	char *line = NULL;

368
	if (self->sym == NULL)
369 370
		return;

371 372
	if (asprintf(&str, "perf annotate -i \"%s\" -d \"%s\" %s 2>&1 | expand",
		     input_name, self->map->dso->name, self->sym->name) < 0)
373 374 375 376 377 378
		return;

	fp = popen(str, "r");
	if (fp == NULL)
		goto out_free_str;

379
	ui_helpline__push("Press ESC to exit");
380
	newtGetScreenSize(&cols, &rows);
381
	tree = newtListbox(0, 0, rows - 5, NEWT_FLAG_SCROLL);
382 383 384 385 386 387 388 389 390

	while (!feof(fp)) {
		if (getline(&line, &line_len, fp) < 0 || !line_len)
			break;
		while (line_len != 0 && isspace(line[line_len - 1]))
			line[--line_len] = '\0';

		if (line_len > max_line_len)
			max_line_len = line_len;
391
		newtListboxAppendEntry(tree, line, NULL);
392 393 394 395
	}
	fclose(fp);
	free(line);

396
	max_usable_width = cols - 22;
397 398 399
	if (max_line_len > max_usable_width)
		max_line_len = max_usable_width;

400
	newtListboxSetWidth(tree, max_line_len);
401

402
	newtCenteredWindow(max_line_len + 2, rows - 5, self->sym->name);
403
	form = newt_form__new();
404
	newtFormAddComponent(form, tree);
405 406 407 408

	newtFormRun(form, &es);
	newtFormDestroy(form);
	newtPopWindow();
409
	ui_helpline__pop();
410 411 412 413
out_free_str:
	free(str);
}

414 415 416 417 418 419 420
static const void *newt__symbol_tree_get_current(newtComponent self)
{
	if (symbol_conf.use_callchain)
		return newtCheckboxTreeGetCurrent(self);
	return newtListboxGetCurrent(self);
}

421
static void hist_browser__selection(newtComponent self, void *data)
422
{
423
	const struct map_symbol **symbol_ptr = data;
424 425 426
	*symbol_ptr = newt__symbol_tree_get_current(self);
}

427 428 429 430 431 432 433 434 435
struct hist_browser {
	newtComponent		form, tree;
	const struct map_symbol *selection;
};

static struct hist_browser *hist_browser__new(void)
{
	struct hist_browser *self = malloc(sizeof(*self));

436 437
	if (self != NULL)
		self->form = NULL;
438 439 440 441 442 443 444 445 446 447 448

	return self;
}

static void hist_browser__delete(struct hist_browser *self)
{
	newtFormDestroy(self->form);
	newtPopWindow();
	free(self);
}

449 450
static int hist_browser__populate(struct hist_browser *self, struct hists *hists,
				  const char *title)
451
{
452 453
	int max_len = 0, idx, cols, rows;
	struct ui_progress *progress;
454
	struct rb_node *nd;
455
	u64 curr_hist = 0;
456 457 458 459 460 461 462 463 464
	char seq[] = ".";
	char str[256];

	if (self->form) {
		newtFormDestroy(self->form);
		newtPopWindow();
	}

	snprintf(str, sizeof(str), "Samples: %Ld                            ",
465
		 hists->stats.total);
466 467 468 469 470 471 472 473 474 475 476 477 478 479
	newtDrawRootText(0, 0, str);

	newtGetScreenSize(NULL, &rows);

	if (symbol_conf.use_callchain)
		self->tree = newtCheckboxTreeMulti(0, 0, rows - 5, seq,
						   NEWT_FLAG_SCROLL);
	else
		self->tree = newtListbox(0, 0, rows - 5,
					(NEWT_FLAG_SCROLL |
					 NEWT_FLAG_RETURNEXIT));

	newtComponentAddCallback(self->tree, hist_browser__selection,
				 &self->selection);
480

481 482
	progress = ui_progress__new("Adding entries to the browser...",
				    hists->nr_entries);
483 484
	if (progress == NULL)
		return -1;
485

486
	idx = 0;
487
	for (nd = rb_first(&hists->entries); nd; nd = rb_next(nd)) {
488
		struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
489 490 491 492 493
		int len;

		if (h->filtered)
			continue;

494
		len = hist_entry__append_browser(h, self->tree, hists->stats.total);
495 496
		if (len > max_len)
			max_len = len;
497
		if (symbol_conf.use_callchain)
498
			hist_entry__append_callchain_browser(h, self->tree,
499
							     hists->stats.total, idx++);
500 501 502
		++curr_hist;
		if (curr_hist % 5)
			ui_progress__update(progress, curr_hist);
503 504
	}

505 506
	ui_progress__delete(progress);

507 508
	newtGetScreenSize(&cols, &rows);

509 510 511 512
	if (max_len > cols)
		max_len = cols - 3;

	if (!symbol_conf.use_callchain)
513
		newtListboxSetWidth(self->tree, max_len);
514 515

	newtCenteredWindow(max_len + (symbol_conf.use_callchain ? 5 : 0),
516
			   rows - 5, title);
517
	self->form = newt_form__new();
518 519 520
	if (self->form == NULL)
		return -1;

521 522 523 524 525 526 527 528 529
	newtFormAddHotKey(self->form, 'A');
	newtFormAddHotKey(self->form, 'a');
	newtFormAddHotKey(self->form, NEWT_KEY_RIGHT);
	newtFormAddComponents(self->form, self->tree, NULL);
	self->selection = newt__symbol_tree_get_current(self->tree);

	return 0;
}

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
static struct thread *hist_browser__selected_thread(struct hist_browser *self)
{
	int *indexes;

	if (!symbol_conf.use_callchain)
		goto out;

	indexes = newtCheckboxTreeFindItem(self->tree, (void *)self->selection);
	if (indexes) {
		bool is_hist_entry = indexes[1] == NEWT_ARG_LAST;
		free(indexes);
		if (is_hist_entry)
			goto out;
	}
	return NULL;
out:
	return *(struct thread **)(self->selection + 1);
}

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
static int hist_browser__title(char *bf, size_t size, const char *input_name,
			       const struct dso *dso, const struct thread *thread)
{
	int printed = 0;

	if (thread)
		printed += snprintf(bf + printed, size - printed,
				    "Thread: %s(%d)",
				    (thread->comm_set ?  thread->comm : ""),
				    thread->pid);
	if (dso)
		printed += snprintf(bf + printed, size - printed,
				    "%sDSO: %s", thread ? " " : "",
				    dso->short_name);
	return printed ?: snprintf(bf, size, "Report: %s", input_name);
}

566
int hists__browse(struct hists *self, const char *helpline, const char *input_name)
567
{
568 569 570
	struct hist_browser *browser = hist_browser__new();
	const struct thread *thread_filter = NULL;
	const struct dso *dso_filter = NULL;
571
	struct newtExitStruct es;
572
	char msg[160];
573 574 575 576 577
	int err = -1;

	if (browser == NULL)
		return -1;

578
	ui_helpline__push(helpline);
579

580 581
	hist_browser__title(msg, sizeof(msg), input_name,
			    dso_filter, thread_filter);
582
	if (hist_browser__populate(browser, self, msg) < 0)
583
		goto out;
584 585

	while (1) {
586
		const struct thread *thread;
587
		const struct dso *dso;
588 589
		char *options[16];
		int nr_options = 0, choice = 0, i,
590
		    annotate = -2, zoom_dso = -2, zoom_thread = -2;
591

592
		newtFormRun(browser->form, &es);
593
		if (es.reason == NEWT_EXIT_HOTKEY) {
594 595
			if (toupper(es.u.key) == 'A')
				goto do_annotate;
596 597 598 599 600 601 602 603 604 605
			if (es.u.key == NEWT_KEY_ESCAPE ||
			    toupper(es.u.key) == 'Q' ||
			    es.u.key == CTRL('c')) {
				if (dialog_yesno("Do you really want to exit?"))
					break;
				else
					continue;
			}
		}

606 607 608 609 610
		if (browser->selection->sym != NULL &&
		    asprintf(&options[nr_options], "Annotate %s",
			     browser->selection->sym->name) > 0)
			annotate = nr_options++;

611 612 613
		thread = hist_browser__selected_thread(browser);
		if (thread != NULL &&
		    asprintf(&options[nr_options], "Zoom %s %s(%d) thread",
614 615 616
			     (thread_filter ? "out of" : "into"),
			     (thread->comm_set ? thread->comm : ""),
			     thread->pid) > 0)
617 618
			zoom_thread = nr_options++;

619 620 621 622 623 624 625
		dso = browser->selection->map ? browser->selection->map->dso : NULL;
		if (dso != NULL &&
		    asprintf(&options[nr_options], "Zoom %s %s DSO",
			     (dso_filter ? "out of" : "into"),
			     (dso->kernel ? "the Kernel" : dso->short_name)) > 0)
			zoom_dso = nr_options++;

626
		options[nr_options++] = (char *)"Exit";
627 628

		choice = popup_menu(nr_options, options);
629 630 631 632

		for (i = 0; i < nr_options - 1; ++i)
			free(options[i]);

633
		if (choice == nr_options - 1)
634
			break;
635 636 637

		if (choice == -1)
			continue;
638
do_annotate:
639
		if (choice == annotate) {
640
			if (browser->selection->map->dso->origin == DSO__ORIG_KERNEL) {
641
				ui_helpline__puts("No vmlinux file found, can't "
642 643 644 645
						 "annotate with just a "
						 "kallsyms file");
				continue;
			}
646
			map_symbol__annotate_browser(browser->selection, input_name);
647
		} else if (choice == zoom_dso) {
648
			if (dso_filter) {
649
				ui_helpline__pop();
650 651
				dso_filter = NULL;
			} else {
652 653
				ui_helpline__fpush("To zoom out press -> + \"Zoom out of %s DSO\"",
						   dso->kernel ? "the Kernel" : dso->short_name);
654 655
				dso_filter = dso;
			}
656
			hists__filter_by_dso(self, dso_filter);
657 658
			hist_browser__title(msg, sizeof(msg), input_name,
					    dso_filter, thread_filter);
659
			if (hist_browser__populate(browser, self, msg) < 0)
660
				goto out;
661
		} else if (choice == zoom_thread) {
662
			if (thread_filter) {
663
				ui_helpline__pop();
664 665
				thread_filter = NULL;
			} else {
666 667 668
				ui_helpline__fpush("To zoom out press -> + \"Zoom out of %s(%d) thread\"",
						   thread->comm_set ? thread->comm : "",
						   thread->pid);
669 670
				thread_filter = thread;
			}
671
			hists__filter_by_thread(self, thread_filter);
672 673
			hist_browser__title(msg, sizeof(msg), input_name,
					    dso_filter, thread_filter);
674
			if (hist_browser__populate(browser, self, msg) < 0)
675
				goto out;
676
		}
677
	}
678 679 680 681
	err = 0;
out:
	hist_browser__delete(browser);
	return err;
682 683 684 685 686 687 688 689 690 691
}

void setup_browser(void)
{
	if (!isatty(1))
		return;

	use_browser = true;
	newtInit();
	newtCls();
692
	ui_helpline__puts(" ");
693 694
}

695
void exit_browser(bool wait_for_ok)
696
{
697 698 699 700 701
	if (use_browser) {
		if (wait_for_ok) {
			char title[] = "Fatal Error", ok[] = "Ok";
			newtWinMessage(title, ok, browser__last_msg);
		}
702
		newtFinished();
703
	}
704
}