├── .gitignore ├── .travis.yml ├── CMakeLists.txt ├── LICENSE ├── README.md ├── bin ├── create-java-perf-map.sh ├── create-links-in ├── dtrace-java-flames ├── dtrace-java-record-stack ├── dtrace-perf-map.pl ├── perf-java-flames ├── perf-java-record-stack ├── perf-java-report-stack └── perf-java-top └── src ├── c ├── perf-map-agent.c ├── perf-map-file.c └── perf-map-file.h └── java └── AttachOnce.java /.gitignore: -------------------------------------------------------------------------------- 1 | CMakeFiles 2 | CMakeCache.txt 3 | cmake_install.cmake 4 | Makefile 5 | *~ 6 | out 7 | .idea 8 | *.iml 9 | *.svg 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: cpp 2 | matrix: 3 | include: 4 | - os: linux 5 | dist: trusty 6 | sudo: required 7 | compiler: gcc 8 | - os: linux 9 | dist: trusty 10 | sudo: required 11 | compiler: clang 12 | - os: osx 13 | osx_image: xcode7.3 14 | compiler: gcc 15 | - os: osx 16 | osx_image: xcode7.3 17 | compiler: clang 18 | - os: osx 19 | osx_image: xcode9 20 | compiler: gcc 21 | - os: osx 22 | osx_image: xcode9 23 | compiler: clang 24 | branches: 25 | only: 26 | - master 27 | before_install: 28 | - if [ $TRAVIS_OS_NAME == linux ]; then sudo apt-get update && sudo apt-get install -y default-jdk && sudo apt-get install -y cmake; fi 29 | - if [ $TRAVIS_OS_NAME == osx ]; then brew update && brew uninstall cmake && brew install cmake && brew tap caskroom/versions && brew cask reinstall java8; fi 30 | - g++ --version 31 | - clang++ --version 32 | - java -version 33 | - if [ $TRAVIS_OS_NAME == osx ]; then export JAVA_HOME=$(/usr/libexec/java_home); fi 34 | 35 | script: cmake . && make 36 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 2.8.6) 2 | project (perf-map-agent) 3 | 4 | # uncomment to make a debug build (including source positions and symbols) 5 | # set(CMAKE_BUILD_TYPE DEBUG) 6 | 7 | # Binaries (agent libperfmap.so and attach-main.jar) will end up in ./out 8 | set(OUTDIR ${PROJECT_BINARY_DIR}/out) 9 | set(LIBRARY_OUTPUT_PATH ${OUTDIR}) 10 | 11 | find_package(JNI) 12 | if (JNI_FOUND) 13 | message (STATUS "JNI_INCLUDE_DIRS=${JNI_INCLUDE_DIRS}") 14 | message (STATUS "JNI_LIBRARIES=${JNI_LIBRARIES}") 15 | message (STATUS "JAVA_INCLUDE_PATH=${JAVA_INCLUDE_PATH}") 16 | message (STATUS "JAVA_INCLUDE_PATH2=${JAVA_INCLUDE_PATH2}") 17 | endif() 18 | INCLUDE_DIRECTORIES(${JAVA_INCLUDE_PATH}) 19 | INCLUDE_DIRECTORIES(${JAVA_INCLUDE_PATH2}) 20 | 21 | add_library(perfmap SHARED src/c/perf-map-agent.c src/c/perf-map-file.c) 22 | 23 | find_package(Java REQUIRED) 24 | include(UseJava) 25 | 26 | set(CMAKE_JAVA_INCLUDE_PATH ${JAVA_INCLUDE_PATH}/../lib/tools.jar) 27 | set(CMAKE_JAVA_TARGET_OUTPUT_DIR ${OUTDIR}) 28 | 29 | #message(STATUS "LIBS: ${Java_JAR_EXECUTABLE} ${Java_INCLUDE_DIRS} incl: ${CMAKE_JAVA_INCLUDE_PATH} output_dir: ${CMAKE_JAVA_TARGET_OUTPUT_DIR}") 30 | add_jar(attach-main src/java/AttachOnce.java ENTRY_POINT net/virtualvoid/perf/AttachOnce OUTPUT_DIR ${OUTDIR}) 31 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # perf-map-agent 2 | 3 | [![Join the chat at https://gitter.im/jrudolph/perf-map-agent](https://badges.gitter.im/jrudolph/perf-map-agent.svg)](https://gitter.im/jrudolph/perf-map-agent?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 4 | [![Build Status](https://travis-ci.org/jvm-profiling-tools/perf-map-agent.svg?branch=master)](https://travis-ci.org/jvm-profiling-tools/perf-map-agent) 5 | 6 | A java agent to generate `/tmp/perf-.map` files for just-in-time(JIT)-compiled methods for use with the [Linux `perf` tools](https://perf.wiki.kernel.org/index.php/Main_Page). 7 | 8 | ## Build 9 | 10 | Make sure `JAVA_HOME` is configured to point to a JDK. You need cmake >= 2.8.6 (see [#30](https://github.com/jrudolph/perf-map-agent/issues/30)). Then run the following on the command line: 11 | 12 | cmake . 13 | make 14 | 15 | # will create links to run scripts in 16 | bin/create-links-in 17 | 18 | ## Architecture 19 | 20 | Linux `perf` tools will expect symbols for code executed from unknown memory regions at `/tmp/perf-.map`. This allows runtimes that 21 | generate code on the fly to supply dynamic symbol mappings to be used with the `perf` suite of tools. 22 | 23 | perf-map-agent is an agent that will generate such a mapping file for Java applications. It consists of a Java agent written C and a small 24 | Java bootstrap application which attaches the agent to a running Java process. 25 | 26 | When the agent is attached it instructs the JVM to report code blobs generated by the JVM at runtime for various purposes. Most importantly, 27 | this includes JIT-compiled methods but also various dynamically-generated infrastructure parts like the dynamically created interpreter, 28 | adaptors, and jump tables for virtual dispatch (see `vtable` and `itable` entries). The agent creates a `/tmp/perf-.map` file which 29 | it fills with one line per code blob that maps a memory location to a code blob name. 30 | 31 | The Java application takes the PID of a Java process as an argument and an arbitrary number of additional arguments which it passes to the agent. 32 | It then attaches to the target process and instructs it to load the agent library. 33 | 34 | ## Command line scripts 35 | 36 | The `bin` directory contains a set of shell scripts to combine common `perf` / `dtrace` perations with creating the map file. 37 | 38 | - `create-java-perf-map.sh ` takes a PID and options. It knows where to find libraries relative to the `bin` directory. 39 | - `perf-java-top ` takes a PID and additional options to pass to `perf top`. Uses the agent to create a new 40 | `/tmp/perf-.map` and then calls `perf top` with the given options. 41 | - `perf-java-record-stack ` takes a PID and additional options to pass to `perf record`. Runs 42 | `perf record -g -p ` to collect performance data including stack traces. Afterwards it uses the agent to create a 43 | new `/tmp/perf-.map` file. 44 | - `perf-java-report-stack ` calls first `perf-java-record-stack ` and then runs 45 | `perf report` to directly analyze the captured data. You can call `perf report -i /tmp/perf-.data` again with any options after the 46 | script has exited to further analyze the data from the previous run. 47 | - `perf-java-flames ` collects data with `perf-java-record-stack` and then creates a visualization 48 | using [@brendangregg's FlameGraph](https://github.com/brendangregg/FlameGraph) tools. To get meaningful stacktraces spanning several JIT-compiled methods, 49 | you need to run your JVM with `-XX:+PreserveFramePointer` (which is available starting from JDK8 update 60 build 19) as detailed 50 | in [ag netflix blog entry](http://techblog.netflix.com/2015/07/java-in-flames.html). 51 | - `create-links-in ` will install symbolic links to the above scripts into ``. 52 | - `dtrace-java-record-stack ` takes a PID. Runs`dtrace` to collect performance data including stack traces. Afterwards it uses the agent to create a 53 | new `/tmp/perf-.map` file. 54 | - `dtrace-java-flames ` collects data with `dtrace-java-record-stack` and then creates a visualization 55 | using [@brendangregg's FlameGraph](https://github.com/brendangregg/FlameGraph) tools. To get meaningful stacktraces spanning several JIT-compiled methods, 56 | you need to run your JVM with `-XX:+PreserveFramePointer` (which is available starting from JDK8 update 60 build 19) as detailed 57 | in [ag netflix blog entry](http://techblog.netflix.com/2015/07/java-in-flames.html). 58 | 59 | Environment variables: 60 | 61 | - `PERF_MAP_OPTIONS`: a string of additional options to pass to the agent as described below. 62 | - `PERF_RECORD_SECONDS`: the number of seconds, `perf-java-report-stack` and similar tools will record performance data 63 | - `PERF_RECORD_FREQ`: the sampling frequence as passed to `perf record -F` 64 | - `FLAMEGRAPH_DIR`: the directory into which [@brendangregg's FlameGraph](https://github.com/brendangregg/FlameGraph) has been checked out 65 | - `PERF_JAVA_TMP`: the directory to put temporary files in, the default is `/tmp` 66 | - `PERF_DATA_FILE`: the file name where `perf-java-record-stack` will output performance data into, the default is `$PERF_JAVA_TMP/perf-.data` 67 | - `PERF_COLLAPSE_OPTS`: a string of additional flags to pass to stackcollapse-perf.pl (found in FLAMEGRAPH_DIR), (add --inline with unfoldall perfmap) 68 | - `PERF_FLAME_OUTPUT`: the file name to which the flamegraph SVG will be written, the default is `flamegraph-.svg` 69 | - `PERF_FLAME_OPTS`: options to pass to flamegraph.pl (found in FLAMEGRAPH_DIR), the default is `--color java` 70 | - `DTRACE_SECONDS`: the number of seconds, `dtrace` and similar tools will record performance data 71 | - `DTRACE_FREQ`: the sampling frequence as passed to `dtrace` 72 | - `DTRACE_JAVA_TMP`: the directory to put temporary files in, the default is `/tmp` 73 | - `DTRACE_DATA_FILE`: the file name where `dtrace-java-record-stack` will output performance data into, the default is `$DTRACE_JAVA_TMP/dtrace-.data` 74 | 75 | ## Options 76 | 77 | You can add a comma separated list of options to `perf-java` (or the `AttachOnce` runner). These options are currently supported: 78 | 79 | - `unfold`: Create extra entries for every codeblock inside a method that was inlined from elsewhere 80 | (named <inlined_method> in <root_method>). Be aware of the effects of 'skid' in relation with unfolding. 81 | See the section below. Also, see the below section about inaccurate inlining information. 82 | - `unfoldall`: Similar to `unfold` but will include the complete inlined stack at a code location in the form 83 | `root_method->inlined method 1->inlined method 2->...->inlined method on top`. 84 | - `unfoldsimple`: similar to `unfold`, however, the extra entries do not include the " in <root_method>" part 85 | - `msig`: include full method signature in the name string 86 | - `dottedclass`: convert class signature (`Ljava/lang/Class;`) to the usual class names with segments separated by dots 87 | (`java.lang.Class`). NOTE: this currently breaks coloring when used in combination with [flamegraphs](https://github.com/brendangregg/FlameGraph). 88 | - `sourcepos`: Adds the name of the source file and the line number on which it is declared for each method. Useful 89 | when profiling Scala applications that crate a lot of synthetic classes and methods. Does not work with native methods. 90 | 91 | ## Known Issues 92 | 93 | ### Skid 94 | 95 | You should be aware that instruction level profiling is not absolutely accurate but suffers from 96 | '[skid](http://www.spinics.net/lists/linux-perf-users/msg02157.html)'. 'skid' means that the actual instruction 97 | pointer may already have moved a bit further when a sample is recorded. In that case, (possibly hot) code is reported at 98 | an address shortly after the actual hot instruction. See this [sample from one of Brendan's presentations](http://www.slideshare.net/brendangregg/scale2015-linux-perfprofiling/65) demonstrating this issue. 99 | 100 | If using `unfold`, perf-map-agent will report sections that contain code inlined from other methods as separate entries. 101 | Unfolded entries can be quite short, e.g. an inlined getter may only consist of a few instructions that now lives inside of another 102 | method's JITed code. The next few instructions may then already belong to another entry. In such a case, it is more likely that skid 103 | will not only affect the instruction pointer inside of a method entry but may affect which entry is chosen in the first place. 104 | 105 | Skid that occurs inside a method is only visible when analyzing the actual assembler code (as with `perf annotate`). Skid that 106 | affects the actual symbol resolution to choose a wrong entry will be much more visible as wrong entries will be reported with 107 | tools that operate on the symbol level like the standard views of `perf report`, `perf top`, or in flame graphs. 108 | 109 | So, while it is tempting to enable unfolded entries for the perceived extra resolution, this extra information is sometimes just noise 110 | which will not only clutter the overall view but may also be misleading or wrong. 111 | 112 | ### Inaccurate mappings using the `unfold*` options 113 | 114 | Hotspot does not retain line number and other debug information for inlined code at other places than safepoints. This 115 | makes sense because you don't usually observe code running between safepoints from the JVM's perspective. This is different 116 | when observing a process from the outside like with `perf`. For observed code locations outside of safepoints, the JVM will 117 | not report any inlining information and perf-map-agent will assign those areas to the host method of the inlining. 118 | 119 | For more fidelity, Hotspot can be instructed to include debug information for non-safepoints as well. Use 120 | `-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints` when running the target process. Note, however, that this will 121 | produce a lot more information with the generated `perf-.map` file potentially growing to MBs of size. 122 | 123 | ### Agent Library Unloading 124 | 125 | Unloading or reloading of a changed agent library is not supported by the JVM (but re-attaching is). Therefore, if you make changes to the 126 | agent and recompile it you need to restart a target process that has an older version loaded to use the newer version. 127 | 128 | ### Missing symbols for libjvm.so 129 | 130 | libjvm.so is the runtime component of the JVM. It is not covered by perf-map-agent but perf will use debug symbols as 131 | provided by the distribution. If symbols for libjvm.so are missing see instructions for your Linux distribution to 132 | install debug symbols for the JVM. See also [issue #39](https://github.com/jrudolph/perf-map-agent/issues/39) which 133 | contains a few pointers about how to install these. 134 | 135 | ## Disclaimer 136 | 137 | I'm not a professional C code writer. The code is very "experimental", and it is e.g. missing checks for error conditions etc.. Use it at your own risk. You have been warned! 138 | 139 | ## License 140 | 141 | This library is licensed under GPLv2. See the LICENSE file. 142 | 143 | -------------------------------------------------------------------------------- /bin/create-java-perf-map.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | #set -x 4 | 5 | CUR_DIR=`pwd` 6 | PID=$1 7 | OPTIONS=$2 8 | ATTACH_JAR=attach-main.jar 9 | PERF_MAP_DIR="$(cd "$(dirname "$0")" && pwd -P)"/.. 10 | ATTACH_JAR_PATH=$PERF_MAP_DIR/out/$ATTACH_JAR 11 | PERF_MAP_FILE=/tmp/perf-$PID.map 12 | if [[ `uname` == 'Linux' ]]; then 13 | LINUX=1; 14 | else 15 | LINUX=2; 16 | fi 17 | 18 | if [[ "$LINUX" == "1" ]]; then 19 | if [ ! -d /proc/$PID ]; then 20 | echo "PID $PID not found" 21 | exit 1 22 | fi 23 | TARGET_UID=$(awk '/^Uid:/{print $2}' /proc/$PID/status) 24 | TARGET_GID=$(awk '/^Gid:/{print $2}' /proc/$PID/status) 25 | fi 26 | 27 | if [ -z "$JAVA_HOME" ]; then 28 | if [[ "$LINUX" == "1" ]]; then 29 | JAVA_HOME=/usr/lib/jvm/default-java 30 | 31 | [ -d "$JAVA_HOME" ] || JAVA_HOME=/etc/alternatives/java_sdk 32 | else 33 | JAVA_HOME=`/usr/libexec/java_home -v 1.8` 34 | fi 35 | fi 36 | [ -d "$JAVA_HOME" ] || (echo "JAVA_HOME directory at '$JAVA_HOME' does not exist." && false) 37 | 38 | 39 | if [[ "$LINUX" == "1" ]]; then 40 | sudo rm $PERF_MAP_FILE -f 41 | (cd $PERF_MAP_DIR/out && sudo -u \#$TARGET_UID -g \#$TARGET_GID $JAVA_HOME/bin/java -cp $ATTACH_JAR_PATH:$JAVA_HOME/lib/tools.jar net.virtualvoid.perf.AttachOnce $PID "$OPTIONS") 42 | sudo chown root:root $PERF_MAP_FILE 43 | else 44 | rm -f $PERF_MAP_FILE 45 | (cd $PERF_MAP_DIR/out && $JAVA_HOME/bin/java -cp $ATTACH_JAR_PATH:$JAVA_HOME/lib/tools.jar net.virtualvoid.perf.AttachOnce $PID "$OPTIONS") 46 | fi 47 | -------------------------------------------------------------------------------- /bin/create-links-in: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | #set -x 4 | 5 | TARGET_DIR=$1 6 | BIN_DIR=`dirname $0` 7 | 8 | if [ -z "$TARGET_DIR" ]; then 9 | echo "Please specify a target directory." 10 | exit 11 | fi 12 | 13 | ln -s $(readlink -f $BIN_DIR/perf-java-top) $TARGET_DIR 14 | ln -s $(readlink -f $BIN_DIR/perf-java-record-stack) $TARGET_DIR 15 | ln -s $(readlink -f $BIN_DIR/perf-java-report-stack) $TARGET_DIR 16 | ln -s $(readlink -f $BIN_DIR/perf-java-flames) $TARGET_DIR 17 | -------------------------------------------------------------------------------- /bin/dtrace-java-flames: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -e 4 | PID=$1 5 | 6 | if [ -z "$DTRACE_JAVA_TMP" ]; then 7 | DTRACE_JAVA_TMP=/tmp 8 | fi 9 | 10 | STACKS=$DTRACE_JAVA_TMP/out-$PID.stacks 11 | COLLAPSED=$DTRACE_JAVA_TMP/out-$PID.collapsed 12 | PERF_MAP_DIR="$(cd "$(dirname "$0")" && pwd -P)"/.. 13 | PERF_MAP_FILE=/tmp/perf-$PID.map 14 | 15 | if [ ! -x "$FLAMEGRAPH_DIR/stackcollapse.pl" ]; then 16 | echo "FlameGraph executable not found at '$FLAMEGRAPH_DIR/stackcollapse.pl'. Please set FLAMEGRAPH_DIR to the root of the clone of https://github.com/brendangregg/FlameGraph." 17 | exit 18 | fi 19 | 20 | if [ -z "$DTRACE_DATA_FILE" ]; then 21 | PERF_DATA_FILE=$DTRACE_JAVA_TMP/dtrace-$PID.data 22 | fi 23 | 24 | if [ -z "$DTRACE_FLAME_OUTPUT" ]; then 25 | DTRACE_FLAME_OUTPUT=flamegraph-$PID.svg 26 | fi 27 | 28 | if [ -z "$DTRACE_FLAME_OPTS" ]; then 29 | DTRACE_FLAME_OPTS="--color=java" 30 | fi 31 | 32 | $PERF_MAP_DIR/bin/dtrace-java-record-stack $* 33 | cat $PERF_DATA_FILE | $PERF_MAP_DIR/bin/dtrace-perf-map.pl $PERF_MAP_FILE > $STACKS 34 | $FLAMEGRAPH_DIR/stackcollapse.pl $DTRACE_COLLAPSE_OPTS $STACKS | tee $COLLAPSED | $FLAMEGRAPH_DIR/flamegraph.pl $DTRACE_FLAME_OPTS > $DTRACE_FLAME_OUTPUT 35 | echo "Flame graph SVG written to DTRACE_FLAME_OUTPUT='`pwd`/$DTRACE_FLAME_OUTPUT'." 36 | -------------------------------------------------------------------------------- /bin/dtrace-java-record-stack: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | PERF_MAP_DIR="$(cd "$(dirname "$0")" && pwd -P)"/.. 6 | 7 | PID=$1 8 | 9 | if [ -z "$DTRACE_JAVA_TMP" ]; then 10 | DTRACE_JAVA_TMP=/tmp 11 | fi 12 | 13 | if [ -z "$DTRACE_SECONDS" ]; then 14 | DTRACE_SECONDS=15 15 | fi 16 | 17 | if [ -z "$DTRACE_FREQ" ]; then 18 | DTRACE_FREQ=99 19 | fi 20 | 21 | if [ -z "$DTRACE_FRAMES" ]; then 22 | DTRACE_FRAMES=100 23 | fi 24 | 25 | if [ -z "$DTRACE_DATA_FILE" ]; then 26 | DTRACE_DATA_FILE=$DTRACE_JAVA_TMP/dtrace-$PID.data 27 | fi 28 | 29 | sudo dtrace -x ustackframes=$DTRACE_FRAMES -n "profile-$DTRACE_FREQ /pid == $PID && arg1/ { @[ustack()] = count(); } tick-"$DTRACE_SECONDS"s { exit(0); }" -p $PID > $DTRACE_DATA_FILE 30 | $PERF_MAP_DIR/bin/create-java-perf-map.sh $PID "$PERF_MAP_OPTIONS" 31 | -------------------------------------------------------------------------------- /bin/dtrace-perf-map.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | use warnings; 4 | no warnings 'portable'; 5 | use strict; 6 | 7 | my $num_args = $#ARGV + 1; 8 | if ($num_args != 1) { 9 | print "\nUsage: $0 perf-*.map\n"; 10 | exit; 11 | } 12 | 13 | my $map_file = $ARGV[0]; 14 | my @map_entries; 15 | 16 | open(my $fh, '<:encoding(UTF-8)', $map_file) or die "Could not open file '$map_file' $!"; 17 | 18 | # Create map of perf-*.map file entries. 19 | while (my $row = <$fh>) { 20 | chomp $row; 21 | my @parts = split / /, $row; 22 | my $address = hex($parts[0]); 23 | my $size = hex($parts[1]); 24 | my $method = $parts[2]; 25 | my @entry = (); 26 | 27 | push @entry, $address; 28 | push @entry, $size; 29 | push @entry, $method; 30 | push @map_entries, [@entry]; 31 | } 32 | 33 | # Process STDIN and replace unkown methods with these provided by the perf-*.map file. 34 | while (my $row = ) { 35 | chomp $row; 36 | if ($row =~ "^ 0x(.+)") { 37 | my $addr = hex($1); 38 | my $size = -1; 39 | foreach my $e (@map_entries) { 40 | my $entry_addr = $e->[0]; 41 | my $entry_size = $e->[1]; 42 | 43 | # First check if we had a match before that had a smaller entry_size. If so its a better match and we should just continue. 44 | if (($size == -1 || $entry_size < $size) && $addr >= $entry_addr && $addr <= ($entry_addr + $entry_size)) { 45 | $row = " $e->[2]"; 46 | $size = $entry_size; 47 | } 48 | } 49 | } 50 | print "$row\n"; 51 | } 52 | -------------------------------------------------------------------------------- /bin/perf-java-flames: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | #set -x 4 | 5 | PID=$1 6 | 7 | if [ -z "$PERF_JAVA_TMP" ]; then 8 | PERF_JAVA_TMP=/tmp 9 | fi 10 | 11 | STACKS=$PERF_JAVA_TMP/out-$PID.stacks 12 | COLLAPSED=$PERF_JAVA_TMP/out-$PID.collapsed 13 | PERF_MAP_DIR=$(dirname $(readlink -f $0))/.. 14 | 15 | if [ ! -x "$FLAMEGRAPH_DIR/stackcollapse-perf.pl" ]; then 16 | echo "FlameGraph executable not found at '$FLAMEGRAPH_DIR/stackcollapse-perf.pl'. Please set FLAMEGRAPH_DIR to the root of the clone of https://github.com/brendangregg/FlameGraph." 17 | exit 18 | fi 19 | 20 | if [ -z "$PERF_DATA_FILE" ]; then 21 | PERF_DATA_FILE=$PERF_JAVA_TMP/perf-$PID.data 22 | fi 23 | 24 | if [ -z "$PERF_FLAME_OUTPUT" ]; then 25 | PERF_FLAME_OUTPUT=flamegraph-$PID.svg 26 | fi 27 | 28 | if [ -z "$PERF_FLAME_OPTS" ]; then 29 | PERF_FLAME_OPTS="--color=java" 30 | fi 31 | 32 | $PERF_MAP_DIR/bin/perf-java-record-stack $* 33 | sudo perf script -i $PERF_DATA_FILE > $STACKS 34 | $FLAMEGRAPH_DIR/stackcollapse-perf.pl $PERF_COLLAPSE_OPTS $STACKS | tee $COLLAPSED | $FLAMEGRAPH_DIR/flamegraph.pl $PERF_FLAME_OPTS > $PERF_FLAME_OUTPUT 35 | echo "Flame graph SVG written to PERF_FLAME_OUTPUT='`readlink -f $PERF_FLAME_OUTPUT`'." 36 | -------------------------------------------------------------------------------- /bin/perf-java-record-stack: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | #set -x 4 | 5 | PERF_MAP_DIR=$(dirname $(readlink -f $0))/.. 6 | PID=$1 7 | 8 | if [ -z "$PERF_JAVA_TMP" ]; then 9 | PERF_JAVA_TMP=/tmp 10 | fi 11 | 12 | if [ -z "$PERF_RECORD_SECONDS" ]; then 13 | PERF_RECORD_SECONDS=15 14 | fi 15 | 16 | if [ -z "$PERF_RECORD_FREQ" ]; then 17 | PERF_RECORD_FREQ=99 18 | fi 19 | 20 | if [ -z "$PERF_DATA_FILE" ]; then 21 | PERF_DATA_FILE=$PERF_JAVA_TMP/perf-$PID.data 22 | fi 23 | 24 | echo "Recording events for $PERF_RECORD_SECONDS seconds (adapt by setting PERF_RECORD_SECONDS)" 25 | sudo perf record -F $PERF_RECORD_FREQ -o $PERF_DATA_FILE -g -p $* -- sleep $PERF_RECORD_SECONDS 26 | $PERF_MAP_DIR/bin/create-java-perf-map.sh $PID "$PERF_MAP_OPTIONS" 27 | -------------------------------------------------------------------------------- /bin/perf-java-report-stack: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | #set -x 4 | 5 | PID=$1 6 | PERF_MAP_DIR=$(dirname $(readlink -f $0))/.. 7 | 8 | if [ -z "$PERF_JAVA_TMP" ]; then 9 | PERF_JAVA_TMP=/tmp 10 | fi 11 | 12 | if [ -z "$PERF_DATA_FILE" ]; then 13 | PERF_DATA_FILE=$PERF_JAVA_TMP/perf-$PID.data 14 | fi 15 | 16 | $PERF_MAP_DIR/bin/perf-java-record-stack $* 17 | sudo perf report -i $PERF_DATA_FILE 18 | -------------------------------------------------------------------------------- /bin/perf-java-top: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | #set -x 4 | 5 | PERF_MAP_DIR=$(dirname $(readlink -f $0))/.. 6 | 7 | PID=$1 8 | $PERF_MAP_DIR/bin/create-java-perf-map.sh $PID "$PERF_MAP_OPTIONS" 9 | sudo perf top -p $* 10 | -------------------------------------------------------------------------------- /src/c/perf-map-agent.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libperfmap: a JVM agent to create perf-.map files for consumption 3 | * with linux perf-tools 4 | * Copyright (C) 2013-2015 Johannes Rudolph 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, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include 27 | #include 28 | #include 29 | 30 | #include "perf-map-file.h" 31 | 32 | #define STRING_BUFFER_SIZE 2000 33 | #define BIG_STRING_BUFFER_SIZE 20000 34 | 35 | bool unfold_inlined_methods = false; 36 | bool unfold_simple = false; 37 | bool unfold_all = false; 38 | bool print_method_signatures = false; 39 | bool print_source_loc = false; 40 | 41 | bool clean_class_names = false; 42 | bool dotted_class_names = false; 43 | bool annotate_java_frames = false; 44 | char *unfold_delimiter = "->"; 45 | 46 | bool debug_dump_unfold_entries = false; 47 | 48 | FILE *method_file = NULL; 49 | 50 | 51 | void open_map_file() { 52 | if (!method_file) 53 | method_file = perf_map_open(getpid()); 54 | } 55 | void close_map_file() { 56 | perf_map_close(method_file); 57 | method_file = NULL; 58 | } 59 | 60 | void deallocate(jvmtiEnv *jvmti, void *string) { 61 | if (string != NULL) (*jvmti)->Deallocate(jvmti, (unsigned char *) string); 62 | } 63 | 64 | char *frame_annotation(bool inlined) { 65 | return annotate_java_frames ? (inlined ? "_[i]" : "_[j]") : ""; 66 | } 67 | 68 | static int get_line_number(jvmtiLineNumberEntry *table, jint entry_count, jlocation loc) { 69 | int i; 70 | for (i = 0; i < entry_count; i++) 71 | if (table[i].start_location > loc) return table[i - 1].line_number; 72 | 73 | return -1; 74 | } 75 | 76 | void class_name_from_sig(char *dest, size_t dest_size, const char *sig) { 77 | if ((clean_class_names || dotted_class_names) && sig[0] == 'L') { 78 | const char *src = clean_class_names ? sig + 1 : sig; 79 | int i; 80 | for(i = 0; i < (dest_size - 1) && src[i]; i++) { 81 | char c = src[i]; 82 | if (dotted_class_names && c == '/') c = '.'; 83 | if (clean_class_names && c == ';') break; 84 | dest[i] = c; 85 | } 86 | dest[i] = 0; 87 | } else 88 | strncpy(dest, sig, dest_size); 89 | } 90 | 91 | static void sig_string(jvmtiEnv *jvmti, jmethodID method, char *output, size_t noutput, char *annotation) { 92 | char *sourcefile = NULL; 93 | char *method_name = NULL; 94 | char *msig = NULL; 95 | char *csig = NULL; 96 | jvmtiLineNumberEntry *lines = NULL; 97 | 98 | jclass class; 99 | jint entrycount = 0; 100 | 101 | strncpy(output, "", noutput); 102 | 103 | if (!(*jvmti)->GetMethodName(jvmti, method, &method_name, &msig, NULL)) { 104 | if (!(*jvmti)->GetMethodDeclaringClass(jvmti, method, &class) && 105 | !(*jvmti)->GetClassSignature(jvmti, class, &csig, NULL)) { 106 | 107 | char source_info[1000] = ""; 108 | char *method_signature = ""; 109 | 110 | if (print_source_loc) { 111 | if (!(*jvmti)->GetSourceFileName(jvmti, class, &sourcefile)) { 112 | if (!(*jvmti)->GetLineNumberTable(jvmti, method, &entrycount, &lines)) { 113 | int lineno = -1; 114 | if(entrycount > 0) lineno = lines[0].line_number; 115 | snprintf(source_info, sizeof(source_info), "(%s:%d)", sourcefile, lineno); 116 | 117 | deallocate(jvmti, lines); 118 | } 119 | deallocate(jvmti, (unsigned char *) sourcefile); 120 | } 121 | } 122 | 123 | if (print_method_signatures && msig) 124 | method_signature = msig; 125 | 126 | char class_name[STRING_BUFFER_SIZE]; 127 | class_name_from_sig(class_name, sizeof(class_name), csig); 128 | snprintf(output, noutput, "%s::%s%s%s%s", 129 | class_name, method_name, method_signature, source_info, annotation); 130 | 131 | deallocate(jvmti, (unsigned char *) csig); 132 | } 133 | deallocate(jvmti, (unsigned char *) method_name); 134 | deallocate(jvmti, (unsigned char *) msig); 135 | } 136 | } 137 | 138 | void generate_single_entry( 139 | jvmtiEnv *jvmti, 140 | jmethodID method, 141 | const void *code_addr, 142 | jint code_size) { 143 | char entry[STRING_BUFFER_SIZE]; 144 | sig_string(jvmti, method, entry, sizeof(entry), frame_annotation(false)); 145 | perf_map_write_entry(method_file, code_addr, (unsigned int) code_size, entry); 146 | } 147 | 148 | /* Generates either a simple or a complex unfolded entry. */ 149 | void generate_unfolded_entry( 150 | jvmtiEnv *jvmti, 151 | jmethodID method, 152 | char *buffer, 153 | size_t buffer_size, 154 | const char *root_name) { 155 | if (unfold_simple) 156 | sig_string(jvmti, method, buffer, buffer_size, ""); 157 | else { 158 | char entry_name[STRING_BUFFER_SIZE]; 159 | sig_string(jvmti, method, entry_name, sizeof(entry_name), ""); 160 | snprintf(buffer, buffer_size, "%s in %s", entry_name, root_name); 161 | } 162 | } 163 | 164 | /* Generates and writes a single entry for a given inlined method. */ 165 | void write_unfolded_entry( 166 | jvmtiEnv *jvmti, 167 | PCStackInfo *info, 168 | jmethodID root_method, 169 | const char *root_name, 170 | const void *start_addr, 171 | const void *end_addr) { 172 | // needs to accommodate: entry_name + " in " + root_name 173 | char inlined_name[STRING_BUFFER_SIZE * 2 + 4]; 174 | const char *entry_p; 175 | 176 | if (unfold_all) { 177 | char full_name[BIG_STRING_BUFFER_SIZE]; 178 | full_name[0] = '\0'; 179 | int i; 180 | // the stack is ordered from leaf@[0] to root@[length-1], so we traverse backwards to construct the unfolded string 181 | const jint first_frame = info->numstackframes - 1; 182 | for (i = first_frame; i >= 0; i--) { 183 | sig_string(jvmti, info->methods[i], inlined_name, sizeof(inlined_name), frame_annotation(i != first_frame)); 184 | strncat(full_name, inlined_name, sizeof(full_name) - 1 - strlen(full_name)); // TODO optimize 185 | if (i != 0) strncat(full_name, unfold_delimiter, sizeof(full_name) -1 - strlen(full_name)); 186 | } 187 | entry_p = full_name; 188 | } else { 189 | jmethodID cur_method = info->methods[0]; // top of stack 190 | if (cur_method != root_method) { 191 | generate_unfolded_entry(jvmti, cur_method, inlined_name, sizeof(inlined_name), root_name); 192 | entry_p = inlined_name; 193 | } else { 194 | entry_p = root_name; 195 | } 196 | } 197 | 198 | perf_map_write_entry(method_file, start_addr, (unsigned int) (end_addr - start_addr), entry_p); 199 | } 200 | 201 | void dump_entries( 202 | jvmtiEnv *jvmti, 203 | jmethodID root_method, 204 | jint code_size, 205 | const void *code_addr, 206 | const void *compile_info) { 207 | const jvmtiCompiledMethodLoadRecordHeader *header = compile_info; 208 | char root_name[STRING_BUFFER_SIZE]; 209 | sig_string(jvmti, root_method, root_name, sizeof(root_name), ""); 210 | printf("At %s size %x from %p to %p", root_name, code_size, code_addr, code_addr + code_size); 211 | if (header->kind == JVMTI_CMLR_INLINE_INFO) { 212 | const jvmtiCompiledMethodLoadInlineRecord *record = (jvmtiCompiledMethodLoadInlineRecord *) header; 213 | printf(" with %d entries\n", record->numpcs); 214 | 215 | int i; 216 | for (i = 0; i < record->numpcs; i++) { 217 | PCStackInfo *info = &record->pcinfo[i]; 218 | printf(" %p has %d stack entries\n", info->pc, info->numstackframes); 219 | 220 | int j; 221 | for (j = 0; j < info->numstackframes; j++) { 222 | char buf[2000]; 223 | sig_string(jvmti, info->methods[j], buf, sizeof(buf), ""); 224 | printf(" %s\n", buf); 225 | } 226 | } 227 | } else printf(" with no inline info\n"); 228 | } 229 | 230 | void generate_unfolded_entries( 231 | jvmtiEnv *jvmti, 232 | jmethodID root_method, 233 | jint code_size, 234 | const void* code_addr, 235 | const void* compile_info) { 236 | const jvmtiCompiledMethodLoadRecordHeader *header = compile_info; 237 | char root_name[STRING_BUFFER_SIZE]; 238 | 239 | sig_string(jvmti, root_method, root_name, sizeof(root_name), ""); 240 | 241 | if (debug_dump_unfold_entries) 242 | dump_entries(jvmti, root_method, code_size, code_addr, compile_info); 243 | 244 | if (header->kind == JVMTI_CMLR_INLINE_INFO) { 245 | const jvmtiCompiledMethodLoadInlineRecord *record = (jvmtiCompiledMethodLoadInlineRecord *) header; 246 | 247 | const void *start_addr = code_addr; 248 | jmethodID cur_method = root_method; 249 | 250 | // walk through the method meta data per PC to extract address range 251 | // per inlined method. 252 | int i; 253 | for (i = 0; i < record->numpcs; i++) { 254 | PCStackInfo *info = &record->pcinfo[i]; 255 | jmethodID top_method = info->methods[0]; 256 | 257 | // as long as the top method remains the same we delay recording 258 | if (cur_method != top_method) { 259 | // top method has changed, record the range for current method 260 | void *end_addr = info->pc; 261 | 262 | if (i > 0) 263 | write_unfolded_entry(jvmti, &record->pcinfo[i - 1], root_method, root_name, start_addr, end_addr); 264 | else 265 | generate_single_entry(jvmti, root_method, start_addr, (unsigned int) (end_addr - start_addr)); 266 | 267 | start_addr = info->pc; 268 | cur_method = top_method; 269 | } 270 | } 271 | 272 | // record the last range if there's a gap 273 | if (start_addr != code_addr + code_size) { 274 | // end_addr is end of this complete code blob 275 | const void *end_addr = code_addr + code_size; 276 | 277 | if (i > 0) 278 | write_unfolded_entry(jvmti, &record->pcinfo[i - 1], root_method, root_name, start_addr, end_addr); 279 | else 280 | generate_single_entry(jvmti, root_method, start_addr, (unsigned int) (end_addr - start_addr)); 281 | } 282 | } else { 283 | generate_single_entry(jvmti, root_method, code_addr, code_size); 284 | } 285 | } 286 | 287 | static void JNICALL 288 | cbCompiledMethodLoad( 289 | jvmtiEnv *jvmti, 290 | jmethodID method, 291 | jint code_size, 292 | const void* code_addr, 293 | jint map_length, 294 | const jvmtiAddrLocationMap* map, 295 | const void* compile_info) { 296 | if (unfold_inlined_methods && compile_info != NULL) 297 | generate_unfolded_entries(jvmti, method, code_size, code_addr, compile_info); 298 | else 299 | generate_single_entry(jvmti, method, code_addr, code_size); 300 | } 301 | 302 | void JNICALL 303 | cbDynamicCodeGenerated(jvmtiEnv *jvmti, 304 | const char* name, 305 | const void* address, 306 | jint length) { 307 | perf_map_write_entry(method_file, address, (unsigned int) length, name); 308 | } 309 | 310 | void set_notification_mode(jvmtiEnv *jvmti, jvmtiEventMode mode) { 311 | (*jvmti)->SetEventNotificationMode(jvmti, mode, JVMTI_EVENT_COMPILED_METHOD_LOAD, (jthread)NULL); 312 | (*jvmti)->SetEventNotificationMode(jvmti, mode, JVMTI_EVENT_DYNAMIC_CODE_GENERATED, (jthread)NULL); 313 | } 314 | 315 | jvmtiError enable_capabilities(jvmtiEnv *jvmti) { 316 | jvmtiCapabilities capabilities; 317 | 318 | memset(&capabilities,0, sizeof(capabilities)); 319 | capabilities.can_generate_all_class_hook_events = 1; 320 | capabilities.can_tag_objects = 1; 321 | capabilities.can_generate_object_free_events = 1; 322 | capabilities.can_get_source_file_name = 1; 323 | capabilities.can_get_line_numbers = 1; 324 | capabilities.can_generate_vm_object_alloc_events = 1; 325 | capabilities.can_generate_compiled_method_load_events = 1; 326 | 327 | // Request these capabilities for this JVM TI environment. 328 | return (*jvmti)->AddCapabilities(jvmti, &capabilities); 329 | } 330 | 331 | jvmtiError set_callbacks(jvmtiEnv *jvmti) { 332 | jvmtiEventCallbacks callbacks; 333 | 334 | memset(&callbacks, 0, sizeof(callbacks)); 335 | callbacks.CompiledMethodLoad = &cbCompiledMethodLoad; 336 | callbacks.DynamicCodeGenerated = &cbDynamicCodeGenerated; 337 | return (*jvmti)->SetEventCallbacks(jvmti, &callbacks, (jint)sizeof(callbacks)); 338 | } 339 | 340 | JNIEXPORT jint JNICALL 341 | Agent_OnAttach(JavaVM *vm, char *options, void *reserved) { 342 | open_map_file(); 343 | 344 | unfold_simple = strstr(options, "unfoldsimple") != NULL; 345 | unfold_all = strstr(options, "unfoldall") != NULL; 346 | unfold_inlined_methods = strstr(options, "unfold") != NULL || unfold_simple || unfold_all; 347 | print_method_signatures = strstr(options, "msig") != NULL; 348 | print_source_loc = strstr(options, "sourcepos") != NULL; 349 | dotted_class_names = strstr(options, "dottedclass") != NULL; 350 | clean_class_names = strstr(options, "cleanclass") != NULL; 351 | annotate_java_frames = strstr(options, "annotate_java_frames") != NULL; 352 | 353 | bool use_semicolon_unfold_delimiter = strstr(options, "use_semicolon_unfold_delimiter") != NULL; 354 | unfold_delimiter = use_semicolon_unfold_delimiter ? ";" : "->"; 355 | 356 | debug_dump_unfold_entries = strstr(options, "debug_dump_unfold_entries") != NULL; 357 | 358 | jvmtiEnv *jvmti; 359 | (*vm)->GetEnv(vm, (void **)&jvmti, JVMTI_VERSION_1); 360 | enable_capabilities(jvmti); 361 | set_callbacks(jvmti); 362 | set_notification_mode(jvmti, JVMTI_ENABLE); 363 | (*jvmti)->GenerateEvents(jvmti, JVMTI_EVENT_DYNAMIC_CODE_GENERATED); 364 | (*jvmti)->GenerateEvents(jvmti, JVMTI_EVENT_COMPILED_METHOD_LOAD); 365 | set_notification_mode(jvmti, JVMTI_DISABLE); 366 | close_map_file(); 367 | 368 | return 0; 369 | } 370 | 371 | -------------------------------------------------------------------------------- /src/c/perf-map-file.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libperfmap: a JVM agent to create perf-.map files for consumption 3 | * with linux perf-tools 4 | * Copyright (C) 2013-2015 Johannes Rudolph 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, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "perf-map-file.h" 27 | 28 | FILE *perf_map_open(pid_t pid) { 29 | char filename[500]; 30 | snprintf(filename, sizeof(filename), "/tmp/perf-%d.map", pid); 31 | FILE * res = fopen(filename, "w"); 32 | if (!res) { 33 | fprintf(stderr, "Couldn't open %s: errno(%d)", filename, errno); 34 | exit(0); 35 | } 36 | return res; 37 | } 38 | 39 | int perf_map_close(FILE *fp) { 40 | if (fp) 41 | return fclose(fp); 42 | else 43 | return 0; 44 | } 45 | 46 | void perf_map_write_entry(FILE *method_file, const void* code_addr, unsigned int code_size, const char* entry) { 47 | if (method_file) 48 | fprintf(method_file, "%lx %x %s\n", (unsigned long) code_addr, code_size, entry); 49 | } 50 | -------------------------------------------------------------------------------- /src/c/perf-map-file.h: -------------------------------------------------------------------------------- 1 | /* 2 | * libperfmap: a JVM agent to create perf-.map files for consumption 3 | * with linux perf-tools 4 | * Copyright (C) 2013-2015 Johannes Rudolph 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, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | */ 20 | 21 | FILE *perf_map_open(pid_t pid); 22 | int perf_map_close(FILE *fp); 23 | void perf_map_write_entry(FILE *method_file, const void* code_addr, unsigned int code_size, const char* entry); 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/java/AttachOnce.java: -------------------------------------------------------------------------------- 1 | /* 2 | * libperfmap: a JVM agent to create perf-.map files for consumption 3 | * with linux perf-tools 4 | * Copyright (C) 2013-2015 Johannes Rudolph 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, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | */ 20 | 21 | package net.virtualvoid.perf; 22 | 23 | import java.io.File; 24 | 25 | import com.sun.tools.attach.VirtualMachine; 26 | import java.lang.management.ManagementFactory; 27 | import java.util.Locale; 28 | 29 | public class AttachOnce { 30 | public static void main(String[] args) throws Exception { 31 | String pid = args[0]; 32 | String options = ""; 33 | if (args.length > 1) options = args[1]; 34 | loadAgent(pid, options); 35 | } 36 | 37 | static void loadAgent(String pid, String options) throws Exception { 38 | VirtualMachine vm = VirtualMachine.attach(pid); 39 | try { 40 | final File lib; 41 | if (System.getProperty("os.name", "").toLowerCase(Locale.US).contains("os x")) { 42 | lib = new File("libperfmap.dylib"); 43 | } else { 44 | lib = new File("libperfmap.so"); 45 | } 46 | String fullPath = lib.getAbsolutePath(); 47 | if (!lib.exists()) { 48 | System.out.printf("Expected %s at '%s' but it didn't exist.\n", lib.getName(), fullPath); 49 | System.exit(1); 50 | } 51 | else vm.loadAgentPath(fullPath, options); 52 | } catch(com.sun.tools.attach.AgentInitializationException e) { 53 | // rethrow all but the expected exception 54 | if (!e.getMessage().equals("Agent_OnAttach failed")) throw e; 55 | } finally { 56 | vm.detach(); 57 | } 58 | } 59 | } 60 | --------------------------------------------------------------------------------