Skip to contentSkip to conversation

perf: add support for profiling jitted code

PATCH Superseded Stephane Eranian 7 participants 26 messages Feb 10, 2015 – Feb 18, 2015 perf events

v1 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

cover perf: add support for profiling jitted code

This patch series extends perf record/report/annotate to enable profiling of jitted (just-in-time compiled) code. The current perf tool provides very limited support for profiling jitted code for some runtime environments. But the support is experimental and cannot be used in complex environments. It relies on files in /tmp, for instance. It does not support annotate mode or rejitted code.

This patch series adds a better way of profiling jitted code with the following advantages:
- support any jitted code environment (some with modifications)
- support Java runtime with JVMTI interface with no modifications
- provides a portable JVMTI agent library
- known to support V8 runtime
- known to support DART runtime
- supports code rejitting and movements
- no files in /tmp
- meta-data file is unique to each run
- no changes to perf report/annotate

The support is based on cooperation with the runtime. For Java runtimes, supporting the JVMTI interface, there is no change necessary. For other runtimes, modifications are necessary to emit the meta-data necessary to support symbolization and annotation of the samples. Those modifications are fairly straighforward and already tested on V8 and DART.

The jit environment emits a binary dump file which contains the jitted code (in raw format) and meta-data describing the mapping of functions. The binary format is documented in the jitdump.h header file. It is adapted from the OProfile jitdump format.

To enable synchronization of the runtime MMAPs with those recorded by the kernel on behalf of the perf tool, the runtime needs to timestamp any record in the dump file using the same time source. The current patch series is relying on Sonny Rao's posix-clock patch series posted on LKML in 2013. The link to the patches is:

	https://lkml.org/lkml/2013/12/6/1044

Without this driver installed, records emitted by the runtime cannot be properly synchronized (inserted in the flow on MMAPS) and symbolization may be incorrect, especially for runtimes moving code around.

The current support only works when the runtime is monitored from start to finish: perf record java --agenpath:libpfmjvmti.so my_class.

Once the run is completed, the jitdump file needs to be injected into the perf.data file. This is accomplished by using the perf inject command. This will also generate an ELF image for each jitted function. The inject MMAP records will point to those ELF images. The reasoning behind using ELF images is that it makes processing for perf report and annotate automatic and transparent. It also makes it easier to package and analyze on a remote machine.

The reporting is unchanged, simply invoke perf report or perf annotate on the modified perf.data file. The jitted code will appear symbolized and the assembly view will display the instruction level profile!

As an added bonus, the series includes support for demangling function signature from OpenJDK.

The current patch series does not include support for source line information. Therefore, the source code cannot yet be displayed in perf annotate. This will come in a later update.

Furthermore, we believe there is a way to skip the perf inject phase and have perf report/annotate directly inject the MMAP records on the fly during processing of the perf.data file. Perf report would also generate the ELF files if necessary. Such optimization, would make using this extension seamless in system-wide mode and larger environments. This will be added in a later update as well.

To use the new feature:
- install the posix clock driver
- make sure you chmod 644 /dev/trace_clock
- compile perf
- cd tools/perf/jvmti; make; install wherever is appropriate

Example using openJDK:

   $ perf record java -agentpath:libjvmti.so my_class
   java: jvmti: jitdump in $HOME/.debug/jit/java-jit-20150207.XXL9649H/jit-6320.dump
   $ perf inject -i perf.data -j $HOME/.debug/jit/java-jit-20150207.XXL9649H/jit-6320.dump -o perf.data.jitted
   $ perf report -i perf.data.jitted

Thanks to all the contributors and testers.

Enjoy,

Stephane Eranian (4):
perf tools: add Java demangling support
perf tools: pass timestamp to map_init
perf inject: add jitdump mmap injection support
perf tools: add JVMTI agent library

 tools/perf/Documentation/perf-inject.txt |  11 +
 tools/perf/Makefile.perf                 |   6 +-
 tools/perf/builtin-inject.c              | 205 ++++++++++++++
 tools/perf/jvmti/Makefile                |  70 +++++
 tools/perf/jvmti/jvmti_agent.c           | 349 +++++++++++++++++++++++
 tools/perf/jvmti/jvmti_agent.h           |  23 ++
 tools/perf/jvmti/libjvmti.c              | 149 ++++++++++
 tools/perf/util/genelf.c                 | 463 +++++++++++++++++++++++++++++++
 tools/perf/util/genelf.h                 |   6 +
 tools/perf/util/jit.h                    |  27 ++
 tools/perf/util/jitdump.c                | 233 ++++++++++++++++
 tools/perf/util/jitdump.h                |  92 ++++++
 tools/perf/util/machine.c                |   8 +-
 tools/perf/util/map.c                    |   9 +-
 tools/perf/util/map.h                    |   5 +-
 tools/perf/util/symbol-elf.c             |   2 +
 tools/perf/util/symbol.c                 | 195 ++++++++++++-
 tools/perf/util/symbol.h                 |   1 +
 18 files changed, 1844 insertions(+), 10 deletions(-)
 create mode 100644 tools/perf/jvmti/Makefile
 create mode 100644 tools/perf/jvmti/jvmti_agent.c
 create mode 100644 tools/perf/jvmti/jvmti_agent.h
 create mode 100644 tools/perf/jvmti/libjvmti.c
 create mode 100644 tools/perf/util/genelf.c
 create mode 100644 tools/perf/util/genelf.h
 create mode 100644 tools/perf/util/jit.h
 create mode 100644 tools/perf/util/jitdump.c
 create mode 100644 tools/perf/util/jitdump.h
Signature · 1 line
1.9.1
#4 lore raw

PATCH 2/4 perf tools: pass timestamp to map_init

This patch passes the sample timestamp down to the map_init function. This is used to sort mmap records.

---
 tools/perf/util/machine.c | 8 ++++++--
 tools/perf/util/map.c     | 9 +++++----
 tools/perf/util/map.h     | 5 +++--
 3 files changed, 14 insertions(+), 8 deletions(-)
tools/perf/util/machine.c +6 -2
index 1bca3a9..3288a71 100644
@@ -1176,7 +1176,9 @@ int machine__process_mmap2_event(struct machine *machine,
 			event->mmap2.ino_generation,
 			event->mmap2.prot,
 			event->mmap2.flags,
-			event->mmap2.filename, type, thread);
+			event->mmap2.filename, type,
+			thread,
+			sample->time);
 
 	if (map == NULL)
 		goto out_problem;
@@ -1223,7 +1225,9 @@ int machine__process_mmap_event(struct machine *machine, union perf_event *event
 			event->mmap.len, event->mmap.pgoff,
 			event->mmap.pid, 0, 0, 0, 0, 0, 0,
 			event->mmap.filename,
-			type, thread);
+			type,
+			thread,
+			sample->time);
 
 	if (map == NULL)
 		goto out_problem;
