xref: /linux/tools/perf/util/llvm.c (revision 62d7cdc8d58702feb31b320f1713642e3977d7f3)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "llvm.h"
3 #include "annotate.h"
4 #include "debug.h"
5 #include "dso.h"
6 #include "map.h"
7 #include "namespaces.h"
8 #include "srcline.h"
9 #include "symbol.h"
10 #include <errno.h>
11 #include <fcntl.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <linux/zalloc.h>
15 #include <linux/bitops.h>
16 
17 #ifdef HAVE_LIBLLVM_SUPPORT
18 #include "llvm-c-helpers.h"
19 #include <llvm-c/Disassembler.h>
20 #include <llvm-c/Target.h>
21 #endif
22 
23 #ifdef HAVE_LIBLLVM_SUPPORT
24 static void free_llvm_inline_frames(struct llvm_a2l_frame *inline_frames,
25 				    int num_frames)
26 {
27 	if (inline_frames != NULL) {
28 		for (int i = 0; i < num_frames; ++i) {
29 			zfree(&inline_frames[i].filename);
30 			zfree(&inline_frames[i].funcname);
31 		}
32 		zfree(&inline_frames);
33 	}
34 }
35 #endif
36 
37 int llvm__addr2line(const char *dso_name __maybe_unused, u64 addr __maybe_unused,
38 		     char **file __maybe_unused, unsigned int *line __maybe_unused,
39 		     struct dso *dso __maybe_unused, bool unwind_inlines __maybe_unused,
40 		     struct inline_node *node __maybe_unused, struct symbol *sym __maybe_unused)
41 {
42 #ifdef HAVE_LIBLLVM_SUPPORT
43 	struct llvm_a2l_frame *inline_frames = NULL;
44 	int num_frames = llvm_addr2line(dso_name, addr, file, line,
45 					node && unwind_inlines, &inline_frames);
46 
47 	if (num_frames <= 0 || !inline_frames) {
48 		/*
49 		 * Error (< 0 -> iterate fallbacks), missing line info (0), or
50 		 * we resolved lines without wanting inlines (1).
51 		 */
52 		return num_frames;
53 	}
54 
55 	for (int i = 0; i < num_frames; ++i) {
56 		struct symbol *inline_sym =
57 			new_inline_sym(dso, sym, inline_frames[i].funcname);
58 		char *srcline = NULL;
59 
60 		if (inline_frames[i].filename) {
61 			srcline =
62 				srcline_from_fileline(inline_frames[i].filename,
63 						      inline_frames[i].line);
64 		}
65 		if (inline_list__append(inline_sym, srcline, node) != 0) {
66 			if (file)
67 				zfree(file);
68 			inline_node__clear_frames(node);
69 			free_llvm_inline_frames(inline_frames, num_frames);
70 			return -1;
71 		}
72 	}
73 	free_llvm_inline_frames(inline_frames, num_frames);
74 
75 	return num_frames;
76 #else
77 	return -1;
78 #endif
79 }
80 
81 #ifdef HAVE_LIBLLVM_SUPPORT
82 static void init_llvm(void)
83 {
84 	static bool init;
85 
86 	if (!init) {
87 		LLVMInitializeAllTargetInfos();
88 		LLVMInitializeAllTargetMCs();
89 		LLVMInitializeAllDisassemblers();
90 		init = true;
91 	}
92 }
93 
94 /*
95  * Whenever LLVM wants to resolve an address into a symbol, it calls this
96  * callback. We don't ever actually _return_ anything (in particular, because
97  * it puts quotation marks around what we return), but we use this as a hint
98  * that there is a branch or PC-relative address in the expression that we
99  * should add some textual annotation for after the instruction. The caller
100  * will use this information to add the actual annotation.
101  */
102 struct symbol_lookup_storage {
103 	u64 branch_addr;
104 	u64 pcrel_load_addr;
105 };
106 
107 static const char *
108 symbol_lookup_callback(void *disinfo, uint64_t value,
109 		       uint64_t *ref_type,
110 		       uint64_t address __maybe_unused,
111 		       const char **ref __maybe_unused)
112 {
113 	struct symbol_lookup_storage *storage = disinfo;
114 
115 	if (*ref_type == LLVMDisassembler_ReferenceType_In_Branch)
116 		storage->branch_addr = value;
117 	else if (*ref_type == LLVMDisassembler_ReferenceType_In_PCrel_Load)
118 		storage->pcrel_load_addr = value;
119 	else if (*ref_type == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
120 		uint64_t adrp_imm;
121 
122 		/* immhi (bits 23:5) and immlo (bits 30:29) */
123 		adrp_imm = ((value & 0x00ffffe0) >> 3) | ((value >> 29) & 0x3);
124 		adrp_imm = sign_extend64(adrp_imm, 20);
125 
126 		/* Calculate the target page address */
127 		storage->pcrel_load_addr = (address & ~0xfffULL) + (adrp_imm << 12);
128 	}
129 	*ref_type = LLVMDisassembler_ReferenceType_InOut_None;
130 	return NULL;
131 }
132 #endif
133 
134 int symbol__disassemble_llvm(const char *filename, struct symbol *sym,
135 			     struct annotate_args *args __maybe_unused)
136 {
137 #ifdef HAVE_LIBLLVM_SUPPORT
138 	struct annotation *notes = symbol__annotation(sym);
139 	struct map *map = args->ms->map;
140 	struct dso *dso = map__dso(map);
141 	u64 start = map__rip_2objdump(map, sym->start);
142 	/* Malloc-ed buffer containing instructions read from disk. */
143 	u8 *code_buf = NULL;
144 	/* Pointer to code to be disassembled. */
145 	const u8 *buf;
146 	u64 buf_len;
147 	u64 pc;
148 	bool is_64bit;
149 	char disasm_buf[2048];
150 	size_t disasm_len;
151 	struct disasm_line *dl;
152 	LLVMDisasmContextRef disasm = NULL;
153 	struct symbol_lookup_storage storage;
154 	char *line_storage = NULL;
155 	size_t line_storage_len = 0;
156 	int ret = -1;
157 
158 	if (args->options->objdump_path)
159 		return -1;
160 
161 	buf = dso__read_symbol(dso, filename, map, sym,
162 			       &code_buf, &buf_len, &is_64bit);
163 	if (buf == NULL)
164 		return errno;
165 
166 	init_llvm();
167 	if (arch__is_x86(args->arch)) {
168 		const char *triplet = is_64bit ? "x86_64-pc-linux" : "i686-pc-linux";
169 
170 		disasm = LLVMCreateDisasm(triplet, &storage, /*tag_type=*/0,
171 					  /*get_op_info=*/NULL, symbol_lookup_callback);
172 	} else {
173 		char triplet[64];
174 		const char *features = NULL;
175 
176 		scnprintf(triplet, sizeof(triplet), "%s-linux-gnu",
177 			  args->arch->name);
178 		if (args->arch->id.e_machine == EM_AARCH64)
179 			features = "+all";
180 		disasm = LLVMCreateDisasmCPUFeatures(triplet, /*cpu=*/"",
181 						     features, &storage,
182 						     /*tag_type=*/0,
183 						     /*get_op_info=*/NULL,
184 						     symbol_lookup_callback);
185 	}
186 
187 	if (disasm == NULL)
188 		goto err;
189 
190 	if (args->options->disassembler_style &&
191 	    !strcmp(args->options->disassembler_style, "intel"))
192 		LLVMSetDisasmOptions(disasm,
193 				     LLVMDisassembler_Option_AsmPrinterVariant);
194 
195 	/*
196 	 * This needs to be set after AsmPrinterVariant, due to a bug in LLVM;
197 	 * setting AsmPrinterVariant makes a new instruction printer, making it
198 	 * forget about the PrintImmHex flag (which is applied before if both
199 	 * are given to the same call).
200 	 */
201 	LLVMSetDisasmOptions(disasm, LLVMDisassembler_Option_PrintImmHex);
202 
203 	/* add the function address and name */
204 	scnprintf(disasm_buf, sizeof(disasm_buf), "%#"PRIx64" <%s>:",
205 		  start, sym->name);
206 
207 	args->offset = -1;
208 	args->line = disasm_buf;
209 	args->line_nr = 0;
210 	args->fileloc = NULL;
211 	args->ms->sym = sym;
212 
213 	dl = disasm_line__new(args);
214 	if (dl == NULL)
215 		goto err;
216 
217 	annotation_line__add(&dl->al, &notes->src->source);
218 
219 	pc = start;
220 	for (u64 offset = 0; offset < buf_len; ) {
221 		unsigned int ins_len;
222 
223 		storage.branch_addr = 0;
224 		storage.pcrel_load_addr = 0;
225 
226 		/*
227 		 * LLVM's API has the code be disassembled as non-const, cast
228 		 * here as we may be disassembling from mapped read-only memory.
229 		 */
230 		ins_len = LLVMDisasmInstruction(disasm, (u8 *)(buf + offset),
231 						buf_len - offset, pc,
232 						disasm_buf, sizeof(disasm_buf));
233 		if (ins_len == 0)
234 			goto err;
235 		disasm_len = strlen(disasm_buf);
236 
237 		if (storage.branch_addr != 0) {
238 			char *name = llvm_name_for_code(dso, filename,
239 							storage.branch_addr);
240 			if (name != NULL) {
241 				disasm_len += scnprintf(disasm_buf + disasm_len,
242 							sizeof(disasm_buf) -
243 								disasm_len,
244 							" <%s>", name);
245 				free(name);
246 			}
247 		}
248 		if (storage.pcrel_load_addr != 0) {
249 			char *name;
250 
251 			if (arch__is_arm64(args->arch)) {
252 				/*
253 				 * For arm64, replace the immediate operand with
254 				 * the resolved address to match objdump's output.
255 				 *
256 				 * Example conversion:
257 				 *   From: adrp  x18, 8014
258 				 *   To:   adrp  x18, ffff800081f5f000
259 				 */
260 				char *s = strchr(disasm_buf, ',');
261 
262 				if (s == NULL)
263 					goto err;
264 
265 				s++;
266 				*s = '\0';
267 				disasm_len = strlen(disasm_buf);
268 				disasm_len += scnprintf(disasm_buf + disasm_len,
269 							sizeof(disasm_buf) - disasm_len,
270 							" %"PRIx64,
271 							storage.pcrel_load_addr);
272 			} else {
273 				/*
274 				 * For other archs, append the resolved address
275 				 * as an inline comment.
276 				 */
277 				disasm_len += scnprintf(disasm_buf + disasm_len,
278 							sizeof(disasm_buf) - disasm_len,
279 							"  # %#"PRIx64,
280 							storage.pcrel_load_addr);
281 			}
282 
283 			/* Append the resolved symbol name if available */
284 			name = llvm_name_for_data(dso, filename, storage.pcrel_load_addr);
285 			if (name) {
286 				disasm_len += scnprintf(disasm_buf + disasm_len,
287 							sizeof(disasm_buf) -
288 							disasm_len,
289 							" <%s>", name);
290 				free(name);
291 			}
292 		}
293 
294 		args->offset = offset;
295 		args->line = expand_tabs(disasm_buf, &line_storage,
296 					 &line_storage_len);
297 		args->line_nr = 0;
298 		args->fileloc = NULL;
299 		args->ms->sym = sym;
300 
301 		llvm_addr2line(filename, pc, &args->fileloc,
302 			       (unsigned int *)&args->line_nr, false, NULL);
303 
304 		dl = disasm_line__new(args);
305 		if (dl == NULL) {
306 			free(args->fileloc);
307 			goto err;
308 		}
309 
310 		annotation_line__add(&dl->al, &notes->src->source);
311 
312 		free(args->fileloc);
313 		pc += ins_len;
314 		offset += ins_len;
315 	}
316 
317 	ret = 0;
318 
319 err:
320 	LLVMDisasmDispose(disasm);
321 	free(code_buf);
322 	free(line_storage);
323 	return ret;
324 #else // HAVE_LIBLLVM_SUPPORT
325 	pr_debug("The LLVM disassembler isn't linked in for %s in %s\n",
326 		 sym->name, filename);
327 	return -1;
328 #endif
329 }
330