├── .gitignore ├── LICENSE ├── README.md ├── bin └── perfj ├── build.gradle ├── codequality ├── HEADER └── checkstyle.xml ├── examples ├── ContextSwitchTest.java ├── L1CacheMiss.java ├── OffCPU.java └── Runner.java ├── gradle.properties ├── gradle ├── buildscript.gradle ├── check.gradle ├── convention.gradle ├── license.gradle ├── maven.gradle ├── release.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images ├── perfj.png └── perfj.svg ├── settings.gradle └── src ├── main └── java │ └── info │ └── minzhou │ └── perfj │ └── PerfJ.java └── perfj ├── c ├── perf-map-agent.c └── perf-map-file.c └── headers └── perf-map-file.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | ################### 3 | *.com 4 | *.class 5 | *.dll 6 | *.exe 7 | *.o 8 | *.so 9 | 10 | # Packages # 11 | ############ 12 | # it's better to unpack these files and commit the raw source 13 | # git has its own built in compression methods 14 | *.7z 15 | *.dmg 16 | *.gz 17 | *.iso 18 | *.jar 19 | *.rar 20 | *.tar 21 | *.zip 22 | 23 | # Logs and databases # 24 | ###################### 25 | *.log 26 | 27 | # OS generated files # 28 | ###################### 29 | .DS_Store* 30 | ehthumbs.db 31 | Icon? 32 | Thumbs.db 33 | 34 | # Editor Files # 35 | ################ 36 | *~ 37 | *.swp 38 | 39 | # Gradle Files # 40 | ################ 41 | .gradle 42 | .m2 43 | 44 | # Build output directies 45 | /target 46 | */target 47 | /build 48 | */build 49 | 50 | # IntelliJ specific files/directories 51 | out 52 | .idea 53 | *.ipr 54 | *.iws 55 | *.iml 56 | atlassian-ide-plugin.xml 57 | 58 | # Eclipse specific files/directories 59 | .classpath 60 | .project 61 | .cproject 62 | .settings 63 | .metadata 64 | 65 | # NetBeans specific files/directories 66 | .nbattrs 67 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PerfJ 2 | 3 | [![Join the chat at https://gitter.im/coderplay/perfj](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/coderplay/perfj?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 4 | 5 | `PerfJ` is a wrapper of linux `perf` for java programs. 6 | 7 | As [Brendan Gregg's words](http://www.brendangregg.com/FlameGraphs/cpuflamegraphs.html#Java) 8 | 9 | >In order to profile java programs, you need a profiler that can sample stack traces. There has historically been two types of profilers: 10 | 11 | >* `System profilers:` like Linux perf, which shows system code paths (eg, JVM GC, syscalls, TCP), but not Java methods. 12 | >* `JVM profilers:` like hprof, LJP, and commercial profilers. These show Java methods, but usually not system code paths. 13 | 14 | >Ideally, we need a profile result that does it all: system and Java code paths. Apart from convenience, it also shows system code-paths in Java context, which can be crucial for understanding a profile properly. 15 | 16 | >The problem is getting a system profiler to understand Java methods and stack traces. If you try Linux perf_events, for example, you'll see hexadecimal numbers and broken stack traces, as it can't convert addresses into Java symbols, and can't walk the JVM stack. 17 | 18 | >There are two specific problems: 19 | 20 | >* The JVM compiles methods on the fly (just-in-time: JIT), and doesn't expose a traditional symbol table for system profilers to read. 21 | >* The JVM also uses the frame pointer register (RBP on x86-64) as a general purpose register, breaking traditional stack walking. 22 | 23 | Thanks to [the work by Brendan Gregg and Zoltan Majo](https://bugs.openjdk.java.net/browse/JDK-8068945). We will have an option to turn on the preservation of frame pointer on JDK 8u60+. 24 | 25 | This project is based on Johannes Rudolph's work at [here](https://github.com/jrudolph/perf-map-agent), but `PerfJ` is more convenient and safer to use. 26 | 27 | `PerfJ` can produce flame graph through [Brendan Gregg's FlameGraph tool](https://github.com/brendangregg/FlameGraph) . 28 | 29 | Below is an example shows the hotspot of a pure java [leveldb](https://github.com/dain/leveldb) program. Green is Java layer, yellow is JVM layer, and red is system layer(native user-level, or kernel). Longer bar means higher cpu percentage. 30 | 31 | ![PerfJ CPU Flame Graph Example](images/perfj.png) 32 | 33 | There is a raw interactive SVG image [here] (http://blog.minzhou.info/perfj/perfj.svg). 34 | 35 | 36 | ## Prerequisites 37 | 38 | * Linux x86_64 39 | * perf 40 | * JDK 8u60 and higher 41 | 42 | ## Build 43 | 44 | Before starting building `PerfJ`, make sure `gcc` is already installed. 45 | 46 | 47 | checkout the source from github 48 | 49 | git clone https://github.com/coderplay/perfj.git 50 | 51 | and run below in the future building 52 | 53 | cd perfj 54 | ./gradlew releaseTarGz 55 | 56 | 57 | ## Installation 58 | 59 | Before install `PerfJ`, you should install Linux perf first 60 | 61 | To install perf on centos/redhat/fedora linux system 62 | 63 | yum install perf.x86_64 64 | 65 | To install perf on ubuntu linux system 66 | 67 | apt-get install linux-tools-common linux-tools-generic linux-tools-`uname -r` 68 | 69 | then download `perfj-*.tgz` from the [release page] (https://github.com/coderplay/perfj/releases), untar it 70 | 71 | tar zxvf perf-*.tgz 72 | 73 | 74 | ## Usage 75 | 76 | Check the [wiki pages] (https://github.com/coderplay/perfj/wiki) 77 | 78 | ## License 79 | 80 | This library is licensed under GPLv2. See the LICENSE file. 81 | -------------------------------------------------------------------------------- /bin/perfj: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | 4 | function print_usage() { 5 | echo "PerfJ is a wrapper of linux perf with enhancement for java programs" 6 | echo "usage: perfj [--version] [--help] COMMAND [ARGS]" 7 | echo "The most commonly used perf commands are:" 8 | echo " annotate Read perf.data (created by perf record) and display annotated code" 9 | echo " archive Create archive with object files with build-ids found in perf.data file" 10 | echo " bench General framework for benchmark suites" 11 | echo " buildid-cache Manage build-id cache." 12 | echo " buildid-list List the buildids in a perf.data file" 13 | echo " diff Read perf.data files and display the differential profile" 14 | echo " evlist List the event names in a perf.data file" 15 | echo " inject Filter to augment the events stream with additional information" 16 | echo " kmem Tool to trace/measure kernel memory(slab) properties" 17 | echo " kvm Tool to trace/measure kvm guest os" 18 | echo " list List all symbolic event types" 19 | echo " lock Analyze lock events" 20 | echo " mem Profile memory accesses" 21 | echo " record Run a command and record its profile into perf.data" 22 | echo " report Read perf.data (created by perf record) and display the profile" 23 | echo " sched Tool to trace/measure scheduler properties (latencies)" 24 | echo " script Read perf.data (created by perf record) and display trace output" 25 | echo " stat Run a command and gather performance counter statistics" 26 | echo " test Runs sanity tests." 27 | echo " timechart Tool to visualize total system behavior during a workload" 28 | echo " top System profiling tool." 29 | echo " trace strace inspired tool" 30 | echo " probe Define new dynamic tracepoints" 31 | echo "" 32 | echo "See 'perf help COMMAND' for more information on a specific command." 33 | } 34 | 35 | 36 | if [ $# = 0 ]; then 37 | print_usage 38 | exit 1 39 | fi 40 | 41 | COMMAND=$1 42 | 43 | if [ -z "$PERFJ_HOME" -o ! -d "$PERFJ_HOME" ] ; then 44 | # resolve links - $0 could be a link to btrace's home 45 | PRG="$0" 46 | progname=`basename "$0"` 47 | PERFJ_HOME=`dirname "$PRG"`/.. 48 | PERFJ_HOME=`cd "$PERFJ_HOME" && pwd` 49 | fi 50 | 51 | ARGS=$@ 52 | PARAMS=$(getopt -q -o p:a -l "pid:,all-cpus" -n "$0" -- "$@"); 53 | 54 | eval set -- "$PARAMS"; 55 | 56 | while true; do 57 | case "$1" in 58 | -p|--pid) 59 | shift; 60 | if [ -n "$1" ]; then 61 | PID=$1 62 | shift; 63 | fi 64 | ;; 65 | -a|--all-cpus) 66 | echo "PerfJ so far doesn't support -a option"; 67 | exit 1 68 | ;; 69 | --) 70 | shift; 71 | break; 72 | ;; 73 | esac 74 | done 75 | 76 | 77 | if [ "$COMMAND" = "kvm" -o "$COMMAND" = "record" -o "$COMMAND" = "trace" -o "$COMMAND" = "top" -o "$COMMAND" = "script" -o "$COMMAND" = "probe" ] ; then 78 | 79 | if [ -z "${PID}" ]; then 80 | echo "-p pid is required by command $COMMAND" 81 | exit 1 82 | fi 83 | 84 | # some Java parameters 85 | if [ "$JAVA_HOME" != "" ]; then 86 | #echo "run java in $JAVA_HOME" 87 | JAVA_HOME=$JAVA_HOME 88 | fi 89 | 90 | if [ "$JAVA_HOME" = "" ]; then 91 | echo "Error: JAVA_HOME is not set." 92 | exit 1 93 | fi 94 | 95 | PERFJ_JAR=$(find "${PERFJ_HOME}" -maxdepth 1 -name "perfj-*.jar") 96 | 97 | if [ -n "${JAVA_USER}" ]; then 98 | JAVA_USER="-u ${JAVA_USER}" 99 | else 100 | JAVA_USER="" 101 | fi 102 | 103 | if [ -n "${PERFJ_JAR}" ]; then 104 | if [ "${JAVA_HOME}" != "" ]; then 105 | TOOLS_JAR="${JAVA_HOME}/lib/tools.jar" 106 | # Remove map file if exists 107 | sudo rm -f /tmp/perf-${PID}.map 108 | sudo ${JAVA_USER} ${JAVA_HOME}/bin/java -cp ${PERFJ_JAR}:${TOOLS_JAR} info.minzhou.perfj.PerfJ ${PID} "unfold" 109 | sudo chown root:root /tmp/perf-${PID}.map 110 | else 111 | echo "Please set JAVA_HOME before running this script" 112 | exit 1 113 | fi 114 | else 115 | echo "Couldn't find perfj-*.jar in ${PERFJ_HOME}" 116 | exit 1 117 | fi 118 | fi 119 | 120 | # Make sure perf is installed 121 | if ! command -v perf >/dev/null 2>&1; then 122 | echo "perf is not installed." 123 | exit 1 124 | fi 125 | 126 | sudo perf ${ARGS} 127 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | 2 | // Establish version and status 3 | ext { 4 | githubProjectName = rootProject.name // Change if github project name is not the same as the root project's name 5 | } 6 | 7 | buildscript { 8 | repositories { 9 | mavenLocal() 10 | mavenCentral() // maven { url 'http://jcenter.bintray.com' } 11 | } 12 | apply from: file('gradle/buildscript.gradle'), to: buildscript 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | mavenLocal() 18 | mavenCentral() 19 | } 20 | } 21 | 22 | 23 | apply from: file('gradle/convention.gradle') 24 | apply from: file('gradle/maven.gradle') 25 | // apply from: file('gradle/check.gradle') 26 | // apply from: file('gradle/license.gradle') 27 | // apply from: file('gradle/release.gradle') 28 | 29 | 30 | apply plugin: 'c' 31 | 32 | model { 33 | platforms { 34 | x86 { 35 | architecture "x86" 36 | } 37 | x64 { 38 | architecture "x86_64" 39 | } 40 | } 41 | 42 | components { 43 | perfj(NativeLibrarySpec) { 44 | // targetPlatform "x86" 45 | // targetPlatform "x64" 46 | binaries.withType(SharedLibraryBinarySpec) { 47 | if (targetPlatform.operatingSystem.linux) { 48 | cCompiler.args '-I', "${org.gradle.internal.jvm.Jvm.current().javaHome}/include" 49 | cCompiler.args '-I', "${org.gradle.internal.jvm.Jvm.current().javaHome}/include/linux" 50 | 51 | sharedLibraryFile file("${buildDir}/classes/main/info/minzhou/perfj/native/libperfj.so") 52 | } 53 | } 54 | 55 | binaries.withType(StaticLibraryBinarySpec) { 56 | buildable false 57 | } 58 | } 59 | } 60 | } 61 | 62 | jar.dependsOn 'perfjSharedLibrary' 63 | 64 | dependencies { 65 | provided files("${org.gradle.internal.jvm.Jvm.current().javaHome}/lib/tools.jar") 66 | } 67 | 68 | -------------------------------------------------------------------------------- /codequality/HEADER: -------------------------------------------------------------------------------- 1 | Copyright ${year} TangoMe, Inc. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /codequality/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | -------------------------------------------------------------------------------- /examples/ContextSwitchTest.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.atomic.AtomicReference; 2 | import java.util.concurrent.locks.LockSupport; 3 | 4 | public final class ContextSwitchTest { 5 | static final int RUNS = 3; 6 | static final int ITERATES = 1000000; 7 | static AtomicReference turn = new AtomicReference(); 8 | 9 | static final class WorkerThread extends Thread { 10 | volatile Thread other; 11 | volatile int nparks; 12 | 13 | public void run() { 14 | final AtomicReference t = turn; 15 | final Thread other = this.other; 16 | if (turn == null || other == null) 17 | throw new NullPointerException(); 18 | int p = 0; 19 | for (int i = 0; i < ITERATES; ++i) { 20 | while (!t.compareAndSet(other, this)) { 21 | LockSupport.park(); 22 | ++p; 23 | } 24 | LockSupport.unpark(other); 25 | } 26 | LockSupport.unpark(other); 27 | nparks = p; 28 | System.out.println("parks: " + p); 29 | 30 | } 31 | } 32 | 33 | static void test() throws Exception { 34 | WorkerThread a = new WorkerThread(); 35 | WorkerThread b = new WorkerThread(); 36 | a.other = b; 37 | b.other = a; 38 | turn.set(a); 39 | long startTime = System.nanoTime(); 40 | a.start(); 41 | b.start(); 42 | a.join(); 43 | b.join(); 44 | long endTime = System.nanoTime(); 45 | int parkNum = a.nparks + b.nparks; 46 | System.out.println("Average time: " + ((endTime - startTime) / parkNum) 47 | + "ns"); 48 | } 49 | 50 | public static void main(String[] args) throws Exception { 51 | for (int i = 0; i < RUNS; i++) { 52 | test(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /examples/L1CacheMiss.java: -------------------------------------------------------------------------------- 1 | public class L1CacheMiss { 2 | private static final int RUNS = 10; 3 | private static final int DIMENSION_1 = 1024 * 1024; 4 | private static final int DIMENSION_2 = 128; 5 | 6 | private static long[][] longs; 7 | 8 | 9 | void cachehit(long[][] longs) { 10 | long sum = 0L; 11 | for (int i = 0; i < DIMENSION_1; i++) { 12 | for (int j = 0; j < DIMENSION_2; j++) { 13 | sum += longs[i][j]; 14 | } 15 | } 16 | } 17 | 18 | void cachemiss(long[][] longs) { 19 | long sum = 0L; 20 | for (int j = 0; j < DIMENSION_2; j++) { 21 | for (int i = 0; i < DIMENSION_1; i++) { 22 | sum += longs[i][j]; 23 | } 24 | } 25 | 26 | } 27 | 28 | public static void main(String[] args) throws Exception { 29 | longs = new long[DIMENSION_1][]; 30 | for (int i = 0; i < DIMENSION_1; i++) { 31 | longs[i] = new long[DIMENSION_2]; 32 | for (int j = 0; j < DIMENSION_2; j++) { 33 | longs[i][j] = 0L; 34 | } 35 | } 36 | System.out.println("starting...."); 37 | 38 | final long start = System.nanoTime(); 39 | L1CacheMiss lcm = new L1CacheMiss(); 40 | 41 | for (int r = 0; r < RUNS; r++) { 42 | lcm.cachehit(longs); 43 | lcm.cachemiss(longs); 44 | 45 | } 46 | System.out.println("duration = " + (System.nanoTime() - start)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /examples/OffCPU.java: -------------------------------------------------------------------------------- 1 | public class OffCPU { 2 | 3 | public static void OnCPU() { 4 | long counter = 0L; 5 | for(int j = 0; j < 1000000; j++) { 6 | counter+=j; 7 | } 8 | 9 | 10 | } 11 | 12 | 13 | public static void main(String[] args) throws Throwable { 14 | 15 | 16 | for (int i = 0; i < 1000000; i++) { 17 | Thread.sleep(10); 18 | OnCPU(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /examples/Runner.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | import java.util.concurrent.*; 3 | 4 | /** 5 | * Created by ruedi on 10/13/14. 6 | * 7 | * Note this test does not make sense for machines with less then 8 cores (L1 cache misses will not be significant) 8 | * However with MAX_WORKER = 4, cache effects still show up, but to a lesser extent 9 | */ 10 | public class Runner { 11 | 12 | static class Work { 13 | 14 | public Random rand = new Random(13); 15 | 16 | int localState[]; 17 | public Work(int localSize) { 18 | this.localState = new int[localSize]; 19 | } 20 | 21 | public int doWork(int iterations, Executor executor, int countDown, CountDownLatch latch ) { 22 | int sum = 0; 23 | for ( int i = 0; i < iterations; i++ ) { 24 | int index = rand.nextInt(localState.length); 25 | sum += localState[index]; 26 | localState[index] = i; 27 | } 28 | if ( countDown > 0 ) { 29 | // submit next message 30 | executor.execute( () -> doWork(iterations,executor,countDown-1,latch) ); 31 | } else { 32 | // finished 33 | latch.countDown(); 34 | } 35 | return sum; 36 | } 37 | 38 | } 39 | 40 | enum Mode { 41 | WorkStealing, 42 | FixedThread, 43 | Dedicated 44 | } 45 | 46 | 47 | final static int MAX_WORKER = 8; 48 | static final int NUM_ACTORS_PER_WORKER = 10; 49 | static int memAcc = 100; 50 | 51 | Work workers[] = new Work[MAX_WORKER*NUM_ACTORS_PER_WORKER]; // 10 actors per thread 52 | 53 | ExecutorService ex; 54 | 55 | ExecutorService threads[] = new ExecutorService[MAX_WORKER]; 56 | Mode mode = Mode.Dedicated; 57 | 58 | public Runner(Mode mode) { 59 | this.mode = mode; 60 | } 61 | 62 | public Runner init(int localSize) { 63 | for (int i = 0; i < workers.length; i++) { 64 | workers[i] = new Work(localSize); 65 | if ( mode == Mode.Dedicated && i < MAX_WORKER ) { 66 | threads[i] = (new ThreadPoolExecutor(1, 1, 67 | 0L, TimeUnit.MILLISECONDS, 68 | new ArrayBlockingQueue(10000))); 69 | 70 | } 71 | } 72 | switch (mode) { 73 | case WorkStealing: 74 | ex = Executors.newWorkStealingPool(MAX_WORKER); break; 75 | case FixedThread: 76 | ex = new ThreadPoolExecutor(MAX_WORKER, MAX_WORKER, 77 | 0L, TimeUnit.MILLISECONDS, 78 | new ArrayBlockingQueue(100000)); 79 | } 80 | return this; 81 | } 82 | 83 | public long run(int iter) throws InterruptedException { 84 | long tim = System.currentTimeMillis(); 85 | CountDownLatch finSignal = new CountDownLatch(workers.length); 86 | for ( int i = 0; i < workers.length; i++ ) { 87 | final int finalI = i; 88 | if ( mode == Mode.Dedicated ) { 89 | ExecutorService dedicatedThread = threads[finalI % MAX_WORKER]; 90 | dedicatedThread.execute(() -> workers[finalI % workers.length].doWork(memAcc, dedicatedThread, iter/workers.length, finSignal )); 91 | } else { 92 | ex.execute( () -> workers[finalI % workers.length].doWork(memAcc,ex, iter/workers.length, finSignal) ); 93 | } 94 | } 95 | finSignal.await(); 96 | long dur = System.currentTimeMillis()-tim; 97 | // System.out.println(mode+" Time "+dur); 98 | return dur; 99 | } 100 | 101 | void shutdown() throws InterruptedException { 102 | if ( mode == Mode.Dedicated ) { 103 | for (int i = 0; i < threads.length; i++) { 104 | ExecutorService thread = threads[i]; 105 | thread.shutdown(); 106 | thread.awaitTermination(10L, TimeUnit.SECONDS); 107 | } 108 | } else { 109 | ex.shutdown(); 110 | ex.awaitTermination(10L, TimeUnit.SECONDS); 111 | } 112 | } 113 | 114 | private static long avgTest(Mode mode, int localSize ) throws InterruptedException { 115 | long sum = 0; 116 | System.gc(); 117 | Runner runner = new Runner(mode).init(localSize); 118 | int iters = 1; 119 | for (int i = 0; i < iters; i++) { 120 | sum += runner.run(1000 * 1000 * 5); 121 | // Thread.sleep(1000); 122 | } 123 | // System.out.println(); 124 | System.out.println("*** "+mode + " average "+sum/iters+" localSize "+localSize*4); 125 | // System.out.println(); 126 | runner.shutdown(); 127 | return sum/iters; 128 | } 129 | 130 | public static void main(String arg[]) throws InterruptedException { 131 | int sizes[] = { 132 | 16, 133 | 64, 134 | 500, 135 | 1000, 136 | 8000, 137 | 80000 138 | }; 139 | long durations[][] = new long[sizes.length][]; 140 | for (int i = 0; i < sizes.length; i++) { 141 | int size = sizes[i]; 142 | for ( int ii = 0; ii < 2; ii++ ) { 143 | System.out.println("warmup =>"); 144 | avgTest(Mode.Dedicated, size); 145 | avgTest(Mode.FixedThread, size); 146 | avgTest(Mode.WorkStealing, size); 147 | } 148 | durations[i] = new long[3]; 149 | int numRuns = 3; 150 | for ( int ii = 0; ii < numRuns; ii++ ) { 151 | System.out.println("run => "+ii); 152 | durations[i][Mode.Dedicated.ordinal()] += avgTest(Mode.Dedicated, size); 153 | durations[i][Mode.FixedThread.ordinal()] += avgTest(Mode.FixedThread, size); 154 | durations[i][Mode.WorkStealing.ordinal()] += avgTest(Mode.WorkStealing, size); 155 | } 156 | for (int j = 0; j < durations[i].length; j++) { 157 | durations[i][j] /= numRuns; 158 | } 159 | } 160 | System.out.println("Final results ************** Worker Threads:"+MAX_WORKER+" actors:"+(MAX_WORKER*NUM_ACTORS_PER_WORKER)+" #mem accesses: "+memAcc ); 161 | for (int i = 0; i < durations.length; i++) { 162 | long[] duration = durations[i]; 163 | for (int j = 0; j < 3; j++) { 164 | System.out.println("local state bytes: "+sizes[i]*4+" "+Mode.values()[j]+" avg:"+duration[j]); 165 | 166 | } 167 | } 168 | } 169 | 170 | } 171 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | version=1.0 2 | -------------------------------------------------------------------------------- /gradle/buildscript.gradle: -------------------------------------------------------------------------------- 1 | // Executed in context of buildscript 2 | repositories { 3 | // Repo in addition to maven central 4 | repositories { maven { url 'http://dl.bintray.com/content/netflixoss/external-gradle-plugins/' } } // For gradle-release 5 | } 6 | 7 | dependencies { 8 | classpath 'nl.javadude.gradle.plugins:license-gradle-plugin:0.10.0' 9 | classpath 'net.saliman:gradle-cobertura-plugin:2.2.7' 10 | classpath 'gradle-release:gradle-release:1.1.5' 11 | classpath 'org.ajoberstar:gradle-git:1.1.0' 12 | } 13 | -------------------------------------------------------------------------------- /gradle/check.gradle: -------------------------------------------------------------------------------- 1 | subprojects { 2 | // Checkstyle 3 | apply plugin: 'checkstyle' 4 | checkstyle { 5 | ignoreFailures = true 6 | configFile = rootProject.file('codequality/checkstyle.xml') 7 | } 8 | 9 | // FindBugs 10 | apply plugin: 'findbugs' 11 | findbugs { 12 | ignoreFailures = true 13 | } 14 | 15 | // PMD 16 | apply plugin: 'pmd' 17 | //tasks.withType(Pmd) { reports.html.enabled true } 18 | 19 | apply plugin: 'cobertura' 20 | cobertura { 21 | coverageSourceDirs = sourceSets.main.java.srcDirs 22 | coverageFormats = ['html'] 23 | coverageIncludes = ['**/*.java', '**/*.groovy'] 24 | coverageExcludes = [] 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /gradle/convention.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' // Plugin as major conventions, overwrites status 2 | 3 | sourceCompatibility = 1.7 4 | 5 | compileJava.options.bootClasspath="${org.gradle.internal.jvm.Jvm.current().javaHome}/jre/lib/rt.jar" 6 | 7 | // GRADLE-2087 workaround, perform after java plugin 8 | status = project.hasProperty('preferredStatus')?project.preferredStatus:(version.contains('SNAPSHOT')?'snapshot':'release') 9 | 10 | // Indenting to align with multi-project branch 11 | task sourcesJar(type: Jar, dependsOn:classes) { 12 | from sourceSets.main.allSource 13 | classifier 'sources' 14 | extension 'jar' 15 | } 16 | 17 | task javadocJar(type: Jar, dependsOn:javadoc) { 18 | from javadoc.destinationDir 19 | classifier 'javadoc' 20 | extension 'jar' 21 | } 22 | 23 | configurations.create('sources') 24 | configurations.create('javadoc') 25 | configurations.archives { 26 | extendsFrom configurations.sources 27 | extendsFrom configurations.javadoc 28 | } 29 | 30 | // When outputing to an Ivy repo, we want to use the proper type field 31 | gradle.taskGraph.whenReady { 32 | def artifacts = project.configurations.sources.artifacts 33 | def sourceArtifact = artifacts.iterator().next() 34 | sourceArtifact.type = 'sources' 35 | } 36 | 37 | artifacts { 38 | sources(sourcesJar) { 39 | // Weird Gradle quirk where type will be used for the extension, but only for sources 40 | type 'jar' 41 | } 42 | javadoc(javadocJar) { 43 | type 'javadoc' 44 | } 45 | } 46 | 47 | configurations { 48 | provided { 49 | description = 'much like compile, but indicates you expect the JDK or a container to provide it. It is only available on the compilation classpath, and is not transitive.' 50 | transitive = true 51 | visible = true 52 | } 53 | } 54 | 55 | project.sourceSets { 56 | main.compileClasspath += project.configurations.provided 57 | main.runtimeClasspath -= project.configurations.provided 58 | test.compileClasspath += project.configurations.provided 59 | test.runtimeClasspath += project.configurations.provided 60 | javadoc.classpath += project.configurations.provided 61 | } 62 | 63 | apply plugin: 'org.ajoberstar.github-pages' // Used to create publishGhPages task 64 | 65 | def docTasks = [:] 66 | [Javadoc,ScalaDoc,Groovydoc].each{ Class docClass -> 67 | tasks.withType(docClass).each { docTask -> 68 | docTasks[docTask.name] = docTask 69 | publishGhPages.dependsOn(docTask) 70 | } 71 | } 72 | 73 | githubPages { 74 | repoUri = "git@github.com:TangoMe/${rootProject.githubProjectName}.git" 75 | pages { 76 | docTasks.each { shortName, docTask -> 77 | from(docTask.outputs.files) { 78 | into "docs/${shortName}" 79 | } 80 | } 81 | } 82 | } 83 | 84 | 85 | // Generate wrapper, which is distributed as part of source to alleviate the need of installing gradle 86 | task createWrapper(type: Wrapper) { 87 | gradleVersion = '2.3' 88 | } 89 | 90 | 91 | task releaseTarGz(dependsOn: assemble, type: Tar) { 92 | baseName "${rootProject.name}" 93 | into "${baseName}-${rootProject.version}" 94 | compression = Compression.GZIP 95 | from(project.file("bin")) { into "bin/" } 96 | from(project.file("conf")) { into "conf/" } 97 | from 'LICENSE' 98 | from 'README.md' 99 | from(jar.archivePath) 100 | from(configurations.runtime) { into("libs/") } 101 | } 102 | -------------------------------------------------------------------------------- /gradle/license.gradle: -------------------------------------------------------------------------------- 1 | // Dependency for plugin was set in buildscript.gradle 2 | 3 | subprojects { 4 | apply plugin: 'license' //nl.javadude.gradle.plugins.license.LicensePlugin 5 | license { 6 | header rootProject.file('codequality/HEADER') 7 | ext.year = Calendar.getInstance().get(Calendar.YEAR) 8 | skipExistingHeaders true 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /gradle/maven.gradle: -------------------------------------------------------------------------------- 1 | // Maven side of things 2 | subprojects { 3 | apply plugin: 'maven' // Java plugin has to have been already applied for the conf2scope mappings to work 4 | apply plugin: 'signing' 5 | 6 | signing { 7 | required { gradle.taskGraph.hasTask(uploadMavenCentral) } 8 | sign configurations.archives 9 | } 10 | 11 | /** 12 | * Publishing to Maven Central example provided from http://jedicoder.blogspot.com/2011/11/automated-gradle-project-deployment-to.html 13 | * artifactory will execute uploadArchives to force generation of ivy.xml, and we don't want that to trigger an upload to maven 14 | * central, so using custom upload task. 15 | */ 16 | task uploadMavenCentral(type:Upload, dependsOn: signArchives) { 17 | configuration = configurations.archives 18 | onlyIf { ['release', 'snapshot'].contains(project.status) } 19 | repositories.mavenDeployer { 20 | beforeDeployment { signing.signPom(it) } 21 | 22 | // To test deployment locally, use the following instead of oss.sonatype.org 23 | //repository(url: "file://localhost/${rootProject.rootDir}/repo") 24 | 25 | def sonatypeUsername = rootProject.hasProperty('sonatypeUsername')?rootProject.sonatypeUsername:'' 26 | def sonatypePassword = rootProject.hasProperty('sonatypePassword')?rootProject.sonatypePassword:'' 27 | 28 | repository(url: 'https://oss.sonatype.org/service/local/staging/deploy/maven2') { 29 | authentication(userName: sonatypeUsername, password: sonatypePassword) 30 | } 31 | 32 | snapshotRepository(url: 'https://oss.sonatype.org/content/repositories/snapshots/') { 33 | authentication(userName: sonatypeUsername, password: sonatypePassword) 34 | } 35 | 36 | // Prevent datastamp from being appending to artifacts during deployment 37 | uniqueVersion = false 38 | 39 | // Closure to configure all the POM with extra info, common to all projects 40 | pom.project { 41 | name "${project.name}" 42 | description "${project.name} developed by TangoMe" 43 | developers { 44 | developer { 45 | id 'tangogithub' 46 | name 'TangoMe Open Source Development' 47 | email 'talent@tango.me' 48 | } 49 | } 50 | licenses { 51 | license { 52 | name 'The Apache Software License, Version 2.0' 53 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 54 | distribution 'repo' 55 | } 56 | } 57 | url "https://github.com/TangoMe/${rootProject.githubProjectName}" 58 | scm { 59 | connection "scm:git:git@github.com:TangoMe/${rootProject.githubProjectName}.git" 60 | url "scm:git:git@github.com:TangoMe/${rootProject.githubProjectName}.git" 61 | developerConnection "scm:git:git@github.com:TangoMe/${rootProject.githubProjectName}.git" 62 | } 63 | issueManagement { 64 | system 'github' 65 | url "https://github.com/TangoMe/${rootProject.githubProjectName}/issues" 66 | } 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /gradle/release.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'release' 2 | 3 | [ uploadIvyLocal: 'uploadLocal', uploadArtifactory: 'artifactoryPublish', buildWithArtifactory: 'build' ].each { key, value -> 4 | // Call out to compile against internal repository 5 | task "${key}"(type: GradleBuild) { 6 | startParameter = project.gradle.startParameter.newInstance() 7 | doFirst { 8 | startParameter.projectProperties = [status: project.status, preferredStatus: project.status] 9 | } 10 | startParameter.addInitScript( file('gradle/tango-oss.gradle') ) 11 | startParameter.getExcludedTaskNames().add('check') 12 | tasks = [ 'build', value ] 13 | } 14 | } 15 | 16 | // Marker task for following code to key in on 17 | task releaseCandidate(dependsOn: release) 18 | task forceCandidate { 19 | onlyIf { gradle.taskGraph.hasTask(releaseCandidate) } 20 | doFirst { project.status = 'candidate' } 21 | } 22 | task forceRelease { 23 | onlyIf { !gradle.taskGraph.hasTask(releaseCandidate) } 24 | doFirst { project.status = 'release' } 25 | } 26 | release.dependsOn([forceCandidate, forceRelease]) 27 | 28 | task uploadMavenCentral(dependsOn: subprojects.tasks.uploadMavenCentral) 29 | task releaseSnapshot(dependsOn: [uploadArtifactory, uploadMavenCentral]) 30 | 31 | // Ensure our versions look like the project status before publishing 32 | task verifyStatus << { 33 | def hasSnapshot = version.contains('-SNAPSHOT') 34 | if (project.status == 'snapshot' && !hasSnapshot) { 35 | throw new GradleException("Version (${version}) needs -SNAPSHOT if publishing snapshot") 36 | } 37 | } 38 | uploadArtifactory.dependsOn(verifyStatus) 39 | uploadMavenCentral.dependsOn(verifyStatus) 40 | 41 | // Ensure upload happens before taggging, hence upload failures will leave repo in a revertable state 42 | preTagCommit.dependsOn([uploadArtifactory, uploadMavenCentral]) 43 | 44 | 45 | gradle.taskGraph.whenReady { taskGraph -> 46 | def hasRelease = taskGraph.hasTask('commitNewVersion') 47 | def indexOf = { return taskGraph.allTasks.indexOf(it) } 48 | 49 | if (hasRelease) { 50 | assert indexOf(build) < indexOf(unSnapshotVersion), 'build target has to be after unSnapshotVersion' 51 | assert indexOf(uploadMavenCentral) < indexOf(preTagCommit), 'preTagCommit has to be after uploadMavenCentral' 52 | assert indexOf(uploadArtifactory) < indexOf(preTagCommit), 'preTagCommit has to be after uploadArtifactory' 53 | } 54 | } 55 | 56 | // Prevent plugin from asking for a version number interactively 57 | ext.'gradle.release.useAutomaticVersion' = "true" 58 | 59 | release { 60 | git.requireBranch = null 61 | } 62 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coderplay/perfj/659da458bae4e6ea90c4b834e27e916f7da06f88/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Jun 21 12:43:58 PDT 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.3-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /images/perfj.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coderplay/perfj/659da458bae4e6ea90c4b834e27e916f7da06f88/images/perfj.png -------------------------------------------------------------------------------- /images/perfj.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | coderplay.github.com/perfj.svg at master · coderplay/coderplay.github.com · GitHub 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | Skip to content 73 |
74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 127 | 128 | 129 | 130 |
131 |
132 |
133 | 134 |
135 |
136 |
137 | 138 | 139 | 180 | 181 |