tools/perf/util/map.c +5 -4
index 62ca9f2..fac9d34 100644
@@ -123,7 +123,7 @@ static inline bool replace_android_lib(const char *filename, char *newfilename)
 }
 
 void map__init(struct map *map, enum map_type type,
-	       u64 start, u64 end, u64 pgoff, struct dso *dso)
+	       u64 start, u64 end, u64 pgoff, struct dso *dso, u64 ts)
 {
 	map->type     = type;
 	map->start    = start;
@@ -137,12 +137,13 @@ void map__init(struct map *map, enum map_type type,
 	map->groups   = NULL;
 	map->referenced = false;
 	map->erange_warned = false;
+	map->time     = ts;
 }
 
 struct map *map__new(struct machine *machine, u64 start, u64 len,
 		     u64 pgoff, u32 pid, u32 d_maj, u32 d_min, u64 ino,
 		     u64 ino_gen, u32 prot, u32 flags, char *filename,
-		     enum map_type type, struct thread *thread)
+		     enum map_type type, struct thread *thread, u64 ts)
 {
 	struct map *map = malloc(sizeof(*map));
 
@@ -182,7 +183,7 @@ struct map *map__new(struct machine *machine, u64 start, u64 len,
 		if (dso == NULL)
 			goto out_delete;
 
-		map__init(map, type, start, start + len, pgoff, dso);
+		map__init(map, type, start, start + len, pgoff, dso, ts);
 
 		if (anon || no_dso) {
 			map->map_ip = map->unmap_ip = identity__map_ip;
@@ -215,7 +216,7 @@ struct map *map__new2(u64 start, struct dso *dso, enum map_type type)
 		/*
 		 * ->end will be filled after we load all the symbols
 		 */
-		map__init(map, type, start, 0, 0, dso);
+		map__init(map, type, start, 0, 0, dso, 0);
 	}
 
 	return map;
tools/perf/util/map.h +3 -2
index 0e42438..9320bf8 100644
@@ -42,6 +42,7 @@ struct map {
 	u32			maj, min; /* only valid for MMAP2 record */
 	u64			ino;      /* only valid for MMAP2 record */
 	u64			ino_generation;/* only valid for MMAP2 record */
+	u64			time;
 
 	/* ip -> dso rip */
 	u64			(*map_ip)(struct map *, u64);
@@ -135,11 +136,11 @@ struct thread;
 typedef int (*symbol_filter_t)(struct map *map, struct symbol *sym);
 
 void map__init(struct map *map, enum map_type type,
-	       u64 start, u64 end, u64 pgoff, struct dso *dso);
+	       u64 start, u64 end, u64 pgoff, struct dso *dso, u64 ts);
 struct map *map__new(struct machine *machine, u64 start, u64 len,
 		     u64 pgoff, u32 pid, u32 d_maj, u32 d_min, u64 ino,
 		     u64 ino_gen, u32 prot, u32 flags,
-		     char *filename, enum map_type type, struct thread *thread);
+		     char *filename, enum map_type type, struct thread *thread, u64 time);
 struct map *map__new2(u64 start, struct dso *dso, enum map_type type);
 void map__delete(struct map *map);
 struct map *map__clone(struct map *map);
Signature · 1 line
1.9.1
#6 lore raw

PATCH 3/4 perf inject: add jitdump mmap injection support

In reply to Stephane Eranian

This patch adds a -j jitdump option to perf inject.

This options injects MMAP records into the perf.data file to cover the jitted code mmaps. It also emits ELF images for each function in the jidump file. Those images are created where the jitdump file is. The MMAP records point to that location as well.

Typical flow:

$ java -agentpath:libpjvmti.so java_class
$ perf inject -j ~/.debug/jit/java-jit-20140514.XXAb0e5C/jit-7640.dump \
              -i perf.data \
              -o perf.data.jitted
$ perf report -i perf.data.jitted

Note that jitdump.h support is not limited to Java, it works with any jitted environment modified to emit the jitdump file format, include those where code can be jitted multiple times and moved around.

The jitdump.h format is adapted from the Oprofile project.

---
 tools/perf/Documentation/perf-inject.txt |  11 +
 tools/perf/Makefile.perf                 |   6 +-
 tools/perf/builtin-inject.c              | 205 ++++++++++++++
 tools/perf/util/genelf.c                 | 463 +++++++++++++++++++++++++++++++
 tools/perf/util/genelf.h                 |   6 +
 tools/perf/util/jit.h                    |  27 ++
 tools/perf/util/jitdump.c                | 233 ++++++++++++++++
 tools/perf/util/jitdump.h                |  92 ++++++
 8 files changed, 1042 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/genelf.c
 create mode 100644 tools/perf/util/genelf.h
 create mode 100644 tools/perf/util/jit.h
 create mode 100644 tools/perf/util/jitdump.c
 create mode 100644 tools/perf/util/jitdump.h
tools/perf/Documentation/perf-inject.txt +11 -0
index dc7442c..237f195 100644
@@ -40,6 +40,17 @@ OPTIONS
 	Merge sched_stat and sched_switch for getting events where and how long
 	tasks slept. sched_switch contains a callchain where a task slept and
 	sched_stat contains a timeslice how long a task slept.
+-j::
+--jit::
+	Merge a jitdump file into the perf.data file by adding mmap records to
+	cover jitted code and emit ELF images for each jitted function. The ELF
+	images are saved in the same directory as the jidump. Use -E to suppress
+	ELF images generation.
+-E::
+--jit-disable-elf::
+	When used with -, it prevents creating the ELF images for each jitted
+	function. Only the jitted code mmap records are injected into the perf.data
+	file. Option as no effect when -j is not used.
 
 --kallsyms=<file>::
 	kallsyms pathname
tools/perf/Makefile.perf +5 -1
index aa6a504..c86c412 100644
@@ -324,6 +324,7 @@ LIB_H += util/perf_regs.h
 LIB_H += util/unwind.h
 LIB_H += util/vdso.h
 LIB_H += util/tsc.h
+LIB_H += util/jitdump.h
 LIB_H += ui/helpline.h
 LIB_H += ui/progress.h
 LIB_H += ui/util.h
@@ -410,6 +411,8 @@ LIB_OBJS += $(OUTPUT)util/data.o
 LIB_OBJS += $(OUTPUT)util/tsc.o
 LIB_OBJS += $(OUTPUT)util/cloexec.o
 LIB_OBJS += $(OUTPUT)util/thread-stack.o
+LIB_OBJS += $(OUTPUT)util/jitdump.o
+LIB_OBJS += $(OUTPUT)util/genelf.o
 
 LIB_OBJS += $(OUTPUT)ui/setup.o
 LIB_OBJS += $(OUTPUT)ui/helpline.o
@@ -496,7 +499,8 @@ BUILTIN_OBJS += $(OUTPUT)builtin-inject.o
 BUILTIN_OBJS += $(OUTPUT)tests/builtin-test.o
 BUILTIN_OBJS += $(OUTPUT)builtin-mem.o
 
-PERFLIBS = $(LIB_FILE) $(LIBAPIKFS) $(LIBTRACEEVENT)
+PERFLIBS = $(LIB_FILE) $(LIBAPIKFS) $(LIBTRACEEVENT) -lcrypto
+
 
 # We choose to avoid "if .. else if .. else .. endif endif"
 # because maintaining the nesting to match is a pain.  If
tools/perf/builtin-inject.c +205 -0

253 lines not on this page · raw message

tools/perf/util/genelf.c new file +463 -0

463 lines not on this page · raw message

tools/perf/util/genelf.h new file +6 -0
new file mode 100644
index 0000000..11307a2
@@ -0,0 +1,6 @@
+#ifndef __GENELF_H__
+#define __GENELF_H__
+
+extern int jit_write_elf(int fd, unsigned long code_addr, const char *sym, const void *code, int csize);
+
+#endif
tools/perf/util/jit.h new file +27 -0
new file mode 100644
index 0000000..e7a54cb
@@ -0,0 +1,27 @@
+#ifndef __JIT_H__
+#define __JIT_H__
+#include <sys/time.h>
+#include <stdint.h>
+
+#include "jitdump.h"
+
+struct jit_buf_desc {
+	union jr_entry  *entry;
+	void            *buf;
+	size_t          bufsize;
+	FILE            *in;
+	int             needs_bswap; /* handles cross-endianess */
+	uint32_t        code_load_count;
+	struct rb_root  code_root;
+};
+ 
+extern int jit_open_dump(const char *name, struct jit_buf_desc *jd);
+extern void jit_close_dump(struct jit_buf_desc *jd);
+extern union jr_entry *jit_get_next_entry(struct jit_buf_desc *jd);
+
+/*
+ * use type = -1 to match any record type
+ */
+extern union jr_entry *jit_get_next_entry_type(struct jit_buf_desc *jd, int type);
+
+#endif /* __JIT_H__ */
tools/perf/util/jitdump.c new file +233 -0

233 lines not on this page · raw message

tools/perf/util/jitdump.h new file +92 -0

92 lines not on this page · raw message

Signature · 1 line
1.9.1
#11 lore raw

PATCH 4/4 perf tools: add JVMTI agent library

In reply to Stephane Eranian

This is a standalone JVMTI library to help profile Java jitted code with perf record/perf report. The library is not installed or compiled automatically by perf Makefile. It is not used directly by perf. It is arch agnostic and has been tested on X86 and ARM. It needs to be used with a Java runtime, such as OpenJDK, as follows:

$ java -agentpath:libjvmti.so .......

When used this way, java will generate a jitdump binary file in $HOME/.debug/java/jit/java-jit-*

This binary dump file contains information to help symbolize and annotate jitted code.

The next step is to inject the jitdump information into the perf.data file:

$ perf inject -j $HOME/.debug/java/jit/java-jit-XXXX/jit-ZZZ.dump \
              -i perf.data -o perf.data.jitted

This injects the MMAP records to cover the jitted code and also generates one ELF image for each jitted function. The ELF images are created in the same subdir as the jitdump file. The MMAP records point there too.

Then to visualize the function or asm profile, simply use the regular perf commands:

$ perf report -i perf.data.jitted
or
$ perf annotate -i perf.data.jitted

JVMTI agent code adapted from OProfile's opagent code.

---
 tools/perf/jvmti/Makefile      |  70 +++++++++
 tools/perf/jvmti/jvmti_agent.c | 349 +++++++++++++++++++++++++++++++++++++++++
 tools/perf/jvmti/jvmti_agent.h |  23 +++
 tools/perf/jvmti/libjvmti.c    | 149 ++++++++++++++++++
 4 files changed, 591 insertions(+)
 create mode 100644 tools/perf/jvmti/Makefile
 create mode 100644 tools/perf/jvmti/jvmti_agent.c
 create mode 100644 tools/perf/jvmti/jvmti_agent.h
 create mode 100644 tools/perf/jvmti/libjvmti.c
tools/perf/jvmti/Makefile new file +70 -0
new file mode 100644
index 0000000..9eda64b
@@ -0,0 +1,70 @@
+ARCH=$(shell uname -m)
+
+ifeq ($(ARCH), x86_64)
+JARCH=amd64
+endif
+ifeq ($(ARCH), armv7l)
+JARCH=armhf
+endif
+ifeq ($(ARCH), armv6l)
+JARCH=armhf
+endif
+ifeq ($(ARCH), ppc64)
+JARCH=powerpc
+endif
+ifeq ($(ARCH), ppc64le)
+JARCH=powerpc
+endif
+
+DESTDIR=/usr/local
+
+VERSION=1
+REVISION=0
+AGE=0
+
+LN=ln -sf
+RM=rm
+
+SJVMTI=libjvmti.so.$(VERSION).$(REVISION).$(AGE)
+VJVMTI=libjvmti.so.$(VERSION)
+SLDFLAGS=-shared -Wl,-soname -Wl,$(VLIBPFM)
+SOLIBEXT=so
+
+JDIR=$(shell /usr/sbin/update-java-alternatives -l | head -1 | cut -d ' ' -f 3)
+# -lrt required in 32-bit mode for clock_gettime()
+LIBS=-lelf -lrt
+INCDIR=-I $(JDIR)/include -I $(JDIR)/include/linux
+
+TARGETS=$(SJVMTI)
+
+SRCS=libjvmti.c jvmti_agent.c
+OBJS=$(SRCS:.c=.o)
+SOBJS=$(OBJS:.o=.lo)
+OPT=-O2 -g -Werror -Wall
+
+CFLAGS=$(INCDIR) $(OPT)
+
+all: $(TARGETS)
+
+.c.o:
+	$(CC) $(CFLAGS) -c $*.c
+.c.lo:
+	$(CC) -fPIC -DPIC $(CFLAGS) -c $*.c -o $*.lo
+
+$(OBJS) $(SOBJS): Makefile jvmti_agent.h ../util/jitdump.h
+
+$(SJVMTI):  $(SOBJS)
+	$(CC) $(CFLAGS) $(SLDFLAGS)  -o $@ $(SOBJS) $(LIBS)
+	$(LN) $@ libjvmti.$(SOLIBEXT)
+
+clean:
+	$(RM) -f *.o *.so.* *.so *.lo
+
+install:
+	-mkdir -p $(DESTDIR)/lib
+	install -m 755 $(SJVMTI) $(DESTDIR)/lib/
+	(cd $(DESTDIR)/lib; $(LN) $(SJVMTI) $(VJVMTI))
+	(cd $(DESTDIR)/lib; $(LN) $(SJVMTI) libjvmti.$(SOLIBEXT))
+	ldconfig
+
+.SUFFIXES: .c .S .o .lo
tools/perf/jvmti/jvmti_agent.c new file +349 -0

349 lines not on this page · raw message

tools/perf/jvmti/jvmti_agent.h new file +23 -0
new file mode 100644
index 0000000..54e5c5e
@@ -0,0 +1,23 @@
+#ifndef __JVMTI_AGENT_H__
+#define __JVMTI_AGENT_H__
+
+#include <sys/types.h>
+#include <stdint.h>
+
+#define __unused __attribute__((unused))
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+void *jvmti_open(void);
+int   jvmti_close(void *agent);
+int   jvmti_write_code(void *agent, char const *symbol_name,
+		       uint64_t vma, void const *code,
+		       const unsigned int code_size);
+
+#if defined(__cplusplus)
+}
+
+#endif
+#endif /* __JVMTI_H__ */
tools/perf/jvmti/libjvmti.c new file +149 -0

149 lines not on this page · raw message

Signature · 1 line
1.9.1
#1 lore raw

PATCH 1/4 perf tools: add Java demangling support

In reply to Stephane Eranian

Add Java function descriptor demangling support.
Something bfd cannot do.

---
 tools/perf/util/symbol-elf.c |   2 +
 tools/perf/util/symbol.c     | 195 ++++++++++++++++++++++++++++++++++++++++++-
 tools/perf/util/symbol.h     |   1 +
 3 files changed, 197 insertions(+), 1 deletion(-)
tools/perf/util/symbol-elf.c +2 -0
index b24f9d8..71ee49b 100644
@@ -1019,6 +1019,8 @@ int dso__load_sym(struct dso *dso, struct map *map,
 				demangle_flags = DMGL_PARAMS | DMGL_ANSI;
 
 			demangled = bfd_demangle(NULL, elf_name, demangle_flags);
+			if (demangled == NULL)
+				demangled = java_demangle_sym(elf_name);
 			if (demangled != NULL)
 				elf_name = demangled;
 		}
tools/perf/util/symbol.c +194 -1

219 lines not on this page · raw message

tools/perf/util/symbol.h +1 -0
index 1650dcb..2a6e23e 100644
@@ -295,4 +295,5 @@ int compare_proc_modules(const char *from, const char *to);
 int setup_list(struct strlist **list, const char *list_str,
 	       const char *list_name);
 
+char * java_demangle_sym(const char *str);
 #endif /* __PERF_SYMBOL */
Signature · 1 line
1.9.1
maintainer
#20 lore raw
In reply to Stephane Eranian
Quoted 7 lines · Stephane Eranian

To enable synchronization of the runtime MMAPs with those recorded by the kernel on behalf of the perf tool, the runtime needs to timestamp any record in the dump file using the same time source. The current patch series is relying on Sonny Rao's posix-clock patch series posted on LKML in 2013. The link to the patches is:

	https://lkml.org/lkml/2013/12/6/1044

At least for x86 you could use something like this:

