xref: /linux/tools/perf/jvmti/jvmti_agent.c (revision 9e90c7985229430428dc9ba0ec7fe422901b456d)
1 /*
2  * jvmti_agent.c: JVMTI agent interface
3  *
4  * Adapted from the Oprofile code in opagent.c:
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  * Copyright 2007 OProfile authors
20  * Jens Wilke
21  * Daniel Hansel
22  * Copyright IBM Corporation 2007
23  */
24 #include <sys/types.h>
25 #include <sys/stat.h> /* for mkdir() */
26 #include <stdio.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <limits.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <time.h>
35 #include <sys/mman.h>
36 #include <syscall.h> /* for gettid() */
37 #include <err.h>
38 #include <linux/kernel.h>
39 
40 #include "jvmti_agent.h"
41 #include "../util/jitdump.h"
42 
43 #define JIT_LANG "java"
44 
45 static char jit_path[PATH_MAX];
46 static void *marker_addr;
47 
48 static inline pid_t gettid(void)
49 {
50 	return (pid_t)syscall(__NR_gettid);
51 }
52 
53 static int get_e_machine(struct jitheader *hdr)
54 {
55 	ssize_t sret;
56 	char id[16];
57 	int fd, ret = -1;
58 	struct {
59 		uint16_t e_type;
60 		uint16_t e_machine;
61 	} info;
62 
63 	fd = open("/proc/self/exe", O_RDONLY);
64 	if (fd == -1)
65 		return -1;
66 
67 	sret = read(fd, id, sizeof(id));
68 	if (sret != sizeof(id))
69 		goto error;
70 
71 	/* check ELF signature */
72 	if (id[0] != 0x7f || id[1] != 'E' || id[2] != 'L' || id[3] != 'F')
73 		goto error;
74 
75 	sret = read(fd, &info, sizeof(info));
76 	if (sret != sizeof(info))
77 		goto error;
78 
79 	hdr->elf_mach = info.e_machine;
80 	ret = 0;
81 error:
82 	close(fd);
83 	return ret;
84 }
85 
86 static int use_arch_timestamp;
87 
88 static inline uint64_t
89 get_arch_timestamp(void)
90 {
91 #if defined(__i386__) || defined(__x86_64__)
92 	unsigned int low, high;
93 
94 	asm volatile("rdtsc" : "=a" (low), "=d" (high));
95 
96 	return low | ((uint64_t)high) << 32;
97 #else
98 	return 0;
99 #endif
100 }
101 
102 #define NSEC_PER_SEC	1000000000
103 static int perf_clk_id = CLOCK_MONOTONIC;
104 
105 static inline uint64_t
106 timespec_to_ns(const struct timespec *ts)
107 {
108         return ((uint64_t) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
109 }
110 
111 static inline uint64_t
112 perf_get_timestamp(void)
113 {
114 	struct timespec ts;
115 	int ret;
116 
117 	if (use_arch_timestamp)
118 		return get_arch_timestamp();
119 
120 	ret = clock_gettime(perf_clk_id, &ts);
121 	if (ret)
122 		return 0;
123 
124 	return timespec_to_ns(&ts);
125 }
126 
127 static int
128 debug_cache_init(void)
129 {
130 	char str[32];
131 	char *base, *p;
132 	struct tm tm;
133 	time_t t;
134 	int ret;
135 
136 	time(&t);
137 	localtime_r(&t, &tm);
138 
139 	base = getenv("JITDUMPDIR");
140 	if (!base)
141 		base = getenv("HOME");
142 	if (!base)
143 		base = ".";
144 
145 	strftime(str, sizeof(str), JIT_LANG"-jit-%Y%m%d", &tm);
146 
147 	snprintf(jit_path, PATH_MAX - 1, "%s/.debug/", base);
148 
149 	ret = mkdir(jit_path, 0755);
150 	if (ret == -1) {
151 		if (errno != EEXIST) {
152 			warn("jvmti: cannot create jit cache dir %s", jit_path);
153 			return -1;
154 		}
155 	}
156 
157 	snprintf(jit_path, PATH_MAX - 1, "%s/.debug/jit", base);
158 	ret = mkdir(jit_path, 0755);
159 	if (ret == -1) {
160 		if (errno != EEXIST) {
161 			warn("cannot create jit cache dir %s", jit_path);
162 			return -1;
163 		}
164 	}
165 
166 	snprintf(jit_path, PATH_MAX - 1, "%s/.debug/jit/%s.XXXXXXXX", base, str);
167 
168 	p = mkdtemp(jit_path);
169 	if (p != jit_path) {
170 		warn("cannot create jit cache dir %s", jit_path);
171 		return -1;
172 	}
173 
174 	return 0;
175 }
176 
177 static int
178 perf_open_marker_file(int fd)
179 {
180 	long pgsz;
181 
182 	pgsz = sysconf(_SC_PAGESIZE);
183 	if (pgsz == -1)
184 		return -1;
185 
186 	/*
187 	 * we mmap the jitdump to create an MMAP RECORD in perf.data file.
188 	 * The mmap is captured either live (perf record running when we mmap)
189 	 * or  in deferred mode, via /proc/PID/maps
190 	 * the MMAP record is used as a marker of a jitdump file for more meta
191 	 * data info about the jitted code. Perf report/annotate detect this
192 	 * special filename and process the jitdump file.
193 	 *
194 	 * mapping must be PROT_EXEC to ensure it is captured by perf record
195 	 * even when not using -d option
196 	 */
197 	marker_addr = mmap(NULL, pgsz, PROT_READ|PROT_EXEC, MAP_PRIVATE, fd, 0);
198 	return (marker_addr == MAP_FAILED) ? -1 : 0;
199 }
200 
201 static void
202 perf_close_marker_file(void)
203 {
204 	long pgsz;
205 
206 	if (!marker_addr)
207 		return;
208 
209 	pgsz = sysconf(_SC_PAGESIZE);
210 	if (pgsz == -1)
211 		return;
212 
213 	munmap(marker_addr, pgsz);
214 }
215 
216 static void
217 init_arch_timestamp(void)
218 {
219 	char *str = getenv("JITDUMP_USE_ARCH_TIMESTAMP");
220 
221 	if (!str || !*str || !strcmp(str, "0"))
222 		return;
223 
224 	use_arch_timestamp = 1;
225 }
226 
227 void *jvmti_open(void)
228 {
229 	char dump_path[PATH_MAX];
230 	struct jitheader header;
231 	int fd;
232 	FILE *fp;
233 
234 	init_arch_timestamp();
235 
236 	/*
237 	 * check if clockid is supported
238 	 */
239 	if (!perf_get_timestamp()) {
240 		if (use_arch_timestamp)
241 			warnx("jvmti: arch timestamp not supported");
242 		else
243 			warnx("jvmti: kernel does not support %d clock id", perf_clk_id);
244 	}
245 
246 	memset(&header, 0, sizeof(header));
247 
248 	debug_cache_init();
249 
250 	/*
251 	 * jitdump file name
252 	 */
253 	scnprintf(dump_path, PATH_MAX, "%s/jit-%i.dump", jit_path, getpid());
254 
255 	fd = open(dump_path, O_CREAT|O_TRUNC|O_RDWR, 0666);
256 	if (fd == -1)
257 		return NULL;
258 
259 	/*
260 	 * create perf.data maker for the jitdump file
261 	 */
262 	if (perf_open_marker_file(fd)) {
263 		warnx("jvmti: failed to create marker file");
264 		return NULL;
265 	}
266 
267 	fp = fdopen(fd, "w+");
268 	if (!fp) {
269 		warn("jvmti: cannot create %s", dump_path);
270 		close(fd);
271 		goto error;
272 	}
273 
274 	warnx("jvmti: jitdump in %s", dump_path);
275 
276 	if (get_e_machine(&header)) {
277 		warn("get_e_machine failed\n");
278 		goto error;
279 	}
280 
281 	header.magic      = JITHEADER_MAGIC;
282 	header.version    = JITHEADER_VERSION;
283 	header.total_size = sizeof(header);
284 	header.pid        = getpid();
285 
286 	header.timestamp = perf_get_timestamp();
287 
288 	if (use_arch_timestamp)
289 		header.flags |= JITDUMP_FLAGS_ARCH_TIMESTAMP;
290 
291 	if (!fwrite(&header, sizeof(header), 1, fp)) {
292 		warn("jvmti: cannot write dumpfile header");
293 		goto error;
294 	}
295 	return fp;
296 error:
297 	fclose(fp);
298 	return NULL;
299 }
300 
301 int
302 jvmti_close(void *agent)
303 {
304 	struct jr_code_close rec;
305 	FILE *fp = agent;
306 
307 	if (!fp) {
308 		warnx("jvmti: invalid fd in close_agent");
309 		return -1;
310 	}
311 
312 	rec.p.id = JIT_CODE_CLOSE;
313 	rec.p.total_size = sizeof(rec);
314 
315 	rec.p.timestamp = perf_get_timestamp();
316 
317 	if (!fwrite(&rec, sizeof(rec), 1, fp))
318 		return -1;
319 
320 	fclose(fp);
321 
322 	fp = NULL;
323 
324 	perf_close_marker_file();
325 
326 	return 0;
327 }
328 
329 int
330 jvmti_write_code(void *agent, char const *sym,
331 	uint64_t vma, void const *code, unsigned int const size)
332 {
333 	static int code_generation = 1;
334 	struct jr_code_load rec;
335 	size_t sym_len;
336 	FILE *fp = agent;
337 	int ret = -1;
338 
339 	/* don't care about 0 length function, no samples */
340 	if (size == 0)
341 		return 0;
342 
343 	if (!fp) {
344 		warnx("jvmti: invalid fd in write_native_code");
345 		return -1;
346 	}
347 
348 	sym_len = strlen(sym) + 1;
349 
350 	rec.p.id           = JIT_CODE_LOAD;
351 	rec.p.total_size   = sizeof(rec) + sym_len;
352 	rec.p.timestamp    = perf_get_timestamp();
353 
354 	rec.code_size  = size;
355 	rec.vma        = vma;
356 	rec.code_addr  = vma;
357 	rec.pid	       = getpid();
358 	rec.tid	       = gettid();
359 
360 	if (code)
361 		rec.p.total_size += size;
362 
363 	/*
364 	 * If JVM is multi-threaded, nultiple concurrent calls to agent
365 	 * may be possible, so protect file writes
366 	 */
367 	flockfile(fp);
368 
369 	/*
370 	 * get code index inside lock to avoid race condition
371 	 */
372 	rec.code_index = code_generation++;
373 
374 	ret = fwrite_unlocked(&rec, sizeof(rec), 1, fp);
375 	fwrite_unlocked(sym, sym_len, 1, fp);
376 
377 	if (code)
378 		fwrite_unlocked(code, size, 1, fp);
379 
380 	funlockfile(fp);
381 
382 	ret = 0;
383 
384 	return ret;
385 }
386 
387 int
388 jvmti_write_debug_info(void *agent, uint64_t code,
389     int nr_lines, jvmti_line_info_t *li,
390     const char * const * file_names)
391 {
392 	struct jr_code_debug_info rec;
393 	size_t sret, len, size, flen = 0;
394 	uint64_t addr;
395 	FILE *fp = agent;
396 	int i;
397 
398 	/*
399 	 * no entry to write
400 	 */
401 	if (!nr_lines)
402 		return 0;
403 
404 	if (!fp) {
405 		warnx("jvmti: invalid fd in write_debug_info");
406 		return -1;
407 	}
408 
409 	for (i = 0; i < nr_lines; ++i) {
410 	    flen += strlen(file_names[i]) + 1;
411 	}
412 
413 	rec.p.id        = JIT_CODE_DEBUG_INFO;
414 	size            = sizeof(rec);
415 	rec.p.timestamp = perf_get_timestamp();
416 	rec.code_addr   = (uint64_t)(uintptr_t)code;
417 	rec.nr_entry    = nr_lines;
418 
419 	/*
420 	 * on disk source line info layout:
421 	 * uint64_t : addr
422 	 * int      : line number
423 	 * int      : column discriminator
424 	 * file[]   : source file name
425 	 */
426 	size += nr_lines * sizeof(struct debug_entry);
427 	size += flen;
428 	rec.p.total_size = size;
429 
430 	/*
431 	 * If JVM is multi-threaded, nultiple concurrent calls to agent
432 	 * may be possible, so protect file writes
433 	 */
434 	flockfile(fp);
435 
436 	sret = fwrite_unlocked(&rec, sizeof(rec), 1, fp);
437 	if (sret != 1)
438 		goto error;
439 
440 	for (i = 0; i < nr_lines; i++) {
441 
442 		addr = (uint64_t)li[i].pc;
443 		len  = sizeof(addr);
444 		sret = fwrite_unlocked(&addr, len, 1, fp);
445 		if (sret != 1)
446 			goto error;
447 
448 		len  = sizeof(li[0].line_number);
449 		sret = fwrite_unlocked(&li[i].line_number, len, 1, fp);
450 		if (sret != 1)
451 			goto error;
452 
453 		len  = sizeof(li[0].discrim);
454 		sret = fwrite_unlocked(&li[i].discrim, len, 1, fp);
455 		if (sret != 1)
456 			goto error;
457 
458 		sret = fwrite_unlocked(file_names[i], strlen(file_names[i]) + 1, 1, fp);
459 		if (sret != 1)
460 			goto error;
461 	}
462 	funlockfile(fp);
463 	return 0;
464 error:
465 	funlockfile(fp);
466 	return -1;
467 }
468