├── .gitignore ├── src └── main │ ├── bash │ ├── jitdump │ └── jitdump-record │ ├── c │ └── jvmti │ │ ├── logger.c │ │ ├── logger.h │ │ ├── jitdump.h │ │ ├── jitdump.c │ │ └── perf-jitdump-agent.c │ └── java │ └── jitdump │ └── Main.java ├── CMakeLists.txt ├── README.md ├── pom.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # Install dir 2 | /jitdump 3 | 4 | # Maven 5 | target/ 6 | 7 | # CMake 8 | CMakeCache.txt 9 | CMakeFiles 10 | CMakeScripts 11 | Testing 12 | Makefile 13 | cmake_install.cmake 14 | install_manifest.txt 15 | compile_commands.json 16 | CTestTestfile.cmake 17 | 18 | # NetBeans 19 | nbproject/ 20 | nbactions.xml 21 | 22 | # Linux Perf 23 | perf.data 24 | perf.data.old 25 | perf.jit.data 26 | perf.jit.data.old 27 | -------------------------------------------------------------------------------- /src/main/bash/jitdump: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Perf-JitDump-Agent: Create jitdump files supported by Linux Perf. 4 | # Copyright (C) 2017 Staffan Friberg 5 | # 6 | # This program is free software; you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation; either version 2 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License along 17 | # with this program. If not, see . 18 | 19 | DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) 20 | $JAVA_HOME/bin/java -cp $JAVA_HOME/lib/tools.jar:$DIR/../lib/Perf-JitDump-Agent.jar jitdump.Main "$@" 21 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 3.5.2) 2 | 3 | project (perf-jitdump-agent) 4 | set(perf-jitdump-agent_VERSION_MAJOR 1) 5 | set(perf-jitdump-agent_VERSION_MINOR 0) 6 | 7 | set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}) 8 | set(C_SOURCE_DIR src/main/c) 9 | 10 | find_package(JNI REQUIRED) 11 | INCLUDE_DIRECTORIES(${JAVA_INCLUDE_PATH} ${JAVA_INCLUDE_PATH2}) 12 | 13 | add_library(perfjitdump SHARED ${C_SOURCE_DIR}/jvmti/perf-jitdump-agent.c ${C_SOURCE_DIR}/jvmti/jitdump.c ${C_SOURCE_DIR}/jvmti/logger.c) 14 | set_property(TARGET perfjitdump PROPERTY C_STANDARD 99) 15 | set_property(TARGET perfjitdump PROPERTY CXX_STANDARD 98) 16 | 17 | if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) 18 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -pedantic") 19 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic") 20 | endif() 21 | 22 | # Installation, by default to local directory named jitdump 23 | set(CMAKE_INSTALL_PREFIX ../jitdump) 24 | 25 | install(DIRECTORY ${PROJECT_BINARY_DIR}/lib 26 | DESTINATION .) 27 | 28 | install(FILES ${PROJECT_BINARY_DIR}/Perf-JitDump-Agent.jar 29 | DESTINATION ./lib) 30 | 31 | install(TARGETS perfjitdump 32 | LIBRARY DESTINATION ./lib) 33 | 34 | install(FILES src/main/bash/jitdump src/main/bash/jitdump-record 35 | DESTINATION ./bin 36 | PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_EXECUTE GROUP_READ) 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/main/bash/jitdump-record: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Perf-JitDump-Agent: Create jitdump files supported by Linux Perf. 4 | # Copyright (C) 2017 Staffan Friberg 5 | # 6 | # This program is free software; you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation; either version 2 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License along 17 | # with this program. If not, see . 18 | 19 | DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) 20 | 21 | processArgs() 22 | { 23 | while [ $# -gt 0 ]; do 24 | case $1 in 25 | (-d|--pid) 26 | DURATION=$2 27 | shift 28 | ;; 29 | (-p|--pid) 30 | PID=$2 31 | shift 32 | ;; 33 | esac 34 | shift 35 | done 36 | 37 | if [ ${PID}x == x ]; then 38 | echo "Must provide a pid with -p|--pid" 39 | exit 1 40 | fi 41 | if [ ${DURATION}x == x ]; then 42 | echo "Must provide a duration with -d|--duration" 43 | exit 1 44 | fi 45 | } 46 | 47 | # Main 48 | 49 | PERF_EXEC=${PERF_EXEC:-`which perf`} 50 | 51 | # Test PERF support for --jit 52 | ${PERF_EXEC} inject --jit -i /dev/null > /dev/null 2>&1 53 | if [ $? -eq 129 ]; then 54 | echo "Perf version (${PERF_EXEC}) does not support 'inject --jit'. Set PERF_EXEC environment variable to a version of PERF that does." 55 | exit 1; 56 | fi 57 | 58 | processArgs "$@" 59 | 60 | 61 | $JAVA_HOME/bin/java -cp $JAVA_HOME/lib/tools.jar:$DIR/../lib/Perf-JitDump-Agent.jar jitdump.Main "$@" 62 | if [ $? -eq 0 ]; then 63 | sudo ${PERF_EXEC} record -g -k 1 -p ${PID} -- sleep ${DURATION} 64 | sudo ${PERF_EXEC} inject -j -i perf.data -o perf.jit.data 65 | else 66 | exit $? 67 | fi 68 | -------------------------------------------------------------------------------- /src/main/c/jvmti/logger.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Perf-JitDump-Agent: Create jitdump files supported by Linux Perf. 3 | * Copyright (C) 2017 Staffan Friberg 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 2 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program 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 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License along 16 | * with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | #include "logger.h" 23 | 24 | typedef struct { 25 | FILE *out; 26 | LogLevel level; 27 | char prefix[64]; 28 | } Logger; 29 | 30 | static Logger logger; 31 | 32 | const char * 33 | log_level_name(LogLevel level) 34 | { 35 | switch (level) { 36 | case LOG_LEVEL_OFF: 37 | return "OFF"; 38 | case LOG_LEVEL_ERROR: 39 | return "ERROR"; 40 | case LOG_LEVEL_WARN: 41 | return "ERROR"; 42 | case LOG_LEVEL_INFO: 43 | return "INFO"; 44 | case LOG_LEVEL_DEBUG: 45 | return "DEBUG"; 46 | case LOG_LEVEL_TRACE: 47 | return "TRACE"; 48 | default: 49 | return "UNKNOWN LEVEL"; 50 | } 51 | } 52 | 53 | void 54 | log_init(FILE *out, LogLevel level, const char *prefix) 55 | { 56 | logger.out = out; 57 | logger.level = level; 58 | if (prefix == NULL) { 59 | logger.prefix[0] = '\0'; 60 | } else { 61 | strncpy(logger.prefix, prefix, 64); 62 | } 63 | } 64 | 65 | void 66 | log_msg(const char *function, int line, LogLevel level, const char *format, ...) 67 | { 68 | if (level <= logger.level) { 69 | va_list vars; 70 | va_start(vars, format); 71 | char message[1024]; 72 | vsnprintf(message, 1024, format, vars); 73 | fprintf(logger.out, "%.64s[%s:%d][%s]: %s\n", logger.prefix, function, line, log_level_name(level), message); 74 | va_end(vars); 75 | } 76 | } -------------------------------------------------------------------------------- /src/main/c/jvmti/logger.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Perf-JitDump-Agent: Create jitdump files supported by Linux Perf. 3 | * Copyright (C) 2017 Staffan Friberg 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 2 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program 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 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License along 16 | * with this program. If not, see . 17 | */ 18 | 19 | #ifndef LOGGER_H 20 | #define LOGGER_H 21 | 22 | #include 23 | 24 | #ifdef __cplusplus 25 | extern "C" { 26 | #endif 27 | 28 | typedef enum { 29 | LOG_LEVEL_OFF = 0, 30 | LOG_LEVEL_ERROR = 1, 31 | LOG_LEVEL_WARN = 2, 32 | LOG_LEVEL_INFO = 3, 33 | LOG_LEVEL_DEBUG = 4, 34 | LOG_LEVEL_TRACE = 5 35 | } LogLevel; 36 | 37 | #define LOG_ERROR(format, ...) log_msg(__func__, __LINE__, LOG_LEVEL_ERROR, format, ##__VA_ARGS__) 38 | #define LOG_WARN(format, ...) log_msg(__func__, __LINE__, LOG_LEVEL_WARN, format, ##__VA_ARGS__) 39 | #define LOG_INFO(format, ...) log_msg(__func__, __LINE__, LOG_LEVEL_INFO, format, ##__VA_ARGS__) 40 | #define LOG_DEBUG(format, ...) log_msg(__func__, __LINE__, LOG_LEVEL_DEBUG, format, ##__VA_ARGS__) 41 | #define LOG_TRACE(format, ...) log_msg(__func__, __LINE__, LOG_LEVEL_TRACE, format, ##__VA_ARGS__) 42 | 43 | /** 44 | * Get level name from LogLevel 45 | * 46 | * @param level Log level to get name for 47 | * @return name of level 48 | */ 49 | const char * 50 | log_level_name(LogLevel level); 51 | 52 | /** 53 | * Initialize log system. 54 | * 55 | * @param out FILE to send the output to 56 | * @param level The lowest Log level to output 57 | * @param prefix Prefix to prepend on each log message 58 | */ 59 | void 60 | log_init(FILE *out, LogLevel level, const char *prefix); 61 | 62 | /** 63 | * Log formatted message at specified level. 64 | * 65 | * For fewer required function parameters use LOG_ macros. 66 | * 67 | * @param function name of function of loged information 68 | * @param line line number for logged information 69 | * @param level Log level of message 70 | * @param format message string format description (see printf) 71 | * @param ... data for message 72 | */ 73 | void 74 | log_msg(const char *function, int line, LogLevel level, const char *format, ...); 75 | 76 | #ifdef __cplusplus 77 | } 78 | #endif 79 | 80 | #endif /* LOGGER_H */ 81 | 82 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Perf-JitDump-Agent 2 | 3 | ## Build 4 | 5 | cd perf-jitdump-agent 6 | mvn package 7 | 8 | # Create a directory named jitdump in the project home directory with scripts and libraries 9 | cd target 10 | make install 11 | 12 | ## Usage 13 | 14 | The agent can either be loaded on JVM start or attached to an already running JVM. 15 | 16 | When loading the agent the following options are available and can be set on the 17 | [command line](http://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#starting). 18 | 19 | verbose=[0-5] 0 is off, and 5 is trace level, by default logging is off. 20 | directory= Location to store JitDump file, byt default $HOME/.debug/jit. 21 | duration= How long to record method compilation to the jitdump file, by default infinite (-1). 22 | 23 | When attaching to an already running JVM use `/jitdump/bin/jitdump -p `, the attach mechanism supports the 24 | same options as when loading the agent, run `/jitdump/bin/jitdump -h` for details. 25 | 26 | ### Recording and Analyzing 27 | 28 | 1. Start Java application (and load agent if you want to be able to start recording directly). 29 | * For correct stack unwinding and maximum information available for the agent add the following options. 30 | * `-XX:+PreserveFramePointer -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints` 31 | * Instead of `-XX:+PreserveFramePointer` the perf recording can on modern hardware use the `-call-graph lbr` option to gather stack traces. 32 | * Ensure that duration is infinite or longer than your intended recording to ensure all compiled methods are registered correctly. 33 | 2. Attach agent unless loaded at start, `/jitdump/bin/jitdump -p ` 34 | * Ensure that duration is infinite or longer than your intended recording to ensure all compiled methods are registered correctly. 35 | 3. `perf record -g -k 1 -p ` 36 | 4. `perf inject -j -i perf.data -o perf.jit.data` 37 | 5. Unpack your Java source code to the current directory to enable `perf report` to find it correctly. 38 | * Don't forget `/src.zip` 39 | 6. `perf report --source --no-children -i perf.jit.data` 40 | 41 | ### Linux Perf Support 42 | 43 | Not all distributions will support the -j/--jit flag with the shipped version of perf. On Ubuntu 16.04 for example, the 44 | man page mentions the flag but the binary does not recognize it. However the recording can still be done with the 45 | version shipped with the distribution, but the inject step requires a self compiled binary with support for the jit 46 | option. Compiling perf is rather straight forward, pull the latest Linux source code and enter the the 47 | `linux/tools/perf` directory and run `make`. Depending on your system you might need to install one or more required 48 | libraries for a successful compilation. 49 | 50 | ## License 51 | 52 | This program is licensed under GPLv2. See the LICENSE file. 53 | 54 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 4.0.0 7 | sfriberg 8 | Perf-JitDump-Agent 9 | 1.0-SNAPSHOT 10 | jar 11 | 12 | 13 | UTF-8 14 | 1.8 15 | 1.8 16 | 17 | 18 | 19 | 20 | com.oracle.jdk 21 | tools 22 | system 23 | ${maven.compiler.target} 24 | ${java.home}/../lib/tools.jar 25 | 26 | 27 | net.sf.jopt-simple 28 | jopt-simple 29 | 5.0.3 30 | 31 | 32 | 33 | 34 | ${project.artifactId} 35 | 36 | 37 | org.apache.maven.plugins 38 | maven-dependency-plugin 39 | 3.0.0 40 | 41 | 42 | package 43 | 44 | copy-dependencies 45 | 46 | 47 | ${project.build.directory}/lib 48 | com.oracle.jdk 49 | 50 | 51 | 52 | 53 | 54 | org.apache.maven.plugins 55 | maven-jar-plugin 56 | 3.0.2 57 | 58 | 59 | 60 | sfriberg.jitdump.Main 61 | true 62 | true 63 | true 64 | 65 | 66 | 67 | 68 | 69 | com.googlecode.cmake-maven-project 70 | cmake-maven-plugin 71 | 3.7.0-b2 72 | 73 | 74 | cmake-generate 75 | 76 | generate 77 | 78 | 79 | ${project.basedir} 80 | ${project.build.directory} 81 | Unix Makefiles 82 | linux-amd64 83 | 84 | 85 | 86 | cmake-compile 87 | 88 | compile 89 | 90 | 91 | ${project.build.directory} 92 | linux-amd64 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /src/main/c/jvmti/jitdump.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Perf-JitDump-Agent: Create jitdump files supported by Linux Perf. 3 | * Copyright (C) 2017 Staffan Friberg 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 2 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program 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 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License along 16 | * with this program. If not, see . 17 | */ 18 | 19 | #ifndef JITDUMP_H 20 | #define JITDUMP_H 21 | 22 | #include 23 | 24 | #ifdef __cplusplus 25 | extern "C" { 26 | #endif 27 | 28 | typedef enum { 29 | JIT_CODE_LOAD = 0, 30 | JIT_CODE_MOVE = 1, 31 | JIT_CODE_DEBUG_INFO = 2, 32 | JIT_CODE_CLOSE = 3, 33 | JIT_CODE_UNWINDING_INFO = 4 34 | } RecordId; 35 | 36 | typedef struct { 37 | uint32_t magic; 38 | uint32_t version; 39 | uint32_t size; 40 | uint32_t e_machine; 41 | uint32_t pad1; 42 | uint32_t pid; 43 | uint64_t timestamp; 44 | uint64_t flags; 45 | } FileHeader; 46 | 47 | typedef struct { 48 | uint32_t id; 49 | uint32_t record_size; 50 | uint64_t timestamp; 51 | } RecordHeader; 52 | 53 | typedef struct { 54 | RecordHeader header; 55 | uint32_t pid; 56 | uint32_t tid; 57 | uint64_t virtual_address; 58 | uint64_t address; 59 | uint64_t size; 60 | uint64_t index; 61 | const char *name; 62 | } CodeLoadRecord; 63 | 64 | typedef struct { 65 | uint64_t address; 66 | uint32_t line; 67 | uint32_t discriminator; 68 | char *filename; 69 | } DebugEntry; 70 | 71 | typedef struct { 72 | RecordHeader header; 73 | uint64_t address; 74 | uint64_t count; 75 | DebugEntry *entries; 76 | } DebugInfoRecord; 77 | 78 | /** 79 | * Get the current timestamp. 80 | * 81 | * @param timestamp set to current timestamp on success with nanosecond resolution 82 | * @return 0 on success 83 | */ 84 | int 85 | getTimestamp(uint64_t *timestamp); 86 | 87 | /** 88 | * Create, open and write file header to a jit dump file. 89 | * The file will be located in a directory and file with the following pattern 90 | * /java-jit-%G%m%d-%H%M.XXXXXX/jit-.dump. 91 | * 92 | * @param dir directory to use to store jit dump information 93 | * @return 0 on success 94 | */ 95 | int 96 | open_jitdump(const char *dir); 97 | 98 | 99 | /** 100 | * Is a jit dump currently active 101 | * @return true if active 102 | */ 103 | bool 104 | is_jitdump_active(); 105 | 106 | /** 107 | * 108 | * Write CloseRecord and close jit dump file. 109 | * 110 | * @return 0 on success 111 | */ 112 | int 113 | close_jitdump(); 114 | 115 | /** 116 | * Write CodeLoadRecord to open jit dump file. 117 | * Must be written after the corresponding DebugInfoRecord. 118 | * 119 | * @param clRecord CodeLoadRecord to write to the jit dump file 120 | * @param diRecord DebugInfoRecord to write to jit dump file, or NULL if no debug information to write 121 | * @return 0 on success 122 | */ 123 | int 124 | write_CodeLoadRecord(CodeLoadRecord *clRecord, DebugInfoRecord *diRecord); 125 | 126 | #ifdef __cplusplus 127 | } 128 | #endif 129 | 130 | #endif /* JITDUMP_H */ 131 | 132 | -------------------------------------------------------------------------------- /src/main/java/jitdump/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Perf-JitDump-Agent: Create jitdump files supported by Linux Perf. 3 | * Copyright (C) 2017 Staffan Friberg 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 2 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program 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 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License along 16 | * with this program. If not, see . 17 | */ 18 | package jitdump; 19 | 20 | import com.sun.tools.attach.AgentInitializationException; 21 | import com.sun.tools.attach.AgentLoadException; 22 | import com.sun.tools.attach.AttachNotSupportedException; 23 | import com.sun.tools.attach.VirtualMachine; 24 | import java.io.Closeable; 25 | import java.io.IOException; 26 | import java.nio.file.Paths; 27 | import joptsimple.OptionException; 28 | import joptsimple.OptionParser; 29 | import joptsimple.OptionSet; 30 | import joptsimple.OptionSpec; 31 | import joptsimple.util.EnumConverter; 32 | 33 | import static java.util.Arrays.asList; 34 | 35 | /** 36 | * Simple Java application to attach and load a agent library to a running JVM using a PID. 37 | */ 38 | public class Main { 39 | 40 | // Determine the location of the JAR file containing this class 41 | private final static String JAR_LOCATION = Main.class.getClassLoader() 42 | .getResource(Main.class.getName().replace('.', '/') + ".class") 43 | .getPath().split("!")[0].replace("file:", ""); 44 | 45 | /** 46 | * Verbose levels for the agent. 47 | */ 48 | private enum Verbose { 49 | OFF(0), 50 | ERROR(1), 51 | WARN(2), 52 | INFO(3), 53 | DEBUG(4), 54 | TRACE(5); 55 | 56 | private final int value; 57 | 58 | private Verbose(int value) { 59 | this.value = value; 60 | } 61 | 62 | public int getValue() { 63 | return value; 64 | } 65 | }; 66 | 67 | /** 68 | * Simple return value translation from the JIT dump native agent. 69 | * 70 | * @param return_value return value to convert 71 | * @return String describing the error 72 | */ 73 | private static String getDescription(int return_value) { 74 | switch (return_value) { 75 | case 0: 76 | return "Success"; 77 | case -1: 78 | return "General error"; 79 | case -30: 80 | return "JitDump is already active"; 81 | case -31: 82 | return "Error creating JitDump file"; 83 | default: 84 | return "Unknown error"; 85 | } 86 | } 87 | 88 | /** 89 | * Attach native JVMTI library to specified Java process. 90 | * 91 | * @param argv command line arguments 92 | * @throws IOException 93 | * @throws AttachNotSupportedException 94 | * @throws AgentLoadException 95 | * @throws AgentInitializationException 96 | */ 97 | public static void main(String... argv) 98 | throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException { 99 | 100 | OptionParser parser = new OptionParser(); 101 | OptionSpec pid = parser.acceptsAll(asList("p", "pid")).withRequiredArg().ofType(Integer.class).required() 102 | .describedAs("PID of the process to attach agent to."); 103 | OptionSpec verbose = parser.acceptsAll(asList("v", "verbose")).withRequiredArg().ofType(Verbose.class) 104 | .withValuesConvertedBy(new EnumConverter(Verbose.class) { 105 | }).defaultsTo(Verbose.OFF).describedAs("Logging level for the native agent."); 106 | OptionSpec version = parser.acceptsAll(asList("V", "version")).forHelp(); 107 | OptionSpec directory = parser.acceptsAll(asList("directory")).withRequiredArg().ofType(String.class) 108 | .defaultsTo(System.getProperty("user.home") + "/.debug/jit").describedAs("Directory to store jitdump."); 109 | OptionSpec duration = parser.acceptsAll(asList("d", "duration")).withRequiredArg().ofType(Long.class) 110 | .defaultsTo(-1L).describedAs("Duration of recording method compilation to jitdump, in seconds."); 111 | OptionSpec library = parser.acceptsAll(asList("l", "library")).withRequiredArg().ofType(String.class) 112 | .defaultsTo(Paths.get(JAR_LOCATION).getParent().resolve("libperfjitdump.so").toAbsolutePath().toString()) 113 | .describedAs("Full path to the libperfjitdump.so."); 114 | OptionSpec help = parser.acceptsAll(asList("h", "help")).forHelp(); 115 | 116 | try { 117 | OptionSet options = parser.parse(argv); 118 | 119 | if (options.has(help)) { 120 | parser.printHelpOn(System.out); 121 | return; 122 | } 123 | 124 | if (options.has(version)) { 125 | Package pkg = Main.class.getPackage(); 126 | System.out.println(pkg.getImplementationTitle() + " " + pkg.getImplementationVersion()); 127 | return; 128 | } 129 | 130 | // Build option string for the agent libarary 131 | StringBuilder agent_options = new StringBuilder(); 132 | if (options.has(verbose)) { 133 | agent_options.append("verbose=").append(options.valueOf(verbose).getValue()).append(','); 134 | } 135 | if (options.has(duration)) { 136 | agent_options.append("duration=").append(options.valueOf(duration)).append(','); 137 | } 138 | if (options.has(directory)) { 139 | agent_options.append("directory=").append(options.valueOf(directory)).append(','); 140 | } 141 | 142 | VirtualMachine vm = VirtualMachine.attach(options.valueOf(pid).toString()); 143 | try (Closeable ac = vm::detach) { 144 | vm.loadAgentPath(options.valueOf(library), agent_options.toString()); 145 | } catch (AgentInitializationException ex) { 146 | System.err.println("Error attaching agent : " + getDescription(ex.returnValue())); 147 | throw ex; 148 | } 149 | 150 | } catch (OptionException e) { 151 | System.err.println(e.getMessage()); 152 | parser.printHelpOn(System.err); 153 | System.exit(1); 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/c/jvmti/jitdump.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Perf-JitDump-Agent: Create jitdump files supported by Linux Perf. 3 | * Copyright (C) 2017 Staffan Friberg 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 2 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program 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 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License along 16 | * with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | #include "jitdump.h" 38 | #include "logger.h" 39 | 40 | static pthread_mutex_t jitdump_lock = PTHREAD_MUTEX_INITIALIZER; 41 | static FILE *jitdump = NULL; 42 | static void *marker = NULL; 43 | static uint64_t code_index = 0; 44 | 45 | int 46 | getTimestamp(uint64_t *timestamp) 47 | { 48 | struct timespec ts; 49 | if (clock_gettime(CLOCK_MONOTONIC, &ts)) { 50 | LOG_ERROR("%s : %s", "Getting Timestamp", strerror(errno)); 51 | return -1; 52 | } 53 | *timestamp = (uint64_t) ts.tv_sec * 1000000000 + ts.tv_nsec; 54 | return 0; 55 | } 56 | 57 | /** 58 | * Get the ELF machine architecture. 59 | * 60 | * @return ELF machine architecture on success, EM_NONE on failure 61 | */ 62 | static uint32_t 63 | getElfMachine() 64 | { 65 | uint32_t e_machine = EM_NONE; 66 | Elf64_Ehdr elf_header; 67 | FILE *exe = fopen("/proc/self/exe", "r"); 68 | 69 | if (exe == NULL) { 70 | LOG_ERROR("%s : %s", "Reading /proc/self/exe", strerror(errno)); 71 | return e_machine; 72 | } 73 | 74 | if (fread(&elf_header, sizeof (Elf64_Ehdr), 1, exe) != 1) { 75 | LOG_ERROR("%s : %s", "Reading /proc/self/exe", strerror(errno)); 76 | goto end; 77 | } 78 | 79 | e_machine = elf_header.e_machine; 80 | 81 | end: 82 | fclose(exe); 83 | return e_machine; 84 | } 85 | 86 | /** 87 | * Write the file header to the jitdump file. 88 | * 89 | * @return 0 on success 90 | */ 91 | static int 92 | writeFileHeader() 93 | { 94 | FileHeader header; 95 | 96 | if (getTimestamp(&header.timestamp)) { 97 | return -1; 98 | } 99 | if ((header.e_machine = getElfMachine()) == EM_NONE) { 100 | return -1; 101 | } 102 | 103 | header.magic = (BYTE_ORDER == LITTLE_ENDIAN) ? 0x4A695444 : 0x4454694a; 104 | header.version = 1; 105 | header.size = sizeof (FileHeader); 106 | header.pad1 = 0; 107 | header.pid = getpid(); 108 | header.flags = 0; 109 | 110 | if (fwrite(&header, sizeof (FileHeader), 1, jitdump) != 1) { 111 | return -1; 112 | } 113 | 114 | return 0; 115 | } 116 | 117 | /** 118 | * Recursively (if required) mkdir directory. 119 | * 120 | * @param dir directory to create 121 | * @return 0 on success 122 | */ 123 | static int 124 | mkdirs(const char *dir) 125 | { 126 | struct stat stats; 127 | if (stat(dir, &stats)) { 128 | char parent[1024]; 129 | strncpy(parent, dir, 1024); 130 | if (!mkdirs(dirname(parent))) { 131 | return mkdir(dir, 0755); 132 | } else { 133 | perror(parent); 134 | return -1; 135 | } 136 | } 137 | return 0; 138 | } 139 | 140 | int 141 | open_jitdump(const char *dir) 142 | { 143 | int error = -1; 144 | char filename[PATH_MAX]; 145 | 146 | if (pthread_mutex_lock(&jitdump_lock)) { 147 | LOG_ERROR("%s : %s", "Locking Mutex", strerror(errno)); 148 | return -1; 149 | } 150 | 151 | if (jitdump == NULL) { 152 | char date[16]; 153 | char temp_dir[PATH_MAX]; 154 | time_t rawtime; 155 | struct tm * timeinfo; 156 | long pgsz; 157 | 158 | if (time(&rawtime) == -1) { 159 | LOG_ERROR("%s : %s", "Getting raw time", strerror(errno)); 160 | goto end; 161 | } 162 | if ((timeinfo = localtime(&rawtime)) == NULL) { 163 | LOG_ERROR("%s", "Getting local time"); 164 | goto end; 165 | } 166 | 167 | strftime(date, 16, "%G%m%d-%H%M", timeinfo); 168 | snprintf(temp_dir, PATH_MAX, "%s/java-jit-%s.XXXXXX", dir, date); 169 | 170 | 171 | if (mkdirs(dir)) { 172 | LOG_ERROR("%s(%s) : %s", "Creating directory", dir, strerror(errno)); 173 | goto end; 174 | } 175 | 176 | if (mkdtemp(temp_dir) == NULL) { 177 | LOG_ERROR("%s(%s) : %s", "Creating directory", temp_dir, strerror(errno)); 178 | goto end; 179 | } 180 | 181 | snprintf(filename, PATH_MAX, "%s/jit-%d.dump", temp_dir, getpid()); 182 | int fd = open(filename, O_CREAT | O_TRUNC | O_RDWR, 0666); 183 | if (fd == -1) { 184 | LOG_ERROR("%s(%s) : %s", "Creating jit dump", filename, strerror(errno)); 185 | goto end; 186 | } 187 | 188 | if ((pgsz = sysconf(_SC_PAGESIZE)) == -1) { 189 | LOG_ERROR("%s : %s", "Getting page size", strerror(errno)); 190 | close(fd); 191 | goto end; 192 | } 193 | 194 | if ((marker = mmap(NULL, pgsz, PROT_EXEC | PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED) { 195 | LOG_ERROR("%s(%s) : %s", "Mapping jit dump", filename, strerror(errno)); 196 | close(fd); 197 | goto end; 198 | } 199 | 200 | if ((jitdump = fdopen(fd, "w")) == NULL) { 201 | LOG_ERROR("%s(%s) : %s", "Opening jit dump", filename, strerror(errno)); 202 | munmap(marker, 0); 203 | marker = NULL; 204 | close(fd); 205 | goto end; 206 | } 207 | 208 | if (writeFileHeader()) { 209 | LOG_ERROR("%s(%s) : %s", "Writing jit dump header", filename, strerror(errno)); 210 | munmap(marker, 0); 211 | marker = NULL; 212 | fclose(jitdump); 213 | jitdump = NULL; 214 | goto end; 215 | } 216 | error = 0; 217 | } else { 218 | LOG_ERROR("%s %s", "Jit dump already active on process", getpid()); 219 | } 220 | 221 | end: 222 | pthread_mutex_unlock(&jitdump_lock); 223 | if (!error) { 224 | LOG_INFO("%s(%s)", "Jit dump opened", filename); 225 | } 226 | return error; 227 | } 228 | 229 | bool 230 | is_jitdump_active() 231 | { 232 | if (!pthread_mutex_lock(&jitdump_lock)) { 233 | bool result = jitdump != NULL && marker != NULL; 234 | pthread_mutex_unlock(&jitdump_lock); 235 | return result; 236 | } 237 | return true; 238 | } 239 | 240 | int 241 | close_jitdump() 242 | { 243 | int error = 0; 244 | 245 | RecordHeader close; 246 | close.id = JIT_CODE_CLOSE; 247 | close.record_size = sizeof (RecordHeader); 248 | getTimestamp(&close.timestamp); 249 | 250 | if (!pthread_mutex_lock(&jitdump_lock)) { 251 | if (jitdump != NULL && marker != NULL) { 252 | if (jitdump != NULL) { 253 | if (fwrite(&close, sizeof (RecordHeader), 1, jitdump) != 1) { 254 | LOG_ERROR("%s : %s", "Writing close record", strerror(errno)); 255 | error = -1; 256 | }; 257 | if (fclose(jitdump)) { 258 | LOG_ERROR("%s : %s", "Closing jit dump", strerror(errno)); 259 | error = -1; 260 | } else { 261 | jitdump = NULL; 262 | } 263 | } 264 | 265 | if (marker != NULL) { 266 | long pgsz; 267 | if ((pgsz = sysconf(_SC_PAGESIZE)) == -1) { 268 | LOG_ERROR("%s : %s", "Getting page size", strerror(errno)); 269 | error = -1; 270 | } else { 271 | if (munmap(marker, pgsz)) { 272 | LOG_ERROR("%s : %s", "Unmapping jit dump", strerror(errno)); 273 | error = -1; 274 | } else { 275 | marker = NULL; 276 | } 277 | } 278 | } 279 | 280 | if (!error) { 281 | LOG_INFO("Jit dump closed"); 282 | } 283 | } 284 | pthread_mutex_unlock(&jitdump_lock); 285 | } 286 | 287 | return error; 288 | } 289 | 290 | /** 291 | * Write DebugInfoRecord to open jit dump file. 292 | * Must be written before the corresponding CodeLoadRecord. 293 | * 294 | * NOTE: Ensure jitdump is available and access is synchronized. 295 | * 296 | * @param diRecord DebugInfoRecord to write to jit dump file 297 | * @return 0 on success 298 | */ 299 | static int 300 | write_DebugInfoRecord(DebugInfoRecord *diRecord) 301 | { 302 | diRecord->count = 0; 303 | diRecord->header.record_size = sizeof (DebugInfoRecord) - sizeof (DebugEntry *); 304 | for (DebugEntry *current = diRecord->entries; current != NULL && current->filename != NULL; current++, diRecord->count++) { 305 | diRecord->header.record_size += (sizeof (DebugEntry) - sizeof (char *)) + strlen(current->filename) + 1; 306 | } 307 | fwrite(diRecord, sizeof (DebugInfoRecord) - sizeof (DebugEntry *), 1, jitdump); 308 | for (DebugEntry *current = diRecord->entries; current != NULL && current->filename != NULL; current++) { 309 | fwrite(current, sizeof (DebugEntry) - sizeof (char *), 1, jitdump); 310 | fwrite((void *) current->filename, strlen(current->filename) + 1, 1, jitdump); 311 | } 312 | return 0; 313 | } 314 | 315 | int 316 | write_CodeLoadRecord(CodeLoadRecord *clRecord, DebugInfoRecord *diRecord) 317 | { 318 | size_t name_len = strlen(clRecord->name) + 1; 319 | clRecord->header.record_size = sizeof (CodeLoadRecord) - sizeof (char *) +name_len + clRecord->size; 320 | 321 | if (!pthread_mutex_lock(&jitdump_lock)) { 322 | if (jitdump != NULL) { 323 | if (diRecord != NULL) { 324 | write_DebugInfoRecord(diRecord); 325 | } 326 | clRecord->index = code_index++; 327 | fwrite(clRecord, sizeof (CodeLoadRecord) - sizeof (char *), 1, jitdump); 328 | fwrite((void *) clRecord->name, name_len, 1, jitdump); 329 | fwrite((void *) clRecord->address, clRecord->size, 1, jitdump); 330 | } 331 | pthread_mutex_unlock(&jitdump_lock); 332 | return 0; 333 | } 334 | return -1; 335 | } 336 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /src/main/c/jvmti/perf-jitdump-agent.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Perf-JitDump-Agent: Create jitdump files supported by Linux Perf. 3 | * Copyright (C) 2017 Staffan Friberg 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 2 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program 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 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License along 16 | * with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "jitdump.h" 35 | #include "logger.h" 36 | 37 | #define LOG_JVMTI_ERROR(jmvti, error, format, ...) log_jvmti(__func__, __LINE__, LOG_LEVEL_ERROR, jvmti, error, format, ##__VA_ARGS__) 38 | #define LOG_JVMTI_WARN(jmvti, error, format, ...) log_jvmti(__func__, __LINE__, LOG_LEVEL_WARN, jvmti, error, format, ##__VA_ARGS__) 39 | #define LOG_JVMTI_INFO(jmvti, error, format, ...) log_jvmti(__func__, __LINE__, LOG_LEVEL_INFO, jvmti, error, format, ##__VA_ARGS__) 40 | #define LOG_JVMTI_DEBUG(jmvti, error, format, ...) log_jvmti(__func__, __LINE__, LOG_LEVEL_DEBUG, jvmti, error, format, ##__VA_ARGS__) 41 | #define LOG_JVMTI_TRACE(jmvti, error, format, ...) log_jvmti(__func__, __LINE__, LOG_LEVEL_TRACE, jvmti, error, format, ##__VA_ARGS__) 42 | 43 | static pthread_mutex_t agent_lock = PTHREAD_MUTEX_INITIALIZER; 44 | static uint64_t start = 0; 45 | static int64_t duration = -1; 46 | 47 | /** 48 | * Log JVMTI error and return the same error code 49 | * 50 | * @param function name of function where error occurred 51 | * @param line line number of error 52 | * @param jvmti JVMTI environment to get error message 53 | * @param error JVMTI error code 54 | * @param format message format 55 | * @param ... message data 56 | * @return the supplied jvmtiError 57 | */ 58 | static jvmtiError 59 | log_jvmti(const char* function, int line, LogLevel level, jvmtiEnv *jvmti, jvmtiError error, char *format, ...) 60 | { 61 | char *error_name; 62 | char message[1024]; 63 | va_list vars; 64 | 65 | va_start(vars, format); 66 | vsnprintf(message, 1024, format, vars); 67 | va_end(vars); 68 | 69 | if (!(*jvmti)->GetErrorName(jvmti, error, &error_name)) { 70 | log_msg(function, line, level, "%s : %s", message, error_name); 71 | (*jvmti)->Deallocate(jvmti, (unsigned char *) error_name); 72 | } else { 73 | log_msg(function, line, level, "%s : jvmtiError = %d", message, error); 74 | } 75 | 76 | return error; 77 | } 78 | 79 | /** 80 | * Get line number corresponding to a Bytecode Index (BCI) from a jvmtiLineNumberEntry array. 81 | * 82 | * @param entries jvmtiLineNumberEntry array 83 | * @param count number of entries in jvmtiLineNumberEntry array 84 | * @param bci BCI to search for 85 | * @return line number (1 or greater) or -1 if not found 86 | */ 87 | static int 88 | bci2line(jvmtiLineNumberEntry* entries, jint count, jint bci) 89 | { 90 | if (bci >= 0) { 91 | for (int i = count - 1; i >= 0; i--) { 92 | if (bci >= entries[i].start_location) { 93 | return entries[i].line_number; 94 | } 95 | } 96 | } else if (count == 1) { 97 | // Only one line entry, simply return that one even if bci is invalid 98 | return entries[0].line_number; 99 | } 100 | return -1; 101 | } 102 | 103 | /** 104 | * Find line number for BCI in method. 105 | * 106 | * @param jvmti JVMTI environment to use to lookup method and BCI entries 107 | * @param method method to search in 108 | * @param bci BCI to locate 109 | * @param line set to the found line number or -1 if not found 110 | * @return jvmtiError 111 | */ 112 | static jvmtiError 113 | get_line_number(jvmtiEnv *jvmti, jmethodID method, jint bci, int *line) 114 | { 115 | jvmtiError error = JVMTI_ERROR_NONE; 116 | *line = -1; 117 | jint count; 118 | jvmtiLineNumberEntry* entries; 119 | if ((error = (*jvmti)->GetLineNumberTable(jvmti, method, &count, &entries)) == JVMTI_ERROR_NONE) { 120 | *line = bci2line(entries, count, bci); 121 | (*jvmti)->Deallocate(jvmti, (unsigned char *) entries); 122 | } 123 | return error; 124 | } 125 | 126 | /** 127 | * Get the full path source filename /package/name/and/Klass.java containing the method with the specified jmethodID. 128 | * 129 | * @param jvmti JVMTI environment to use to look up required information 130 | * @param method method to find the source filename for 131 | * @param filename set to the source filename on success or NULL otherwise. Must be freed after use. 132 | * @return jvmtiError 133 | */ 134 | static jvmtiError 135 | get_filename(jvmtiEnv *jvmti, jmethodID method, char **filename) 136 | { 137 | jvmtiError error = JVMTI_ERROR_NONE; 138 | jclass klass; 139 | 140 | *filename = NULL; 141 | 142 | //TODO: For a large method with many inlined methods do we need to consider DeleteLocalRef to not get too many local refs 143 | //http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html#wp18654 144 | if ((error = (*jvmti)->GetMethodDeclaringClass(jvmti, method, &klass)) == JVMTI_ERROR_NONE) { 145 | char *klass_signature; 146 | if ((error = (*jvmti)->GetClassSignature(jvmti, klass, &klass_signature, NULL)) == JVMTI_ERROR_NONE) { 147 | char *file; 148 | if ((error = (*jvmti)->GetSourceFileName(jvmti, klass, &file)) == JVMTI_ERROR_NONE) { 149 | char *path = klass_signature[0] == 'L' ? klass_signature + 1 : klass_signature; 150 | char *last_slash = strrchr(path, '/'); 151 | int path_len = last_slash == NULL ? 0 : last_slash - path; 152 | int length = path_len + strlen(file) + 2; 153 | if ((*filename = malloc(length * sizeof (char))) != NULL) { 154 | if (last_slash == NULL) { 155 | snprintf(*filename, length, "%s", file); 156 | } else { 157 | snprintf(*filename, length, "%.*s/%s", path_len, path, file); 158 | } 159 | } else { 160 | error = JVMTI_ERROR_OUT_OF_MEMORY; 161 | } 162 | (*jvmti)->Deallocate(jvmti, (unsigned char *) file); 163 | } 164 | (*jvmti)->Deallocate(jvmti, (unsigned char *) klass_signature); 165 | } 166 | } 167 | return error; 168 | } 169 | 170 | /** 171 | * Get method name for a specific jmethodID. 172 | * 173 | * @param jvmti JVMTI environment to use to look up required information 174 | * @param method jmethodID of the method 175 | * @param method_name set to method name on success or NULL otherwise. Must be freed after use. 176 | * @return jvmtiError 177 | */ 178 | static jvmtiError 179 | get_method_name(jvmtiEnv *jvmti, jmethodID method, char **method_name) 180 | { 181 | jvmtiError error = JVMTI_ERROR_NONE; 182 | jclass klass; 183 | 184 | if ((error = (*jvmti)->GetMethodDeclaringClass(jvmti, method, &klass)) == JVMTI_ERROR_NONE) { 185 | char *klass_signature; 186 | if ((error = (*jvmti)->GetClassSignature(jvmti, klass, &klass_signature, NULL)) == JVMTI_ERROR_NONE) { 187 | char *name; 188 | char *signature; 189 | if ((error = (*jvmti)->GetMethodName(jvmti, method, &name, &signature, NULL)) == JVMTI_ERROR_NONE) { 190 | //strlen crashes on some signatures 191 | char *package = klass_signature[0] == 'L' ? klass_signature + 1 : klass_signature; 192 | int package_len = 0; 193 | for (; package[package_len] != ';' && package[package_len] != '\0'; package_len++) { 194 | if (package[package_len] == '/') { 195 | package[package_len] = '.'; 196 | } 197 | } 198 | int length = package_len + strlen(name) + strlen(signature) + 2; 199 | *method_name = malloc(length * sizeof (char)); 200 | snprintf(*method_name, length, "%.*s.%s%s", package_len, package, name, signature); 201 | 202 | (*jvmti)->Deallocate(jvmti, (unsigned char *) signature); 203 | (*jvmti)->Deallocate(jvmti, (unsigned char *) name); 204 | } 205 | (*jvmti)->Deallocate(jvmti, (unsigned char *) klass_signature); 206 | } 207 | } 208 | return error; 209 | } 210 | 211 | /** 212 | * Get available debug entries for the current method. 213 | * 214 | * @param jvmti JVMTI environment to use to look up required information 215 | * @param header header of jvmtiCompiledMethodLoadRecord 216 | * @param debug_entries JitDumpDebugEntry points to a null terminated array if successful or NULL otherwise 217 | * @return jvmtiError 218 | */ 219 | static jvmtiError 220 | get_DebugEntries(jvmtiEnv *jvmti, jvmtiCompiledMethodLoadRecordHeader *header, 221 | const char *method_name, DebugEntry **debug_entries) 222 | { 223 | *debug_entries = NULL; 224 | 225 | // check header is valid 226 | if (JVMTI_CMLR_MAJOR_VERSION == header->majorinfoversion 227 | && JVMTI_CMLR_MINOR_VERSION == header->minorinfoversion) { 228 | 229 | int numpcs = 0; 230 | jvmtiCompiledMethodLoadRecordHeader *iterator = header; 231 | do { 232 | if (JVMTI_CMLR_INLINE_INFO == iterator->kind) { 233 | jvmtiCompiledMethodLoadInlineRecord *record = (jvmtiCompiledMethodLoadInlineRecord *) iterator; 234 | numpcs += record->numpcs; 235 | } 236 | } while ((iterator = iterator->next) != NULL); 237 | 238 | if (numpcs > 0) { 239 | 240 | if ((*debug_entries = calloc(numpcs + 1, sizeof (DebugEntry))) == NULL) { 241 | return JVMTI_ERROR_OUT_OF_MEMORY; 242 | } 243 | 244 | DebugEntry *current = *debug_entries; 245 | do { 246 | if (JVMTI_CMLR_INLINE_INFO == header->kind) { 247 | jvmtiCompiledMethodLoadInlineRecord *record = (jvmtiCompiledMethodLoadInlineRecord *) header; 248 | for (int i = 0; i < record->numpcs; i++) { 249 | // Only care about the method on the top of the stack which is the actual code 250 | int inlined_bci = record->pcinfo[i].bcis[0]; 251 | jmethodID inlined_method = record->pcinfo[i].methods[0]; 252 | jvmtiError error; 253 | int inlined_line; 254 | char *inlined_filename; 255 | 256 | //TODO: Why do we get so many BCI that are -1 257 | // According to perf-map-agent HotSpot does not retain line number information for inlined methods 258 | 259 | //TODO: Potentially cache method filename as many will probably be the repetitions 260 | if ((error = get_filename(jvmti, inlined_method, &inlined_filename)) == JVMTI_ERROR_NONE) { 261 | if ((error = get_line_number(jvmti, inlined_method, inlined_bci, &inlined_line)) != JVMTI_ERROR_NONE) { 262 | LOG_JVMTI_DEBUG(jvmti, error, "%s : Unable to get line number for %s with bci %d", method_name, inlined_filename, inlined_bci); 263 | free(inlined_filename); 264 | continue; 265 | } 266 | } else { 267 | // Print error message 268 | char *inline_method_name; 269 | if (get_method_name(jvmti, inlined_method, &inline_method_name) == JVMTI_ERROR_NONE) { 270 | LOG_JVMTI_DEBUG(jvmti, error, "%s : Unable to get filename for the inlined method %s", method_name, inline_method_name); 271 | free(inline_method_name); 272 | } else { 273 | LOG_JVMTI_DEBUG(jvmti, error, "%s : Unable to get filename for a inlined method", method_name); 274 | } 275 | continue; 276 | } 277 | 278 | // Filter out entries with bad line number information 279 | if (inlined_line > 0) { 280 | current->address = (uint64_t) record->pcinfo[i].pc; 281 | current->discriminator = 0; 282 | current->line = inlined_line; 283 | current->filename = inlined_filename; 284 | LOG_TRACE("DebugInfo %s : 0x%X : %s:%d", method_name, current->address, current->filename, current->line); 285 | current++; 286 | } else { 287 | free(inlined_filename); 288 | } 289 | } 290 | } 291 | } while ((header = header->next) != NULL); 292 | } 293 | } 294 | return JVMTI_ERROR_NONE; 295 | } 296 | 297 | /** 298 | * Check if the sampling duration has expired. 299 | * 300 | * @return true if duration is larger than 0 and has expired 301 | */ 302 | static bool 303 | duration_expired() 304 | { 305 | if (duration > 0) { 306 | uint64_t current; 307 | if (!getTimestamp(¤t)) { 308 | if (duration < (current - start)) { 309 | LOG_INFO("Duration (%lds) has expired.\n", duration / 1000000000); 310 | return true; 311 | } 312 | } 313 | } 314 | return false; 315 | } 316 | 317 | /** 318 | * Disable JVMTI callbacks and events. 319 | * 320 | * @param jvmti JVMTI environment to clear 321 | * @return jvmtiError 322 | */ 323 | static jvmtiError 324 | stop_jvmti(jvmtiEnv *jvmti) 325 | { 326 | jvmtiError error = JVMTI_ERROR_NONE; 327 | jvmtiEventCallbacks callbacks; 328 | 329 | if ((error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_DISABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL)) != JVMTI_ERROR_NONE) { 330 | LOG_JVMTI_ERROR(jvmti, error, "Disabling Compiled Method Load Event"); 331 | } 332 | if ((error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_DISABLE, JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL)) != JVMTI_ERROR_NONE) { 333 | LOG_JVMTI_ERROR(jvmti, error, "Disabling Dynamic Code Generated Event"); 334 | } 335 | 336 | memset(&callbacks, 0, sizeof (jvmtiEventCallbacks)); 337 | if ((error = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof (jvmtiEventCallbacks))) != JVMTI_ERROR_NONE) { 338 | LOG_JVMTI_ERROR(jvmti, error, "Clearing Callbacks"); 339 | } 340 | return error; 341 | } 342 | 343 | void JNICALL 344 | method_load(jvmtiEnv *jvmti, 345 | jmethodID method, 346 | jint code_size, 347 | const void* code_addr, 348 | jint map_length, 349 | const jvmtiAddrLocationMap* map, 350 | const void* compile_info) 351 | { 352 | jvmtiError error = JVMTI_ERROR_NONE; 353 | char *method_name; 354 | CodeLoadRecord cl; 355 | 356 | if (duration_expired()) { 357 | if (!pthread_mutex_lock(&agent_lock)) { 358 | stop_jvmti(jvmti); 359 | close_jitdump(); 360 | pthread_mutex_unlock(&agent_lock); 361 | } 362 | return; 363 | } 364 | 365 | if ((error = get_method_name(jvmti, method, &method_name)) != JVMTI_ERROR_NONE) { 366 | LOG_JVMTI_ERROR(jvmti, error, "Getting Method Name"); 367 | return; 368 | } 369 | 370 | cl.header.id = JIT_CODE_LOAD; 371 | cl.name = method_name; 372 | cl.pid = getpid(); 373 | cl.tid = pthread_self(); 374 | cl.address = cl.virtual_address = (uint64_t) code_addr; 375 | cl.size = code_size; 376 | if (getTimestamp(&cl.header.timestamp)) { 377 | goto end; 378 | } 379 | 380 | LOG_DEBUG("Loaded Method : %s 0x%X-0x%X (%ld)", cl.name, cl.address, (cl.address + cl.size), cl.size); 381 | 382 | // TODO: Improve code flow 383 | if (compile_info != NULL) { 384 | 385 | DebugEntry *entries; 386 | error = get_DebugEntries(jvmti, (jvmtiCompiledMethodLoadRecordHeader*) compile_info, method_name, &entries); 387 | if (error == JVMTI_ERROR_NONE) { 388 | DebugInfoRecord di; 389 | di.header.id = JIT_CODE_DEBUG_INFO; 390 | di.header.timestamp = cl.header.timestamp; 391 | di.address = cl.address; 392 | di.entries = entries; 393 | write_CodeLoadRecord(&cl, &di); 394 | if (di.entries != NULL) { 395 | for (DebugEntry *current = di.entries; current->filename != NULL; current++) { 396 | free(current->filename); 397 | } 398 | free(di.entries); 399 | } 400 | } else { 401 | write_CodeLoadRecord(&cl, NULL); 402 | } 403 | 404 | } else { 405 | write_CodeLoadRecord(&cl, NULL); 406 | } 407 | 408 | end: 409 | free(method_name); 410 | } 411 | 412 | void JNICALL 413 | code_generated(jvmtiEnv *jvmti, 414 | const char* method_name, 415 | const void* address, 416 | jint length) 417 | { 418 | if (duration_expired()) { 419 | if (!pthread_mutex_lock(&agent_lock)) { 420 | stop_jvmti(jvmti); 421 | close_jitdump(); 422 | pthread_mutex_unlock(&agent_lock); 423 | } 424 | } else { 425 | LOG_DEBUG("Code Generated : %s", method_name); 426 | CodeLoadRecord codeload; 427 | codeload.header.id = JIT_CODE_LOAD; 428 | if (getTimestamp(&codeload.header.timestamp)) { 429 | return; 430 | } 431 | codeload.pid = getpid(); 432 | codeload.tid = pthread_self(); 433 | codeload.address = codeload.virtual_address = (uint64_t) address; 434 | codeload.size = length; 435 | codeload.name = method_name; 436 | write_CodeLoadRecord(&codeload, NULL); 437 | } 438 | } 439 | 440 | /** 441 | * Parse agent arguments. 442 | * 443 | * @param args arguments to agent 444 | * @param directory will be set to the directory to where to store the JIT dump 445 | * @return 0 on success 446 | */ 447 | static int 448 | parse_args(char *args, char *directory) 449 | { 450 | 451 | snprintf(directory, PATH_MAX, "%s/%s", getenv("HOME"), ".debug/jit"); 452 | int level = LOG_LEVEL_WARN; 453 | 454 | //check options 455 | if (args != NULL) { 456 | for (char *option = strtok(args, ","); option != NULL; option = strtok(NULL, ",")) { 457 | if (strstr(option, "verbose") != NULL) { 458 | sscanf(option, "verbose=%d", &level); 459 | } else if (strstr(option, "duration") != NULL) { 460 | sscanf(option, "duration=%ld", &duration); 461 | duration = duration * 1000000000; 462 | if (duration > 0 && getTimestamp(&start)) { 463 | return -1; 464 | } 465 | } else if (strstr(option, "directory") != NULL) { 466 | sscanf(option, "directory=%4096s", directory); 467 | } 468 | } 469 | } 470 | 471 | 472 | log_init(stdout, level, "perf-jitdump-agent"); 473 | LOG_INFO("Logging Enabled: %s", log_level_name(level)); 474 | LOG_INFO("Duration: %lds", duration >= 0 ? duration / 1000000000 : duration); 475 | LOG_INFO("JitDump Output Directory: %s", directory); 476 | return 0; 477 | } 478 | 479 | /** 480 | * Setup JVMTI capabilities, events and callbacks. 481 | * 482 | * @param jvmti JVMTI environment to setup 483 | * @return jvmtiError code 484 | */ 485 | static jvmtiError 486 | setup_jvmti(jvmtiEnv *jvmti) 487 | { 488 | jvmtiError error; 489 | jvmtiCapabilities capabilities; 490 | jvmtiEventCallbacks callbacks; 491 | 492 | memset(&capabilities, 0, sizeof (jvmtiCapabilities)); 493 | capabilities.can_generate_compiled_method_load_events = 1; 494 | capabilities.can_get_source_file_name = 1; 495 | capabilities.can_get_line_numbers = 1; 496 | if ((error = (*jvmti)->AddCapabilities(jvmti, &capabilities)) != JVMTI_ERROR_NONE) { 497 | return LOG_JVMTI_ERROR(jvmti, error, "Adding Capabilities"); 498 | } 499 | 500 | memset(&callbacks, 0, sizeof (jvmtiEventCallbacks)); 501 | callbacks.CompiledMethodLoad = method_load; 502 | callbacks.DynamicCodeGenerated = code_generated; 503 | if ((error = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof (jvmtiEventCallbacks))) != JVMTI_ERROR_NONE) { 504 | return LOG_JVMTI_ERROR(jvmti, error, "Setting Callbacks"); 505 | } 506 | 507 | if ((error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL)) != JVMTI_ERROR_NONE) { 508 | return LOG_JVMTI_ERROR(jvmti, error, "Enabling Compiled Method Load Event"); 509 | } 510 | if ((error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL)) != JVMTI_ERROR_NONE) { 511 | return LOG_JVMTI_ERROR(jvmti, error, "Enabling Dynamic Code Generated Event"); 512 | } 513 | 514 | return JVMTI_ERROR_NONE; 515 | } 516 | 517 | JNIEXPORT jint JNICALL 518 | Agent_OnLoad(JavaVM *vm, char *args, void *reserved) 519 | { 520 | int error = 0; 521 | char directory[PATH_MAX]; 522 | jint jni_error; 523 | jvmtiEnv *jvmti; 524 | 525 | if (pthread_mutex_lock(&agent_lock)) { 526 | LOG_ERROR("%s : %s", "Locking Mutex", strerror(errno)); 527 | return -1; 528 | } 529 | 530 | if (is_jitdump_active()) { 531 | LOG_ERROR("Jit dump is already active"); 532 | error = -1; 533 | goto end; 534 | } 535 | 536 | if (parse_args(args, directory)) { 537 | error = -1; 538 | goto end; 539 | } 540 | LOG_INFO("Loading Agent"); 541 | 542 | if (open_jitdump(directory)) { 543 | error = -1; 544 | goto end; 545 | } 546 | 547 | if ((jni_error = (*vm)->GetEnv(vm, (void**) &jvmti, JVMTI_VERSION_1_2)) != JNI_OK) { 548 | LOG_ERROR("Error getting JVMTI environment: %d", jni_error); 549 | error = -1; 550 | goto end; 551 | } 552 | 553 | if (setup_jvmti(jvmti) != JVMTI_ERROR_NONE) { 554 | error = -1; 555 | goto end; 556 | } 557 | 558 | LOG_INFO("Agent Loaded"); 559 | 560 | end: 561 | pthread_mutex_unlock(&agent_lock); 562 | return error; 563 | } 564 | 565 | JNIEXPORT jint JNICALL 566 | Agent_OnAttach(JavaVM* vm, char *args, void *reserved) 567 | { 568 | int error = 0; 569 | jvmtiEnv *jvmti; 570 | jint jni_error; 571 | jvmtiError jvmti_error; 572 | char directory[PATH_MAX]; 573 | 574 | if (pthread_mutex_lock(&agent_lock)) { 575 | return -1; 576 | } 577 | 578 | if (is_jitdump_active()) { 579 | // Since jit dump is active logging must be configured as well 580 | LOG_ERROR("Jit dump is already active"); 581 | error = -30; 582 | goto end; 583 | } 584 | 585 | if (parse_args(args, directory)) { 586 | error = -1; 587 | goto end; 588 | } 589 | LOG_INFO("Attaching Agent"); 590 | 591 | if (open_jitdump(directory)) { 592 | error = -31; 593 | goto end; 594 | } 595 | 596 | if ((jni_error = (*vm)->GetEnv(vm, (void **) &jvmti, JVMTI_VERSION_1_2)) != JNI_OK) { 597 | LOG_ERROR("Error getting JVMTI environment: %d\n", jni_error); 598 | error = -1; 599 | goto end; 600 | } 601 | 602 | if (setup_jvmti(jvmti) != JVMTI_ERROR_NONE) { 603 | error = -1; 604 | goto end; 605 | } 606 | 607 | if ((jvmti_error = (*jvmti)->GenerateEvents(jvmti, JVMTI_EVENT_DYNAMIC_CODE_GENERATED)) != JVMTI_ERROR_NONE || 608 | (jvmti_error = (*jvmti)->GenerateEvents(jvmti, JVMTI_EVENT_COMPILED_METHOD_LOAD)) != JVMTI_ERROR_NONE) { 609 | LOG_JVMTI_ERROR(jvmti, jvmti_error, "Generating Events"); 610 | error = -1; 611 | } 612 | 613 | // If duration is 0 exit directly 614 | // Looks like GenerateEvent calls are blocking so we should have written all data as when we get here 615 | if (duration == 0) { 616 | stop_jvmti(jvmti); 617 | close_jitdump(); 618 | } 619 | 620 | end: 621 | pthread_mutex_unlock(&agent_lock); 622 | if (error == 0) { 623 | LOG_INFO("Agent Attached"); 624 | } 625 | return error; 626 | } 627 | 628 | JNIEXPORT void JNICALL 629 | Agent_OnUnload(JavaVM * vm) 630 | { 631 | close_jitdump(); 632 | LOG_INFO("Agent Unloaded"); 633 | } 634 | --------------------------------------------------------------------------------