lkml.kernel.org/r/aa2dd2e4f1e9f2225758be5ba00f14d6909a8ce1.1423180257.git.shli@fb.com

We can re-create the perf_clock() from the tsc with the mult, shift and offset provided in the perf userpage.

maintainer
#7 lore raw

Re: [PATCH 3/4] perf inject: add jitdump mmap injection support

In reply to Stephane Eranian

tools/perf/Makefile.perf BUILTIN_OBJS += $(OUTPUT)builtin-inject.o · line 503

Quoted 12 lines · Stephane Eranian
tools/perf/Makefile.perf +2 -1
index aa6a504..c86c412 100644
@@ -496,7 +499,8 @@ BUILTIN_OBJS += $(OUTPUT)builtin-inject.o
 BUILTIN_OBJS += $(OUTPUT)tests/builtin-test.o
 BUILTIN_OBJS += $(OUTPUT)builtin-mem.o
 
-PERFLIBS = $(LIB_FILE) $(LIBAPIKFS) $(LIBTRACEEVENT)
+PERFLIBS = $(LIB_FILE) $(LIBAPIKFS) $(LIBTRACEEVENT) -lcrypto
+

Should we not add auto-detect magic for that? Otherwise perf will stop building on machines without libssl.

#8 lore raw

Re: [PATCH 3/4] perf inject: add jitdump mmap injection support

Quoted 11 lines · Peter Zijlstra
Quoted 9 lines · Stephane Eranian
tools/perf/Makefile.perf +0 -0
index aa6a504..c86c412 100644
@@ -496,7 +499,8 @@ BUILTIN_OBJS += $(OUTPUT)builtin-inject.o
 BUILTIN_OBJS += $(OUTPUT)tests/builtin-test.o
 BUILTIN_OBJS += $(OUTPUT)builtin-mem.o
 
Quoted 6 lines

tools/perf/Makefile.perf BUILTIN_OBJS += $(OUTPUT)builtin-inject.o · line 503

Quoted 3 lines
tools/perf/Makefile.perf +2 -1
-PERFLIBS = $(LIB_FILE) $(LIBAPIKFS) $(LIBTRACEEVENT)
+PERFLIBS = $(LIB_FILE) $(LIBAPIKFS) $(LIBTRACEEVENT) -lcrypto
+

Should we not add auto-detect magic for that? Otherwise perf will stop building on machines without libssl.

Good point.
The ssl support is needed to create the buildid for each generated ELF image.

#21 lore raw
In reply to Peter Zijlstra

Peter,

Quoted 9 lines · Peter Zijlstra
Quoted 7 lines · Stephane Eranian

To enable synchronization of the runtime MMAPs with those recorded by the kernel on behalf of the perf tool, the runtime needs to timestamp any record in the dump file using the same time source. The current patch series is relying on Sonny Rao's posix-clock patch series posted on LKML in 2013. The link to the patches is:

      https://lkml.org/lkml/2013/12/6/1044
Quoted 6 lines

At least for x86 you could use something like this:

lkml.kernel.org/r/aa2dd2e4f1e9f2225758be5ba00f14d6909a8ce1.1423180257.git.shli@fb.com

We can re-create the perf_clock() from the tsc with the mult, shift and offset provided in the perf userpage.

I had forgotten that I had modified Sonny's patch to use sched_clock(). I will post V2 using David Ahern's driver instead.

But, we need a portable solution, there are jitted environment on other architectures.

#9 lore raw

Re: [PATCH 3/4] perf inject: add jitdump mmap injection support

In reply to Stephane Eranian
Quoted 9 lines · Stephane Eranian
tools/perf/Documentation/perf-inject.txt +1 -0
index dc7442c..237f195 100644
@@ -40,6 +40,17 @@ OPTIONS
  	Merge sched_stat and sched_switch for getting events where and how long
  	tasks slept. sched_switch contains a callchain where a task slept and
  	sched_stat contains a timeslice how long a task slept.
+-j::

tools/perf/Documentation/perf-inject.txt OPTIONS · line 53

Quoted 10 lines
tools/perf/Documentation/perf-inject.txt +10 -0
+--jit::
+	Merge a jitdump file into the perf.data file by adding mmap records to
+	cover jitted code and emit ELF images for each jitted function. The ELF
+	images are saved in the same directory as the jidump. Use -E to suppress
+	ELF images generation.
+-E::
+--jit-disable-elf::
+	When used with -, it prevents creating the ELF images for each jitted
+	function. Only the jitted code mmap records are injected into the perf.data
+	file. Option as no effect when -j is not used.

s/as/has/. But it would better to avoid the double negative. Maye something like this instead:

This option requires -j|--jit.

David

maintainer
#22 lore raw
In reply to Stephane Eranian
Quoted 2 lines · Stephane Eranian

But, we need a portable solution, there are jitted environment on other architectures.

Yeah, I'm aware of that. But the time people are not liking any of those patches.

The thing that seems to have most traction is something like

lkml.kernel.org/r/[email protected]

Which would basically make the trace clock be CLOCK_MONOTONIC.

#23 lore raw
Quoted 5 lines · Peter Zijlstra
Quoted 2 lines · Stephane Eranian

But, we need a portable solution, there are jitted environment on other architectures.

Quoted 9 lines

Yeah, I'm aware of that. But the time people are not liking any of those patches.

The thing that seems to have most traction is something like

   lkml.kernel.org/r/[email protected]

Which would basically make the trace clock be CLOCK_MONOTONIC.

Sure, but IF that solution is ever adopted it will apply to top of tree kernels. In the meantime users of long term kernels (enterprise, LTS, other) need to be able to use this feature.

I understand that Ingo (and probably you as well) have a disdain for the kernel module approach mentioned above and it is not the preferred approach. But given the resistance for over *4 years* to solutions to this problem the module does provide a solution for the existing user base.

David

maintainer
#2 lore raw

Re: [PATCH 1/4] perf tools: add Java demangling support

In reply to Stephane Eranian
Quoted 5 lines · Stephane Eranian

Add Java function descriptor demangling support.
Something bfd cannot do.

---

[SNIP]

