├── .travis.yml ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── src ├── main │ └── java │ │ └── com │ │ └── github │ │ └── chrishantha │ │ └── jfr │ │ └── flamegraph │ │ └── output │ │ ├── OutputWriterParameters.java │ │ ├── SecondsToNanosConverter.java │ │ ├── FlameGraphOutputWriter.java │ │ ├── OutputType.java │ │ ├── Application.java │ │ ├── FoldedOutputWriter.java │ │ ├── JsonOutputWriter.java │ │ ├── EventType.java │ │ └── JFRToFlameGraphWriter.java ├── dist │ └── bin │ │ ├── create_flamegraph.sh │ │ └── create_flamegraphs.sh └── test │ └── java │ └── com │ └── github │ └── chrishantha │ └── jfr │ └── flamegraph │ └── output │ └── ApplicationTest.java ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = "jfr-flame-graph" 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chrishantha/jfr-flame-graph/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 2 | hs_err_pid* 3 | 4 | #Gradle 5 | .gradle/ 6 | build/ 7 | 8 | #Eclipse 9 | .project 10 | .classpath 11 | 12 | #Idea 13 | .idea/ 14 | *.iml 15 | out/ 16 | 17 | .metadata 18 | bin/ 19 | tmp/ 20 | *.tmp 21 | *.bak 22 | *.swp 23 | *~.nib 24 | .settings/ 25 | 26 | #Local Flame Graphs 27 | *.svg 28 | 29 | -------------------------------------------------------------------------------- /src/main/java/com/github/chrishantha/jfr/flamegraph/output/OutputWriterParameters.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 M. Isuru Tharanga Chrishantha Perera 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.chrishantha.jfr.flamegraph.output; 17 | 18 | import com.beust.jcommander.Parameter; 19 | 20 | /** 21 | * Additional parameters for Output Writers 22 | */ 23 | public final class OutputWriterParameters { 24 | 25 | @Parameter(names = {"-l", "--live"}, description = "Export stack trace sample timestamp (in json output type)") 26 | boolean live = false; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/github/chrishantha/jfr/flamegraph/output/SecondsToNanosConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Stefan Oehme 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.chrishantha.jfr.flamegraph.output; 17 | 18 | import com.beust.jcommander.converters.LongConverter; 19 | 20 | import java.util.concurrent.TimeUnit; 21 | 22 | public class SecondsToNanosConverter extends LongConverter { 23 | public SecondsToNanosConverter(String optionName) { 24 | super(optionName); 25 | } 26 | 27 | @Override 28 | public Long convert(String value) { 29 | Long seconds = super.convert(value); 30 | return TimeUnit.SECONDS.toNanos(seconds); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/github/chrishantha/jfr/flamegraph/output/FlameGraphOutputWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 M. Isuru Tharanga Chrishantha Perera 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.chrishantha.jfr.flamegraph.output; 17 | 18 | import java.io.BufferedWriter; 19 | import java.io.IOException; 20 | import java.time.Duration; 21 | import java.time.Instant; 22 | import java.util.Stack; 23 | 24 | /** 25 | * Process stack traces and write the output 26 | */ 27 | public interface FlameGraphOutputWriter { 28 | 29 | void initialize(OutputWriterParameters parameters); 30 | 31 | void processEvent(Instant startTimestamp, Instant endTimestamp, Duration duration, Stack stack, long value); 32 | 33 | void writeOutput(BufferedWriter bufferedWriter) throws IOException; 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/github/chrishantha/jfr/flamegraph/output/OutputType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 M. Isuru Tharanga Chrishantha Perera 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.chrishantha.jfr.flamegraph.output; 17 | 18 | /** 19 | * Output Types for different FlameGraph implementations 20 | */ 21 | public enum OutputType { 22 | 23 | /** 24 | * Create folded output 25 | */ 26 | FOLDED("folded") { 27 | @Override 28 | public FlameGraphOutputWriter createFlameGraphOutputWriter() { 29 | return new FoldedOutputWriter(); 30 | } 31 | }, 32 | 33 | /** 34 | * Create json output for d3-flame-graph 35 | */ 36 | JSON("json") { 37 | @Override 38 | public FlameGraphOutputWriter createFlameGraphOutputWriter() { 39 | return new JsonOutputWriter(); 40 | } 41 | }; 42 | 43 | private final String name; 44 | 45 | OutputType(String name) { 46 | this.name = name; 47 | } 48 | 49 | public abstract FlameGraphOutputWriter createFlameGraphOutputWriter(); 50 | 51 | @Override 52 | public String toString() { 53 | return name; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/dist/bin/create_flamegraph.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2016 M. Isuru Tharanga Chrishantha Perera 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # ---------------------------------------------------------------------------- 17 | # Create a Flame Graph 18 | # ---------------------------------------------------------------------------- 19 | set -e 20 | 21 | JFG_DIR=$(dirname "$0") 22 | 23 | if [ ! -x "$FLAMEGRAPH_DIR/flamegraph.pl" ]; then 24 | (>&2 echo "Please clone https://github.com/brendangregg/FlameGraph and set FLAMEGRAPH_DIR to the root directory") 25 | exit 1 26 | fi 27 | 28 | function help { 29 | echo "" 30 | echo "Usage: " 31 | echo "create-flamegraph.sh [some options supported by jfr-flame-graph]" 32 | echo "" 33 | echo "See: jfr-flame-graph -h" 34 | echo "" 35 | } 36 | 37 | jfr_file="" 38 | 39 | while getopts "df:airsx:y:e:" opts 40 | do 41 | case $opts in 42 | f) 43 | jfr_file=${OPTARG} 44 | ;; 45 | \?) 46 | help 47 | exit 1 48 | ;; 49 | esac 50 | done 51 | 52 | if [[ ! -f $jfr_file ]]; then 53 | (>&2 echo "Please specify the JFR file") 54 | (>&2 help) 55 | exit 1 56 | fi 57 | 58 | jfr_filename=$(basename $jfr_file) 59 | 60 | # Use folded output type 61 | ${JFG_DIR}/jfr-flame-graph -ot folded $* | $FLAMEGRAPH_DIR/flamegraph.pl --title "Flame Graph: $jfr_filename" -------------------------------------------------------------------------------- /src/main/java/com/github/chrishantha/jfr/flamegraph/output/Application.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 M. Isuru Tharanga Chrishantha Perera 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.chrishantha.jfr.flamegraph.output; 17 | 18 | import com.beust.jcommander.JCommander; 19 | import com.beust.jcommander.ParameterException; 20 | 21 | public class Application { 22 | 23 | public static void main(String[] args) throws Exception { 24 | final JCommander jcmdr = new JCommander(); 25 | jcmdr.setProgramName(JFRToFlameGraphWriter.class.getSimpleName()); 26 | 27 | OutputWriterParameters parameters = new OutputWriterParameters(); 28 | JFRToFlameGraphWriter jfrToFlameGraphWriter = new JFRToFlameGraphWriter(parameters); 29 | 30 | jcmdr.addObject(parameters); 31 | jcmdr.addObject(jfrToFlameGraphWriter); 32 | 33 | try { 34 | jcmdr.parse(args); 35 | } catch (ParameterException e) { 36 | System.err.println(e.getMessage()); 37 | return; 38 | } 39 | 40 | if (jfrToFlameGraphWriter.help) { 41 | jcmdr.usage(); 42 | return; 43 | } 44 | 45 | try { 46 | jfrToFlameGraphWriter.process(); 47 | } catch (Exception e) { 48 | System.err.println(e.getMessage()); 49 | throw e; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/github/chrishantha/jfr/flamegraph/output/FoldedOutputWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 M. Isuru Tharanga Chrishantha Perera 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.chrishantha.jfr.flamegraph.output; 17 | 18 | import java.io.BufferedWriter; 19 | import java.io.IOException; 20 | import java.time.Duration; 21 | import java.time.Instant; 22 | import java.util.LinkedHashMap; 23 | import java.util.Map; 24 | import java.util.Stack; 25 | 26 | /** 27 | * Create folded output to be used with flamegraph.pl 28 | */ 29 | public class FoldedOutputWriter implements FlameGraphOutputWriter { 30 | 31 | /** 32 | * The data model for folded stacks 33 | */ 34 | private final Map stackTraceMap = new LinkedHashMap<>(); 35 | 36 | @Override 37 | public void initialize(OutputWriterParameters parameters) { 38 | } 39 | 40 | @Override 41 | public void processEvent(Instant startTimestamp, Instant endTimestamp, Duration duration, Stack stack, long value) { 42 | StringBuilder stackTraceBuilder = new StringBuilder(); 43 | boolean appendSemicolon = false; 44 | while (!stack.empty()) { 45 | if (appendSemicolon) { 46 | stackTraceBuilder.append(";"); 47 | } else { 48 | appendSemicolon = true; 49 | } 50 | stackTraceBuilder.append(stack.pop()); 51 | } 52 | String stackTrace = stackTraceBuilder.toString(); 53 | Long count = stackTraceMap.get(stackTrace); 54 | if (count == null) { 55 | count = value; 56 | } else { 57 | count += value; 58 | } 59 | stackTraceMap.put(stackTrace, count); 60 | } 61 | 62 | @Override 63 | public void writeOutput(BufferedWriter bufferedWriter) throws IOException { 64 | for (Map.Entry entry : stackTraceMap.entrySet()) { 65 | bufferedWriter.write(String.format("%s %d%n", entry.getKey(), entry.getValue())); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/test/java/com/github/chrishantha/jfr/flamegraph/output/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 M. Isuru Tharanga Chrishantha Perera 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.chrishantha.jfr.flamegraph.output; 17 | 18 | import com.beust.jcommander.JCommander; 19 | import junit.framework.Test; 20 | import junit.framework.TestCase; 21 | import junit.framework.TestSuite; 22 | 23 | import java.io.File; 24 | import java.io.IOException; 25 | 26 | /** 27 | * Unit tests for the main Application. 28 | */ 29 | public class ApplicationTest extends TestCase { 30 | 31 | private OutputWriterParameters parameters; 32 | private JFRToFlameGraphWriter jfrToFlameGraphWriter; 33 | 34 | @Override 35 | protected void setUp() throws Exception { 36 | parameters = new OutputWriterParameters(); 37 | jfrToFlameGraphWriter = new JFRToFlameGraphWriter(parameters); 38 | } 39 | 40 | /** 41 | * @return the suite of tests being tested 42 | */ 43 | public static Test suite() { 44 | return new TestSuite(ApplicationTest.class); 45 | } 46 | 47 | private void parseCommands(String[] args) { 48 | JCommander jc = new JCommander(); 49 | jc.addObject(jfrToFlameGraphWriter); 50 | jc.addObject(parameters); 51 | jc.parse(args); 52 | } 53 | 54 | public void testJFRToFlameGraphWriterOutputFile() throws IOException { 55 | File tmp = File.createTempFile(getClass().getName(), ""); 56 | String[] args = {"-f", tmp.toString(), "-o", tmp.toString()}; 57 | parseCommands(args); 58 | assertTrue(tmp.exists()); 59 | assertEquals(tmp, jfrToFlameGraphWriter.jfrdump); 60 | assertEquals(tmp, jfrToFlameGraphWriter.outputFile); 61 | assertFalse(jfrToFlameGraphWriter.ignoreLineNumbers); 62 | } 63 | 64 | public void testIgnoreLineNumbersOption() throws IOException { 65 | String[] args = {"-f", "temp", "-i"}; 66 | parseCommands(args); 67 | assertTrue(jfrToFlameGraphWriter.ignoreLineNumbers); 68 | } 69 | 70 | public void testLiveOption() throws IOException { 71 | String[] args = {"-f", "temp", "-l"}; 72 | parseCommands(args); 73 | assertTrue(parameters.live); 74 | } 75 | 76 | public void testEventTypeOption() throws Exception { 77 | String[] args = {"-f", "temp", "-e", "allocation-tlab"}; 78 | parseCommands(args); 79 | assertEquals(EventType.ALLOCATION_IN_NEW_TLAB, jfrToFlameGraphWriter.eventType); 80 | } 81 | 82 | public void testEventTypeOptionDefaultValue() throws Exception { 83 | String[] args = {"-f", "temp"}; 84 | parseCommands(args); 85 | assertEquals(EventType.METHOD_PROFILING_SAMPLE, jfrToFlameGraphWriter.eventType); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Note: Travis has removed the support for Oracle JDK 8. Therefore the build status is removed temporarily. 2 | 3 | Converting JFR Method Profiling Samples to FlameGraph compatible format. 4 | ======================================================================== 5 | 6 | This is a simple application to read Method Profiling Samples from Java Flight Recorder dump and convert those Stack Traces to [FlameGraph] compatible format. 7 | 8 | [FlameGraph]: https://github.com/brendangregg/FlameGraph 9 | 10 | This application uses the unsupported [JMC Parser]. 11 | 12 | [JMC Parser]: http://hirt.se/blog/?p=446 13 | 14 | See my blog post on "[Flame Graphs with Java Flight Recordings]" for more details. 15 | 16 | [Flame Graphs with Java Flight Recordings]: http://isuru-perera.blogspot.com/2015/05/flame-graphs-with-java-flight-recordings.html 17 | 18 | ## Prerequisites 19 | 20 | This project depends on Oracle JDK 8. Therefore, make sure that `JAVA_HOME` is set to Oracle JDK 8. 21 | 22 | ## How to build and install 23 | 24 | Build and install `jfr-flame-graph` app using 25 | 26 | ``` 27 | ./gradlew installDist 28 | ``` 29 | 30 | This will install the executable into `./build/install/jfr-flame-graph/bin`. 31 | 32 | You can add this location to your `PATH`. 33 | 34 | ## Clone FlameGraph repository 35 | 36 | Clone [Brendan]'s [FlameGraph] repository and set the environment variable `FLAMEGRAPH_DIR` to FlameGraph directory 37 | 38 | [Brendan]: http://www.brendangregg.com/bio.html 39 | 40 | ``` 41 | git clone https://github.com/brendangregg/FlameGraph.git 42 | export FLAMEGRAPH_DIR=/path/to/FlameGraph 43 | ``` 44 | 45 | ## How to generate a Flame Graph 46 | 47 | There are helper scripts, to generate the flame graphs in `./build/install/jfr-flame-graph/bin` directory. 48 | 49 | For example: 50 | 51 | ``` 52 | ./create_flamegraph.sh -f /tmp/highcpu.jfr -i > flamegraph.svg 53 | ``` 54 | Open the SVG file in your web browser. 55 | 56 | Use -h with scripts to see the available options. 57 | 58 | For example: 59 | ``` 60 | $ ./jfr-flame-graph -h 61 | Usage: JFRToFlameGraphWriter [options] 62 | Options: 63 | -d, --decompress 64 | Decompress the JFR file 65 | Default: false 66 | -et, --end-timestamp 67 | End timestamp in seconds for filtering 68 | Default: 9223372036854775807 69 | -e, --event 70 | Type of event used to generate the flamegraph 71 | Default: cpu 72 | Possible Values: [cpu, allocation-tlab, allocation-outside-tlab, exceptions, monitor-blocked, io] 73 | -h, --help 74 | Display Help 75 | -ha, --hide-arguments 76 | Hide arguments in methods 77 | Default: false 78 | -i, --ignore-line-numbers 79 | Ignore Line Numbers in Stack Frame 80 | Default: false 81 | * -f, --jfrdump 82 | Java Flight Recorder Dump 83 | -l, --live 84 | Export stack trace sample timestamp (in json output type) 85 | Default: false 86 | -o, --output 87 | Output file 88 | -ot, --output-type 89 | Output type 90 | Default: folded 91 | Possible Values: [folded, json] 92 | -j, --print-jfr-details 93 | Print JFR details and exit 94 | Default: false 95 | -t, --print-timestamp 96 | Print timestamp in JFR Details 97 | Default: false 98 | -rv, --show-return-value 99 | Show return value for methods in the stack 100 | Default: false 101 | -st, --start-timestamp 102 | Start timestamp in seconds for filtering 103 | Default: -9223372036854775808 104 | -sn, --use-simple-names 105 | Use simple names instead of qualified names in the stack 106 | Default: false 107 | ``` 108 | 109 | ## License 110 | 111 | Copyright (C) 2015 M. Isuru Tharanga Chrishantha Perera 112 | 113 | Licensed under the Apache License, Version 2.0 114 | -------------------------------------------------------------------------------- /src/main/java/com/github/chrishantha/jfr/flamegraph/output/JsonOutputWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 M. Isuru Tharanga Chrishantha Perera 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.chrishantha.jfr.flamegraph.output; 17 | 18 | import com.google.gson.Gson; 19 | import com.google.gson.GsonBuilder; 20 | 21 | import java.io.BufferedWriter; 22 | import java.io.IOException; 23 | import java.time.Duration; 24 | import java.time.Instant; 25 | import java.util.ArrayList; 26 | import java.util.HashMap; 27 | import java.util.List; 28 | import java.util.Map; 29 | import java.util.Stack; 30 | import java.util.concurrent.TimeUnit; 31 | 32 | /** 33 | * Create JSON output to be used with d3-flame-graph. https://github.com/spiermar/d3-flame-graph 34 | *