182 | 183 | /coderplay.github.com 186 | 187 | 188 | 189 | 190 | 191 |

192 |
193 |
194 | 195 |
196 |
197 |
198 | 199 | 243 | 244 |
245 | 246 |
248 |

HTTPS clone URL

249 |
250 | 252 | 253 | 254 | 255 |
256 |
257 | 258 | 259 |
261 |

Subversion checkout URL

262 |
263 | 265 | 266 | 267 | 268 |
269 |
270 | 271 | 272 | 273 |
You can clone with 274 |
or
. 275 | 276 | 277 | 278 |
279 | 280 | 281 | 282 | 283 | 288 | 289 | Download ZIP 290 | 291 |
292 |
293 | 294 |
295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 |
303 | 304 |
305 | 309 | 310 | branch: 311 | master 312 | 313 | 314 | 369 |
370 | 371 |
372 | 377 | 378 | 379 | 380 |
381 | 382 | 385 |
386 | 387 | 388 |
389 | Fetching contributors… 390 |
391 | 392 |
393 |

394 |

Cannot retrieve contributors at this time

395 |
396 |
397 |
398 |
399 |
400 | 408 | 409 |
410 | Raw 411 | History 412 |
413 | 414 | 415 | 416 | 419 |
420 | 421 |
422 | 1294.42 kB 423 |
424 |
425 | 426 | 427 |
428 | 429 |
430 |
434 | 435 |
Sorry, something went wrong. Reload?
436 |
Sorry, we cannot display this file.
437 |
Sorry, this file is invalid so it cannot be displayed.
438 | 439 |
440 |
441 | 442 |
443 | 444 |
445 | 446 | Jump to Line 447 | 452 | 453 |
454 | 455 |
456 | 457 |
458 |
459 | 460 | 461 |
462 | 463 |
464 | 487 |
488 | 489 | 490 |
491 |
492 |
493 | 494 |
495 |
496 |
497 |
498 |
499 | 508 |
509 | 510 | 511 | 512 | 513 | 514 | 515 |
516 | 517 | 518 | Something went wrong with that request. Please try again. 519 |
520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name='perfj' 2 | -------------------------------------------------------------------------------- /src/main/java/info/minzhou/perfj/PerfJ.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This program is free software; you can redistribute it and/or modify 3 | * it under the terms of the GNU General Public License as published by 4 | * the Free Software Foundation; either version 2 of the License, or 5 | * (at your option) any later version. 6 | * 7 | * This program is distributed in the hope that it will be useful, 8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | * GNU General Public License for more details. 11 | * 12 | * You should have received a copy of the GNU General Public License along 13 | * with this program; if not, write to the Free Software Foundation, Inc., 14 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 15 | */ 16 | 17 | package info.minzhou.perfj; 18 | 19 | import com.sun.tools.attach.VirtualMachine; 20 | 21 | import java.io.*; 22 | import java.util.Enumeration; 23 | import java.util.Properties; 24 | import java.util.UUID; 25 | 26 | public class PerfJ { 27 | 28 | public static final String PERFJ_SYSTEM_PROPERTIES_FILE = "info-minzhou-perfj.properties"; 29 | public static final String KEY_PERFJ_LIB_PATH = "info.minzhou.perfj.lib.path"; 30 | public static final String KEY_PERFJ_LIB_NAME = "info.minzhou.perfj.lib.name"; 31 | public static final String KEY_PERFJ_TEMPDIR = "info.minzhou.perfj.tempdir"; 32 | public static final String KEY_PERFJ_USE_SYSTEMLIB = "info.minzhou.perfj.use.systemlib"; 33 | 34 | 35 | static { 36 | loadSystemProperties(); 37 | } 38 | 39 | /** 40 | * load system properties when configuration file of the name 41 | * {@link #PERFJ_SYSTEM_PROPERTIES_FILE} is found 42 | */ 43 | private static void loadSystemProperties() { 44 | try { 45 | InputStream is = Thread.currentThread().getContextClassLoader() 46 | .getResourceAsStream(PERFJ_SYSTEM_PROPERTIES_FILE); 47 | 48 | if (is == null) { 49 | return; // no configuration file is found 50 | } 51 | 52 | // Load property file 53 | Properties props = new Properties(); 54 | props.load(is); 55 | is.close(); 56 | Enumeration names = props.propertyNames(); 57 | while (names.hasMoreElements()) { 58 | String name = (String) names.nextElement(); 59 | if (name.startsWith("info.minzhou.perfj.")) { 60 | if (System.getProperty(name) == null) { 61 | System.setProperty(name, props.getProperty(name)); 62 | } 63 | } 64 | } 65 | } catch (Throwable ex) { 66 | System.err.println("Could not load '" + PERFJ_SYSTEM_PROPERTIES_FILE + "' from classpath: " 67 | + ex.toString()); 68 | } 69 | } 70 | 71 | 72 | 73 | private static File findNativeLibrary() { 74 | boolean useSystemLib = Boolean.parseBoolean(System.getProperty(KEY_PERFJ_USE_SYSTEMLIB, "false")); 75 | if (useSystemLib) { 76 | return null; // Use a pre-installed libperfj 77 | } 78 | 79 | // Try to load the library in info.minzhou.perfj.lib.path */ 80 | String perfjNativeLibraryPath = System.getProperty(KEY_PERFJ_LIB_PATH); 81 | String perfjNativeLibraryName = System.getProperty(KEY_PERFJ_LIB_NAME); 82 | 83 | // Resolve the library file name with a suffix (e.g., dll, .so, etc.) 84 | if (perfjNativeLibraryName == null) { 85 | perfjNativeLibraryName = System.mapLibraryName("perfj"); 86 | } 87 | 88 | if (perfjNativeLibraryPath != null) { 89 | File nativeLib = new File(perfjNativeLibraryPath, perfjNativeLibraryName); 90 | if (nativeLib.exists()) { 91 | return nativeLib; 92 | } 93 | } 94 | 95 | // Load native library inside a jar file 96 | perfjNativeLibraryPath = "/info/minzhou/perfj/native"; 97 | boolean hasNativeLib = hasResource(perfjNativeLibraryPath + "/" + perfjNativeLibraryName); 98 | 99 | if (!hasNativeLib) { 100 | throw new RuntimeException("no native library is found for perfj"); 101 | } 102 | 103 | // Temporary folder for the native lib. Use the value of info.minzhou.perfj.tempdir or java.io.tmpdir 104 | File tempFolder = new File(System.getProperty(KEY_PERFJ_TEMPDIR, System.getProperty("java.io.tmpdir"))); 105 | if (!tempFolder.exists()) { 106 | boolean created = tempFolder.mkdirs(); 107 | if (!created) { 108 | // if created == false, it will fail eventually in the later part 109 | } 110 | } 111 | 112 | // Extract and load a native library inside the jar file 113 | return extractLibraryFile(perfjNativeLibraryPath, perfjNativeLibraryName, tempFolder.getAbsolutePath()); 114 | } 115 | 116 | private static boolean hasResource(String path) { 117 | return PerfJ.class.getResource(path) != null; 118 | } 119 | 120 | 121 | /** 122 | * Extract the specified library file to the target folder 123 | * 124 | * @param libraryFolder 125 | * @param libraryFileName 126 | * @param targetFolder 127 | * @return 128 | */ 129 | private static File extractLibraryFile(String libraryFolder, String libraryFileName, String targetFolder) { 130 | String nativeLibraryFilePath = libraryFolder + "/" + libraryFileName; 131 | 132 | // Attach UUID to the native library file to ensure multiple processes can read the libperfj multiple times. 133 | String uuid = UUID.randomUUID().toString(); 134 | String extractedLibFileName = String.format("perfj-%s-%s", uuid, libraryFileName); 135 | File extractedLibFile = new File(targetFolder, extractedLibFileName); 136 | 137 | try { 138 | // Extract a native library file into the target directory 139 | InputStream reader = null; 140 | FileOutputStream writer = null; 141 | try { 142 | reader = PerfJ.class.getResourceAsStream(nativeLibraryFilePath); 143 | try { 144 | writer = new FileOutputStream(extractedLibFile); 145 | 146 | byte[] buffer = new byte[8192]; 147 | int bytesRead = 0; 148 | while ((bytesRead = reader.read(buffer)) != -1) { 149 | writer.write(buffer, 0, bytesRead); 150 | } 151 | } finally { 152 | if (writer != null) { 153 | writer.close(); 154 | } 155 | } 156 | } finally { 157 | if (reader != null) { 158 | reader.close(); 159 | } 160 | 161 | // Delete the extracted lib file on JVM exit. 162 | extractedLibFile.deleteOnExit(); 163 | } 164 | 165 | // Set executable (x) flag to enable Java to load the native library 166 | boolean success = extractedLibFile.setReadable(true) && 167 | extractedLibFile.setWritable(true, true) && 168 | extractedLibFile.setExecutable(true); 169 | if (!success) { 170 | // Setting file flag may fail, but in this case another error will be thrown in later phase 171 | } 172 | 173 | // Check whether the contents are properly copied from the resource folder 174 | { 175 | InputStream nativeIn = null; 176 | InputStream extractedLibIn = null; 177 | try { 178 | nativeIn = PerfJ.class.getResourceAsStream(nativeLibraryFilePath); 179 | extractedLibIn = new FileInputStream(extractedLibFile); 180 | 181 | if (!contentsEquals(nativeIn, extractedLibIn)) { 182 | throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile)); 183 | } 184 | } finally { 185 | if (nativeIn != null) { 186 | nativeIn.close(); 187 | } 188 | if (extractedLibIn != null) { 189 | extractedLibIn.close(); 190 | } 191 | } 192 | } 193 | 194 | return new File(targetFolder, extractedLibFileName); 195 | } catch (IOException e) { 196 | e.printStackTrace(System.err); 197 | return null; 198 | } 199 | } 200 | 201 | private static boolean contentsEquals(InputStream in1, InputStream in2) 202 | throws IOException { 203 | if (!(in1 instanceof BufferedInputStream)) { 204 | in1 = new BufferedInputStream(in1); 205 | } 206 | if (!(in2 instanceof BufferedInputStream)) { 207 | in2 = new BufferedInputStream(in2); 208 | } 209 | 210 | int ch = in1.read(); 211 | while (ch != -1) { 212 | int ch2 = in2.read(); 213 | if (ch != ch2) { 214 | return false; 215 | } 216 | ch = in1.read(); 217 | } 218 | int ch2 = in2.read(); 219 | return ch2 == -1; 220 | } 221 | 222 | private static void loadAgent(String pid, String options) throws Exception { 223 | VirtualMachine vm = VirtualMachine.attach(pid); 224 | try { 225 | vm.loadAgentPath(findNativeLibrary().getAbsolutePath(), options); 226 | } catch (com.sun.tools.attach.AgentInitializationException e) { 227 | // rethrow all but the expected exception 228 | if (!e.getMessage().equals("Agent_OnAttach failed")) throw e; 229 | } finally { 230 | vm.detach(); 231 | } 232 | } 233 | 234 | public static void main(String[] args) throws Exception { 235 | String pid = args[0]; 236 | String options = ""; 237 | if (args.length > 1) options = args[1]; 238 | loadAgent(pid, options); 239 | } 240 | 241 | 242 | } 243 | 244 | -------------------------------------------------------------------------------- /src/perfj/c/perf-map-agent.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libperfj: a JVM agent to create perf-.map files for consumption 3 | * with linux perf-tools 4 | * Copyright (C) 2013 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 | FILE *method_file = NULL; 33 | int unfold_inlined_methods = 0; 34 | int print_method_signatures = 0; 35 | int clean_class_names = 0; 36 | 37 | void open_map_file() { 38 | if (!method_file) 39 | method_file = perf_map_open(getpid()); 40 | } 41 | void close_map_file() { 42 | perf_map_close(method_file); 43 | method_file = NULL; 44 | } 45 | 46 | static int get_line_number(jvmtiLineNumberEntry *table, jint entry_count, jlocation loc) { 47 | int i; 48 | for (i = 0; i < entry_count; i++) 49 | if (table[i].start_location > loc) 50 | return table[i - 1].line_number; 51 | 52 | return -1; 53 | } 54 | 55 | void class_name_from_sig(char *dest, size_t dest_size, const char *sig) { 56 | if (clean_class_names && sig[0] == 'L') { 57 | char *src = (char *)sig + 1; 58 | int i; 59 | for(i = 0; i < (dest_size - 1) && src[i]; i++) { 60 | char c = src[i]; 61 | if (c == '/') c = '.'; 62 | if (c == ';') c = 0; 63 | dest[i] = c; 64 | } 65 | dest[i] = 0; 66 | } else 67 | strncpy(dest, sig, dest_size); 68 | } 69 | 70 | static void sig_string(jvmtiEnv *jvmti, jmethodID method, char *output, size_t noutput) { 71 | char *name; 72 | char *msig; 73 | jclass class; 74 | char *csig; 75 | 76 | (*jvmti)->GetMethodName(jvmti, method, &name, &msig, NULL); 77 | (*jvmti)->GetMethodDeclaringClass(jvmti, method, &class); 78 | (*jvmti)->GetClassSignature(jvmti, class, &csig, NULL); 79 | 80 | char class_name[1000]; 81 | class_name_from_sig(class_name, sizeof(class_name), csig); 82 | 83 | if (print_method_signatures) 84 | snprintf(output, noutput, "%s.%s%s", class_name, name, msig); 85 | else 86 | snprintf(output, noutput, "%s.%s", class_name, name); 87 | 88 | (*jvmti)->Deallocate(jvmti, name); 89 | (*jvmti)->Deallocate(jvmti, msig); 90 | (*jvmti)->Deallocate(jvmti, csig); 91 | } 92 | 93 | void generate_single_entry(jvmtiEnv *jvmti, jmethodID method, const void *code_addr, jint code_size) { 94 | char entry[100]; 95 | sig_string(jvmti, method, entry, sizeof(entry)); 96 | perf_map_write_entry(method_file, code_addr, code_size, entry); 97 | } 98 | 99 | void generate_unfolded_entries( 100 | jvmtiEnv *jvmti, 101 | jmethodID method, 102 | jint code_size, 103 | const void* code_addr, 104 | jint map_length, 105 | const jvmtiAddrLocationMap* map, 106 | const void* compile_info) { 107 | bool hasInlineInfo = false; 108 | 109 | int i; 110 | const jvmtiCompiledMethodLoadRecordHeader *current = compile_info; 111 | char root_name[1000]; 112 | char entry_name[1000]; 113 | char entry[1000]; 114 | sig_string(jvmti, method, root_name, sizeof(root_name)); 115 | while (current != NULL) { 116 | if (current->kind == JVMTI_CMLR_INLINE_INFO) { 117 | hasInlineInfo = true; 118 | const jvmtiCompiledMethodLoadInlineRecord *record = 119 | (jvmtiCompiledMethodLoadInlineRecord *) current; 120 | const void *start_addr = code_addr; 121 | jmethodID cur_method = method; 122 | const char *cur_entry = root_name; 123 | for (i = 0; i < record->numpcs; i++) { 124 | PCStackInfo *info = &record->pcinfo[i]; 125 | jmethodID top_method = info->methods[0]; 126 | if (cur_method != top_method) { 127 | void *end_addr = info->pc; 128 | 129 | if (top_method != method) { 130 | sig_string(jvmti, top_method, entry_name, 131 | sizeof(entry_name)); 132 | snprintf(entry, sizeof(entry), "%s in %s", entry_name, 133 | root_name); 134 | cur_entry = entry; 135 | } else 136 | cur_entry = root_name; 137 | 138 | perf_map_write_entry(method_file, start_addr, 139 | end_addr - start_addr, cur_entry); 140 | 141 | start_addr = info->pc; 142 | cur_method = top_method; 143 | } 144 | } 145 | 146 | if (start_addr < code_addr + code_size) { 147 | const void *end_addr = code_addr + code_size; 148 | sig_string(jvmti, cur_method, entry_name, sizeof(entry_name)); 149 | snprintf(entry, sizeof(entry), "%s in %s", entry_name, 150 | root_name); 151 | 152 | perf_map_write_entry(method_file, start_addr, 153 | end_addr - start_addr, cur_entry); 154 | } 155 | 156 | } 157 | current = (jvmtiCompiledMethodLoadRecordHeader *) current->next; 158 | } 159 | 160 | if (!hasInlineInfo) { 161 | generate_single_entry(jvmti, method, code_addr, code_size); 162 | } 163 | } 164 | 165 | static void JNICALL 166 | cbCompiledMethodLoad( 167 | jvmtiEnv *jvmti, 168 | jmethodID method, 169 | jint code_size, 170 | const void* code_addr, 171 | jint map_length, 172 | const jvmtiAddrLocationMap* map, 173 | const void* compile_info) { 174 | if (unfold_inlined_methods) 175 | generate_unfolded_entries(jvmti, method, code_size, code_addr, map_length, map, compile_info); 176 | else 177 | generate_single_entry(jvmti, method, code_addr, code_size); 178 | } 179 | 180 | void JNICALL 181 | cbDynamicCodeGenerated(jvmtiEnv *jvmti, 182 | const char* name, 183 | const void* address, 184 | jint length) { 185 | perf_map_write_entry(method_file, address, length, name); 186 | } 187 | 188 | void set_notification_mode(jvmtiEnv *jvmti, jvmtiEventMode mode) { 189 | (*jvmti)->SetEventNotificationMode(jvmti, mode, 190 | JVMTI_EVENT_COMPILED_METHOD_LOAD, (jthread)NULL); 191 | (*jvmti)->SetEventNotificationMode(jvmti, mode, 192 | JVMTI_EVENT_DYNAMIC_CODE_GENERATED, (jthread)NULL); 193 | } 194 | 195 | jvmtiError enable_capabilities(jvmtiEnv *jvmti) { 196 | jvmtiCapabilities capabilities; 197 | 198 | memset(&capabilities,0, sizeof(capabilities)); 199 | capabilities.can_generate_all_class_hook_events = 1; 200 | capabilities.can_tag_objects = 1; 201 | capabilities.can_generate_object_free_events = 1; 202 | capabilities.can_get_source_file_name = 1; 203 | capabilities.can_get_line_numbers = 1; 204 | capabilities.can_generate_vm_object_alloc_events = 1; 205 | capabilities.can_generate_compiled_method_load_events = 1; 206 | 207 | // Request these capabilities for this JVM TI environment. 208 | return (*jvmti)->AddCapabilities(jvmti, &capabilities); 209 | } 210 | 211 | jvmtiError set_callbacks(jvmtiEnv *jvmti) { 212 | jvmtiEventCallbacks callbacks; 213 | 214 | memset(&callbacks, 0, sizeof(callbacks)); 215 | callbacks.CompiledMethodLoad = &cbCompiledMethodLoad; 216 | callbacks.DynamicCodeGenerated = &cbDynamicCodeGenerated; 217 | return (*jvmti)->SetEventCallbacks(jvmti, &callbacks, (jint)sizeof(callbacks)); 218 | } 219 | 220 | JNIEXPORT jint JNICALL 221 | Agent_OnAttach(JavaVM *vm, char *options, void *reserved) { 222 | open_map_file(); 223 | 224 | unfold_inlined_methods = strstr(options, "unfold") != NULL; 225 | print_method_signatures = strstr(options, "msig") != NULL; 226 | clean_class_names = strstr(options, "dottedclass") != NULL; 227 | 228 | jvmtiEnv *jvmti; 229 | (*vm)->GetEnv(vm, (void **)&jvmti, JVMTI_VERSION_1); 230 | enable_capabilities(jvmti); 231 | set_callbacks(jvmti); 232 | set_notification_mode(jvmti, JVMTI_ENABLE); 233 | (*jvmti)->GenerateEvents(jvmti, JVMTI_EVENT_DYNAMIC_CODE_GENERATED); 234 | (*jvmti)->GenerateEvents(jvmti, JVMTI_EVENT_COMPILED_METHOD_LOAD); 235 | set_notification_mode(jvmti, JVMTI_DISABLE); 236 | close_map_file(); 237 | 238 | // FAIL to get the JVM to maybe unload this lib (untested) 239 | return 1; 240 | } 241 | 242 | -------------------------------------------------------------------------------- /src/perfj/c/perf-map-file.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libperfj: a JVM agent to create perf-.map files for consumption 3 | * with linux perf-tools 4 | * Copyright (C) 2013 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 | 24 | #include 25 | #include 26 | 27 | #include "perf-map-file.h" 28 | 29 | FILE *perf_map_open(pid_t pid) { 30 | char filename[500]; 31 | snprintf(filename, sizeof(filename), "/tmp/perf-%d.map", pid); 32 | FILE * res = fopen(filename, "w"); 33 | if (!res) error(0, errno, "Couldn't open %s.", filename); 34 | return res; 35 | } 36 | 37 | int perf_map_close(FILE *fp) { 38 | if (fp) 39 | return fclose(fp); 40 | else 41 | return 0; 42 | } 43 | 44 | void perf_map_write_entry(FILE *method_file, const void* code_addr, 45 | unsigned int code_size, const char* entry) { 46 | if (method_file) { 47 | fprintf(method_file, "%lx %x %s\n", (unsigned long) code_addr, 48 | code_size, entry); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/perfj/headers/perf-map-file.h: -------------------------------------------------------------------------------- 1 | /* 2 | * libperfj: a JVM agent to create perf-.map files for consumption 3 | * with linux perf-tools 4 | * Copyright (C) 2013 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 | void perf_map_write_entry(FILE *method_file, const void* code_addr, unsigned int code_size, const char* entry); 23 | 24 | 25 | --------------------------------------------------------------------------------