Quoted 39 lines
tools/perf/util/symbol.c +39 -0
+/*
+ * Demangle Java function signature (Hotspot, not GCJ)
+ * input:
+ * 	str: string to parse. String is not modified
+ * return:
+ *	if can demangle then a a newly allocate string is returned.
+ *	if cannot demangle, then NULL is returned
+ *
+ * Note that caller is responsible for freeing demangled string
+ */
+char *
+java_demangle_sym(const char *str)
+{
+	char *buf, *ptr;
+	char *p;
+	size_t len, l1;
+
+	if (!str)
+		return NULL;
+
+	/* find start of retunr type */
+	p = strrchr(str, ')');
+	if (!p)
+		return NULL;
+
+	/*
+	 * expansion factor estimated to 3x
+	 */
+	len = strlen(str) * 3 + 1;
+	buf = malloc(len);
+	if (!buf)
+		return NULL;
+
+	buf[0] = '\0';
+	/*
+	 * get return type first
+	 */
+	ptr = __demangle_java_sym(p+1, NULL, buf, len, MODE_TYPE);
+	if (!ptr)

tools/perf/util/symbol.c int dso__load_kallsyms(struct dso *dso, const char *filename, · line 1425

Quoted 10 lines
tools/perf/util/symbol.c +10 -0
+		goto error;
+
+	/* add space between return type and function prototype */
+	l1 = strlen(buf);
+	buf[l1++] = ' ';
+
+	/* process function up to return type */
+	ptr = __demangle_java_sym(str, p + 1, buf + l1, len - l1, MODE_PREFIX);
+	if (!ptr)
+		goto error;

Do we really need to use return type for Java symbol name? Note that for C++ demangling, we show function name only by default and parameters will be shown when user gave -v option.

Thanks,
Namhyung

Quoted 8 lines
tools/perf/util/symbol.c +8 -0
+
+	return buf;
+error:
+	free(buf);
+	return NULL;
+}
+
+
maintainer
#10 lore raw

Re: [PATCH 3/4] perf inject: add jitdump mmap injection support

In reply to David Ahern
Quoted 24 lines · David Ahern
Quoted 9 lines · Stephane Eranian
tools/perf/Documentation/perf-inject.txt +1 -0
index dc7442c..237f195 100644
@@ -40,6 +40,17 @@ OPTIONS
 	Merge sched_stat and sched_switch for getting events where and how long
 	tasks slept. sched_switch contains a callchain where a task slept and
 	sched_stat contains a timeslice how long a task slept.
+-j::

tools/perf/Documentation/perf-inject.txt OPTIONS · line 53

Quoted 10 lines
tools/perf/Documentation/perf-inject.txt +10 -0
+--jit::
+	Merge a jitdump file into the perf.data file by adding mmap records to
+	cover jitted code and emit ELF images for each jitted function. The ELF
+	images are saved in the same directory as the jidump. Use -E to suppress
+	ELF images generation.
+-E::
+--jit-disable-elf::
+	When used with -, it prevents creating the ELF images for each jitted
+	function. Only the jitted code mmap records are injected into the perf.data
+	file. Option as no effect when -j is not used.

s/as/has/. But it would better to avoid the double negative. Maye something like this instead:

Quoted 1 line

This option requires -j|--jit.

I think same thing may go to the option name itself. It can be, say, --jit-create-elf and turned on by default. When one wants to disable it, [s]he can use --no-jit-create-elf. Of course this way we cannot use the short name (-E) for disabling tho.

Thanks,
Namhyung

maintainer
#12 lore raw

Re: [PATCH 4/4] perf tools: add JVMTI agent library

In reply to Stephane Eranian
Quoted 70 lines · Stephane Eranian

This is a standalone JVMTI library to help profile Java jitted code with perf record/perf report. The library is not installed or compiled automatically by perf Makefile. It is not used directly by perf. It is arch agnostic and has been tested on X86 and ARM. It needs to be used with a Java runtime, such as OpenJDK, as follows:

$ java -agentpath:libjvmti.so .......

When used this way, java will generate a jitdump binary file in $HOME/.debug/java/jit/java-jit-*

This binary dump file contains information to help symbolize and annotate jitted code.

The next step is to inject the jitdump information into the perf.data file:

$ perf inject -j $HOME/.debug/java/jit/java-jit-XXXX/jit-ZZZ.dump \
              -i perf.data -o perf.data.jitted

This injects the MMAP records to cover the jitted code and also generates one ELF image for each jitted function. The ELF images are created in the same subdir as the jitdump file. The MMAP records point there too.

Then to visualize the function or asm profile, simply use the regular perf commands:

$ perf report -i perf.data.jitted
or
$ perf annotate -i perf.data.jitted

JVMTI agent code adapted from OProfile's opagent code.

---
 tools/perf/jvmti/Makefile      |  70 +++++++++
 tools/perf/jvmti/jvmti_agent.c | 349 +++++++++++++++++++++++++++++++++++++++++
 tools/perf/jvmti/jvmti_agent.h |  23 +++
 tools/perf/jvmti/libjvmti.c    | 149 ++++++++++++++++++
 4 files changed, 591 insertions(+)
 create mode 100644 tools/perf/jvmti/Makefile
 create mode 100644 tools/perf/jvmti/jvmti_agent.c
 create mode 100644 tools/perf/jvmti/jvmti_agent.h
 create mode 100644 tools/perf/jvmti/libjvmti.c
tools/perf/jvmti/Makefile new file +20 -0
new file mode 100644
index 0000000..9eda64b
@@ -0,0 +1,70 @@
+ARCH=$(shell uname -m)
+
+ifeq ($(ARCH), x86_64)
+JARCH=amd64
+endif
+ifeq ($(ARCH), armv7l)
+JARCH=armhf
+endif
+ifeq ($(ARCH), armv6l)
+JARCH=armhf
+endif
+ifeq ($(ARCH), ppc64)
+JARCH=powerpc
+endif
+ifeq ($(ARCH), ppc64le)
+JARCH=powerpc
+endif
+
+DESTDIR=/usr/local
+

tools/perf/jvmti/Makefile line 30

Quoted 10 lines
tools/perf/jvmti/Makefile new file +10 -0
+VERSION=1
+REVISION=0
+AGE=0
+
+LN=ln -sf
+RM=rm
+
+SJVMTI=libjvmti.so.$(VERSION).$(REVISION).$(AGE)
+VJVMTI=libjvmti.so.$(VERSION)
+SLDFLAGS=-shared -Wl,-soname -Wl,$(VLIBPFM)

s/VLIBPFM/VLIBJVMTI/ ?

Thanks,
Namhyung

Quoted 40 lines
tools/perf/jvmti/Makefile new file +40 -0
+SOLIBEXT=so
+
+JDIR=$(shell /usr/sbin/update-java-alternatives -l | head -1 | cut -d ' ' -f 3)
+# -lrt required in 32-bit mode for clock_gettime()
+LIBS=-lelf -lrt
+INCDIR=-I $(JDIR)/include -I $(JDIR)/include/linux
+
+TARGETS=$(SJVMTI)
+
+SRCS=libjvmti.c jvmti_agent.c
+OBJS=$(SRCS:.c=.o)
+SOBJS=$(OBJS:.o=.lo)
+OPT=-O2 -g -Werror -Wall
+
+CFLAGS=$(INCDIR) $(OPT)
+
+all: $(TARGETS)
+
+.c.o:
+	$(CC) $(CFLAGS) -c $*.c
+.c.lo:
+	$(CC) -fPIC -DPIC $(CFLAGS) -c $*.c -o $*.lo
+
+$(OBJS) $(SOBJS): Makefile jvmti_agent.h ../util/jitdump.h
+
+$(SJVMTI):  $(SOBJS)
+	$(CC) $(CFLAGS) $(SLDFLAGS)  -o $@ $(SOBJS) $(LIBS)
+	$(LN) $@ libjvmti.$(SOLIBEXT)
+
+clean:
+	$(RM) -f *.o *.so.* *.so *.lo
+
+install:
+	-mkdir -p $(DESTDIR)/lib
+	install -m 755 $(SJVMTI) $(DESTDIR)/lib/
+	(cd $(DESTDIR)/lib; $(LN) $(SJVMTI) $(VJVMTI))
+	(cd $(DESTDIR)/lib; $(LN) $(SJVMTI) libjvmti.$(SOLIBEXT))
+	ldconfig
+
+.SUFFIXES: .c .S .o .lo
#3 lore raw

Re: [PATCH 1/4] perf tools: add Java demangling support

In reply to Stephane Eranian
Quoted 3 lines · Stephane Eranian

Add Java function descriptor demangling support.
Something bfd cannot do.

SNIP

Quoted 10 lines
tools/perf/util/symbol.c +10 -0
+	}
+	buf[rlen] = '\0';
+	return buf;
+error:
+	return NULL;
+}
+
+/*
+ * Demangle Java function signature (Hotspot, not GCJ)
+ * input:

tools/perf/util/symbol.c int dso__load_kallsyms(struct dso *dso, const char *filename, · line 1389

Quoted 10 lines
tools/perf/util/symbol.c +10 -0
+ * 	str: string to parse. String is not modified
+ * return:
+ *	if can demangle then a a newly allocate string is returned.
+ *	if cannot demangle, then NULL is returned
+ *
+ * Note that caller is responsible for freeing demangled string
+ */
+char *
+java_demangle_sym(const char *str)
+{

This seem fairly separated functionality, could you please move it into new object?

Also could you please document in more details requested input and produced output strings of this function?

It's nice function to have automated test that translates strings and verify expected output. IMO it'd help documenting the function as well.

thanks,
jirka

#13 lore raw

Re: [PATCH 4/4] perf tools: add JVMTI agent library

In reply to Stephane Eranian

On Wed, Feb 11, 2015 at 12:42:45AM +0100, Stephane Eranian wrote:

SNIP

tools/perf/jvmti/Makefile line 33

Quoted 9 lines
tools/perf/jvmti/Makefile new file +9 -0
+LN=ln -sf
+RM=rm
+
+SJVMTI=libjvmti.so.$(VERSION).$(REVISION).$(AGE)
+VJVMTI=libjvmti.so.$(VERSION)
+SLDFLAGS=-shared -Wl,-soname -Wl,$(VLIBPFM)
+SOLIBEXT=so
+
+JDIR=$(shell /usr/sbin/update-java-alternatives -l | head -1 | cut -d ' ' -f 3)

I had to se JDIR manualy..

is there some generic way to get above dir? It does not work on Fedora, 'yum provides' did not find any package carrying update-java-alternatives binary..

jirka

#24 lore raw
In reply to Stephane Eranian

On Wed, Feb 11, 2015 at 12:42:41AM +0100, Stephane Eranian wrote:

SNIP

Quoted 11 lines

To use the new feature:
- install the posix clock driver
- make sure you chmod 644 /dev/trace_clock
- compile perf
- cd tools/perf/jvmti; make; install wherever is appropriate

Example using openJDK:

   $ perf record java -agentpath:libjvmti.so my_class
   java: jvmti: jitdump in $HOME/.debug/jit/java-jit-20150207.XXL9649H/jit-6320.dump
   $ perf inject -i perf.data -j $HOME/.debug/jit/java-jit-20150207.XXL9649H/jit-6320.dump -o perf.data.jitted
   $ perf report -i perf.data.jitted

So report should display Java symbols now right? Is there something wrong with my test below?

thanks,
jirka

[jolsa@ibm-x3650m4-01 perf]$ ./perf record java -agentpath:./jvmti/libjvmti.so Puppy
java: jvmti: jitdump in /home/jolsa/.debug/jit/java-jit-20150212.XXru95af/jit-3777.dump Passed Name is :tommy
Puppy's age is :2
Variable Value :2
^C[ perf record: Woken up 3 times to write data ]
[ perf record: Captured and wrote 0.666 MB perf.data (17258 samples) ]

[jolsa@ibm-x3650m4-01 perf]$ ./perf inject -v -i perf.data -j /home/jolsa/.debug/jit/java-jit-20150212.XXru95af/jit-3777.dump -o perf.data.jitted build id event received for /lib/modules/3.19.0-rc7jit+/build/vmlinux: 4bb9dab963421f041b3eb3ec588fc07a58de4fa8
build id event received for /usr/bin/bash: c9f090657c35c10d6edeca09f62de9d22060a706
build id event received for /usr/lib64/ld-2.18.so: dddaf5704dbe9ace5c31f12ab90d8bfeb8fc5eb3
build id event received for [vdso]: b9e5cb1dcb2ab0d9d969fdc0816c4ad9af37e26b
build id event received for /usr/lib64/libc-2.18.so: f1b808c85f949e82cf864c1ef5a13c8acc703e3b
build id event received for /usr/lib64/libpthread-2.18.so: 5b1e8bb0e7ae081585497d797e06614815b768ef
build id event received for /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31.x86_64/jre/lib/amd64/server/libjvm.so: 7b87f33ae1b3150058839496dbe5b5521f8977b3 build id event received for /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31.x86_64/jre/lib/amd64/libjava.so: 32594e2184996cd7ff8257c8ef70656d91d2b03c build id event received for /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31.x86_64/jre/lib/amd64/libzip.so: 5cbb2075b9b316fc39dd0d5f9b0dcc8825256a4b version=1
size=32(0)
ts=0x26feca
pid=3777
elf_mach=62
failed to write feature 2

[jolsa@ibm-x3650m4-01 perf]$ ./perf report -i perf.data.jitted --stdio | head -13 Failed to open /tmp/perf-3777.map, continuing without symbols
# To display the perf.data header info, please use --header/--header-only options. #
# Samples: 17K of event 'cycles'
# Event count (approx.): 9728779054
#

# Overhead  Command    Shared Object       Symbol                                               
# ........  .........  ..................  .....................................................
#
    50.90%  java-abrt  perf-3777.map       [.] 0x00007f93a501e550                               
    15.00%  java-abrt  perf-3777.map       [.] 0x00007f93a501e586                               
    14.16%  java-abrt  perf-3777.map       [.] 0x00007f93a501e579                               
    12.63%  java-abrt  perf-3777.map       [.] 0x00007f93a501e67b                               
     3.04%  java-abrt  perf-3777.map       [.] 0x00007f93a501e685            
#14 lore raw

Re: [PATCH 4/4] perf tools: add JVMTI agent library

In reply to Jiri Olsa
Quoted 16 lines · Jiri Olsa

On Wed, Feb 11, 2015 at 12:42:45AM +0100, Stephane Eranian wrote:

SNIP

tools/perf/jvmti/Makefile line 33

Quoted 9 lines
tools/perf/jvmti/Makefile new file +9 -0
+LN=ln -sf
+RM=rm
+
+SJVMTI=libjvmti.so.$(VERSION).$(REVISION).$(AGE)
+VJVMTI=libjvmti.so.$(VERSION)
+SLDFLAGS=-shared -Wl,-soname -Wl,$(VLIBPFM)
+SOLIBEXT=so
+
+JDIR=$(shell /usr/sbin/update-java-alternatives -l | head -1 | cut -d ' ' -f 3)

I had to se JDIR manualy..

Quoted 4 lines

is there some generic way to get above dir? It does not work on Fedora, 'yum provides' did not find any package carrying update-java-alternatives binary..

This one comes from the java-common package on Ubuntu.

#15 lore raw

Re: [PATCH 4/4] perf tools: add JVMTI agent library

In reply to Stephane Eranian
Quoted 3 lines

This injects the MMAP records to cover the jitted code and also generates one ELF image for each jitted function. The ELF images are created in the same subdir as the jitdump file. The MMAP records point there too.

How about line numbers? That would need a lot of code to generate dwarf, right?

-Andi

#16 lore raw

Re: [PATCH 4/4] perf tools: add JVMTI agent library

Andi,

Quoted 6 lines · Andi Kleen
Quoted 3 lines

This injects the MMAP records to cover the jitted code and also generates one ELF image for each jitted function. The ELF images are created in the same subdir as the jitdump file. The MMAP records point there too.

How about line numbers? That would need a lot of code to generate dwarf, right?

The JVMTI agent does not generate the ELF files. It can extract line numbers form the JVMTI interface and put them into the jitdump file.

Then that information would need to be encoded into dwarf in the ELF file.

I have not looked at how much is needed to do that.

#25 lore raw
In reply to Jiri Olsa

Jiri,

Quoted 10 lines · Jiri Olsa

On Wed, Feb 11, 2015 at 12:42:41AM +0100, Stephane Eranian wrote:

SNIP

Quoted 6 lines

To use the new feature:
- install the posix clock driver
- make sure you chmod 644 /dev/trace_clock
- compile perf
- cd tools/perf/jvmti; make; install wherever is appropriate

Quoted 9 lines
Quoted 5 lines

Example using openJDK:

   $ perf record java -agentpath:libjvmti.so my_class
   java: jvmti: jitdump in $HOME/.debug/jit/java-jit-20150207.XXL9649H/jit-6320.dump
   $ perf inject -i perf.data -j $HOME/.debug/jit/java-jit-20150207.XXL9649H/jit-6320.dump -o perf.data.jitted
   $ perf report -i perf.data.jitted

So report should display Java symbols now right? Is there something wrong with my test below?

That is because the timestamps are incorrect. Sorry about that. Sonny's module as is is not going to generate the correct timestamps. I will V2 today. It uses another module from David and it works because it is using the same time source as perf_events.

Quoted 46 lines

thanks,
jirka

[jolsa@ibm-x3650m4-01 perf]$ ./perf record java -agentpath:./jvmti/libjvmti.so Puppy
java: jvmti: jitdump in /home/jolsa/.debug/jit/java-jit-20150212.XXru95af/jit-3777.dump Passed Name is :tommy
Puppy's age is :2
Variable Value :2
^C[ perf record: Woken up 3 times to write data ]
[ perf record: Captured and wrote 0.666 MB perf.data (17258 samples) ]

[jolsa@ibm-x3650m4-01 perf]$ ./perf inject -v -i perf.data -j /home/jolsa/.debug/jit/java-jit-20150212.XXru95af/jit-3777.dump -o perf.data.jitted build id event received for /lib/modules/3.19.0-rc7jit+/build/vmlinux: 4bb9dab963421f041b3eb3ec588fc07a58de4fa8
build id event received for /usr/bin/bash: c9f090657c35c10d6edeca09f62de9d22060a706
build id event received for /usr/lib64/ld-2.18.so: dddaf5704dbe9ace5c31f12ab90d8bfeb8fc5eb3
build id event received for [vdso]: b9e5cb1dcb2ab0d9d969fdc0816c4ad9af37e26b
build id event received for /usr/lib64/libc-2.18.so: f1b808c85f949e82cf864c1ef5a13c8acc703e3b
build id event received for /usr/lib64/libpthread-2.18.so: 5b1e8bb0e7ae081585497d797e06614815b768ef
build id event received for /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31.x86_64/jre/lib/amd64/server/libjvm.so: 7b87f33ae1b3150058839496dbe5b5521f8977b3 build id event received for /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31.x86_64/jre/lib/amd64/libjava.so: 32594e2184996cd7ff8257c8ef70656d91d2b03c build id event received for /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31.x86_64/jre/lib/amd64/libzip.so: 5cbb2075b9b316fc39dd0d5f9b0dcc8825256a4b version=1
size=32(0)
ts=0x26feca
pid=3777
elf_mach=62
failed to write feature 2

[jolsa@ibm-x3650m4-01 perf]$ ./perf report -i perf.data.jitted --stdio | head -13 Failed to open /tmp/perf-3777.map, continuing without symbols
# To display the perf.data header info, please use --header/--header-only options. #
# Samples: 17K of event 'cycles'
# Event count (approx.): 9728779054
#

# Overhead  Command    Shared Object       Symbol
# ........  .........  ..................  .....................................................
#
    50.90%  java-abrt  perf-3777.map       [.] 0x00007f93a501e550
    15.00%  java-abrt  perf-3777.map       [.] 0x00007f93a501e586
    14.16%  java-abrt  perf-3777.map       [.] 0x00007f93a501e579
    12.63%  java-abrt  perf-3777.map       [.] 0x00007f93a501e67b
     3.04%  java-abrt  perf-3777.map       [.] 0x00007f93a501e685
reviewer
#17 lore raw

Re: [PATCH 4/4] perf tools: add JVMTI agent library

In reply to Stephane Eranian
Quoted 434 lines · Stephane Eranian

This is a standalone JVMTI library to help profile Java jitted code with perf record/perf report. The library is not installed or compiled automatically by perf Makefile. It is not used directly by perf. It is arch agnostic and has been tested on X86 and ARM. It needs to be used with a Java runtime, such as OpenJDK, as follows:

$ java -agentpath:libjvmti.so .......

When used this way, java will generate a jitdump binary file in $HOME/.debug/java/jit/java-jit-*

This binary dump file contains information to help symbolize and annotate jitted code.

The next step is to inject the jitdump information into the perf.data file:

$ perf inject -j $HOME/.debug/java/jit/java-jit-XXXX/jit-ZZZ.dump \
              -i perf.data -o perf.data.jitted

This injects the MMAP records to cover the jitted code and also generates one ELF image for each jitted function. The ELF images are created in the same subdir as the jitdump file. The MMAP records point there too.

Then to visualize the function or asm profile, simply use the regular perf commands:

$ perf report -i perf.data.jitted
or
$ perf annotate -i perf.data.jitted

JVMTI agent code adapted from OProfile's opagent code.

---
 tools/perf/jvmti/Makefile      |  70 +++++++++
 tools/perf/jvmti/jvmti_agent.c | 349 +++++++++++++++++++++++++++++++++++++++++
 tools/perf/jvmti/jvmti_agent.h |  23 +++
 tools/perf/jvmti/libjvmti.c    | 149 ++++++++++++++++++
 4 files changed, 591 insertions(+)
 create mode 100644 tools/perf/jvmti/Makefile
 create mode 100644 tools/perf/jvmti/jvmti_agent.c
 create mode 100644 tools/perf/jvmti/jvmti_agent.h
 create mode 100644 tools/perf/jvmti/libjvmti.c
tools/perf/jvmti/Makefile new file +70 -0
new file mode 100644
index 0000000..9eda64b
@@ -0,0 +1,70 @@
+ARCH=$(shell uname -m)
+
+ifeq ($(ARCH), x86_64)
+JARCH=amd64
+endif
+ifeq ($(ARCH), armv7l)
+JARCH=armhf
+endif
+ifeq ($(ARCH), armv6l)
+JARCH=armhf
+endif
+ifeq ($(ARCH), ppc64)
+JARCH=powerpc
+endif
+ifeq ($(ARCH), ppc64le)
+JARCH=powerpc
+endif
+
+DESTDIR=/usr/local
+
+VERSION=1
+REVISION=0
+AGE=0
+
+LN=ln -sf
+RM=rm
+
+SJVMTI=libjvmti.so.$(VERSION).$(REVISION).$(AGE)
+VJVMTI=libjvmti.so.$(VERSION)
+SLDFLAGS=-shared -Wl,-soname -Wl,$(VLIBPFM)
+SOLIBEXT=so
+
+JDIR=$(shell /usr/sbin/update-java-alternatives -l | head -1 | cut -d ' ' -f 3)
+# -lrt required in 32-bit mode for clock_gettime()
+LIBS=-lelf -lrt
+INCDIR=-I $(JDIR)/include -I $(JDIR)/include/linux
+
+TARGETS=$(SJVMTI)
+
+SRCS=libjvmti.c jvmti_agent.c
+OBJS=$(SRCS:.c=.o)
+SOBJS=$(OBJS:.o=.lo)
+OPT=-O2 -g -Werror -Wall
+
+CFLAGS=$(INCDIR) $(OPT)
+
+all: $(TARGETS)
+
+.c.o:
+	$(CC) $(CFLAGS) -c $*.c
+.c.lo:
+	$(CC) -fPIC -DPIC $(CFLAGS) -c $*.c -o $*.lo
+
+$(OBJS) $(SOBJS): Makefile jvmti_agent.h ../util/jitdump.h
+
+$(SJVMTI):  $(SOBJS)
+	$(CC) $(CFLAGS) $(SLDFLAGS)  -o $@ $(SOBJS) $(LIBS)
+	$(LN) $@ libjvmti.$(SOLIBEXT)
+
+clean:
+	$(RM) -f *.o *.so.* *.so *.lo
+
+install:
+	-mkdir -p $(DESTDIR)/lib
+	install -m 755 $(SJVMTI) $(DESTDIR)/lib/
+	(cd $(DESTDIR)/lib; $(LN) $(SJVMTI) $(VJVMTI))
+	(cd $(DESTDIR)/lib; $(LN) $(SJVMTI) libjvmti.$(SOLIBEXT))
+	ldconfig
+
+.SUFFIXES: .c .S .o .lo
tools/perf/jvmti/jvmti_agent.c new file +308 -0
new file mode 100644
index 0000000..d2d5215
@@ -0,0 +1,349 @@
+/*
+ * jvmti_agent.c: JVMTI agent interface
+ *
+ * Adapted from the Oprofile code in opagent.c:
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * Copyright 2007 OProfile authors
+ * Jens Wilke
+ * Daniel Hansel
+ * Copyright IBM Corporation 2007
+ */
+#include <sys/types.h>
+#include <sys/stat.h> /* for mkdir() */
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <limits.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <time.h>
+#include <syscall.h> /* for gettid() */
+#include <err.h>
+
+#include "jvmti_agent.h"
+#include "../util/jitdump.h"
+
+#define JIT_LANG "java"
+
+static char jit_path[PATH_MAX];
+
+/*
+ * padding buffer
+ */
+static const char pad_bytes[7];
+
+/*
+ * perf_events event fd
+ */
+static int perf_fd;
+
+static inline pid_t gettid(void)
+{
+	return (pid_t)syscall(__NR_gettid);
+}
+
+static int get_e_machine(struct jitheader *hdr)
+{
+	ssize_t sret;
+	char id[16];
+	int fd, ret = -1;
+	int m = -1;
+	struct {
+		uint16_t e_type;
+		uint16_t e_machine;
+	} info;
+
+	fd = open("/proc/self/exe", O_RDONLY);
+	if (fd == -1)
+		return -1;
+
+	sret = read(fd, id, sizeof(id));
+	if (sret != sizeof(id))
+		goto error;
+
+	/* check ELF signature */
+	if (id[0] != 0x7f || id[1] != 'E' || id[2] != 'L' || id[3] != 'F')
+		goto error;
+
+	sret = read(fd, &info, sizeof(info));
+	if (sret != sizeof(info))
+		goto error;
+
+	m = info.e_machine;
+	if (m < 0)
+		m = 0; /* ELF EM_NONE */
+
+	hdr->elf_mach = m;
+	ret = 0;
+error:
+	close(fd);
+	return ret;
+}
+
+#define CLOCK_DEVICE "/dev/trace_clock"
+#define CLOCKFD 3
+#define FD_TO_CLOCKID(fd)	((~(clockid_t) (fd) << 3) | CLOCKFD)
+#define CLOCKID_TO_FD(id)	((~(int) (id) >> 3) & ~CLOCKFD)
+
+#define NSEC_PER_SEC	1000000000
+
+#ifndef CLOCK_INVALID
+#define CLOCK_INVALID -1
+#endif
+
+static inline clockid_t get_clockid(int fd)
+{
+	return FD_TO_CLOCKID(fd);
+}
+
+static int
+perf_open_timestamp(void)
+{
+	int fd, id;
+
+	fd = open(CLOCK_DEVICE, O_RDONLY);
+	if (fd == -1) {
+		if (errno == ENOENT)
+			warnx("jvmti: %s not present, check your kernel for trace_clock module", CLOCK_DEVICE);
+		if (errno == EPERM)
+			warnx("jvmti: %s has wrong permissions, suggesting chmod 644 %s", CLOCK_DEVICE, CLOCK_DEVICE);
+	}
+
+	id = get_clockid(fd);
+	if (CLOCK_INVALID == id)
+		return CLOCK_INVALID;
+
+	return get_clockid(fd);
+}
+
+static inline void
+perf_close_timestamp(int id)
+{
+        close(CLOCKID_TO_FD(id));
+}
+
+
+static inline uint64_t
+timespec_to_ns(const struct timespec *ts)
+{
+        return ((uint64_t) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
+}
+
+static inline uint64_t
+perf_get_timestamp(int id)
+{
+	struct timespec ts;
+
+	clock_gettime(id, &ts);
+	return timespec_to_ns(&ts);
+}
+
+static int
+debug_cache_init(void)
+{
+	char str[32];
+	char *base, *p;
+	struct tm tm;
+	time_t t;
+	int ret;
+
+	time(&t);
+	localtime_r(&t, &tm);
+
+	base = getenv("JITDUMPDIR");
+	if (!base)
+		base = getenv("HOME");
+	if (!base)
+		base = ".";
+
+	strftime(str, sizeof(str), JIT_LANG"-jit-%Y%m%d", &tm);
+
+	snprintf(jit_path, PATH_MAX - 1, "%s/.debug/", base);
+
+	ret = mkdir(jit_path, 0755);
+	if (ret == -1) {
+		if (errno != EEXIST) {
+			warn("jvmti: cannot create jit cache dir %s", jit_path);
+			return -1;
+		}
+	}
+
+	snprintf(jit_path, PATH_MAX - 1, "%s/.debug/jit", base);
+	ret = mkdir(jit_path, 0755);
+	if (ret == -1) {
+		if (errno != EEXIST) {
+			warn("cannot create jit cache dir %s", jit_path);
+			return -1;
+		}
+	}
+
+	snprintf(jit_path, PATH_MAX - 1, "%s/.debug/jit/%s.XXXXXXXX", base, str);
+
+	p = mkdtemp(jit_path);
+	if (p != jit_path) {
+		warn("cannot create jit cache dir %s", jit_path);
+		return -1;
+	}
+
+	return 0;
+}
+
+void *jvmti_open(void)
+{
+	int pad_cnt;
+	char dump_path[PATH_MAX];
+	struct jitheader header;
+	FILE *fp;
+
+	perf_fd = perf_open_timestamp();
+	if (perf_fd == -1)
+		warnx("jvmti: kernel does not support /dev/trace_clock or permissions are wrong on that device");
+
+	memset(&header, 0, sizeof(header));
+
+	debug_cache_init();
+
+	snprintf(dump_path, PATH_MAX, "%s/jit-%i.dump", jit_path, getpid());
+
+	fp = fopen(dump_path, "w");
+	if (!fp) {
+		warn("jvmti: cannot create %s", dump_path);
+		goto error;
+	}
+
+	warnx("jvmti: jitdump in %s", dump_path);
+
+	if (get_e_machine(&header)) {
+		warn("get_e_machine failed\n");
+		goto error;
+	}
+
+	header.magic      = JITHEADER_MAGIC;
+	header.version    = JITHEADER_VERSION;
+	header.total_size = sizeof(header);
+	header.pid        = getpid();
+
+	/* calculate amount of padding '\0' */
+	pad_cnt = PADDING_8ALIGNED(header.total_size);
+	header.total_size += pad_cnt;
+
+	header.timestamp = perf_get_timestamp(perf_fd);
+
+	if (!fwrite(&header, sizeof(header), 1, fp)) {
+		warn("jvmti: cannot write dumpfile header");
+		goto error;
+	}
+
+	/* write padding '\0' if necessary */
+	if (pad_cnt && !fwrite(pad_bytes, pad_cnt, 1, fp)) {
+		warn("jvmti: cannot write dumpfile header padding");
+		goto error;
+	}
+
+	return fp;
+error:
+	fclose(fp);
+	perf_close_timestamp(perf_fd);
+	return NULL;
+}
+
+int
+jvmti_close(void *agent)
+{
+	struct jr_code_close rec;
+	FILE *fp = agent;
+
+	if (!fp) {
+		warnx("jvmti: incalid fd in close_agent");
+		return -1;
+	}
+
+	rec.p.id = JIT_CODE_CLOSE;
+	rec.p.total_size = sizeof(rec);
+
+	rec.p.timestamp = perf_get_timestamp(perf_fd);
+
+	if (!fwrite(&rec, sizeof(rec), 1, fp))
+		return -1;
+
+	fclose(fp);
+
+	perf_close_timestamp(perf_fd);
+
+	fp = NULL;
+
+	return 0;
+}
+
+int jvmti_write_code(void *agent, char const *sym,
+	uint64_t vma, void const *code, unsigned int const size)
+{
+	static int code_generation = 1;
+	struct jr_code_load rec;
+	size_t sym_len;
+	size_t padding_count;
+	FILE *fp = agent;
+	int ret = -1;
+
+	/* don't care about 0 length function, no samples */
+	if (size == 0)
+		return 0;
+
+	if (!fp) {
+		warnx("jvmti: invalid fd in write_native_code");

tools/perf/jvmti/jvmti_agent.c line 318

Quoted 10 lines
tools/perf/jvmti/jvmti_agent.c new file +10 -0
+		return -1;
+	}
+
+	sym_len = strlen(sym) + 1;
+
+	rec.p.id           = JIT_CODE_LOAD;
+	rec.p.total_size   = sizeof(rec) + sym_len;
+	padding_count      = PADDING_8ALIGNED(rec.p.total_size);
+	rec.p. total_size += padding_count;
+	rec.p.timestamp    = perf_get_timestamp(perf_fd);

Do you know whether the JVM is guaranteed not to start executing the generated code before the return of compiled_method_load_cb(), otherwise the timestamp will be too late?

Quoted 216 lines
tools/perf/jvmti/jvmti_agent.c new file +31 -0
+
+	rec.code_size  = size;
+	rec.vma        = vma;
+	rec.code_addr  = vma;
+	rec.pid	       = getpid();
+	rec.tid	       = gettid();
+	rec.code_index = code_generation++;
+
+	if (code)
+		rec.p.total_size += size;
+
+	/*
+	 * If JVM is multi-threaded, nultiple concurrent calls to agent
+	 * may be possible, so protect file writes
+	 */
+	flockfile(fp);
+
+	ret = fwrite_unlocked(&rec, sizeof(rec), 1, fp);
+	fwrite_unlocked(sym, sym_len, 1, fp);
+	if (code)
+		fwrite_unlocked(code, size, 1, fp);
+
+	if (padding_count)
+		fwrite_unlocked(pad_bytes, padding_count, 1, fp);
+
+	funlockfile(fp);
+
+	ret = 0;
+
+	return ret;
+}
tools/perf/jvmti/jvmti_agent.h new file +23 -0
new file mode 100644
index 0000000..54e5c5e
@@ -0,0 +1,23 @@
+#ifndef __JVMTI_AGENT_H__
+#define __JVMTI_AGENT_H__
+
+#include <sys/types.h>
+#include <stdint.h>
+
+#define __unused __attribute__((unused))
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+void *jvmti_open(void);
+int   jvmti_close(void *agent);
+int   jvmti_write_code(void *agent, char const *symbol_name,
+		       uint64_t vma, void const *code,
+		       const unsigned int code_size);
+
+#if defined(__cplusplus)
+}
+
+#endif
+#endif /* __JVMTI_H__ */
tools/perf/jvmti/libjvmti.c new file +149 -0
new file mode 100644
index 0000000..8b8d782
@@ -0,0 +1,149 @@
+#include <sys/types.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <err.h>
+#include <jvmti.h>
+
+#include "jvmti_agent.h"
+
+void *jvmti_agent;
+
+static void JNICALL
+compiled_method_load_cb(jvmtiEnv *jvmti,
+			jmethodID method,
+			jint code_size,
+			void const *code_addr,
+			jint map_length,
+			jvmtiAddrLocationMap const *map,
+			void const *compile_info __unused)
+{
+	jclass decl_class;
+	char *class_sign = NULL;
+	char *func_name = NULL;
+	char *func_sign = NULL;
+	jvmtiError ret;
+	size_t len;
+
+	ret = (*jvmti)->GetMethodDeclaringClass(jvmti, method,
+						&decl_class);
+	if (ret != JVMTI_ERROR_NONE) {
+		warnx("jvmti: getmethoddeclaringclass failed");
+		return;
+	}
+
+	ret = (*jvmti)->GetClassSignature(jvmti, decl_class,
+					  &class_sign, NULL);
+	if (ret != JVMTI_ERROR_NONE) {
+		warnx("jvmti: getclassignature failed");
+		goto error;
+	}
+
+	ret = (*jvmti)->GetMethodName(jvmti, method, &func_name,
+				      &func_sign, NULL);
+	if (ret != JVMTI_ERROR_NONE) {
+		warnx("jvmti: failed getmethodname");
+		goto error;
+	}
+
+	len = strlen(func_name) + strlen(class_sign) + strlen(func_sign) + 2;
+
+	{
+		char str[len];
+		uint64_t addr = (uint64_t)(unsigned long)code_addr;
+		snprintf(str, len, "%s%s%s", class_sign, func_name, func_sign);
+		ret = jvmti_write_code(jvmti_agent, str, addr, code_addr, code_size);
+		if (ret)
+			warnx("jvmti: write_code() failed");
+	}
+error:
+	(*jvmti)->Deallocate(jvmti, (unsigned char *)func_name);
+	(*jvmti)->Deallocate(jvmti, (unsigned char *)func_sign);
+	(*jvmti)->Deallocate(jvmti, (unsigned char *)class_sign);
+}
+
+static void JNICALL
+code_generated_cb(jvmtiEnv *jvmti,
+		  char const *name,
+		  void const *code_addr,
+		  jint code_size)
+{
+	uint64_t addr = (uint64_t)(unsigned long)code_addr;
+	int ret;
+
+	ret = jvmti_write_code(jvmti_agent, name, addr, code_addr, code_size);
+	if (ret)
+		warnx("jvmti: write_code() failed for code_generated");
+}
+
+JNIEXPORT jint JNICALL
+Agent_OnLoad(JavaVM *jvm, char *options, void *reserved __unused)
+{
+	jvmtiEventCallbacks cb;
+	jvmtiCapabilities caps1;
+	jvmtiEnv *jvmti = NULL;
+	jint ret;
+
+	jvmti_agent = jvmti_open();
+	if (!jvmti_agent) {
+		warnx("jvmti: open_agent failed");
+		return -1;
+	}
+
+	/*
+	 * Request a JVMTI interface version 1 environment
+	 */
+	ret = (*jvm)->GetEnv(jvm, (void *)&jvmti, JVMTI_VERSION_1);
+	if (ret != JNI_OK) {
+		warnx("jvmti: jvmti version 1 not supported");
+		return -1;
+	}
+
+	/*
+	 * acquire method_load capability, we require it
+	 */
+	memset(&caps1, 0, sizeof(caps1));
+	caps1.can_generate_compiled_method_load_events = 1;
+
+	ret = (*jvmti)->AddCapabilities(jvmti, &caps1);
+	if (ret != JVMTI_ERROR_NONE) {
+		warnx("jvmti: acquire compiled_method capability failed");
+		return -1;
+	}
+
+	memset(&cb, 0, sizeof(cb));
+
+	cb.CompiledMethodLoad   = compiled_method_load_cb;
+	cb.DynamicCodeGenerated = code_generated_cb;
+
+	ret = (*jvmti)->SetEventCallbacks(jvmti, &cb, sizeof(cb));
+	if (ret != JVMTI_ERROR_NONE) {
+		warnx("jvmti: cannot set event callbacks");
+		return -1;
+	}
+
+	ret = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE,
+			JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
+	if (ret != JVMTI_ERROR_NONE) {
+		warnx("jvmti: setnotification failed for method_load");
+		return -1;
+	}
+
+	ret = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE,
+			JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL);
+	if (ret != JVMTI_ERROR_NONE) {
+		warnx("jvmti: setnotification failed on code_generated");
+		return -1;
+	}
+	return 0;
+}
+
+JNIEXPORT void JNICALL
+Agent_OnUnload(JavaVM *jvm __unused)
+{
+	int ret;
+
+	ret = jvmti_close(jvmti_agent);
+	if (ret)
+		errx(1, "Error: op_close_agent()");
+}
#18 lore raw