35 | * This is similar to https://github.com/spiermar/node-stack-convert 36 | *

37 | */ 38 | public class JsonOutputWriter implements FlameGraphOutputWriter { 39 | 40 | /** 41 | * The bottom of the stack must be "root" 42 | */ 43 | private static final String ROOT = "root"; 44 | 45 | /** 46 | * The data model for live json 47 | */ 48 | private LiveRecording liveRecording = new LiveRecording(); 49 | 50 | /** 51 | * The data model for json 52 | */ 53 | private StackFrame profile = new StackFrame(ROOT); 54 | 55 | private boolean exportTimestamp; 56 | 57 | private class LiveRecording { 58 | 59 | Map profilesMap = new HashMap<>(); 60 | 61 | public StackFrame getProfile(long startTimestampSecEpoch) { 62 | StackFrame profile = profilesMap.get(startTimestampSecEpoch); 63 | if (profile == null) { 64 | profile = new StackFrame(ROOT); 65 | profilesMap.put(startTimestampSecEpoch, profile); 66 | } 67 | return profile; 68 | } 69 | } 70 | 71 | private class StackFrame { 72 | 73 | String name; 74 | int value = 0; 75 | List children = null; 76 | transient Map childrenMap = new HashMap<>(); 77 | 78 | public StackFrame(String name) { 79 | this.name = name; 80 | } 81 | 82 | public StackFrame addFrame(String frameName) { 83 | if (children == null) { 84 | children = new ArrayList<>(); 85 | } 86 | StackFrame frame = childrenMap.get(frameName); 87 | if (frame == null) { 88 | frame = new StackFrame(frameName); 89 | childrenMap.put(frameName, frame); 90 | children.add(frame); 91 | } 92 | frame.value++; 93 | return frame; 94 | } 95 | } 96 | 97 | @Override 98 | public void initialize(OutputWriterParameters parameters) { 99 | exportTimestamp = parameters.live; 100 | } 101 | 102 | @Override 103 | public void processEvent(Instant startTimestamp, Instant endTimestamp, Duration duration, Stack stack, long size) { 104 | StackFrame frame; 105 | if (exportTimestamp) { 106 | long startTimestampSecEpoch = startTimestamp.getEpochSecond(); 107 | frame = liveRecording.getProfile(startTimestampSecEpoch); 108 | } else { 109 | frame = profile; 110 | } 111 | 112 | while (!stack.empty()) { 113 | frame = frame.addFrame(stack.pop()); 114 | } 115 | } 116 | 117 | @Override 118 | public void writeOutput(BufferedWriter bufferedWriter) throws IOException { 119 | Gson gson = new GsonBuilder().create(); 120 | if (exportTimestamp) { 121 | gson.toJson(this.liveRecording.profilesMap, bufferedWriter); 122 | } else { 123 | gson.toJson(this.profile, bufferedWriter); 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/com/github/chrishantha/jfr/flamegraph/output/EventType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Leonardo Freitas Gomes 3 | * Copyright 2018 Stefan Oehme 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.github.chrishantha.jfr.flamegraph.output; 18 | 19 | import com.beust.jcommander.IStringConverter; 20 | import jdk.jfr.consumer.RecordedEvent; 21 | 22 | import java.util.Arrays; 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | import java.util.concurrent.TimeUnit; 26 | 27 | /** 28 | * Different types of events possibly available in a JFR recording. 29 | *

30 | * Each type can be activated using a command line option and can match one or many 31 | * JFR event types. Each type knows how to convert the event into a numeric value 32 | * that will make the flame graph most meaningful. For allocation events this would 33 | * be the number of bytes allocated, while for file reads it would be the duration of 34 | * the read operation. 35 | */ 36 | public enum EventType { 37 | 38 | METHOD_PROFILING_SAMPLE("cpu", ValueField.COUNT, "jdk.ExecutionSample"), 39 | ALLOCATION_IN_NEW_TLAB("allocation-tlab", ValueField.TLAB_SIZE, "jdk.ObjectAllocationInNewTLAB"), 40 | ALLOCATION_OUTSIDE_TLAB("allocation-outside-tlab", ValueField.ALLOCATION_SIZE, "jdk.ObjectAllocationOutsideTLAB"), 41 | JAVA_EXCEPTION("exceptions", ValueField.COUNT, "jdk.JavaExceptionThrow"), 42 | JAVA_MONITOR_BLOCKED("monitor-blocked", ValueField.DURATION, "Java Monitor Blocked"), 43 | IO("io", ValueField.DURATION, "File Read", "File Write", "Socket Read", "Socket Write"); 44 | 45 | private final String commandLineOption; 46 | private final ValueField valueField; 47 | private final String[] eventNames; 48 | 49 | EventType(String commandLineOption, ValueField valueField, String... eventNames) { 50 | this.eventNames = eventNames; 51 | this.commandLineOption = commandLineOption; 52 | this.valueField = valueField; 53 | } 54 | 55 | public boolean matches(RecordedEvent event) { 56 | String name = event.getEventType().getName(); 57 | return Arrays.stream(eventNames).anyMatch(name::equals); 58 | } 59 | 60 | public long getValue(RecordedEvent event) { 61 | return valueField.getValue(event); 62 | } 63 | 64 | @Override 65 | public String toString() { 66 | return commandLineOption; 67 | } 68 | 69 | 70 | public static final class EventTypeConverter implements IStringConverter { 71 | private static final Map typesByOption = new HashMap<>(); 72 | 73 | static { 74 | for (EventType type : EventType.values()) { 75 | typesByOption.put(type.commandLineOption, type); 76 | } 77 | } 78 | 79 | @Override 80 | public EventType convert(String commandLineOption) { 81 | EventType eventType = typesByOption.get(commandLineOption); 82 | if (eventType == null) { 83 | throw new IllegalArgumentException("Event type [" + commandLineOption + "] does not exist."); 84 | } 85 | return eventType; 86 | } 87 | } 88 | 89 | private enum ValueField { 90 | COUNT { 91 | @Override 92 | public long getValue(RecordedEvent event) { 93 | return 1; 94 | } 95 | }, 96 | DURATION { 97 | @Override 98 | public long getValue(RecordedEvent event) { 99 | long nanos = (long) event.getValue("(duration)"); 100 | return TimeUnit.NANOSECONDS.toMillis(nanos); 101 | } 102 | }, 103 | ALLOCATION_SIZE { 104 | @Override 105 | public long getValue(RecordedEvent event) { 106 | return (long) event.getValue("allocationSize") / 1000; 107 | } 108 | }, 109 | TLAB_SIZE { 110 | @Override 111 | public long getValue(RecordedEvent event) { 112 | return (long) event.getValue("tlabSize") / 1000; 113 | } 114 | }; 115 | 116 | public abstract long getValue(RecordedEvent event); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/dist/bin/create_flamegraphs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2016 M. Isuru Tharanga Chrishantha Perera 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # ---------------------------------------------------------------------------- 17 | # Create multiple flame graphs 18 | # ---------------------------------------------------------------------------- 19 | set -e 20 | 21 | JFG_DIR=$(dirname "$0") 22 | 23 | if [ ! -x "$FLAMEGRAPH_DIR/flamegraph.pl" ]; then 24 | echo "Please clone https://github.com/brendangregg/FlameGraph and set FLAMEGRAPH_DIR to the root directory" 25 | exit 1 26 | fi 27 | 28 | function help { 29 | echo "" 30 | echo "Usage: " 31 | echo "create-flamegraphs.sh [options]" 32 | echo "" 33 | echo "Options:" 34 | echo "-f: JFR file" 35 | echo "-d: Decompress the JFR file" 36 | echo "-m: Interval in minutes. Default 10" 37 | echo "-o: Output Directory. Default \"Output\"" 38 | echo "-i: Ignore line numbers" 39 | echo "-s: Save folded output" 40 | echo "" 41 | } 42 | 43 | jfr_file="" 44 | minutes=10 45 | output_dir="" 46 | decompress="" 47 | ignore_lines="" 48 | save_folded_output=false 49 | 50 | while getopts "df:m:io:s" opts 51 | do 52 | case $opts in 53 | f) 54 | jfr_file=${OPTARG} 55 | ;; 56 | d) 57 | decompress="-d" 58 | ;; 59 | m) 60 | minutes=${OPTARG} 61 | ;; 62 | i) 63 | ignore_lines="-i" 64 | ;; 65 | o) 66 | output_dir=${OPTARG} 67 | ;; 68 | s) 69 | save_folded_output=true 70 | ;; 71 | \?) 72 | help 73 | exit 1 74 | ;; 75 | esac 76 | done 77 | 78 | if [[ ! -f $jfr_file ]]; then 79 | echo "Please specify the JFR file" 80 | help 81 | exit 1 82 | fi 83 | 84 | #If no directory was provided, we need to create the default one 85 | if [[ ! -d $output_dir ]]; then 86 | output_dir="output" 87 | mkdir -p $output_dir 88 | fi 89 | 90 | #Validate output directory 91 | if [[ ! -d $output_dir ]]; then 92 | echo "Please specify a directory to create the flamegraphs" 93 | exit 1 94 | fi 95 | 96 | jfr_filename=$(basename $jfr_file) 97 | 98 | details=$(${JFG_DIR}/jfr-flame-graph -ot folded $decompress -f $jfr_file -j -t) 99 | 100 | echo "$details" 101 | 102 | startTimestamp=$(echo $details | sed -r 's/.*Min Start Event\s*: ([0-9]*).*/\1/') 103 | endTimestamp=$(echo $details | sed -r 's/.*Max End Event\s*: ([0-9]*).*/\1/') 104 | 105 | interval=$(($minutes * 60)) 106 | 107 | i=$startTimestamp 108 | end=$endTimestamp 109 | 110 | dateformat="%Y-%m-%d %I:%M:%S %p" 111 | 112 | set +e 113 | 114 | while [ $i -lt $end ]; do 115 | s=$i 116 | i=$(($i+$interval)) 117 | e=$i 118 | 119 | if [ $e -gt $end ]; then 120 | e=$end 121 | fi 122 | 123 | title="Flame Graph for $jfr_filename from $(date --date @$s +"$dateformat") to $(date --date @$e +"$dateformat")" 124 | 125 | echo Generating $title 126 | 127 | output_file=flamegraph-$s-$e.svg 128 | 129 | # Use folded output type 130 | flamegraph_output_command="${JFG_DIR}/jfr-flame-graph" 131 | flamegraph_output_args=(-ot folded $decompress -f $jfr_file -st $s -et $e $ignore_lines) 132 | framegraph_generate_command="$FLAMEGRAPH_DIR/flamegraph.pl" 133 | framegraph_generate_args=(--title "$title" --width 1600) 134 | 135 | if [[ "$save_folded_output" = true ]]; then 136 | $($flamegraph_output_command "${flamegraph_output_args[@]}" > $output_dir/$output_file.folded) 137 | cat $output_dir/$output_file.folded | $framegraph_generate_command "${framegraph_generate_args[@]}" > $output_dir/$output_file 138 | else 139 | $flamegraph_output_command "${flamegraph_output_args[@]}" | $framegraph_generate_command "${framegraph_generate_args[@]}" > $output_dir/$output_file 140 | fi 141 | 142 | flamegraph_status=("${PIPESTATUS[@]}") 143 | if [ ${flamegraph_status[1]} -eq 0 ] 144 | then 145 | # Create array 146 | output_files+=($output_file) 147 | else 148 | rm $output_dir/$output_file 149 | fi 150 | done 151 | 152 | #Generate HTML 153 | index_file=$output_dir/index.html 154 | 155 | cat << _EOF_ > $index_file 156 | 157 | 158 | 159 | 160 | 161 | Flame Graphs 162 | 163 | 164 | 165 |

166 | 167 | 168 | _EOF_ 169 | for f in "${output_files[@]}" 170 | do 171 | echo "" >> $index_file 172 | done 173 | cat << _EOF_ >> $index_file 174 |
175 | 176 | 199 | 200 | 201 | 202 | _EOF_ 203 | 204 | echo Script executed in $SECONDS seconds. -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /src/main/java/com/github/chrishantha/jfr/flamegraph/output/JFRToFlameGraphWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 M. Isuru Tharanga Chrishantha Perera 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.chrishantha.jfr.flamegraph.output; 17 | 18 | import com.beust.jcommander.Parameter; 19 | import jdk.jfr.consumer.*; 20 | 21 | import java.io.BufferedWriter; 22 | import java.io.File; 23 | import java.io.FileInputStream; 24 | import java.io.FileOutputStream; 25 | import java.io.FileWriter; 26 | import java.io.IOException; 27 | import java.io.PrintWriter; 28 | import java.io.Writer; 29 | import java.text.MessageFormat; 30 | import java.time.Duration; 31 | import java.time.Instant; 32 | import java.time.ZoneId; 33 | import java.time.format.DateTimeFormatter; 34 | import java.time.format.FormatStyle; 35 | import java.util.ArrayList; 36 | import java.util.List; 37 | import java.util.Stack; 38 | import java.util.StringJoiner; 39 | import java.util.concurrent.TimeUnit; 40 | import java.util.stream.Collectors; 41 | import java.util.zip.GZIPInputStream; 42 | 43 | /** 44 | * Parse JFR dump and create a compatible output for Flame Graph 45 | */ 46 | public final class JFRToFlameGraphWriter { 47 | 48 | private final OutputWriterParameters parameters; 49 | @Parameter(names = {"-h", "--help"}, description = "Display Help", help = true) 50 | boolean help; 51 | 52 | @Parameter(names = {"-f", "--jfrdump"}, description = "Java Flight Recorder Dump", required = true) 53 | File jfrdump; 54 | 55 | @Parameter(names = {"-ot", "--output-type"}, description = "Output type") 56 | OutputType outputType = OutputType.FOLDED; 57 | 58 | @Parameter(names = {"-o", "--output"}, description = "Output file") 59 | File outputFile; 60 | 61 | @Parameter(names = {"-d", "--decompress"}, description = "Decompress the JFR file") 62 | boolean decompress; 63 | 64 | @Parameter(names = {"-i", "--ignore-line-numbers"}, description = "Ignore Line Numbers in Stack Frame") 65 | boolean ignoreLineNumbers; 66 | 67 | @Parameter(names = {"-rv", "--show-return-value"}, description = "Show return value for methods in the stack") 68 | boolean showReturnValue; 69 | 70 | @Parameter(names = {"-sn", 71 | "--use-simple-names"}, description = "Use simple names instead of qualified names in the stack") 72 | boolean useSimpleNames; 73 | 74 | @Parameter(names = {"-ha", "--hide-arguments"}, description = "Hide arguments in methods") 75 | boolean hideArguments; 76 | 77 | @Parameter(names = {"-j", "--print-jfr-details"}, description = "Print JFR details and exit") 78 | boolean printJFRDetails; 79 | 80 | @Parameter(names = {"-t", "--print-timestamp"}, description = "Print timestamp in JFR Details") 81 | boolean printTimestamp; 82 | 83 | @Parameter(names = {"-st", "--start-timestamp"}, description = "Start timestamp in seconds for filtering", converter = SecondsToNanosConverter.class) 84 | long startTimestamp = Long.MIN_VALUE; 85 | 86 | @Parameter(names = {"-et", "--end-timestamp"}, description = "End timestamp in seconds for filtering", converter = SecondsToNanosConverter.class) 87 | long endTimestamp = Long.MAX_VALUE; 88 | 89 | @Parameter(names = {"-e", 90 | "--event"}, description = "Type of event used to generate the flamegraph", converter = EventType.EventTypeConverter.class) 91 | EventType eventType = EventType.METHOD_PROFILING_SAMPLE; 92 | 93 | private static final String EVENT_VALUE_STACK = "stackTrace"; 94 | 95 | private static final String PRINT_FORMAT = "%-16s: %s%n"; 96 | 97 | private static final String DURATION_FORMAT = "{0} h {1} min"; 98 | 99 | public JFRToFlameGraphWriter(OutputWriterParameters parameters) { 100 | this.parameters = parameters; 101 | } 102 | 103 | public void process() throws Exception { 104 | RecordingFile recording = loadRecording(); 105 | 106 | if (printJFRDetails) { 107 | printJFRDetails(recording); 108 | } else { 109 | convertToStacks(recording); 110 | } 111 | } 112 | 113 | private RecordingFile loadRecording() throws IOException { 114 | RecordingFile recording; 115 | try { 116 | recording = new RecordingFile(jfrdump.toPath()); 117 | } catch (Exception e) { 118 | System.err.println("Could not load the JFR file."); 119 | if (!decompress) { 120 | System.err.println("If the JFR file is compressed, try the decompress option"); 121 | } 122 | throw e; 123 | } 124 | return recording; 125 | } 126 | 127 | private void convertToStacks(RecordingFile recording) throws IOException { 128 | 129 | // System.out.println(recording.readEventTypes().stream().map(e -> e.getName()).collect(Collectors.toList())); 130 | 131 | FlameGraphOutputWriter flameGraphOutputWriter = outputType.createFlameGraphOutputWriter(); 132 | flameGraphOutputWriter.initialize(parameters); 133 | 134 | while (recording.hasMoreEvents()) { 135 | RecordedEvent event = recording.readEvent(); 136 | if (!eventType.matches(event)) { 137 | continue; 138 | } 139 | if (!matchesTimeRange(event)) { 140 | continue; 141 | } 142 | 143 | RecordedStackTrace flrStackTrace = (RecordedStackTrace) event.getValue(EVENT_VALUE_STACK); 144 | if (flrStackTrace != null) { 145 | Stack stack = getStack(event); 146 | long value = eventType.getValue(event); 147 | flameGraphOutputWriter.processEvent(event.getStartTime(), event.getEndTime(), event.getDuration(), stack, value); 148 | } 149 | } 150 | 151 | try (Writer writer = outputFile != null ? new FileWriter(outputFile) : new PrintWriter(System.out); 152 | BufferedWriter bufferedWriter = new BufferedWriter(writer)) { 153 | flameGraphOutputWriter.writeOutput(bufferedWriter); 154 | } 155 | } 156 | 157 | private boolean matchesTimeRange(RecordedEvent event) { 158 | Instant eventStartTimestamp = event.getStartTime(); 159 | Instant eventEndTimestamp = event.getEndTime(); 160 | if (eventStartTimestamp.getNano() >= startTimestamp && eventStartTimestamp.getNano() <= endTimestamp) { 161 | return true; 162 | } else if (eventEndTimestamp.getNano() >= startTimestamp && eventEndTimestamp.getNano() <= endTimestamp) { 163 | return true; 164 | } 165 | return false; 166 | } 167 | 168 | private void printJFRDetails(RecordingFile recording) throws IOException { 169 | // ITimeRange timeRange = recording.getTimeRange(); 170 | 171 | // long startTimestamp = TimeUnit.NANOSECONDS.toSeconds(timeRange.getStartTimestamp()); 172 | // long endTimestamp = TimeUnit.NANOSECONDS.toSeconds(timeRange.getEndTimestamp()); 173 | // 174 | // Duration d = Duration.ofNanos(timeRange.getDuration()); 175 | // long hours = d.toHours(); 176 | // long minutes = d.minusHours(hours).toMinutes(); 177 | 178 | // IView view = recording.createView(); 179 | 180 | Instant minEventStartTimestamp = Instant.MAX; 181 | Instant maxEventEndTimestamp = Instant.MIN; 182 | 183 | // view.setFilter(eventType::matches); 184 | 185 | while (recording.hasMoreEvents()) { 186 | RecordedEvent event = recording.readEvent(); 187 | Instant eventStartTimestamp = event.getStartTime(); 188 | Instant eventEndTimestamp = event.getEndTime(); 189 | if (eventStartTimestamp.isBefore(minEventStartTimestamp)) { 190 | minEventStartTimestamp = eventStartTimestamp; 191 | } 192 | 193 | if (eventEndTimestamp.isAfter(maxEventEndTimestamp)) { 194 | maxEventEndTimestamp = eventEndTimestamp; 195 | } 196 | } 197 | 198 | Duration eventsDuration = Duration.between(minEventStartTimestamp, maxEventEndTimestamp); 199 | long eventHours = eventsDuration.toHours(); 200 | long eventMinutes = eventsDuration.minusHours(eventHours).toMinutes(); 201 | 202 | System.out.println("JFR Details"); 203 | if (printTimestamp) { 204 | // System.out.format(PRINT_FORMAT, "Start", startTimestamp); 205 | // System.out.format(PRINT_FORMAT, "End", endTimestamp); 206 | System.out.format(PRINT_FORMAT, "Min Start Event", minEventStartTimestamp); 207 | System.out.format(PRINT_FORMAT, "Max End Event", maxEventEndTimestamp); 208 | } else { 209 | // Instant startInstant = Instant.ofEpochSecond(startTimestamp); 210 | // Instant endInstant = Instant.ofEpochSecond(endTimestamp); 211 | DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG) 212 | .withZone(ZoneId.systemDefault()); 213 | // System.out.format(PRINT_FORMAT, "Start", formatter.format(startInstant)); 214 | // System.out.format(PRINT_FORMAT, "End", formatter.format(endInstant)); 215 | System.out.format(PRINT_FORMAT, "Min Start Event", formatter.format(minEventStartTimestamp)); 216 | System.out.format(PRINT_FORMAT, "Max End Event", formatter.format(maxEventEndTimestamp)); 217 | } 218 | // System.out.format(PRINT_FORMAT, "JFR Duration", MessageFormat.format(DURATION_FORMAT, hours, minutes)); 219 | System.out.format(PRINT_FORMAT, "Events Duration", 220 | MessageFormat.format(DURATION_FORMAT, eventHours, eventMinutes)); 221 | } 222 | 223 | private Stack getStack(RecordedEvent event) { 224 | RecordedStackTrace flrStackTrace = (RecordedStackTrace) event.getValue(EVENT_VALUE_STACK); 225 | Stack stack = new Stack<>(); 226 | if (flrStackTrace == null) { 227 | return stack; 228 | } 229 | for (RecordedFrame frame : flrStackTrace.getFrames()) { 230 | String frameName = getFrameName(frame); 231 | if (frameName != null) { 232 | stack.push(frameName); 233 | } 234 | } 235 | return stack; 236 | } 237 | 238 | private String getFrameName(RecordedFrame frame) { 239 | StringBuilder methodBuilder = new StringBuilder(); 240 | RecordedMethod method = frame.getMethod(); 241 | if (method == null) { 242 | return null; 243 | } 244 | 245 | // methodBuilder.append(method.getHumanReadable(showReturnValue, !useSimpleNames, true, !useSimpleNames, !hideArguments, !useSimpleNames)); 246 | methodBuilder.append(formatMethod(method)); 247 | if (!ignoreLineNumbers) { 248 | methodBuilder.append(":"); 249 | methodBuilder.append(frame.getLineNumber()); 250 | } 251 | return methodBuilder.toString(); 252 | } 253 | 254 | private File decompressFile(final File compressedFile) throws IOException { 255 | byte[] buffer = new byte[8 * 1024]; 256 | 257 | File decompressedFile; 258 | 259 | try (GZIPInputStream compressedStream = new GZIPInputStream(new FileInputStream(compressedFile)); 260 | FileOutputStream uncompressedFileStream = new FileOutputStream( 261 | decompressedFile = File.createTempFile("jfr_", null))) { 262 | 263 | decompressedFile.deleteOnExit(); 264 | int numberOfBytes; 265 | 266 | while ((numberOfBytes = compressedStream.read(buffer)) > 0) { 267 | uncompressedFileStream.write(buffer, 0, numberOfBytes); 268 | } 269 | } 270 | 271 | return decompressedFile; 272 | } 273 | 274 | private String formatMethod(RecordedMethod m) { 275 | StringBuilder sb = new StringBuilder(); 276 | sb.append(m.getType().getName()); 277 | sb.append("."); 278 | sb.append(m.getName()); 279 | sb.append("("); 280 | StringJoiner sj = new StringJoiner(", "); 281 | String md = m.getDescriptor().replace("/", "."); 282 | String parameter = md.substring(1, md.lastIndexOf(")")); 283 | for (String qualifiedName : decodeDescriptors(parameter, "")) { 284 | String typeName = qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1); 285 | sj.add(typeName); 286 | } 287 | sb.append(sj); 288 | sb.append(")"); 289 | return sb.toString(); 290 | } 291 | 292 | List decodeDescriptors(String descriptor, String arraySize) { 293 | List descriptors = new ArrayList<>(); 294 | for (int index = 0; index < descriptor.length(); index++) { 295 | String arrayBrackets = ""; 296 | while (descriptor.charAt(index) == '[') { 297 | arrayBrackets = arrayBrackets + "[" + arraySize + "]" ; 298 | arraySize = ""; 299 | index++; 300 | } 301 | char c = descriptor.charAt(index); 302 | String type; 303 | switch (c) { 304 | case 'L': 305 | int endIndex = descriptor.indexOf(';', index); 306 | type = descriptor.substring(index + 1, endIndex); 307 | index = endIndex; 308 | break; 309 | case 'I': 310 | type = "int"; 311 | break; 312 | case 'J': 313 | type = "long"; 314 | break; 315 | case 'Z': 316 | type = "boolean"; 317 | break; 318 | case 'D': 319 | type = "double"; 320 | break; 321 | case 'F': 322 | type = "float"; 323 | break; 324 | case 'S': 325 | type = "short"; 326 | break; 327 | case 'C': 328 | type = "char"; 329 | break; 330 | case 'B': 331 | type = "byte"; 332 | break; 333 | default: 334 | type = ""; 335 | } 336 | descriptors.add(type + arrayBrackets); 337 | } 338 | return descriptors; 339 | } 340 | 341 | } 342 | --------------------------------------------------------------------------------