xref: /linux/tools/perf/util/disasm.c (revision 83e5b8f9bf2edfa1aac0d09d994792da594fec56)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <ctype.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <inttypes.h>
6 #include <libgen.h>
7 #include <regex.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 
11 #include <linux/string.h>
12 #include <subcmd/run-command.h>
13 
14 #include "annotate.h"
15 #include "annotate-data.h"
16 #include "build-id.h"
17 #include "debug.h"
18 #include "disasm.h"
19 #include "disasm_bpf.h"
20 #include "dso.h"
21 #include "dwarf-regs.h"
22 #include "env.h"
23 #include "evsel.h"
24 #include "map.h"
25 #include "maps.h"
26 #include "namespaces.h"
27 #include "srcline.h"
28 #include "symbol.h"
29 #include "util.h"
30 
31 static regex_t	 file_lineno;
32 
33 /* These can be referred from the arch-dependent code */
34 static struct ins_ops call_ops;
35 static struct ins_ops dec_ops;
36 static struct ins_ops jump_ops;
37 static struct ins_ops mov_ops;
38 static struct ins_ops nop_ops;
39 static struct ins_ops lock_ops;
40 static struct ins_ops ret_ops;
41 static struct ins_ops load_store_ops;
42 static struct ins_ops arithmetic_ops;
43 
44 static int jump__scnprintf(struct ins *ins, char *bf, size_t size,
45 			   struct ins_operands *ops, int max_ins_name);
46 static int call__scnprintf(struct ins *ins, char *bf, size_t size,
47 			   struct ins_operands *ops, int max_ins_name);
48 
49 static void ins__sort(struct arch *arch);
50 static int disasm_line__parse(char *line, const char **namep, char **rawp);
51 static int disasm_line__parse_powerpc(struct disasm_line *dl, struct annotate_args *args);
52 static char *expand_tabs(char *line, char **storage, size_t *storage_len);
53 
54 static __attribute__((constructor)) void symbol__init_regexpr(void)
55 {
56 	regcomp(&file_lineno, "^/[^:]+:([0-9]+)", REG_EXTENDED);
57 }
58 
59 static int arch__grow_instructions(struct arch *arch)
60 {
61 	struct ins *new_instructions;
62 	size_t new_nr_allocated;
63 
64 	if (arch->nr_instructions_allocated == 0 && arch->instructions)
65 		goto grow_from_non_allocated_table;
66 
67 	new_nr_allocated = arch->nr_instructions_allocated + 128;
68 	new_instructions = realloc(arch->instructions, new_nr_allocated * sizeof(struct ins));
69 	if (new_instructions == NULL)
70 		return -1;
71 
72 out_update_instructions:
73 	arch->instructions = new_instructions;
74 	arch->nr_instructions_allocated = new_nr_allocated;
75 	return 0;
76 
77 grow_from_non_allocated_table:
78 	new_nr_allocated = arch->nr_instructions + 128;
79 	new_instructions = calloc(new_nr_allocated, sizeof(struct ins));
80 	if (new_instructions == NULL)
81 		return -1;
82 
83 	memcpy(new_instructions, arch->instructions, arch->nr_instructions);
84 	goto out_update_instructions;
85 }
86 
87 static int arch__associate_ins_ops(struct arch* arch, const char *name, struct ins_ops *ops)
88 {
89 	struct ins *ins;
90 
91 	if (arch->nr_instructions == arch->nr_instructions_allocated &&
92 	    arch__grow_instructions(arch))
93 		return -1;
94 
95 	ins = &arch->instructions[arch->nr_instructions];
96 	ins->name = strdup(name);
97 	if (!ins->name)
98 		return -1;
99 
100 	ins->ops  = ops;
101 	arch->nr_instructions++;
102 
103 	ins__sort(arch);
104 	return 0;
105 }
106 
107 #include "arch/arc/annotate/instructions.c"
108 #include "arch/arm/annotate/instructions.c"
109 #include "arch/arm64/annotate/instructions.c"
110 #include "arch/csky/annotate/instructions.c"
111 #include "arch/loongarch/annotate/instructions.c"
112 #include "arch/mips/annotate/instructions.c"
113 #include "arch/x86/annotate/instructions.c"
114 #include "arch/powerpc/annotate/instructions.c"
115 #include "arch/riscv64/annotate/instructions.c"
116 #include "arch/s390/annotate/instructions.c"
117 #include "arch/sparc/annotate/instructions.c"
118 
119 static struct arch architectures[] = {
120 	{
121 		.name = "arc",
122 		.init = arc__annotate_init,
123 	},
124 	{
125 		.name = "arm",
126 		.init = arm__annotate_init,
127 	},
128 	{
129 		.name = "arm64",
130 		.init = arm64__annotate_init,
131 	},
132 	{
133 		.name = "csky",
134 		.init = csky__annotate_init,
135 	},
136 	{
137 		.name = "mips",
138 		.init = mips__annotate_init,
139 		.objdump = {
140 			.comment_char = '#',
141 		},
142 	},
143 	{
144 		.name = "x86",
145 		.init = x86__annotate_init,
146 		.instructions = x86__instructions,
147 		.nr_instructions = ARRAY_SIZE(x86__instructions),
148 		.insn_suffix = "bwlq",
149 		.objdump =  {
150 			.comment_char = '#',
151 			.register_char = '%',
152 			.memory_ref_char = '(',
153 			.imm_char = '$',
154 		},
155 #ifdef HAVE_LIBDW_SUPPORT
156 		.update_insn_state = update_insn_state_x86,
157 #endif
158 	},
159 	{
160 		.name = "powerpc",
161 		.init = powerpc__annotate_init,
162 #ifdef HAVE_LIBDW_SUPPORT
163 		.update_insn_state = update_insn_state_powerpc,
164 #endif
165 	},
166 	{
167 		.name = "riscv64",
168 		.init = riscv64__annotate_init,
169 	},
170 	{
171 		.name = "s390",
172 		.init = s390__annotate_init,
173 		.objdump =  {
174 			.comment_char = '#',
175 		},
176 	},
177 	{
178 		.name = "sparc",
179 		.init = sparc__annotate_init,
180 		.objdump = {
181 			.comment_char = '#',
182 		},
183 	},
184 	{
185 		.name = "loongarch",
186 		.init = loongarch__annotate_init,
187 		.objdump = {
188 			.comment_char = '#',
189 		},
190 	},
191 };
192 
193 static int arch__key_cmp(const void *name, const void *archp)
194 {
195 	const struct arch *arch = archp;
196 
197 	return strcmp(name, arch->name);
198 }
199 
200 static int arch__cmp(const void *a, const void *b)
201 {
202 	const struct arch *aa = a;
203 	const struct arch *ab = b;
204 
205 	return strcmp(aa->name, ab->name);
206 }
207 
208 static void arch__sort(void)
209 {
210 	const int nmemb = ARRAY_SIZE(architectures);
211 
212 	qsort(architectures, nmemb, sizeof(struct arch), arch__cmp);
213 }
214 
215 struct arch *arch__find(const char *name)
216 {
217 	const int nmemb = ARRAY_SIZE(architectures);
218 	static bool sorted;
219 
220 	if (!sorted) {
221 		arch__sort();
222 		sorted = true;
223 	}
224 
225 	return bsearch(name, architectures, nmemb, sizeof(struct arch), arch__key_cmp);
226 }
227 
228 bool arch__is(struct arch *arch, const char *name)
229 {
230 	return !strcmp(arch->name, name);
231 }
232 
233 static void ins_ops__delete(struct ins_operands *ops)
234 {
235 	if (ops == NULL)
236 		return;
237 	zfree(&ops->source.raw);
238 	zfree(&ops->source.name);
239 	zfree(&ops->target.raw);
240 	zfree(&ops->target.name);
241 }
242 
243 static int ins__raw_scnprintf(struct ins *ins, char *bf, size_t size,
244 			      struct ins_operands *ops, int max_ins_name)
245 {
246 	return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name, ops->raw);
247 }
248 
249 int ins__scnprintf(struct ins *ins, char *bf, size_t size,
250 		   struct ins_operands *ops, int max_ins_name)
251 {
252 	if (ins->ops->scnprintf)
253 		return ins->ops->scnprintf(ins, bf, size, ops, max_ins_name);
254 
255 	return ins__raw_scnprintf(ins, bf, size, ops, max_ins_name);
256 }
257 
258 bool ins__is_fused(struct arch *arch, const char *ins1, const char *ins2)
259 {
260 	if (!arch || !arch->ins_is_fused)
261 		return false;
262 
263 	return arch->ins_is_fused(arch, ins1, ins2);
264 }
265 
266 static int call__parse(struct arch *arch, struct ins_operands *ops, struct map_symbol *ms,
267 		struct disasm_line *dl __maybe_unused)
268 {
269 	char *endptr, *tok, *name;
270 	struct map *map = ms->map;
271 	struct addr_map_symbol target = {
272 		.ms = { .map = map, },
273 	};
274 
275 	ops->target.addr = strtoull(ops->raw, &endptr, 16);
276 
277 	name = strchr(endptr, '<');
278 	if (name == NULL)
279 		goto indirect_call;
280 
281 	name++;
282 
283 	if (arch->objdump.skip_functions_char &&
284 	    strchr(name, arch->objdump.skip_functions_char))
285 		return -1;
286 
287 	tok = strchr(name, '>');
288 	if (tok == NULL)
289 		return -1;
290 
291 	*tok = '\0';
292 	ops->target.name = strdup(name);
293 	*tok = '>';
294 
295 	if (ops->target.name == NULL)
296 		return -1;
297 find_target:
298 	target.addr = map__objdump_2mem(map, ops->target.addr);
299 
300 	if (maps__find_ams(ms->maps, &target) == 0 &&
301 	    map__rip_2objdump(target.ms.map, map__map_ip(target.ms.map, target.addr)) == ops->target.addr)
302 		ops->target.sym = target.ms.sym;
303 
304 	return 0;
305 
306 indirect_call:
307 	tok = strchr(endptr, '*');
308 	if (tok != NULL) {
309 		endptr++;
310 
311 		/* Indirect call can use a non-rip register and offset: callq  *0x8(%rbx).
312 		 * Do not parse such instruction.  */
313 		if (strstr(endptr, "(%r") == NULL)
314 			ops->target.addr = strtoull(endptr, NULL, 16);
315 	}
316 	goto find_target;
317 }
318 
319 static int call__scnprintf(struct ins *ins, char *bf, size_t size,
320 			   struct ins_operands *ops, int max_ins_name)
321 {
322 	if (ops->target.sym)
323 		return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name, ops->target.sym->name);
324 
325 	if (ops->target.addr == 0)
326 		return ins__raw_scnprintf(ins, bf, size, ops, max_ins_name);
327 
328 	if (ops->target.name)
329 		return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name, ops->target.name);
330 
331 	return scnprintf(bf, size, "%-*s *%" PRIx64, max_ins_name, ins->name, ops->target.addr);
332 }
333 
334 static struct ins_ops call_ops = {
335 	.parse	   = call__parse,
336 	.scnprintf = call__scnprintf,
337 };
338 
339 bool ins__is_call(const struct ins *ins)
340 {
341 	return ins->ops == &call_ops || ins->ops == &s390_call_ops || ins->ops == &loongarch_call_ops;
342 }
343 
344 /*
345  * Prevents from matching commas in the comment section, e.g.:
346  * ffff200008446e70:       b.cs    ffff2000084470f4 <generic_exec_single+0x314>  // b.hs, b.nlast
347  *
348  * and skip comma as part of function arguments, e.g.:
349  * 1d8b4ac <linemap_lookup(line_maps const*, unsigned int)+0xcc>
350  */
351 static inline const char *validate_comma(const char *c, struct ins_operands *ops)
352 {
353 	if (ops->jump.raw_comment && c > ops->jump.raw_comment)
354 		return NULL;
355 
356 	if (ops->jump.raw_func_start && c > ops->jump.raw_func_start)
357 		return NULL;
358 
359 	return c;
360 }
361 
362 static int jump__parse(struct arch *arch, struct ins_operands *ops, struct map_symbol *ms,
363 		struct disasm_line *dl __maybe_unused)
364 {
365 	struct map *map = ms->map;
366 	struct symbol *sym = ms->sym;
367 	struct addr_map_symbol target = {
368 		.ms = { .map = map, },
369 	};
370 	const char *c = strchr(ops->raw, ',');
371 	u64 start, end;
372 
373 	ops->jump.raw_comment = strchr(ops->raw, arch->objdump.comment_char);
374 	ops->jump.raw_func_start = strchr(ops->raw, '<');
375 
376 	c = validate_comma(c, ops);
377 
378 	/*
379 	 * Examples of lines to parse for the _cpp_lex_token@@Base
380 	 * function:
381 	 *
382 	 * 1159e6c: jne    115aa32 <_cpp_lex_token@@Base+0xf92>
383 	 * 1159e8b: jne    c469be <cpp_named_operator2name@@Base+0xa72>
384 	 *
385 	 * The first is a jump to an offset inside the same function,
386 	 * the second is to another function, i.e. that 0xa72 is an
387 	 * offset in the cpp_named_operator2name@@base function.
388 	 */
389 	/*
390 	 * skip over possible up to 2 operands to get to address, e.g.:
391 	 * tbnz	 w0, #26, ffff0000083cd190 <security_file_permission+0xd0>
392 	 */
393 	if (c != NULL) {
394 		c++;
395 		ops->target.addr = strtoull(c, NULL, 16);
396 		if (!ops->target.addr) {
397 			c = strchr(c, ',');
398 			c = validate_comma(c, ops);
399 			if (c != NULL) {
400 				c++;
401 				ops->target.addr = strtoull(c, NULL, 16);
402 			}
403 		}
404 	} else {
405 		ops->target.addr = strtoull(ops->raw, NULL, 16);
406 	}
407 
408 	target.addr = map__objdump_2mem(map, ops->target.addr);
409 	start = map__unmap_ip(map, sym->start);
410 	end = map__unmap_ip(map, sym->end);
411 
412 	ops->target.outside = target.addr < start || target.addr > end;
413 
414 	/*
415 	 * FIXME: things like this in _cpp_lex_token (gcc's cc1 program):
416 
417 		cpp_named_operator2name@@Base+0xa72
418 
419 	 * Point to a place that is after the cpp_named_operator2name
420 	 * boundaries, i.e.  in the ELF symbol table for cc1
421 	 * cpp_named_operator2name is marked as being 32-bytes long, but it in
422 	 * fact is much larger than that, so we seem to need a symbols__find()
423 	 * routine that looks for >= current->start and  < next_symbol->start,
424 	 * possibly just for C++ objects?
425 	 *
426 	 * For now lets just make some progress by marking jumps to outside the
427 	 * current function as call like.
428 	 *
429 	 * Actual navigation will come next, with further understanding of how
430 	 * the symbol searching and disassembly should be done.
431 	 */
432 	if (maps__find_ams(ms->maps, &target) == 0 &&
433 	    map__rip_2objdump(target.ms.map, map__map_ip(target.ms.map, target.addr)) == ops->target.addr)
434 		ops->target.sym = target.ms.sym;
435 
436 	if (!ops->target.outside) {
437 		ops->target.offset = target.addr - start;
438 		ops->target.offset_avail = true;
439 	} else {
440 		ops->target.offset_avail = false;
441 	}
442 
443 	return 0;
444 }
445 
446 static int jump__scnprintf(struct ins *ins, char *bf, size_t size,
447 			   struct ins_operands *ops, int max_ins_name)
448 {
449 	const char *c;
450 
451 	if (!ops->target.addr || ops->target.offset < 0)
452 		return ins__raw_scnprintf(ins, bf, size, ops, max_ins_name);
453 
454 	if (ops->target.outside && ops->target.sym != NULL)
455 		return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name, ops->target.sym->name);
456 
457 	c = strchr(ops->raw, ',');
458 	c = validate_comma(c, ops);
459 
460 	if (c != NULL) {
461 		const char *c2 = strchr(c + 1, ',');
462 
463 		c2 = validate_comma(c2, ops);
464 		/* check for 3-op insn */
465 		if (c2 != NULL)
466 			c = c2;
467 		c++;
468 
469 		/* mirror arch objdump's space-after-comma style */
470 		if (*c == ' ')
471 			c++;
472 	}
473 
474 	return scnprintf(bf, size, "%-*s %.*s%" PRIx64, max_ins_name,
475 			 ins->name, c ? c - ops->raw : 0, ops->raw,
476 			 ops->target.offset);
477 }
478 
479 static void jump__delete(struct ins_operands *ops __maybe_unused)
480 {
481 	/*
482 	 * The ops->jump.raw_comment and ops->jump.raw_func_start belong to the
483 	 * raw string, don't free them.
484 	 */
485 }
486 
487 static struct ins_ops jump_ops = {
488 	.free	   = jump__delete,
489 	.parse	   = jump__parse,
490 	.scnprintf = jump__scnprintf,
491 };
492 
493 bool ins__is_jump(const struct ins *ins)
494 {
495 	return ins->ops == &jump_ops || ins->ops == &loongarch_jump_ops;
496 }
497 
498 static int comment__symbol(char *raw, char *comment, u64 *addrp, char **namep)
499 {
500 	char *endptr, *name, *t;
501 
502 	if (strstr(raw, "(%rip)") == NULL)
503 		return 0;
504 
505 	*addrp = strtoull(comment, &endptr, 16);
506 	if (endptr == comment)
507 		return 0;
508 	name = strchr(endptr, '<');
509 	if (name == NULL)
510 		return -1;
511 
512 	name++;
513 
514 	t = strchr(name, '>');
515 	if (t == NULL)
516 		return 0;
517 
518 	*t = '\0';
519 	*namep = strdup(name);
520 	*t = '>';
521 
522 	return 0;
523 }
524 
525 static int lock__parse(struct arch *arch, struct ins_operands *ops, struct map_symbol *ms,
526 		struct disasm_line *dl __maybe_unused)
527 {
528 	ops->locked.ops = zalloc(sizeof(*ops->locked.ops));
529 	if (ops->locked.ops == NULL)
530 		return 0;
531 
532 	if (disasm_line__parse(ops->raw, &ops->locked.ins.name, &ops->locked.ops->raw) < 0)
533 		goto out_free_ops;
534 
535 	ops->locked.ins.ops = ins__find(arch, ops->locked.ins.name, 0);
536 
537 	if (ops->locked.ins.ops == NULL)
538 		goto out_free_ops;
539 
540 	if (ops->locked.ins.ops->parse &&
541 	    ops->locked.ins.ops->parse(arch, ops->locked.ops, ms, NULL) < 0)
542 		goto out_free_ops;
543 
544 	return 0;
545 
546 out_free_ops:
547 	zfree(&ops->locked.ops);
548 	return 0;
549 }
550 
551 static int lock__scnprintf(struct ins *ins, char *bf, size_t size,
552 			   struct ins_operands *ops, int max_ins_name)
553 {
554 	int printed;
555 
556 	if (ops->locked.ins.ops == NULL)
557 		return ins__raw_scnprintf(ins, bf, size, ops, max_ins_name);
558 
559 	printed = scnprintf(bf, size, "%-*s ", max_ins_name, ins->name);
560 	return printed + ins__scnprintf(&ops->locked.ins, bf + printed,
561 					size - printed, ops->locked.ops, max_ins_name);
562 }
563 
564 static void lock__delete(struct ins_operands *ops)
565 {
566 	struct ins *ins = &ops->locked.ins;
567 
568 	if (ins->ops && ins->ops->free)
569 		ins->ops->free(ops->locked.ops);
570 	else
571 		ins_ops__delete(ops->locked.ops);
572 
573 	zfree(&ops->locked.ops);
574 	zfree(&ops->locked.ins.name);
575 	zfree(&ops->target.raw);
576 	zfree(&ops->target.name);
577 }
578 
579 static struct ins_ops lock_ops = {
580 	.free	   = lock__delete,
581 	.parse	   = lock__parse,
582 	.scnprintf = lock__scnprintf,
583 };
584 
585 /*
586  * Check if the operand has more than one registers like x86 SIB addressing:
587  *   0x1234(%rax, %rbx, 8)
588  *
589  * But it doesn't care segment selectors like %gs:0x5678(%rcx), so just check
590  * the input string after 'memory_ref_char' if exists.
591  */
592 static bool check_multi_regs(struct arch *arch, const char *op)
593 {
594 	int count = 0;
595 
596 	if (arch->objdump.register_char == 0)
597 		return false;
598 
599 	if (arch->objdump.memory_ref_char) {
600 		op = strchr(op, arch->objdump.memory_ref_char);
601 		if (op == NULL)
602 			return false;
603 	}
604 
605 	while ((op = strchr(op, arch->objdump.register_char)) != NULL) {
606 		count++;
607 		op++;
608 	}
609 
610 	return count > 1;
611 }
612 
613 static int mov__parse(struct arch *arch, struct ins_operands *ops, struct map_symbol *ms __maybe_unused,
614 		struct disasm_line *dl __maybe_unused)
615 {
616 	char *s = strchr(ops->raw, ','), *target, *comment, prev;
617 
618 	if (s == NULL)
619 		return -1;
620 
621 	*s = '\0';
622 
623 	/*
624 	 * x86 SIB addressing has something like 0x8(%rax, %rcx, 1)
625 	 * then it needs to have the closing parenthesis.
626 	 */
627 	if (strchr(ops->raw, '(')) {
628 		*s = ',';
629 		s = strchr(ops->raw, ')');
630 		if (s == NULL || s[1] != ',')
631 			return -1;
632 		*++s = '\0';
633 	}
634 
635 	ops->source.raw = strdup(ops->raw);
636 	*s = ',';
637 
638 	if (ops->source.raw == NULL)
639 		return -1;
640 
641 	ops->source.multi_regs = check_multi_regs(arch, ops->source.raw);
642 
643 	target = skip_spaces(++s);
644 	comment = strchr(s, arch->objdump.comment_char);
645 
646 	if (comment != NULL)
647 		s = comment - 1;
648 	else
649 		s = strchr(s, '\0') - 1;
650 
651 	while (s > target && isspace(s[0]))
652 		--s;
653 	s++;
654 	prev = *s;
655 	*s = '\0';
656 
657 	ops->target.raw = strdup(target);
658 	*s = prev;
659 
660 	if (ops->target.raw == NULL)
661 		goto out_free_source;
662 
663 	ops->target.multi_regs = check_multi_regs(arch, ops->target.raw);
664 
665 	if (comment == NULL)
666 		return 0;
667 
668 	comment = skip_spaces(comment);
669 	comment__symbol(ops->source.raw, comment + 1, &ops->source.addr, &ops->source.name);
670 	comment__symbol(ops->target.raw, comment + 1, &ops->target.addr, &ops->target.name);
671 
672 	return 0;
673 
674 out_free_source:
675 	zfree(&ops->source.raw);
676 	return -1;
677 }
678 
679 static int mov__scnprintf(struct ins *ins, char *bf, size_t size,
680 			   struct ins_operands *ops, int max_ins_name)
681 {
682 	return scnprintf(bf, size, "%-*s %s,%s", max_ins_name, ins->name,
683 			 ops->source.name ?: ops->source.raw,
684 			 ops->target.name ?: ops->target.raw);
685 }
686 
687 static struct ins_ops mov_ops = {
688 	.parse	   = mov__parse,
689 	.scnprintf = mov__scnprintf,
690 };
691 
692 #define PPC_22_30(R)    (((R) >> 1) & 0x1ff)
693 #define MINUS_EXT_XO_FORM	234
694 #define SUB_EXT_XO_FORM		232
695 #define	ADD_ZERO_EXT_XO_FORM	202
696 #define	SUB_ZERO_EXT_XO_FORM	200
697 
698 static int arithmetic__scnprintf(struct ins *ins, char *bf, size_t size,
699 		struct ins_operands *ops, int max_ins_name)
700 {
701 	return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name,
702 			ops->raw);
703 }
704 
705 /*
706  * Sets the fields: multi_regs and "mem_ref".
707  * "mem_ref" is set for ops->source which is later used to
708  * fill the objdump->memory_ref-char field. This ops is currently
709  * used by powerpc and since binary instruction code is used to
710  * extract opcode, regs and offset, no other parsing is needed here.
711  *
712  * Dont set multi regs for 4 cases since it has only one operand
713  * for source:
714  * - Add to Minus One Extended XO-form ( Ex: addme, addmeo )
715  * - Subtract From Minus One Extended XO-form ( Ex: subfme )
716  * - Add to Zero Extended XO-form ( Ex: addze, addzeo )
717  * - Subtract From Zero Extended XO-form ( Ex: subfze )
718  */
719 static int arithmetic__parse(struct arch *arch __maybe_unused, struct ins_operands *ops,
720 		struct map_symbol *ms __maybe_unused, struct disasm_line *dl)
721 {
722 	int opcode = PPC_OP(dl->raw.raw_insn);
723 
724 	ops->source.mem_ref = false;
725 	if (opcode == 31) {
726 		if ((opcode != MINUS_EXT_XO_FORM) && (opcode != SUB_EXT_XO_FORM) \
727 				&& (opcode != ADD_ZERO_EXT_XO_FORM) && (opcode != SUB_ZERO_EXT_XO_FORM))
728 			ops->source.multi_regs = true;
729 	}
730 
731 	ops->target.mem_ref = false;
732 	ops->target.multi_regs = false;
733 
734 	return 0;
735 }
736 
737 static struct ins_ops arithmetic_ops = {
738 	.parse     = arithmetic__parse,
739 	.scnprintf = arithmetic__scnprintf,
740 };
741 
742 static int load_store__scnprintf(struct ins *ins, char *bf, size_t size,
743 		struct ins_operands *ops, int max_ins_name)
744 {
745 	return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name,
746 			ops->raw);
747 }
748 
749 /*
750  * Sets the fields: multi_regs and "mem_ref".
751  * "mem_ref" is set for ops->source which is later used to
752  * fill the objdump->memory_ref-char field. This ops is currently
753  * used by powerpc and since binary instruction code is used to
754  * extract opcode, regs and offset, no other parsing is needed here
755  */
756 static int load_store__parse(struct arch *arch __maybe_unused, struct ins_operands *ops,
757 		struct map_symbol *ms __maybe_unused, struct disasm_line *dl __maybe_unused)
758 {
759 	ops->source.mem_ref = true;
760 	ops->source.multi_regs = false;
761 	/* opcode 31 is of X form */
762 	if (PPC_OP(dl->raw.raw_insn) == 31)
763 		ops->source.multi_regs = true;
764 
765 	ops->target.mem_ref = false;
766 	ops->target.multi_regs = false;
767 
768 	return 0;
769 }
770 
771 static struct ins_ops load_store_ops = {
772 	.parse     = load_store__parse,
773 	.scnprintf = load_store__scnprintf,
774 };
775 
776 static int dec__parse(struct arch *arch __maybe_unused, struct ins_operands *ops, struct map_symbol *ms __maybe_unused,
777 		struct disasm_line *dl __maybe_unused)
778 {
779 	char *target, *comment, *s, prev;
780 
781 	target = s = ops->raw;
782 
783 	while (s[0] != '\0' && !isspace(s[0]))
784 		++s;
785 	prev = *s;
786 	*s = '\0';
787 
788 	ops->target.raw = strdup(target);
789 	*s = prev;
790 
791 	if (ops->target.raw == NULL)
792 		return -1;
793 
794 	comment = strchr(s, arch->objdump.comment_char);
795 	if (comment == NULL)
796 		return 0;
797 
798 	comment = skip_spaces(comment);
799 	comment__symbol(ops->target.raw, comment + 1, &ops->target.addr, &ops->target.name);
800 
801 	return 0;
802 }
803 
804 static int dec__scnprintf(struct ins *ins, char *bf, size_t size,
805 			   struct ins_operands *ops, int max_ins_name)
806 {
807 	return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name,
808 			 ops->target.name ?: ops->target.raw);
809 }
810 
811 static struct ins_ops dec_ops = {
812 	.parse	   = dec__parse,
813 	.scnprintf = dec__scnprintf,
814 };
815 
816 static int nop__scnprintf(struct ins *ins __maybe_unused, char *bf, size_t size,
817 			  struct ins_operands *ops __maybe_unused, int max_ins_name)
818 {
819 	return scnprintf(bf, size, "%-*s", max_ins_name, "nop");
820 }
821 
822 static struct ins_ops nop_ops = {
823 	.scnprintf = nop__scnprintf,
824 };
825 
826 static struct ins_ops ret_ops = {
827 	.scnprintf = ins__raw_scnprintf,
828 };
829 
830 bool ins__is_nop(const struct ins *ins)
831 {
832 	return ins->ops == &nop_ops;
833 }
834 
835 bool ins__is_ret(const struct ins *ins)
836 {
837 	return ins->ops == &ret_ops;
838 }
839 
840 bool ins__is_lock(const struct ins *ins)
841 {
842 	return ins->ops == &lock_ops;
843 }
844 
845 static int ins__key_cmp(const void *name, const void *insp)
846 {
847 	const struct ins *ins = insp;
848 
849 	return strcmp(name, ins->name);
850 }
851 
852 static int ins__cmp(const void *a, const void *b)
853 {
854 	const struct ins *ia = a;
855 	const struct ins *ib = b;
856 
857 	return strcmp(ia->name, ib->name);
858 }
859 
860 static void ins__sort(struct arch *arch)
861 {
862 	const int nmemb = arch->nr_instructions;
863 
864 	qsort(arch->instructions, nmemb, sizeof(struct ins), ins__cmp);
865 }
866 
867 static struct ins_ops *__ins__find(struct arch *arch, const char *name, struct disasm_line *dl)
868 {
869 	struct ins *ins;
870 	const int nmemb = arch->nr_instructions;
871 
872 	if (arch__is(arch, "powerpc")) {
873 		/*
874 		 * For powerpc, identify the instruction ops
875 		 * from the opcode using raw_insn.
876 		 */
877 		struct ins_ops *ops;
878 
879 		ops = check_ppc_insn(dl);
880 		if (ops)
881 			return ops;
882 	}
883 
884 	if (!arch->sorted_instructions) {
885 		ins__sort(arch);
886 		arch->sorted_instructions = true;
887 	}
888 
889 	ins = bsearch(name, arch->instructions, nmemb, sizeof(struct ins), ins__key_cmp);
890 	if (ins)
891 		return ins->ops;
892 
893 	if (arch->insn_suffix) {
894 		char tmp[32];
895 		char suffix;
896 		size_t len = strlen(name);
897 
898 		if (len == 0 || len >= sizeof(tmp))
899 			return NULL;
900 
901 		suffix = name[len - 1];
902 		if (strchr(arch->insn_suffix, suffix) == NULL)
903 			return NULL;
904 
905 		strcpy(tmp, name);
906 		tmp[len - 1] = '\0'; /* remove the suffix and check again */
907 
908 		ins = bsearch(tmp, arch->instructions, nmemb, sizeof(struct ins), ins__key_cmp);
909 	}
910 	return ins ? ins->ops : NULL;
911 }
912 
913 struct ins_ops *ins__find(struct arch *arch, const char *name, struct disasm_line *dl)
914 {
915 	struct ins_ops *ops = __ins__find(arch, name, dl);
916 
917 	if (!ops && arch->associate_instruction_ops)
918 		ops = arch->associate_instruction_ops(arch, name);
919 
920 	return ops;
921 }
922 
923 static void disasm_line__init_ins(struct disasm_line *dl, struct arch *arch, struct map_symbol *ms)
924 {
925 	dl->ins.ops = ins__find(arch, dl->ins.name, dl);
926 
927 	if (!dl->ins.ops)
928 		return;
929 
930 	if (dl->ins.ops->parse && dl->ins.ops->parse(arch, &dl->ops, ms, dl) < 0)
931 		dl->ins.ops = NULL;
932 }
933 
934 static int disasm_line__parse(char *line, const char **namep, char **rawp)
935 {
936 	char tmp, *name = skip_spaces(line);
937 
938 	if (name[0] == '\0')
939 		return -1;
940 
941 	*rawp = name + 1;
942 
943 	while ((*rawp)[0] != '\0' && !isspace((*rawp)[0]))
944 		++*rawp;
945 
946 	tmp = (*rawp)[0];
947 	(*rawp)[0] = '\0';
948 	*namep = strdup(name);
949 
950 	if (*namep == NULL)
951 		goto out;
952 
953 	(*rawp)[0] = tmp;
954 	*rawp = strim(*rawp);
955 
956 	return 0;
957 
958 out:
959 	return -1;
960 }
961 
962 /*
963  * Parses the result captured from symbol__disassemble_*
964  * Example, line read from DSO file in powerpc:
965  * line:    38 01 81 e8
966  * opcode: fetched from arch specific get_opcode_insn
967  * rawp_insn: e8810138
968  *
969  * rawp_insn is used later to extract the reg/offset fields
970  */
971 #define	PPC_OP(op)	(((op) >> 26) & 0x3F)
972 #define	RAW_BYTES	11
973 
974 static int disasm_line__parse_powerpc(struct disasm_line *dl, struct annotate_args *args)
975 {
976 	char *line = dl->al.line;
977 	const char **namep = &dl->ins.name;
978 	char **rawp = &dl->ops.raw;
979 	char *tmp_raw_insn, *name_raw_insn = skip_spaces(line);
980 	char *name = skip_spaces(name_raw_insn + RAW_BYTES);
981 	int disasm = 0;
982 	int ret = 0;
983 
984 	if (args->options->disassembler_used)
985 		disasm = 1;
986 
987 	if (name_raw_insn[0] == '\0')
988 		return -1;
989 
990 	if (disasm)
991 		ret = disasm_line__parse(name, namep, rawp);
992 	else
993 		*namep = "";
994 
995 	tmp_raw_insn = strndup(name_raw_insn, 11);
996 	if (tmp_raw_insn == NULL)
997 		return -1;
998 
999 	remove_spaces(tmp_raw_insn);
1000 
1001 	sscanf(tmp_raw_insn, "%x", &dl->raw.raw_insn);
1002 	if (disasm)
1003 		dl->raw.raw_insn = be32_to_cpu(dl->raw.raw_insn);
1004 
1005 	return ret;
1006 }
1007 
1008 static void annotation_line__init(struct annotation_line *al,
1009 				  struct annotate_args *args,
1010 				  int nr)
1011 {
1012 	al->offset = args->offset;
1013 	al->line = strdup(args->line);
1014 	al->line_nr = args->line_nr;
1015 	al->fileloc = args->fileloc;
1016 	al->data_nr = nr;
1017 }
1018 
1019 static void annotation_line__exit(struct annotation_line *al)
1020 {
1021 	zfree_srcline(&al->path);
1022 	zfree(&al->line);
1023 	zfree(&al->cycles);
1024 	zfree(&al->br_cntr);
1025 }
1026 
1027 static size_t disasm_line_size(int nr)
1028 {
1029 	struct annotation_line *al;
1030 
1031 	return (sizeof(struct disasm_line) + (sizeof(al->data[0]) * nr));
1032 }
1033 
1034 /*
1035  * Allocating the disasm annotation line data with
1036  * following structure:
1037  *
1038  *    -------------------------------------------
1039  *    struct disasm_line | struct annotation_line
1040  *    -------------------------------------------
1041  *
1042  * We have 'struct annotation_line' member as last member
1043  * of 'struct disasm_line' to have an easy access.
1044  */
1045 struct disasm_line *disasm_line__new(struct annotate_args *args)
1046 {
1047 	struct disasm_line *dl = NULL;
1048 	struct annotation *notes = symbol__annotation(args->ms.sym);
1049 	int nr = notes->src->nr_events;
1050 
1051 	dl = zalloc(disasm_line_size(nr));
1052 	if (!dl)
1053 		return NULL;
1054 
1055 	annotation_line__init(&dl->al, args, nr);
1056 	if (dl->al.line == NULL)
1057 		goto out_delete;
1058 
1059 	if (args->offset != -1) {
1060 		if (arch__is(args->arch, "powerpc")) {
1061 			if (disasm_line__parse_powerpc(dl, args) < 0)
1062 				goto out_free_line;
1063 		} else if (disasm_line__parse(dl->al.line, &dl->ins.name, &dl->ops.raw) < 0)
1064 			goto out_free_line;
1065 
1066 		disasm_line__init_ins(dl, args->arch, &args->ms);
1067 	}
1068 
1069 	return dl;
1070 
1071 out_free_line:
1072 	zfree(&dl->al.line);
1073 out_delete:
1074 	free(dl);
1075 	return NULL;
1076 }
1077 
1078 void disasm_line__free(struct disasm_line *dl)
1079 {
1080 	if (dl->ins.ops && dl->ins.ops->free)
1081 		dl->ins.ops->free(&dl->ops);
1082 	else
1083 		ins_ops__delete(&dl->ops);
1084 	zfree(&dl->ins.name);
1085 	annotation_line__exit(&dl->al);
1086 	free(dl);
1087 }
1088 
1089 int disasm_line__scnprintf(struct disasm_line *dl, char *bf, size_t size, bool raw, int max_ins_name)
1090 {
1091 	if (raw || !dl->ins.ops)
1092 		return scnprintf(bf, size, "%-*s %s", max_ins_name, dl->ins.name, dl->ops.raw);
1093 
1094 	return ins__scnprintf(&dl->ins, bf, size, &dl->ops, max_ins_name);
1095 }
1096 
1097 /*
1098  * symbol__parse_objdump_line() parses objdump output (with -d --no-show-raw)
1099  * which looks like following
1100  *
1101  *  0000000000415500 <_init>:
1102  *    415500:       sub    $0x8,%rsp
1103  *    415504:       mov    0x2f5ad5(%rip),%rax        # 70afe0 <_DYNAMIC+0x2f8>
1104  *    41550b:       test   %rax,%rax
1105  *    41550e:       je     415515 <_init+0x15>
1106  *    415510:       callq  416e70 <__gmon_start__@plt>
1107  *    415515:       add    $0x8,%rsp
1108  *    415519:       retq
1109  *
1110  * it will be parsed and saved into struct disasm_line as
1111  *  <offset>       <name>  <ops.raw>
1112  *
1113  * The offset will be a relative offset from the start of the symbol and -1
1114  * means that it's not a disassembly line so should be treated differently.
1115  * The ops.raw part will be parsed further according to type of the instruction.
1116  */
1117 static int symbol__parse_objdump_line(struct symbol *sym,
1118 				      struct annotate_args *args,
1119 				      char *parsed_line, int *line_nr, char **fileloc)
1120 {
1121 	struct map *map = args->ms.map;
1122 	struct annotation *notes = symbol__annotation(sym);
1123 	struct disasm_line *dl;
1124 	char *tmp;
1125 	s64 line_ip, offset = -1;
1126 	regmatch_t match[2];
1127 
1128 	/* /filename:linenr ? Save line number and ignore. */
1129 	if (regexec(&file_lineno, parsed_line, 2, match, 0) == 0) {
1130 		*line_nr = atoi(parsed_line + match[1].rm_so);
1131 		free(*fileloc);
1132 		*fileloc = strdup(parsed_line);
1133 		return 0;
1134 	}
1135 
1136 	/* Process hex address followed by ':'. */
1137 	line_ip = strtoull(parsed_line, &tmp, 16);
1138 	if (parsed_line != tmp && tmp[0] == ':' && tmp[1] != '\0') {
1139 		u64 start = map__rip_2objdump(map, sym->start),
1140 		    end = map__rip_2objdump(map, sym->end);
1141 
1142 		offset = line_ip - start;
1143 		if ((u64)line_ip < start || (u64)line_ip >= end)
1144 			offset = -1;
1145 		else
1146 			parsed_line = tmp + 1;
1147 	}
1148 
1149 	args->offset  = offset;
1150 	args->line    = parsed_line;
1151 	args->line_nr = *line_nr;
1152 	args->fileloc = *fileloc;
1153 	args->ms.sym  = sym;
1154 
1155 	dl = disasm_line__new(args);
1156 	(*line_nr)++;
1157 
1158 	if (dl == NULL)
1159 		return -1;
1160 
1161 	if (!disasm_line__has_local_offset(dl)) {
1162 		dl->ops.target.offset = dl->ops.target.addr -
1163 					map__rip_2objdump(map, sym->start);
1164 		dl->ops.target.offset_avail = true;
1165 	}
1166 
1167 	/* kcore has no symbols, so add the call target symbol */
1168 	if (dl->ins.ops && ins__is_call(&dl->ins) && !dl->ops.target.sym) {
1169 		struct addr_map_symbol target = {
1170 			.addr = dl->ops.target.addr,
1171 			.ms = { .map = map, },
1172 		};
1173 
1174 		if (!maps__find_ams(args->ms.maps, &target) &&
1175 		    target.ms.sym->start == target.al_addr)
1176 			dl->ops.target.sym = target.ms.sym;
1177 	}
1178 
1179 	annotation_line__add(&dl->al, &notes->src->source);
1180 	return 0;
1181 }
1182 
1183 static void delete_last_nop(struct symbol *sym)
1184 {
1185 	struct annotation *notes = symbol__annotation(sym);
1186 	struct list_head *list = &notes->src->source;
1187 	struct disasm_line *dl;
1188 
1189 	while (!list_empty(list)) {
1190 		dl = list_entry(list->prev, struct disasm_line, al.node);
1191 
1192 		if (dl->ins.ops) {
1193 			if (!ins__is_nop(&dl->ins))
1194 				return;
1195 		} else {
1196 			if (!strstr(dl->al.line, " nop ") &&
1197 			    !strstr(dl->al.line, " nopl ") &&
1198 			    !strstr(dl->al.line, " nopw "))
1199 				return;
1200 		}
1201 
1202 		list_del_init(&dl->al.node);
1203 		disasm_line__free(dl);
1204 	}
1205 }
1206 
1207 int symbol__strerror_disassemble(struct map_symbol *ms, int errnum, char *buf, size_t buflen)
1208 {
1209 	struct dso *dso = map__dso(ms->map);
1210 
1211 	BUG_ON(buflen == 0);
1212 
1213 	if (errnum >= 0) {
1214 		str_error_r(errnum, buf, buflen);
1215 		return 0;
1216 	}
1217 
1218 	switch (errnum) {
1219 	case SYMBOL_ANNOTATE_ERRNO__NO_VMLINUX: {
1220 		char bf[SBUILD_ID_SIZE + 15] = " with build id ";
1221 		char *build_id_msg = NULL;
1222 
1223 		if (dso__has_build_id(dso)) {
1224 			build_id__snprintf(dso__bid(dso), bf + 15, sizeof(bf) - 15);
1225 			build_id_msg = bf;
1226 		}
1227 		scnprintf(buf, buflen,
1228 			  "No vmlinux file%s\nwas found in the path.\n\n"
1229 			  "Note that annotation using /proc/kcore requires CAP_SYS_RAWIO capability.\n\n"
1230 			  "Please use:\n\n"
1231 			  "  perf buildid-cache -vu vmlinux\n\n"
1232 			  "or:\n\n"
1233 			  "  --vmlinux vmlinux\n", build_id_msg ?: "");
1234 	}
1235 		break;
1236 	case SYMBOL_ANNOTATE_ERRNO__NO_LIBOPCODES_FOR_BPF:
1237 		scnprintf(buf, buflen, "Please link with binutils's libopcode to enable BPF annotation");
1238 		break;
1239 	case SYMBOL_ANNOTATE_ERRNO__ARCH_INIT_REGEXP:
1240 		scnprintf(buf, buflen, "Problems with arch specific instruction name regular expressions.");
1241 		break;
1242 	case SYMBOL_ANNOTATE_ERRNO__ARCH_INIT_CPUID_PARSING:
1243 		scnprintf(buf, buflen, "Problems while parsing the CPUID in the arch specific initialization.");
1244 		break;
1245 	case SYMBOL_ANNOTATE_ERRNO__BPF_INVALID_FILE:
1246 		scnprintf(buf, buflen, "Invalid BPF file: %s.", dso__long_name(dso));
1247 		break;
1248 	case SYMBOL_ANNOTATE_ERRNO__BPF_MISSING_BTF:
1249 		scnprintf(buf, buflen, "The %s BPF file has no BTF section, compile with -g or use pahole -J.",
1250 			  dso__long_name(dso));
1251 		break;
1252 	case SYMBOL_ANNOTATE_ERRNO__COULDNT_DETERMINE_FILE_TYPE:
1253 		scnprintf(buf, buflen, "Couldn't determine the file %s type.", dso__long_name(dso));
1254 		break;
1255 	default:
1256 		scnprintf(buf, buflen, "Internal error: Invalid %d error code\n", errnum);
1257 		break;
1258 	}
1259 
1260 	return 0;
1261 }
1262 
1263 static int dso__disassemble_filename(struct dso *dso, char *filename, size_t filename_size)
1264 {
1265 	char linkname[PATH_MAX];
1266 	char *build_id_filename;
1267 	char *build_id_path = NULL;
1268 	char *pos;
1269 	int len;
1270 
1271 	if (dso__symtab_type(dso) == DSO_BINARY_TYPE__KALLSYMS &&
1272 	    !dso__is_kcore(dso))
1273 		return SYMBOL_ANNOTATE_ERRNO__NO_VMLINUX;
1274 
1275 	build_id_filename = dso__build_id_filename(dso, NULL, 0, false);
1276 	if (build_id_filename) {
1277 		__symbol__join_symfs(filename, filename_size, build_id_filename);
1278 		free(build_id_filename);
1279 	} else {
1280 		if (dso__has_build_id(dso))
1281 			return ENOMEM;
1282 		goto fallback;
1283 	}
1284 
1285 	build_id_path = strdup(filename);
1286 	if (!build_id_path)
1287 		return ENOMEM;
1288 
1289 	/*
1290 	 * old style build-id cache has name of XX/XXXXXXX.. while
1291 	 * new style has XX/XXXXXXX../{elf,kallsyms,vdso}.
1292 	 * extract the build-id part of dirname in the new style only.
1293 	 */
1294 	pos = strrchr(build_id_path, '/');
1295 	if (pos && strlen(pos) < SBUILD_ID_SIZE - 2)
1296 		dirname(build_id_path);
1297 
1298 	if (dso__is_kcore(dso))
1299 		goto fallback;
1300 
1301 	len = readlink(build_id_path, linkname, sizeof(linkname) - 1);
1302 	if (len < 0)
1303 		goto fallback;
1304 
1305 	linkname[len] = '\0';
1306 	if (strstr(linkname, DSO__NAME_KALLSYMS) ||
1307 		access(filename, R_OK)) {
1308 fallback:
1309 		/*
1310 		 * If we don't have build-ids or the build-id file isn't in the
1311 		 * cache, or is just a kallsyms file, well, lets hope that this
1312 		 * DSO is the same as when 'perf record' ran.
1313 		 */
1314 		if (dso__kernel(dso) && dso__long_name(dso)[0] == '/')
1315 			snprintf(filename, filename_size, "%s", dso__long_name(dso));
1316 		else
1317 			__symbol__join_symfs(filename, filename_size, dso__long_name(dso));
1318 
1319 		mutex_lock(dso__lock(dso));
1320 		if (access(filename, R_OK) && errno == ENOENT && dso__nsinfo(dso)) {
1321 			char *new_name = dso__filename_with_chroot(dso, filename);
1322 			if (new_name) {
1323 				strlcpy(filename, new_name, filename_size);
1324 				free(new_name);
1325 			}
1326 		}
1327 		mutex_unlock(dso__lock(dso));
1328 	} else if (dso__binary_type(dso) == DSO_BINARY_TYPE__NOT_FOUND) {
1329 		dso__set_binary_type(dso, DSO_BINARY_TYPE__BUILD_ID_CACHE);
1330 	}
1331 
1332 	free(build_id_path);
1333 	return 0;
1334 }
1335 
1336 #ifdef HAVE_LIBCAPSTONE_SUPPORT
1337 #include <capstone/capstone.h>
1338 
1339 int capstone_init(struct machine *machine, csh *cs_handle, bool is64, bool disassembler_style);
1340 
1341 static int open_capstone_handle(struct annotate_args *args, bool is_64bit,
1342 				csh *handle)
1343 {
1344 	struct annotation_options *opt = args->options;
1345 	cs_mode mode = is_64bit ? CS_MODE_64 : CS_MODE_32;
1346 
1347 	/* TODO: support more architectures */
1348 	if (!arch__is(args->arch, "x86"))
1349 		return -1;
1350 
1351 	if (cs_open(CS_ARCH_X86, mode, handle) != CS_ERR_OK)
1352 		return -1;
1353 
1354 	if (!opt->disassembler_style ||
1355 	    !strcmp(opt->disassembler_style, "att"))
1356 		cs_option(*handle, CS_OPT_SYNTAX, CS_OPT_SYNTAX_ATT);
1357 
1358 	/*
1359 	 * Resolving address operands to symbols is implemented
1360 	 * on x86 by investigating instruction details.
1361 	 */
1362 	cs_option(*handle, CS_OPT_DETAIL, CS_OPT_ON);
1363 
1364 	return 0;
1365 }
1366 #endif
1367 
1368 #if defined(HAVE_LIBCAPSTONE_SUPPORT) || defined(HAVE_LIBLLVM_SUPPORT)
1369 struct find_file_offset_data {
1370 	u64 ip;
1371 	u64 offset;
1372 };
1373 
1374 /* This will be called for each PHDR in an ELF binary */
1375 static int find_file_offset(u64 start, u64 len, u64 pgoff, void *arg)
1376 {
1377 	struct find_file_offset_data *data = arg;
1378 
1379 	if (start <= data->ip && data->ip < start + len) {
1380 		data->offset = pgoff + data->ip - start;
1381 		return 1;
1382 	}
1383 	return 0;
1384 }
1385 
1386 static u8 *
1387 read_symbol(const char *filename, struct map *map, struct symbol *sym,
1388 	    u64 *len, bool *is_64bit)
1389 {
1390 	struct dso *dso = map__dso(map);
1391 	struct nscookie nsc;
1392 	u64 start = map__rip_2objdump(map, sym->start);
1393 	u64 end = map__rip_2objdump(map, sym->end);
1394 	int fd, count;
1395 	u8 *buf = NULL;
1396 	struct find_file_offset_data data = {
1397 		.ip = start,
1398 	};
1399 
1400 	*is_64bit = false;
1401 
1402 	nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
1403 	fd = open(filename, O_RDONLY);
1404 	nsinfo__mountns_exit(&nsc);
1405 	if (fd < 0)
1406 		return NULL;
1407 
1408 	if (file__read_maps(fd, /*exe=*/true, find_file_offset, &data,
1409 			    is_64bit) == 0)
1410 		goto err;
1411 
1412 	*len = end - start;
1413 	buf = malloc(*len);
1414 	if (buf == NULL)
1415 		goto err;
1416 
1417 	count = pread(fd, buf, *len, data.offset);
1418 	close(fd);
1419 	fd = -1;
1420 
1421 	if ((u64)count != *len)
1422 		goto err;
1423 
1424 	return buf;
1425 
1426 err:
1427 	if (fd >= 0)
1428 		close(fd);
1429 	free(buf);
1430 	return NULL;
1431 }
1432 #endif
1433 
1434 #if !defined(HAVE_LIBCAPSTONE_SUPPORT) || !defined(HAVE_LIBLLVM_SUPPORT)
1435 static void symbol__disassembler_missing(const char *disassembler, const char *filename,
1436 					 struct symbol *sym)
1437 {
1438 	pr_debug("The %s disassembler isn't linked in for %s in %s\n",
1439 		 disassembler, sym->name, filename);
1440 }
1441 #endif
1442 
1443 #ifdef HAVE_LIBCAPSTONE_SUPPORT
1444 static void print_capstone_detail(cs_insn *insn, char *buf, size_t len,
1445 				  struct annotate_args *args, u64 addr)
1446 {
1447 	int i;
1448 	struct map *map = args->ms.map;
1449 	struct symbol *sym;
1450 
1451 	/* TODO: support more architectures */
1452 	if (!arch__is(args->arch, "x86"))
1453 		return;
1454 
1455 	if (insn->detail == NULL)
1456 		return;
1457 
1458 	for (i = 0; i < insn->detail->x86.op_count; i++) {
1459 		cs_x86_op *op = &insn->detail->x86.operands[i];
1460 		u64 orig_addr;
1461 
1462 		if (op->type != X86_OP_MEM)
1463 			continue;
1464 
1465 		/* only print RIP-based global symbols for now */
1466 		if (op->mem.base != X86_REG_RIP)
1467 			continue;
1468 
1469 		/* get the target address */
1470 		orig_addr = addr + insn->size + op->mem.disp;
1471 		addr = map__objdump_2mem(map, orig_addr);
1472 
1473 		if (dso__kernel(map__dso(map))) {
1474 			/*
1475 			 * The kernel maps can be splitted into sections,
1476 			 * let's find the map first and the search the symbol.
1477 			 */
1478 			map = maps__find(map__kmaps(map), addr);
1479 			if (map == NULL)
1480 				continue;
1481 		}
1482 
1483 		/* convert it to map-relative address for search */
1484 		addr = map__map_ip(map, addr);
1485 
1486 		sym = map__find_symbol(map, addr);
1487 		if (sym == NULL)
1488 			continue;
1489 
1490 		if (addr == sym->start) {
1491 			scnprintf(buf, len, "\t# %"PRIx64" <%s>",
1492 				  orig_addr, sym->name);
1493 		} else {
1494 			scnprintf(buf, len, "\t# %"PRIx64" <%s+%#"PRIx64">",
1495 				  orig_addr, sym->name, addr - sym->start);
1496 		}
1497 		break;
1498 	}
1499 }
1500 
1501 static int symbol__disassemble_capstone_powerpc(char *filename, struct symbol *sym,
1502 					struct annotate_args *args)
1503 {
1504 	struct annotation *notes = symbol__annotation(sym);
1505 	struct map *map = args->ms.map;
1506 	struct dso *dso = map__dso(map);
1507 	struct nscookie nsc;
1508 	u64 start = map__rip_2objdump(map, sym->start);
1509 	u64 end = map__rip_2objdump(map, sym->end);
1510 	u64 len = end - start;
1511 	u64 offset;
1512 	int i, fd, count;
1513 	bool is_64bit = false;
1514 	bool needs_cs_close = false;
1515 	u8 *buf = NULL;
1516 	struct find_file_offset_data data = {
1517 		.ip = start,
1518 	};
1519 	csh handle;
1520 	char disasm_buf[512];
1521 	struct disasm_line *dl;
1522 	u32 *line;
1523 	bool disassembler_style = false;
1524 
1525 	if (args->options->objdump_path)
1526 		return -1;
1527 
1528 	nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
1529 	fd = open(filename, O_RDONLY);
1530 	nsinfo__mountns_exit(&nsc);
1531 	if (fd < 0)
1532 		return -1;
1533 
1534 	if (file__read_maps(fd, /*exe=*/true, find_file_offset, &data,
1535 			    &is_64bit) == 0)
1536 		goto err;
1537 
1538 	if (!args->options->disassembler_style ||
1539 			!strcmp(args->options->disassembler_style, "att"))
1540 		disassembler_style = true;
1541 
1542 	if (capstone_init(maps__machine(args->ms.maps), &handle, is_64bit, disassembler_style) < 0)
1543 		goto err;
1544 
1545 	needs_cs_close = true;
1546 
1547 	buf = malloc(len);
1548 	if (buf == NULL)
1549 		goto err;
1550 
1551 	count = pread(fd, buf, len, data.offset);
1552 	close(fd);
1553 	fd = -1;
1554 
1555 	if ((u64)count != len)
1556 		goto err;
1557 
1558 	line = (u32 *)buf;
1559 
1560 	/* add the function address and name */
1561 	scnprintf(disasm_buf, sizeof(disasm_buf), "%#"PRIx64" <%s>:",
1562 		  start, sym->name);
1563 
1564 	args->offset = -1;
1565 	args->line = disasm_buf;
1566 	args->line_nr = 0;
1567 	args->fileloc = NULL;
1568 	args->ms.sym = sym;
1569 
1570 	dl = disasm_line__new(args);
1571 	if (dl == NULL)
1572 		goto err;
1573 
1574 	annotation_line__add(&dl->al, &notes->src->source);
1575 
1576 	/*
1577 	 * TODO: enable disassm for powerpc
1578 	 * count = cs_disasm(handle, buf, len, start, len, &insn);
1579 	 *
1580 	 * For now, only binary code is saved in disassembled line
1581 	 * to be used in "type" and "typeoff" sort keys. Each raw code
1582 	 * is 32 bit instruction. So use "len/4" to get the number of
1583 	 * entries.
1584 	 */
1585 	count = len/4;
1586 
1587 	for (i = 0, offset = 0; i < count; i++) {
1588 		args->offset = offset;
1589 		sprintf(args->line, "%x", line[i]);
1590 
1591 		dl = disasm_line__new(args);
1592 		if (dl == NULL)
1593 			break;
1594 
1595 		annotation_line__add(&dl->al, &notes->src->source);
1596 
1597 		offset += 4;
1598 	}
1599 
1600 	/* It failed in the middle */
1601 	if (offset != len) {
1602 		struct list_head *list = &notes->src->source;
1603 
1604 		/* Discard all lines and fallback to objdump */
1605 		while (!list_empty(list)) {
1606 			dl = list_first_entry(list, struct disasm_line, al.node);
1607 
1608 			list_del_init(&dl->al.node);
1609 			disasm_line__free(dl);
1610 		}
1611 		count = -1;
1612 	}
1613 
1614 out:
1615 	if (needs_cs_close)
1616 		cs_close(&handle);
1617 	free(buf);
1618 	return count < 0 ? count : 0;
1619 
1620 err:
1621 	if (fd >= 0)
1622 		close(fd);
1623 	count = -1;
1624 	goto out;
1625 }
1626 
1627 static int symbol__disassemble_capstone(char *filename, struct symbol *sym,
1628 					struct annotate_args *args)
1629 {
1630 	struct annotation *notes = symbol__annotation(sym);
1631 	struct map *map = args->ms.map;
1632 	u64 start = map__rip_2objdump(map, sym->start);
1633 	u64 len;
1634 	u64 offset;
1635 	int i, count, free_count;
1636 	bool is_64bit = false;
1637 	bool needs_cs_close = false;
1638 	u8 *buf = NULL;
1639 	csh handle;
1640 	cs_insn *insn = NULL;
1641 	char disasm_buf[512];
1642 	struct disasm_line *dl;
1643 
1644 	if (args->options->objdump_path)
1645 		return -1;
1646 
1647 	buf = read_symbol(filename, map, sym, &len, &is_64bit);
1648 	if (buf == NULL)
1649 		return -1;
1650 
1651 	/* add the function address and name */
1652 	scnprintf(disasm_buf, sizeof(disasm_buf), "%#"PRIx64" <%s>:",
1653 		  start, sym->name);
1654 
1655 	args->offset = -1;
1656 	args->line = disasm_buf;
1657 	args->line_nr = 0;
1658 	args->fileloc = NULL;
1659 	args->ms.sym = sym;
1660 
1661 	dl = disasm_line__new(args);
1662 	if (dl == NULL)
1663 		goto err;
1664 
1665 	annotation_line__add(&dl->al, &notes->src->source);
1666 
1667 	if (open_capstone_handle(args, is_64bit, &handle) < 0)
1668 		goto err;
1669 
1670 	needs_cs_close = true;
1671 
1672 	free_count = count = cs_disasm(handle, buf, len, start, len, &insn);
1673 	for (i = 0, offset = 0; i < count; i++) {
1674 		int printed;
1675 
1676 		printed = scnprintf(disasm_buf, sizeof(disasm_buf),
1677 				    "       %-7s %s",
1678 				    insn[i].mnemonic, insn[i].op_str);
1679 		print_capstone_detail(&insn[i], disasm_buf + printed,
1680 				      sizeof(disasm_buf) - printed, args,
1681 				      start + offset);
1682 
1683 		args->offset = offset;
1684 		args->line = disasm_buf;
1685 
1686 		dl = disasm_line__new(args);
1687 		if (dl == NULL)
1688 			goto err;
1689 
1690 		annotation_line__add(&dl->al, &notes->src->source);
1691 
1692 		offset += insn[i].size;
1693 	}
1694 
1695 	/* It failed in the middle: probably due to unknown instructions */
1696 	if (offset != len) {
1697 		struct list_head *list = &notes->src->source;
1698 
1699 		/* Discard all lines and fallback to objdump */
1700 		while (!list_empty(list)) {
1701 			dl = list_first_entry(list, struct disasm_line, al.node);
1702 
1703 			list_del_init(&dl->al.node);
1704 			disasm_line__free(dl);
1705 		}
1706 		count = -1;
1707 	}
1708 
1709 out:
1710 	if (needs_cs_close) {
1711 		cs_close(&handle);
1712 		if (free_count > 0)
1713 			cs_free(insn, free_count);
1714 	}
1715 	free(buf);
1716 	return count < 0 ? count : 0;
1717 
1718 err:
1719 	if (needs_cs_close) {
1720 		struct disasm_line *tmp;
1721 
1722 		/*
1723 		 * It probably failed in the middle of the above loop.
1724 		 * Release any resources it might add.
1725 		 */
1726 		list_for_each_entry_safe(dl, tmp, &notes->src->source, al.node) {
1727 			list_del(&dl->al.node);
1728 			disasm_line__free(dl);
1729 		}
1730 	}
1731 	count = -1;
1732 	goto out;
1733 }
1734 #else // HAVE_LIBCAPSTONE_SUPPORT
1735 static int symbol__disassemble_capstone(char *filename, struct symbol *sym,
1736 					struct annotate_args *args __maybe_unused)
1737 {
1738 	symbol__disassembler_missing("capstone", filename, sym);
1739 	return -1;
1740 }
1741 
1742 static int symbol__disassemble_capstone_powerpc(char *filename, struct symbol *sym,
1743 						struct annotate_args *args __maybe_unused)
1744 {
1745 	symbol__disassembler_missing("capstone powerpc", filename, sym);
1746 	return -1;
1747 }
1748 #endif // HAVE_LIBCAPSTONE_SUPPORT
1749 
1750 static int symbol__disassemble_raw(char *filename, struct symbol *sym,
1751 					struct annotate_args *args)
1752 {
1753 	struct annotation *notes = symbol__annotation(sym);
1754 	struct map *map = args->ms.map;
1755 	struct dso *dso = map__dso(map);
1756 	u64 start = map__rip_2objdump(map, sym->start);
1757 	u64 end = map__rip_2objdump(map, sym->end);
1758 	u64 len = end - start;
1759 	u64 offset;
1760 	int i, count;
1761 	u8 *buf = NULL;
1762 	char disasm_buf[512];
1763 	struct disasm_line *dl;
1764 	u32 *line;
1765 
1766 	/* Return if objdump is specified explicitly */
1767 	if (args->options->objdump_path)
1768 		return -1;
1769 
1770 	pr_debug("Reading raw instruction from : %s using dso__data_read_offset\n", filename);
1771 
1772 	buf = malloc(len);
1773 	if (buf == NULL)
1774 		goto err;
1775 
1776 	count = dso__data_read_offset(dso, NULL, sym->start, buf, len);
1777 
1778 	line = (u32 *)buf;
1779 
1780 	if ((u64)count != len)
1781 		goto err;
1782 
1783 	/* add the function address and name */
1784 	scnprintf(disasm_buf, sizeof(disasm_buf), "%#"PRIx64" <%s>:",
1785 		  start, sym->name);
1786 
1787 	args->offset = -1;
1788 	args->line = disasm_buf;
1789 	args->line_nr = 0;
1790 	args->fileloc = NULL;
1791 	args->ms.sym = sym;
1792 
1793 	dl = disasm_line__new(args);
1794 	if (dl == NULL)
1795 		goto err;
1796 
1797 	annotation_line__add(&dl->al, &notes->src->source);
1798 
1799 	/* Each raw instruction is 4 byte */
1800 	count = len/4;
1801 
1802 	for (i = 0, offset = 0; i < count; i++) {
1803 		args->offset = offset;
1804 		sprintf(args->line, "%x", line[i]);
1805 		dl = disasm_line__new(args);
1806 		if (dl == NULL)
1807 			break;
1808 
1809 		annotation_line__add(&dl->al, &notes->src->source);
1810 		offset += 4;
1811 	}
1812 
1813 	/* It failed in the middle */
1814 	if (offset != len) {
1815 		struct list_head *list = &notes->src->source;
1816 
1817 		/* Discard all lines and fallback to objdump */
1818 		while (!list_empty(list)) {
1819 			dl = list_first_entry(list, struct disasm_line, al.node);
1820 
1821 			list_del_init(&dl->al.node);
1822 			disasm_line__free(dl);
1823 		}
1824 		count = -1;
1825 	}
1826 
1827 out:
1828 	free(buf);
1829 	return count < 0 ? count : 0;
1830 
1831 err:
1832 	count = -1;
1833 	goto out;
1834 }
1835 
1836 #ifdef HAVE_LIBLLVM_SUPPORT
1837 #include <llvm-c/Disassembler.h>
1838 #include <llvm-c/Target.h>
1839 #include "util/llvm-c-helpers.h"
1840 
1841 struct symbol_lookup_storage {
1842 	u64 branch_addr;
1843 	u64 pcrel_load_addr;
1844 };
1845 
1846 /*
1847  * Whenever LLVM wants to resolve an address into a symbol, it calls this
1848  * callback. We don't ever actually _return_ anything (in particular, because
1849  * it puts quotation marks around what we return), but we use this as a hint
1850  * that there is a branch or PC-relative address in the expression that we
1851  * should add some textual annotation for after the instruction. The caller
1852  * will use this information to add the actual annotation.
1853  */
1854 static const char *
1855 symbol_lookup_callback(void *disinfo, uint64_t value,
1856 		       uint64_t *ref_type,
1857 		       uint64_t address __maybe_unused,
1858 		       const char **ref __maybe_unused)
1859 {
1860 	struct symbol_lookup_storage *storage = disinfo;
1861 
1862 	if (*ref_type == LLVMDisassembler_ReferenceType_In_Branch)
1863 		storage->branch_addr = value;
1864 	else if (*ref_type == LLVMDisassembler_ReferenceType_In_PCrel_Load)
1865 		storage->pcrel_load_addr = value;
1866 	*ref_type = LLVMDisassembler_ReferenceType_InOut_None;
1867 	return NULL;
1868 }
1869 
1870 static int symbol__disassemble_llvm(char *filename, struct symbol *sym,
1871 				    struct annotate_args *args)
1872 {
1873 	struct annotation *notes = symbol__annotation(sym);
1874 	struct map *map = args->ms.map;
1875 	struct dso *dso = map__dso(map);
1876 	u64 start = map__rip_2objdump(map, sym->start);
1877 	u8 *buf;
1878 	u64 len;
1879 	u64 pc;
1880 	bool is_64bit;
1881 	char triplet[64];
1882 	char disasm_buf[2048];
1883 	size_t disasm_len;
1884 	struct disasm_line *dl;
1885 	LLVMDisasmContextRef disasm = NULL;
1886 	struct symbol_lookup_storage storage;
1887 	char *line_storage = NULL;
1888 	size_t line_storage_len = 0;
1889 	int ret = -1;
1890 
1891 	if (args->options->objdump_path)
1892 		return -1;
1893 
1894 	LLVMInitializeAllTargetInfos();
1895 	LLVMInitializeAllTargetMCs();
1896 	LLVMInitializeAllDisassemblers();
1897 
1898 	buf = read_symbol(filename, map, sym, &len, &is_64bit);
1899 	if (buf == NULL)
1900 		return -1;
1901 
1902 	if (arch__is(args->arch, "x86")) {
1903 		if (is_64bit)
1904 			scnprintf(triplet, sizeof(triplet), "x86_64-pc-linux");
1905 		else
1906 			scnprintf(triplet, sizeof(triplet), "i686-pc-linux");
1907 	} else {
1908 		scnprintf(triplet, sizeof(triplet), "%s-linux-gnu",
1909 			  args->arch->name);
1910 	}
1911 
1912 	disasm = LLVMCreateDisasm(triplet, &storage, 0, NULL,
1913 				  symbol_lookup_callback);
1914 	if (disasm == NULL)
1915 		goto err;
1916 
1917 	if (args->options->disassembler_style &&
1918 	    !strcmp(args->options->disassembler_style, "intel"))
1919 		LLVMSetDisasmOptions(disasm,
1920 				     LLVMDisassembler_Option_AsmPrinterVariant);
1921 
1922 	/*
1923 	 * This needs to be set after AsmPrinterVariant, due to a bug in LLVM;
1924 	 * setting AsmPrinterVariant makes a new instruction printer, making it
1925 	 * forget about the PrintImmHex flag (which is applied before if both
1926 	 * are given to the same call).
1927 	 */
1928 	LLVMSetDisasmOptions(disasm, LLVMDisassembler_Option_PrintImmHex);
1929 
1930 	/* add the function address and name */
1931 	scnprintf(disasm_buf, sizeof(disasm_buf), "%#"PRIx64" <%s>:",
1932 		  start, sym->name);
1933 
1934 	args->offset = -1;
1935 	args->line = disasm_buf;
1936 	args->line_nr = 0;
1937 	args->fileloc = NULL;
1938 	args->ms.sym = sym;
1939 
1940 	dl = disasm_line__new(args);
1941 	if (dl == NULL)
1942 		goto err;
1943 
1944 	annotation_line__add(&dl->al, &notes->src->source);
1945 
1946 	pc = start;
1947 	for (u64 offset = 0; offset < len; ) {
1948 		unsigned int ins_len;
1949 
1950 		storage.branch_addr = 0;
1951 		storage.pcrel_load_addr = 0;
1952 
1953 		ins_len = LLVMDisasmInstruction(disasm, buf + offset,
1954 						len - offset, pc,
1955 						disasm_buf, sizeof(disasm_buf));
1956 		if (ins_len == 0)
1957 			goto err;
1958 		disasm_len = strlen(disasm_buf);
1959 
1960 		if (storage.branch_addr != 0) {
1961 			char *name = llvm_name_for_code(dso, filename,
1962 							storage.branch_addr);
1963 			if (name != NULL) {
1964 				disasm_len += scnprintf(disasm_buf + disasm_len,
1965 							sizeof(disasm_buf) -
1966 								disasm_len,
1967 							" <%s>", name);
1968 				free(name);
1969 			}
1970 		}
1971 		if (storage.pcrel_load_addr != 0) {
1972 			char *name = llvm_name_for_data(dso, filename,
1973 							storage.pcrel_load_addr);
1974 			disasm_len += scnprintf(disasm_buf + disasm_len,
1975 						sizeof(disasm_buf) - disasm_len,
1976 						"  # %#"PRIx64,
1977 						storage.pcrel_load_addr);
1978 			if (name) {
1979 				disasm_len += scnprintf(disasm_buf + disasm_len,
1980 							sizeof(disasm_buf) -
1981 							disasm_len,
1982 							" <%s>", name);
1983 				free(name);
1984 			}
1985 		}
1986 
1987 		args->offset = offset;
1988 		args->line = expand_tabs(disasm_buf, &line_storage,
1989 					 &line_storage_len);
1990 		args->line_nr = 0;
1991 		args->fileloc = NULL;
1992 		args->ms.sym = sym;
1993 
1994 		llvm_addr2line(filename, pc, &args->fileloc,
1995 			       (unsigned int *)&args->line_nr, false, NULL);
1996 
1997 		dl = disasm_line__new(args);
1998 		if (dl == NULL)
1999 			goto err;
2000 
2001 		annotation_line__add(&dl->al, &notes->src->source);
2002 
2003 		free(args->fileloc);
2004 		pc += ins_len;
2005 		offset += ins_len;
2006 	}
2007 
2008 	ret = 0;
2009 
2010 err:
2011 	LLVMDisasmDispose(disasm);
2012 	free(buf);
2013 	free(line_storage);
2014 	return ret;
2015 }
2016 #else // HAVE_LIBLLVM_SUPPORT
2017 static int symbol__disassemble_llvm(char *filename, struct symbol *sym,
2018 				    struct annotate_args *args __maybe_unused)
2019 {
2020 	symbol__disassembler_missing("LLVM", filename, sym);
2021 	return -1;
2022 }
2023 #endif // HAVE_LIBLLVM_SUPPORT
2024 
2025 /*
2026  * Possibly create a new version of line with tabs expanded. Returns the
2027  * existing or new line, storage is updated if a new line is allocated. If
2028  * allocation fails then NULL is returned.
2029  */
2030 static char *expand_tabs(char *line, char **storage, size_t *storage_len)
2031 {
2032 	size_t i, src, dst, len, new_storage_len, num_tabs;
2033 	char *new_line;
2034 	size_t line_len = strlen(line);
2035 
2036 	for (num_tabs = 0, i = 0; i < line_len; i++)
2037 		if (line[i] == '\t')
2038 			num_tabs++;
2039 
2040 	if (num_tabs == 0)
2041 		return line;
2042 
2043 	/*
2044 	 * Space for the line and '\0', less the leading and trailing
2045 	 * spaces. Each tab may introduce 7 additional spaces.
2046 	 */
2047 	new_storage_len = line_len + 1 + (num_tabs * 7);
2048 
2049 	new_line = malloc(new_storage_len);
2050 	if (new_line == NULL) {
2051 		pr_err("Failure allocating memory for tab expansion\n");
2052 		return NULL;
2053 	}
2054 
2055 	/*
2056 	 * Copy regions starting at src and expand tabs. If there are two
2057 	 * adjacent tabs then 'src == i', the memcpy is of size 0 and the spaces
2058 	 * are inserted.
2059 	 */
2060 	for (i = 0, src = 0, dst = 0; i < line_len && num_tabs; i++) {
2061 		if (line[i] == '\t') {
2062 			len = i - src;
2063 			memcpy(&new_line[dst], &line[src], len);
2064 			dst += len;
2065 			new_line[dst++] = ' ';
2066 			while (dst % 8 != 0)
2067 				new_line[dst++] = ' ';
2068 			src = i + 1;
2069 			num_tabs--;
2070 		}
2071 	}
2072 
2073 	/* Expand the last region. */
2074 	len = line_len - src;
2075 	memcpy(&new_line[dst], &line[src], len);
2076 	dst += len;
2077 	new_line[dst] = '\0';
2078 
2079 	free(*storage);
2080 	*storage = new_line;
2081 	*storage_len = new_storage_len;
2082 	return new_line;
2083 }
2084 
2085 static int symbol__disassemble_objdump(const char *filename, struct symbol *sym,
2086 				       struct annotate_args *args)
2087 {
2088 	struct annotation_options *opts = &annotate_opts;
2089 	struct map *map = args->ms.map;
2090 	struct dso *dso = map__dso(map);
2091 	char *command;
2092 	FILE *file;
2093 	int lineno = 0;
2094 	char *fileloc = NULL;
2095 	int nline;
2096 	char *line;
2097 	size_t line_len;
2098 	const char *objdump_argv[] = {
2099 		"/bin/sh",
2100 		"-c",
2101 		NULL, /* Will be the objdump command to run. */
2102 		"--",
2103 		NULL, /* Will be the symfs path. */
2104 		NULL,
2105 	};
2106 	struct child_process objdump_process;
2107 	int err;
2108 
2109 	err = asprintf(&command,
2110 		 "%s %s%s --start-address=0x%016" PRIx64
2111 		 " --stop-address=0x%016" PRIx64
2112 		 " %s -d %s %s %s %c%s%c %s%s -C \"$1\"",
2113 		 opts->objdump_path ?: "objdump",
2114 		 opts->disassembler_style ? "-M " : "",
2115 		 opts->disassembler_style ?: "",
2116 		 map__rip_2objdump(map, sym->start),
2117 		 map__rip_2objdump(map, sym->end),
2118 		 opts->show_linenr ? "-l" : "",
2119 		 opts->show_asm_raw ? "" : "--no-show-raw-insn",
2120 		 opts->annotate_src ? "-S" : "",
2121 		 opts->prefix ? "--prefix " : "",
2122 		 opts->prefix ? '"' : ' ',
2123 		 opts->prefix ?: "",
2124 		 opts->prefix ? '"' : ' ',
2125 		 opts->prefix_strip ? "--prefix-strip=" : "",
2126 		 opts->prefix_strip ?: "");
2127 
2128 	if (err < 0) {
2129 		pr_err("Failure allocating memory for the command to run\n");
2130 		return err;
2131 	}
2132 
2133 	pr_debug("Executing: %s\n", command);
2134 
2135 	objdump_argv[2] = command;
2136 	objdump_argv[4] = filename;
2137 
2138 	/* Create a pipe to read from for stdout */
2139 	memset(&objdump_process, 0, sizeof(objdump_process));
2140 	objdump_process.argv = objdump_argv;
2141 	objdump_process.out = -1;
2142 	objdump_process.err = -1;
2143 	objdump_process.no_stderr = 1;
2144 	if (start_command(&objdump_process)) {
2145 		pr_err("Failure starting to run %s\n", command);
2146 		err = -1;
2147 		goto out_free_command;
2148 	}
2149 
2150 	file = fdopen(objdump_process.out, "r");
2151 	if (!file) {
2152 		pr_err("Failure creating FILE stream for %s\n", command);
2153 		/*
2154 		 * If we were using debug info should retry with
2155 		 * original binary.
2156 		 */
2157 		err = -1;
2158 		goto out_close_stdout;
2159 	}
2160 
2161 	/* Storage for getline. */
2162 	line = NULL;
2163 	line_len = 0;
2164 
2165 	nline = 0;
2166 	while (!feof(file)) {
2167 		const char *match;
2168 		char *expanded_line;
2169 
2170 		if (getline(&line, &line_len, file) < 0 || !line)
2171 			break;
2172 
2173 		/* Skip lines containing "filename:" */
2174 		match = strstr(line, filename);
2175 		if (match && match[strlen(filename)] == ':')
2176 			continue;
2177 
2178 		expanded_line = strim(line);
2179 		expanded_line = expand_tabs(expanded_line, &line, &line_len);
2180 		if (!expanded_line)
2181 			break;
2182 
2183 		/*
2184 		 * The source code line number (lineno) needs to be kept in
2185 		 * across calls to symbol__parse_objdump_line(), so that it
2186 		 * can associate it with the instructions till the next one.
2187 		 * See disasm_line__new() and struct disasm_line::line_nr.
2188 		 */
2189 		if (symbol__parse_objdump_line(sym, args, expanded_line,
2190 					       &lineno, &fileloc) < 0)
2191 			break;
2192 		nline++;
2193 	}
2194 	free(line);
2195 	free(fileloc);
2196 
2197 	err = finish_command(&objdump_process);
2198 	if (err)
2199 		pr_err("Error running %s\n", command);
2200 
2201 	if (nline == 0) {
2202 		err = -1;
2203 		pr_err("No output from %s\n", command);
2204 	}
2205 
2206 	/*
2207 	 * kallsyms does not have symbol sizes so there may a nop at the end.
2208 	 * Remove it.
2209 	 */
2210 	if (dso__is_kcore(dso))
2211 		delete_last_nop(sym);
2212 
2213 	fclose(file);
2214 
2215 out_close_stdout:
2216 	close(objdump_process.out);
2217 
2218 out_free_command:
2219 	free(command);
2220 	return err;
2221 }
2222 
2223 int symbol__disassemble(struct symbol *sym, struct annotate_args *args)
2224 {
2225 	struct annotation_options *options = args->options;
2226 	struct map *map = args->ms.map;
2227 	struct dso *dso = map__dso(map);
2228 	char symfs_filename[PATH_MAX];
2229 	bool delete_extract = false;
2230 	struct kcore_extract kce;
2231 	bool decomp = false;
2232 	int err = dso__disassemble_filename(dso, symfs_filename, sizeof(symfs_filename));
2233 
2234 	if (err)
2235 		return err;
2236 
2237 	pr_debug("%s: filename=%s, sym=%s, start=%#" PRIx64 ", end=%#" PRIx64 "\n", __func__,
2238 		 symfs_filename, sym->name, map__unmap_ip(map, sym->start),
2239 		 map__unmap_ip(map, sym->end));
2240 
2241 	pr_debug("annotating [%p] %30s : [%p] %30s\n", dso, dso__long_name(dso), sym, sym->name);
2242 
2243 	if (dso__binary_type(dso) == DSO_BINARY_TYPE__BPF_PROG_INFO) {
2244 		return symbol__disassemble_bpf(sym, args);
2245 	} else if (dso__binary_type(dso) == DSO_BINARY_TYPE__BPF_IMAGE) {
2246 		return symbol__disassemble_bpf_image(sym, args);
2247 	} else if (dso__binary_type(dso) == DSO_BINARY_TYPE__NOT_FOUND) {
2248 		return SYMBOL_ANNOTATE_ERRNO__COULDNT_DETERMINE_FILE_TYPE;
2249 	} else if (dso__is_kcore(dso)) {
2250 		kce.addr = map__rip_2objdump(map, sym->start);
2251 		kce.kcore_filename = symfs_filename;
2252 		kce.len = sym->end - sym->start;
2253 		kce.offs = sym->start;
2254 
2255 		if (!kcore_extract__create(&kce)) {
2256 			delete_extract = true;
2257 			strlcpy(symfs_filename, kce.extract_filename, sizeof(symfs_filename));
2258 		}
2259 	} else if (dso__needs_decompress(dso)) {
2260 		char tmp[KMOD_DECOMP_LEN];
2261 
2262 		if (dso__decompress_kmodule_path(dso, symfs_filename, tmp, sizeof(tmp)) < 0)
2263 			return -1;
2264 
2265 		decomp = true;
2266 		strcpy(symfs_filename, tmp);
2267 	}
2268 
2269 	/*
2270 	 * For powerpc data type profiling, use the dso__data_read_offset to
2271 	 * read raw instruction directly and interpret the binary code to
2272 	 * understand instructions and register fields. For sort keys as type
2273 	 * and typeoff, disassemble to mnemonic notation is not required in
2274 	 * case of powerpc.
2275 	 */
2276 	if (arch__is(args->arch, "powerpc")) {
2277 		extern const char *sort_order;
2278 
2279 		if (sort_order && !strstr(sort_order, "sym")) {
2280 			err = symbol__disassemble_raw(symfs_filename, sym, args);
2281 			if (err == 0)
2282 				goto out_remove_tmp;
2283 
2284 			err = symbol__disassemble_capstone_powerpc(symfs_filename, sym, args);
2285 			if (err == 0)
2286 				goto out_remove_tmp;
2287 		}
2288 	}
2289 
2290 	/* FIXME: LLVM and CAPSTONE should support source code */
2291 	if (options->annotate_src && !options->hide_src_code) {
2292 		err = symbol__disassemble_objdump(symfs_filename, sym, args);
2293 		if (err == 0)
2294 			goto out_remove_tmp;
2295 	}
2296 
2297 	err = -1;
2298 	for (u8 i = 0; i < ARRAY_SIZE(options->disassemblers) && err != 0; i++) {
2299 		enum perf_disassembler dis = options->disassemblers[i];
2300 
2301 		switch (dis) {
2302 		case PERF_DISASM_LLVM:
2303 			args->options->disassembler_used = PERF_DISASM_LLVM;
2304 			err = symbol__disassemble_llvm(symfs_filename, sym, args);
2305 			break;
2306 		case PERF_DISASM_CAPSTONE:
2307 			args->options->disassembler_used = PERF_DISASM_CAPSTONE;
2308 			err = symbol__disassemble_capstone(symfs_filename, sym, args);
2309 			break;
2310 		case PERF_DISASM_OBJDUMP:
2311 			args->options->disassembler_used = PERF_DISASM_OBJDUMP;
2312 			err = symbol__disassemble_objdump(symfs_filename, sym, args);
2313 			break;
2314 		case PERF_DISASM_UNKNOWN: /* End of disassemblers. */
2315 		default:
2316 			args->options->disassembler_used = PERF_DISASM_UNKNOWN;
2317 			goto out_remove_tmp;
2318 		}
2319 		if (err == 0)
2320 			pr_debug("Disassembled with %s\n", perf_disassembler__strs[dis]);
2321 	}
2322 out_remove_tmp:
2323 	if (decomp)
2324 		unlink(symfs_filename);
2325 
2326 	if (delete_extract)
2327 		kcore_extract__delete(&kce);
2328 
2329 	return err;
2330 }
2331