Re: [PATCH 4/4] perf tools: add JVMTI agent library

Quoted 441 lines · Adrian Hunter
Quoted 440 lines · Stephane Eranian

This is a standalone JVMTI library to help profile Java jitted code with perf record/perf report. The library is not installed or compiled automatically by perf Makefile. It is not used directly by perf. It is arch agnostic and has been tested on X86 and ARM. It needs to be used with a Java runtime, such as OpenJDK, as follows:

$ java -agentpath:libjvmti.so .......

When used this way, java will generate a jitdump binary file in $HOME/.debug/java/jit/java-jit-*

This binary dump file contains information to help symbolize and annotate jitted code.

The next step is to inject the jitdump information into the perf.data file:

$ perf inject -j $HOME/.debug/java/jit/java-jit-XXXX/jit-ZZZ.dump \
              -i perf.data -o perf.data.jitted

This injects the MMAP records to cover the jitted code and also generates one ELF image for each jitted function. The ELF images are created in the same subdir as the jitdump file. The MMAP records point there too.

Then to visualize the function or asm profile, simply use the regular perf commands:

$ perf report -i perf.data.jitted
or
$ perf annotate -i perf.data.jitted

JVMTI agent code adapted from OProfile's opagent code.

---
 tools/perf/jvmti/Makefile      |  70 +++++++++
 tools/perf/jvmti/jvmti_agent.c | 349 +++++++++++++++++++++++++++++++++++++++++
 tools/perf/jvmti/jvmti_agent.h |  23 +++
 tools/perf/jvmti/libjvmti.c    | 149 ++++++++++++++++++
 4 files changed, 591 insertions(+)
 create mode 100644 tools/perf/jvmti/Makefile
 create mode 100644 tools/perf/jvmti/jvmti_agent.c
 create mode 100644 tools/perf/jvmti/jvmti_agent.h
 create mode 100644 tools/perf/jvmti/libjvmti.c
tools/perf/jvmti/Makefile new file +70 -0
new file mode 100644
index 0000000..9eda64b
@@ -0,0 +1,70 @@
+ARCH=$(shell uname -m)
+
+ifeq ($(ARCH), x86_64)
+JARCH=amd64
+endif
+ifeq ($(ARCH), armv7l)
+JARCH=armhf
+endif
+ifeq ($(ARCH), armv6l)
+JARCH=armhf
+endif
+ifeq ($(ARCH), ppc64)
+JARCH=powerpc
+endif
+ifeq ($(ARCH), ppc64le)
+JARCH=powerpc
+endif
+
+DESTDIR=/usr/local
+
+VERSION=1
+REVISION=0
+AGE=0
+
+LN=ln -sf
+RM=rm
+
+SJVMTI=libjvmti.so.$(VERSION).$(REVISION).$(AGE)
+VJVMTI=libjvmti.so.$(VERSION)
+SLDFLAGS=-shared -Wl,-soname -Wl,$(VLIBPFM)
+SOLIBEXT=so
+
+JDIR=$(shell /usr/sbin/update-java-alternatives -l | head -1 | cut -d ' ' -f 3)
+# -lrt required in 32-bit mode for clock_gettime()
+LIBS=-lelf -lrt
+INCDIR=-I $(JDIR)/include -I $(JDIR)/include/linux
+
+TARGETS=$(SJVMTI)
+
+SRCS=libjvmti.c jvmti_agent.c
+OBJS=$(SRCS:.c=.o)
+SOBJS=$(OBJS:.o=.lo)
+OPT=-O2 -g -Werror -Wall
+
+CFLAGS=$(INCDIR) $(OPT)
+
+all: $(TARGETS)
+
+.c.o:
+     $(CC) $(CFLAGS) -c $*.c
+.c.lo:
+     $(CC) -fPIC -DPIC $(CFLAGS) -c $*.c -o $*.lo
+
+$(OBJS) $(SOBJS): Makefile jvmti_agent.h ../util/jitdump.h
+
+$(SJVMTI):  $(SOBJS)
+     $(CC) $(CFLAGS) $(SLDFLAGS)  -o $@ $(SOBJS) $(LIBS)
+     $(LN) $@ libjvmti.$(SOLIBEXT)
+
+clean:
+     $(RM) -f *.o *.so.* *.so *.lo
+
+install:
+     -mkdir -p $(DESTDIR)/lib
+     install -m 755 $(SJVMTI) $(DESTDIR)/lib/
+     (cd $(DESTDIR)/lib; $(LN) $(SJVMTI) $(VJVMTI))
+     (cd $(DESTDIR)/lib; $(LN) $(SJVMTI) libjvmti.$(SOLIBEXT))
+     ldconfig
+
+.SUFFIXES: .c .S .o .lo
tools/perf/jvmti/jvmti_agent.c new file +314 -0
new file mode 100644
index 0000000..d2d5215
@@ -0,0 +1,349 @@
+/*
+ * jvmti_agent.c: JVMTI agent interface
+ *
+ * Adapted from the Oprofile code in opagent.c:
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * Copyright 2007 OProfile authors
+ * Jens Wilke
+ * Daniel Hansel
+ * Copyright IBM Corporation 2007
+ */
+#include <sys/types.h>
+#include <sys/stat.h> /* for mkdir() */
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <limits.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <time.h>
+#include <syscall.h> /* for gettid() */
+#include <err.h>
+
+#include "jvmti_agent.h"
+#include "../util/jitdump.h"
+
+#define JIT_LANG "java"
+
+static char jit_path[PATH_MAX];
+
+/*
+ * padding buffer
+ */
+static const char pad_bytes[7];
+
+/*
+ * perf_events event fd
+ */
+static int perf_fd;
+
+static inline pid_t gettid(void)
+{
+     return (pid_t)syscall(__NR_gettid);
+}
+
+static int get_e_machine(struct jitheader *hdr)
+{
+     ssize_t sret;
+     char id[16];
+     int fd, ret = -1;
+     int m = -1;
+     struct {
+             uint16_t e_type;
+             uint16_t e_machine;
+     } info;
+
+     fd = open("/proc/self/exe", O_RDONLY);
+     if (fd == -1)
+             return -1;
+
+     sret = read(fd, id, sizeof(id));
+     if (sret != sizeof(id))
+             goto error;
+
+     /* check ELF signature */
+     if (id[0] != 0x7f || id[1] != 'E' || id[2] != 'L' || id[3] != 'F')
+             goto error;
+
+     sret = read(fd, &info, sizeof(info));
+     if (sret != sizeof(info))
+             goto error;
+
+     m = info.e_machine;
+     if (m < 0)
+             m = 0; /* ELF EM_NONE */
+
+     hdr->elf_mach = m;
+     ret = 0;
+error:
+     close(fd);
+     return ret;
+}
+
+#define CLOCK_DEVICE "/dev/trace_clock"
+#define CLOCKFD 3
+#define FD_TO_CLOCKID(fd)    ((~(clockid_t) (fd) << 3) | CLOCKFD)
+#define CLOCKID_TO_FD(id)    ((~(int) (id) >> 3) & ~CLOCKFD)
+
+#define NSEC_PER_SEC 1000000000
+
+#ifndef CLOCK_INVALID
+#define CLOCK_INVALID -1
+#endif
+
+static inline clockid_t get_clockid(int fd)
+{
+     return FD_TO_CLOCKID(fd);
+}
+
+static int
+perf_open_timestamp(void)
+{
+     int fd, id;
+
+     fd = open(CLOCK_DEVICE, O_RDONLY);
+     if (fd == -1) {
+             if (errno == ENOENT)
+                     warnx("jvmti: %s not present, check your kernel for trace_clock module", CLOCK_DEVICE);
+             if (errno == EPERM)
+                     warnx("jvmti: %s has wrong permissions, suggesting chmod 644 %s", CLOCK_DEVICE, CLOCK_DEVICE);
+     }
+
+     id = get_clockid(fd);
+     if (CLOCK_INVALID == id)
+             return CLOCK_INVALID;
+
+     return get_clockid(fd);
+}
+
+static inline void
+perf_close_timestamp(int id)
+{
+        close(CLOCKID_TO_FD(id));
+}
+
+
+static inline uint64_t
+timespec_to_ns(const struct timespec *ts)
+{
+        return ((uint64_t) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
+}
+
+static inline uint64_t
+perf_get_timestamp(int id)
+{
+     struct timespec ts;
+
+     clock_gettime(id, &ts);
+     return timespec_to_ns(&ts);
+}
+
+static int
+debug_cache_init(void)
+{
+     char str[32];
+     char *base, *p;
+     struct tm tm;
+     time_t t;
+     int ret;
+
+     time(&t);
+     localtime_r(&t, &tm);
+
+     base = getenv("JITDUMPDIR");
+     if (!base)
+             base = getenv("HOME");
+     if (!base)
+             base = ".";
+
+     strftime(str, sizeof(str), JIT_LANG"-jit-%Y%m%d", &tm);
+
+     snprintf(jit_path, PATH_MAX - 1, "%s/.debug/", base);
+
+     ret = mkdir(jit_path, 0755);
+     if (ret == -1) {
+             if (errno != EEXIST) {
+                     warn("jvmti: cannot create jit cache dir %s", jit_path);
+                     return -1;
+             }
+     }
+
+     snprintf(jit_path, PATH_MAX - 1, "%s/.debug/jit", base);
+     ret = mkdir(jit_path, 0755);
+     if (ret == -1) {
+             if (errno != EEXIST) {
+                     warn("cannot create jit cache dir %s", jit_path);
+                     return -1;
+             }
+     }
+
+     snprintf(jit_path, PATH_MAX - 1, "%s/.debug/jit/%s.XXXXXXXX", base, str);
+
+     p = mkdtemp(jit_path);
+     if (p != jit_path) {
+             warn("cannot create jit cache dir %s", jit_path);
+             return -1;
+     }
+
+     return 0;
+}
+
+void *jvmti_open(void)
+{
+     int pad_cnt;
+     char dump_path[PATH_MAX];
+     struct jitheader header;
+     FILE *fp;
+
+     perf_fd = perf_open_timestamp();
+     if (perf_fd == -1)
+             warnx("jvmti: kernel does not support /dev/trace_clock or permissions are wrong on that device");
+
+     memset(&header, 0, sizeof(header));
+
+     debug_cache_init();
+
+     snprintf(dump_path, PATH_MAX, "%s/jit-%i.dump", jit_path, getpid());
+
+     fp = fopen(dump_path, "w");
+     if (!fp) {
+             warn("jvmti: cannot create %s", dump_path);
+             goto error;
+     }
+
+     warnx("jvmti: jitdump in %s", dump_path);
+
+     if (get_e_machine(&header)) {
+             warn("get_e_machine failed\n");
+             goto error;
+     }
+
+     header.magic      = JITHEADER_MAGIC;
+     header.version    = JITHEADER_VERSION;
+     header.total_size = sizeof(header);
+     header.pid        = getpid();
+
+     /* calculate amount of padding '\0' */
+     pad_cnt = PADDING_8ALIGNED(header.total_size);
+     header.total_size += pad_cnt;
+
+     header.timestamp = perf_get_timestamp(perf_fd);
+
+     if (!fwrite(&header, sizeof(header), 1, fp)) {
+             warn("jvmti: cannot write dumpfile header");
+             goto error;
+     }
+
+     /* write padding '\0' if necessary */
+     if (pad_cnt && !fwrite(pad_bytes, pad_cnt, 1, fp)) {
+             warn("jvmti: cannot write dumpfile header padding");
+             goto error;
+     }
+
+     return fp;
+error:
+     fclose(fp);
+     perf_close_timestamp(perf_fd);
+     return NULL;
+}
+
+int
+jvmti_close(void *agent)
+{
+     struct jr_code_close rec;
+     FILE *fp = agent;
+
+     if (!fp) {
+             warnx("jvmti: incalid fd in close_agent");
+             return -1;
+     }
+
+     rec.p.id = JIT_CODE_CLOSE;
+     rec.p.total_size = sizeof(rec);
+
+     rec.p.timestamp = perf_get_timestamp(perf_fd);
+
+     if (!fwrite(&rec, sizeof(rec), 1, fp))
+             return -1;
+
+     fclose(fp);
+
+     perf_close_timestamp(perf_fd);
+
+     fp = NULL;
+
+     return 0;
+}
+
+int jvmti_write_code(void *agent, char const *sym,
+     uint64_t vma, void const *code, unsigned int const size)
+{
+     static int code_generation = 1;
+     struct jr_code_load rec;
+     size_t sym_len;
+     size_t padding_count;
+     FILE *fp = agent;
+     int ret = -1;
+
+     /* don't care about 0 length function, no samples */
+     if (size == 0)
+             return 0;
+
+     if (!fp) {
+             warnx("jvmti: invalid fd in write_native_code");
+             return -1;
+     }
+
+     sym_len = strlen(sym) + 1;
+
+     rec.p.id           = JIT_CODE_LOAD;
Quoted 9 lines

tools/perf/jvmti/jvmti_agent.c line 318

Quoted 4 lines
tools/perf/jvmti/jvmti_agent.c new file +4 -0
+     rec.p.total_size   = sizeof(rec) + sym_len;
+     padding_count      = PADDING_8ALIGNED(rec.p.total_size);
+     rec.p. total_size += padding_count;
+     rec.p.timestamp    = perf_get_timestamp(perf_fd);

Do you know whether the JVM is guaranteed not to start executing the generated code before the return of compiled_method_load_cb(), otherwise the timestamp will be too late?

I don't know that. I did not check.
But are you saying the callback may be asynchronous with the JIT compiler? The callback need to happen only after the code is jitted for obvious reasons.

Quoted 217 lines
Quoted 216 lines
tools/perf/jvmti/jvmti_agent.c new file +31 -0
+
+     rec.code_size  = size;
+     rec.vma        = vma;
+     rec.code_addr  = vma;
+     rec.pid        = getpid();
+     rec.tid        = gettid();
+     rec.code_index = code_generation++;
+
+     if (code)
+             rec.p.total_size += size;
+
+     /*
+      * If JVM is multi-threaded, nultiple concurrent calls to agent
+      * may be possible, so protect file writes
+      */
+     flockfile(fp);
+
+     ret = fwrite_unlocked(&rec, sizeof(rec), 1, fp);
+     fwrite_unlocked(sym, sym_len, 1, fp);
+     if (code)
+             fwrite_unlocked(code, size, 1, fp);
+
+     if (padding_count)
+             fwrite_unlocked(pad_bytes, padding_count, 1, fp);
+
+     funlockfile(fp);
+
+     ret = 0;
+
+     return ret;
+}
tools/perf/jvmti/jvmti_agent.h new file +23 -0
new file mode 100644
index 0000000..54e5c5e
@@ -0,0 +1,23 @@
+#ifndef __JVMTI_AGENT_H__
+#define __JVMTI_AGENT_H__
+
+#include <sys/types.h>
+#include <stdint.h>
+
+#define __unused __attribute__((unused))
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+void *jvmti_open(void);
+int   jvmti_close(void *agent);
+int   jvmti_write_code(void *agent, char const *symbol_name,
+                    uint64_t vma, void const *code,
+                    const unsigned int code_size);
+
+#if defined(__cplusplus)
+}
+
+#endif
+#endif /* __JVMTI_H__ */
tools/perf/jvmti/libjvmti.c new file +149 -0
new file mode 100644
index 0000000..8b8d782
@@ -0,0 +1,149 @@
+#include <sys/types.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <err.h>
+#include <jvmti.h>
+
+#include "jvmti_agent.h"
+
+void *jvmti_agent;
+
+static void JNICALL
+compiled_method_load_cb(jvmtiEnv *jvmti,
+                     jmethodID method,
+                     jint code_size,
+                     void const *code_addr,
+                     jint map_length,
+                     jvmtiAddrLocationMap const *map,
+                     void const *compile_info __unused)
+{
+     jclass decl_class;
+     char *class_sign = NULL;
+     char *func_name = NULL;
+     char *func_sign = NULL;
+     jvmtiError ret;
+     size_t len;
+
+     ret = (*jvmti)->GetMethodDeclaringClass(jvmti, method,
+                                             &decl_class);
+     if (ret != JVMTI_ERROR_NONE) {
+             warnx("jvmti: getmethoddeclaringclass failed");
+             return;
+     }
+
+     ret = (*jvmti)->GetClassSignature(jvmti, decl_class,
+                                       &class_sign, NULL);
+     if (ret != JVMTI_ERROR_NONE) {
+             warnx("jvmti: getclassignature failed");
+             goto error;
+     }
+
+     ret = (*jvmti)->GetMethodName(jvmti, method, &func_name,
+                                   &func_sign, NULL);
+     if (ret != JVMTI_ERROR_NONE) {
+             warnx("jvmti: failed getmethodname");
+             goto error;
+     }
+
+     len = strlen(func_name) + strlen(class_sign) + strlen(func_sign) + 2;
+
+     {
+             char str[len];
+             uint64_t addr = (uint64_t)(unsigned long)code_addr;
+             snprintf(str, len, "%s%s%s", class_sign, func_name, func_sign);
+             ret = jvmti_write_code(jvmti_agent, str, addr, code_addr, code_size);
+             if (ret)
+                     warnx("jvmti: write_code() failed");
+     }
+error:
+     (*jvmti)->Deallocate(jvmti, (unsigned char *)func_name);
+     (*jvmti)->Deallocate(jvmti, (unsigned char *)func_sign);
+     (*jvmti)->Deallocate(jvmti, (unsigned char *)class_sign);
+}
+
+static void JNICALL
+code_generated_cb(jvmtiEnv *jvmti,
+               char const *name,
+               void const *code_addr,
+               jint code_size)
+{
+     uint64_t addr = (uint64_t)(unsigned long)code_addr;
+     int ret;
+
+     ret = jvmti_write_code(jvmti_agent, name, addr, code_addr, code_size);
+     if (ret)
+             warnx("jvmti: write_code() failed for code_generated");
+}
+
+JNIEXPORT jint JNICALL
+Agent_OnLoad(JavaVM *jvm, char *options, void *reserved __unused)
+{
+     jvmtiEventCallbacks cb;
+     jvmtiCapabilities caps1;
+     jvmtiEnv *jvmti = NULL;
+     jint ret;
+
+     jvmti_agent = jvmti_open();
+     if (!jvmti_agent) {
+             warnx("jvmti: open_agent failed");
+             return -1;
+     }
+
+     /*
+      * Request a JVMTI interface version 1 environment
+      */
+     ret = (*jvm)->GetEnv(jvm, (void *)&jvmti, JVMTI_VERSION_1);
+     if (ret != JNI_OK) {
+             warnx("jvmti: jvmti version 1 not supported");
+             return -1;
+     }
+
+     /*
+      * acquire method_load capability, we require it
+      */
+     memset(&caps1, 0, sizeof(caps1));
+     caps1.can_generate_compiled_method_load_events = 1;
+
+     ret = (*jvmti)->AddCapabilities(jvmti, &caps1);
+     if (ret != JVMTI_ERROR_NONE) {
+             warnx("jvmti: acquire compiled_method capability failed");
+             return -1;
+     }
+
+     memset(&cb, 0, sizeof(cb));
+
+     cb.CompiledMethodLoad   = compiled_method_load_cb;
+     cb.DynamicCodeGenerated = code_generated_cb;
+
+     ret = (*jvmti)->SetEventCallbacks(jvmti, &cb, sizeof(cb));
+     if (ret != JVMTI_ERROR_NONE) {
+             warnx("jvmti: cannot set event callbacks");
+             return -1;
+     }
+
+     ret = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE,
+                     JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
+     if (ret != JVMTI_ERROR_NONE) {
+             warnx("jvmti: setnotification failed for method_load");
+             return -1;
+     }
+
+     ret = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE,
+                     JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL);
+     if (ret != JVMTI_ERROR_NONE) {
+             warnx("jvmti: setnotification failed on code_generated");
+             return -1;
+     }
+     return 0;
+}
+
+JNIEXPORT void JNICALL
+Agent_OnUnload(JavaVM *jvm __unused)
+{
+     int ret;
+
+     ret = jvmti_close(jvmti_agent);
+     if (ret)
+             errx(1, "Error: op_close_agent()");
+}
reviewer
#19 lore raw

Re: [PATCH 4/4] perf tools: add JVMTI agent library

Quoted 36 lines · Stephane Eranian
Quoted 35 lines · Adrian Hunter
Quoted 34 lines · Stephane Eranian

This is a standalone JVMTI library to help profile Java jitted code with perf record/perf report. The library is not installed or compiled automatically by perf Makefile. It is not used directly by perf. It is arch agnostic and has been tested on X86 and ARM. It needs to be used with a Java runtime, such as OpenJDK, as follows:

$ java -agentpath:libjvmti.so .......

When used this way, java will generate a jitdump binary file in $HOME/.debug/java/jit/java-jit-*

This binary dump file contains information to help symbolize and annotate jitted code.

The next step is to inject the jitdump information into the perf.data file:

$ perf inject -j $HOME/.debug/java/jit/java-jit-XXXX/jit-ZZZ.dump \
              -i perf.data -o perf.data.jitted

This injects the MMAP records to cover the jitted code and also generates one ELF image for each jitted function. The ELF images are created in the same subdir as the jitdump file. The MMAP records point there too.

Then to visualize the function or asm profile, simply use the regular perf commands:

$ perf report -i perf.data.jitted
or
$ perf annotate -i perf.data.jitted

JVMTI agent code adapted from OProfile's opagent code.

---

[snip]

Quoted 32 lines
Quoted 23 lines
Quoted 23 lines
tools/perf/jvmti/jvmti_agent.c new file +23 -0
+
+int jvmti_write_code(void *agent, char const *sym,
+     uint64_t vma, void const *code, unsigned int const size)
+{
+     static int code_generation = 1;
+     struct jr_code_load rec;
+     size_t sym_len;
+     size_t padding_count;
+     FILE *fp = agent;
+     int ret = -1;
+
+     /* don't care about 0 length function, no samples */
+     if (size == 0)
+             return 0;
+
+     if (!fp) {
+             warnx("jvmti: invalid fd in write_native_code");
+             return -1;
+     }
+
+     sym_len = strlen(sym) + 1;
+
+     rec.p.id           = JIT_CODE_LOAD;
Quoted 9 lines

tools/perf/jvmti/jvmti_agent.c line 318

Quoted 4 lines
tools/perf/jvmti/jvmti_agent.c new file +4 -0
+     rec.p.total_size   = sizeof(rec) + sym_len;
+     padding_count      = PADDING_8ALIGNED(rec.p.total_size);
+     rec.p. total_size += padding_count;
+     rec.p.timestamp    = perf_get_timestamp(perf_fd);

Do you know whether the JVM is guaranteed not to start executing the generated code before the return of compiled_method_load_cb(), otherwise the timestamp will be too late?

Quoted 2 lines

I don't know that. I did not check.
But are you saying the callback may be asynchronous with the JIT compiler?

Possibly, although it seems unlikely. But perhaps there are other threads waiting for the code and it lets them go at the same time. I guess we can assume that doesn't happen. When we use it with Intel PT it will show up if the timestamp isn't before the first execution, because there will be decoder errors.