├── .gitignore ├── AUTHORS ├── COPYING ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md └── src ├── display.cc ├── display.h ├── entry.cc ├── globals.h ├── profiler.cc ├── profiler.h └── stacktraces.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | 19 | # Compiled Static libraries 20 | *.lai 21 | *.la 22 | *.a 23 | *.lib 24 | 25 | # Executables 26 | *.exe 27 | *.out 28 | *.app 29 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Google Inc. 2 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM centos:centos6 2 | 3 | # Setup gcc to compile profiler 4 | # http://superuser.com/questions/381160/how-to-install-gcc-4-7-x-4-8-x-on-centos 5 | RUN \ 6 | yum install -y wget which java-1.7.0-openjdk-devel.x86_64 && \ 7 | cd /etc/yum.repos.d && \ 8 | wget http://people.centos.org/tru/devtools-1.1/devtools-1.1.repo && \ 9 | yum --enablerepo=testing-1.1-devtools-6 install -y devtoolset-1.1-gcc devtoolset-1.1-gcc-c++ 10 | 11 | ENV CC /opt/centos/devtoolset-1.1/root/usr/bin/gcc 12 | ENV CPP /opt/centos/devtoolset-1.1/root/usr/bin/cpp 13 | ENV CXX /opt/centos/devtoolset-1.1/root/usr/bin/c++ 14 | ENV PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/centos/devtoolset-1.1/root/usr/bin 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL:=/bin/bash 2 | UNAME:=$(shell uname | tr '[A-Z]' '[a-z]') 3 | PWD:=$(shell pwd) 4 | 5 | BITS?=64 6 | ifeq ($(UNAME), darwin) 7 | READLINK_ARGS:="" 8 | PLATFORM_WARNINGS:=-Weverything -Wno-c++98-compat-pedantic -Wno-padded \ 9 | -Wno-missing-prototypes 10 | PLATFORM_COPTS:=-std=c++11 -stdlib=libc++ -DTARGET_RT_MAC_CFM=0 11 | HEADERS:=Headers 12 | CC=clang++ 13 | LDFLAGS=-Wl,-fatal_warnings -Wl,-std=c++11 -Wl,-stdlib=libc++ 14 | ifeq ($(BITS), 64) 15 | # Why is this not $!$#@ defined? 16 | PLATFORM_COPTS+=-D__LP64__=1 17 | endif 18 | else ifeq ($(UNAME), linux) 19 | READLINK_ARGS:="-f" 20 | PLATFORM_COPTS:=-mfpmath=sse -std=gnu++0x 21 | PLATFORM_WARNINGS:=-Wframe-larger-than=16384 -Wno-unused-but-set-variable \ 22 | -Wunused-but-set-parameter -Wvla -Wno-conversion-null \ 23 | -Wno-builtin-macro-redefined 24 | HEADERS:=include 25 | CC=g++ 26 | LDFLAGS=-Wl,--fatal-warnings 27 | endif 28 | 29 | JAVA_HOME := $(shell \ 30 | [[ -n "$${JAVA_HOME}" ]] || \ 31 | JAVA_HOME=$$(dirname $$(readlink $(READLINK_ARGS) $$(which java)))/../; \ 32 | [[ "$${JAVA_HOME}" =~ /jre/ ]] && JAVA_HOME=$${JAVA_HOME}/../; \ 33 | [[ -n "$${JAVA_HOME}" ]] || (echo "Cannot find JAVA_HOME" && exit) ; \ 34 | echo $${JAVA_HOME}) 35 | AGENT=liblagent.so 36 | LIBS=-ldl 37 | BUILD_DIR ?= $(shell mkdir build-$(BITS) 2> /dev/null ; echo build-$(BITS)) 38 | SRC_DIR:=${PWD}/src 39 | OPT?=-O2 40 | GLOBAL_WARNINGS=-Wall -Werror -Wformat-security -Wno-char-subscripts \ 41 | -Wno-sign-compare -Wno-strict-overflow -Wwrite-strings -Wnon-virtual-dtor \ 42 | -Woverloaded-virtual 43 | GLOBAL_COPTS=-fdiagnostics-show-option -fno-exceptions \ 44 | -fno-omit-frame-pointer -fno-strict-aliasing -funsigned-char \ 45 | -fno-asynchronous-unwind-tables -m$(BITS) -msse2 -g \ 46 | -D__STDC_FORMAT_MACROS 47 | COPTS:=$(PLATFORM_COPTS) $(GLOBAL_COPTS) $(PLATFORM_WARNINGS) \ 48 | $(GLOBAL_WARNINGS) $(OPT) 49 | 50 | INCLUDES=-I$(JAVA_HOME)/$(HEADERS) -I$(JAVA_HOME)/$(HEADERS)/$(UNAME) 51 | 52 | 53 | # LDFLAGS+=-Wl,--export-dynamic-symbol=Agent_OnLoad 54 | 55 | SOURCES=$(wildcard $(SRC_DIR)/*.cc) 56 | _OBJECTS=$(SOURCES:.cc=.pic.o) 57 | OBJECTS = $(patsubst $(SRC_DIR)/%,$(BUILD_DIR)/%,$(_OBJECTS)) 58 | 59 | $(BUILD_DIR)/%.pic.o: $(SRC_DIR)/%.cc 60 | $(CC) $(INCLUDES) $(COPTS) -Fvisibility=hidden -fPIC -c $< -o $@ 61 | 62 | $(AGENT): $(OBJECTS) 63 | $(CC) $(COPTS) -shared -o $(BUILD_DIR)/$(AGENT) \ 64 | -Bsymbolic $(OBJECTS) $(LIBS) 65 | 66 | all: $(AGENT) 67 | 68 | clean: 69 | rm -rf $(BUILD_DIR)/* 70 | 71 | DOCKER_IMAGE_NAME="lightweight_java_profiler/build" 72 | docker-build: 73 | @docker build -t $(DOCKER_IMAGE_NAME) . 74 | 75 | docker-run: 76 | @docker run -t -i -v $(PWD):$(PWD) -w $(PWD) $(DOCKER_IMAGE_NAME) bash 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | lightweight-java-profiler 2 | ========================= 3 | 4 | Fork of https://code.google.com/p/lightweight-java-profiler/ 5 | -------------------------------------------------------------------------------- /src/display.cc: -------------------------------------------------------------------------------- 1 | #include "display.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | // The map used here doesn't need to be ordered, but unordered_map 11 | // seems to cause problems out of the box on Ubuntu, and hash_map is 12 | // non-standard. 13 | #include 14 | #include 15 | 16 | void StackTracesPrinter::PrintStackTraces(TraceData *traces, int length) { 17 | int count = 0; 18 | int total = 0; 19 | for (int i = 0; i < length; i++) { 20 | if (traces[i].count != 0) { 21 | total += traces[i].count; 22 | count++; 23 | fprintf(file_, "%" PRIdPTR " ", traces[i].count); 24 | PrintStackTrace(&traces[i]); 25 | fprintf(file_, "\n"); 26 | } 27 | } 28 | fprintf(file_, "Total trace count = %d, Total traces = %d\n", total, count); 29 | } 30 | 31 | typedef std::pair PairCallFrame; 32 | typedef std::pair FrameCount; 33 | 34 | struct Sorter { 35 | bool operator()(const FrameCount f1, const FrameCount f2) { 36 | return f1.second > f2.second; 37 | } 38 | }; 39 | 40 | void StackTracesPrinter::PrintLeafHistogram(TraceData *traces, int length) { 41 | fprintf(file_, "\n\nHot methods:\n"); 42 | std::map hot_methods; 43 | for (int i = 0; i < length; i++) { 44 | if (traces[i].count != 0) { 45 | JVMPI_CallTrace *t = &(traces[i].trace); 46 | JVMPI_CallFrame *f = t->frames; 47 | JVMPI_CallFrame *last_frame = f + t->num_frames; 48 | while (f->lineno == -99 && f != last_frame) { 49 | f++; 50 | } 51 | if (f == last_frame) { 52 | continue; 53 | } 54 | 55 | PairCallFrame pair(f->lineno, f->method_id); 56 | hot_methods[pair] += traces[i].count; 57 | } 58 | } 59 | 60 | std::vector sorted_methods; 61 | Sorter sorter; 62 | 63 | sorted_methods.reserve(hot_methods.size()); 64 | 65 | for (auto method = hot_methods.begin(); method != hot_methods.end(); ++ method) { 66 | sorted_methods.emplace_back(method->first, method->second); 67 | } 68 | 69 | std::sort(sorted_methods.begin(), sorted_methods.end(), sorter); 70 | 71 | JVMPI_CallFrame last; 72 | last.method_id = NULL; 73 | last.lineno = 0; 74 | 75 | for (auto method = sorted_methods.begin(); method != sorted_methods.end(); ++ method) { 76 | int count = method->second; 77 | PairCallFrame *f = &(method->first); 78 | JVMPI_CallFrame curr_frame; 79 | curr_frame.lineno = f->first; 80 | curr_frame.method_id = f->second; 81 | if (curr_frame.lineno == last.lineno && 82 | curr_frame.method_id == last.method_id) { 83 | continue; 84 | } 85 | fprintf(file_, "%10d ", count); 86 | PrintStackFrame(&curr_frame); 87 | last = curr_frame; 88 | } 89 | } 90 | 91 | // This method changes the standard class signature "Lfoo/bar;" format 92 | // to a more readable "foo.bar" format. 93 | static void CleanJavaSignature(char *signature_ptr) { 94 | size_t signature_length = strlen(signature_ptr); // ugh! 95 | if (signature_length < 3) { // I'm not going to even try. 96 | return; 97 | } 98 | 99 | signature_ptr[0] = ' '; 100 | for (size_t i = 1; i < signature_length - 1; ++i) { 101 | if (signature_ptr[i] == '/') { 102 | signature_ptr[i] = '.'; 103 | } 104 | } 105 | signature_ptr[signature_length - 1] = '\0'; 106 | } 107 | 108 | // Given a method and a location, this method gets the line number. 109 | // Kind of expensive, comparatively. 110 | jint StackTracesPrinter::GetLineNumber(jmethodID method, jlocation location) { 111 | jint entry_count; 112 | JvmtiScopedPtr table_ptr_ctr(jvmti_); 113 | jint line_number = -1; 114 | 115 | // Shortcut for native methods. 116 | if (location == -1) { 117 | return -1; 118 | } 119 | 120 | int jvmti_error = jvmti_->GetLineNumberTable(method, 121 | &entry_count, 122 | table_ptr_ctr.GetRef()); 123 | 124 | // Go through all the line numbers... 125 | if (JVMTI_ERROR_NONE != jvmti_error) { 126 | table_ptr_ctr.AbandonBecauseOfError(); 127 | } else { 128 | jvmtiLineNumberEntry *table_ptr = table_ptr_ctr.Get(); 129 | if (entry_count > 1) { 130 | jlocation last_location = table_ptr[0].start_location; 131 | for (int l = 1; l < entry_count; l++) { 132 | // ... and if you see one that is in the right place for your 133 | // location, you've found the line number! 134 | if ((location < table_ptr[l].start_location) && 135 | (location >= last_location)) { 136 | line_number = table_ptr[l-1].line_number; 137 | return line_number; 138 | } 139 | last_location = table_ptr[l].start_location; 140 | } 141 | if (location >= last_location) { 142 | return table_ptr[entry_count - 1].line_number; 143 | } 144 | } else if (entry_count == 1) { 145 | line_number = table_ptr[0].line_number; 146 | } 147 | } 148 | return line_number; 149 | } 150 | 151 | bool StackTracesPrinter::GetStackFrameElements(JVMPI_CallFrame *frame, 152 | string *file_name, 153 | string *class_name, 154 | string *method_name, 155 | int *line_number) { 156 | jint error; 157 | JvmtiScopedPtr name_ptr(jvmti_); 158 | 159 | // Get method name, put it in name_ptr 160 | if ((error = jvmti_->GetMethodName(frame->method_id, name_ptr.GetRef(), NULL, 161 | NULL)) != 162 | JVMTI_ERROR_NONE) { 163 | name_ptr.AbandonBecauseOfError(); 164 | if (error == JVMTI_ERROR_INVALID_METHODID) { 165 | static int once = 0; 166 | if (!once) { 167 | once = 1; 168 | fprintf(stderr, "One of your monitoring interfaces " 169 | "is having trouble resolving its stack traces. " 170 | "GetMethodName on a jmethodID involved in a stacktrace " 171 | "resulted in an INVALID_METHODID error which usually " 172 | "indicates its declaring class has been unloaded.\n"); 173 | fprintf(stderr, "Unexpected JVMTI error %d in GetMethodName", error); 174 | } 175 | } 176 | return false; 177 | } 178 | 179 | // Get class name, put it in signature_ptr 180 | jclass declaring_class; 181 | JVMTI_ERROR_1( 182 | jvmti_->GetMethodDeclaringClass(frame->method_id, &declaring_class), 183 | false); 184 | 185 | JvmtiScopedPtr signature_ptr2(jvmti_); 186 | JVMTI_ERROR_CLEANUP_1( 187 | jvmti_->GetClassSignature(declaring_class, signature_ptr2.GetRef(), NULL), 188 | false, signature_ptr2.AbandonBecauseOfError()); 189 | 190 | // Get source file, put it in source_name_ptr 191 | char *filename; 192 | JvmtiScopedPtr source_name_ptr(jvmti_); 193 | static char file_unknown[] = "UnknownFile"; 194 | if (JVMTI_ERROR_NONE != 195 | jvmti_->GetSourceFileName(declaring_class, source_name_ptr.GetRef())) { 196 | source_name_ptr.AbandonBecauseOfError(); 197 | filename = file_unknown; 198 | } else { 199 | filename = source_name_ptr.Get(); 200 | } 201 | 202 | CleanJavaSignature(signature_ptr2.Get()); 203 | 204 | // CleanJavaSignature prepends a ' ' character 205 | *class_name = signature_ptr2.Get() + 1; 206 | *method_name = name_ptr.Get(); 207 | *file_name = filename; 208 | 209 | if (line_number != NULL) { 210 | // TODO(jeremymanson): is frame->lineno correct? GetLineNumber 211 | // expects a BCI. 212 | *line_number = GetLineNumber(frame->method_id, frame->lineno); 213 | } 214 | 215 | return true; 216 | } 217 | 218 | bool StackTracesPrinter::PrintStackFrame(JVMPI_CallFrame *frame) { 219 | if (frame->lineno == -99) { 220 | // This should never happen in a stock hotspot build 221 | return false; 222 | } 223 | 224 | string method_name, class_name, file_name; 225 | int line_num; 226 | GetStackFrameElements(frame, &file_name, &class_name, &method_name, 227 | &line_num); 228 | fprintf(file_, "\t%s.%s(%s:%d)\n", class_name.c_str(), method_name.c_str(), 229 | file_name.c_str(), line_num); 230 | return true; 231 | } 232 | 233 | void StackTracesPrinter::PrintStackTrace(TraceData *trace) { 234 | JVMPI_CallTrace *t = &(trace->trace); 235 | if (t->num_frames < 0) { 236 | // Error trace - don't bother to print it. 237 | return; 238 | } 239 | 240 | fprintf(file_, "%d ", t->num_frames); 241 | for (int i = 0; i < t->num_frames; i++) { 242 | JVMPI_CallFrame *curr_frame = &(t->frames[i]); 243 | PrintStackFrame(curr_frame); 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /src/display.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | #include "globals.h" 7 | #include "profiler.h" 8 | 9 | #ifndef DISPLAY_H 10 | #define DISPLAY_H 11 | 12 | // Some platforms have a ::string class that is different from ::std::string 13 | // (although the interface is the same, of course). On other platforms, 14 | // ::string is the same as ::std::string. 15 | #ifndef HAS_GLOBAL_STRING 16 | using std::string; 17 | #endif 18 | 19 | class StackTracesPrinter { 20 | public: 21 | StackTracesPrinter(FILE *file, jvmtiEnv *jvmti) 22 | : file_(file), jvmti_(jvmti) {} 23 | 24 | void PrintStackTraces(TraceData *traces, int length); 25 | 26 | void PrintLeafHistogram(TraceData *traces, int length); 27 | 28 | private: 29 | FILE *file_; 30 | 31 | jvmtiEnv *jvmti_; 32 | 33 | bool PrintStackFrame(JVMPI_CallFrame *frame); 34 | 35 | void PrintStackTrace(TraceData *trace); 36 | 37 | bool GetStackFrameElements(JVMPI_CallFrame *frame, string *method_name, 38 | string *class_name, string *file_name, 39 | int *line_number); 40 | 41 | jint GetLineNumber(jmethodID method, jlocation location); 42 | 43 | DISALLOW_COPY_AND_ASSIGN(StackTracesPrinter); 44 | }; 45 | 46 | #endif // DISPLAY_H 47 | -------------------------------------------------------------------------------- /src/entry.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include 7 | 8 | #include "globals.h" 9 | #include "profiler.h" 10 | #include "stacktraces.h" 11 | 12 | static Profiler *prof; 13 | FILE *Globals::OutFile; 14 | 15 | void JNICALL OnThreadStart(jvmtiEnv *jvmti_env, JNIEnv *jni_env, 16 | jthread thread) { 17 | IMPLICITLY_USE(jvmti_env); 18 | IMPLICITLY_USE(thread); 19 | Accessors::SetCurrentJniEnv(jni_env); 20 | } 21 | 22 | void JNICALL OnThreadEnd(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread) { 23 | IMPLICITLY_USE(jvmti_env); 24 | IMPLICITLY_USE(jni_env); 25 | IMPLICITLY_USE(thread); 26 | } 27 | 28 | // This has to be here, or the VM turns off class loading events. 29 | // And AsyncGetCallTrace needs class loading events to be turned on! 30 | void JNICALL OnClassLoad(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, 31 | jclass klass) { 32 | IMPLICITLY_USE(jvmti_env); 33 | IMPLICITLY_USE(jni_env); 34 | IMPLICITLY_USE(thread); 35 | IMPLICITLY_USE(klass); 36 | } 37 | 38 | // Calls GetClassMethods on a given class to force the creation of 39 | // jmethodIDs of it. 40 | void CreateJMethodIDsForClass(jvmtiEnv *jvmti, jclass klass) { 41 | jint method_count; 42 | JvmtiScopedPtr methods(jvmti); 43 | jvmtiError e = jvmti->GetClassMethods(klass, &method_count, methods.GetRef()); 44 | if (e != JVMTI_ERROR_NONE && e != JVMTI_ERROR_CLASS_NOT_PREPARED) { 45 | // JVMTI_ERROR_CLASS_NOT_PREPARED is okay because some classes may 46 | // be loaded but not prepared at this point. 47 | JvmtiScopedPtr ksig(jvmti); 48 | JVMTI_ERROR((jvmti->GetClassSignature(klass, ksig.GetRef(), NULL))); 49 | fprintf( 50 | stderr, 51 | "Failed to create method IDs for methods in class %s with error %d ", 52 | ksig.Get(), e); 53 | } 54 | } 55 | 56 | void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jni_env, jthread thread) { 57 | IMPLICITLY_USE(thread); 58 | IMPLICITLY_USE(jni_env); 59 | // Forces the creation of jmethodIDs of the classes that had already 60 | // been loaded (eg java.lang.Object, java.lang.ClassLoader) and 61 | // OnClassPrepare() misses. 62 | jint class_count; 63 | JvmtiScopedPtr classes(jvmti); 64 | JVMTI_ERROR((jvmti->GetLoadedClasses(&class_count, classes.GetRef()))); 65 | jclass *classList = classes.Get(); 66 | for (int i = 0; i < class_count; ++i) { 67 | jclass klass = classList[i]; 68 | CreateJMethodIDsForClass(jvmti, klass); 69 | } 70 | prof->Start(); 71 | } 72 | 73 | void JNICALL OnClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *jni_env, 74 | jthread thread, jclass klass) { 75 | IMPLICITLY_USE(jni_env); 76 | IMPLICITLY_USE(thread); 77 | // We need to do this to "prime the pump", as it were -- make sure 78 | // that all of the methodIDs have been initialized internally, for 79 | // AsyncGetCallTrace. I imagine it slows down class loading a mite, 80 | // but honestly, how fast does class loading have to be? 81 | CreateJMethodIDsForClass(jvmti_env, klass); 82 | } 83 | 84 | void JNICALL OnVMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) { 85 | IMPLICITLY_USE(jvmti_env); 86 | IMPLICITLY_USE(jni_env); 87 | 88 | prof->Stop(); 89 | prof->DumpToFile(Globals::OutFile); 90 | } 91 | 92 | static bool PrepareJvmti(jvmtiEnv *jvmti) { 93 | // Set the list of permissions to do the various internal VM things 94 | // we want to do. 95 | jvmtiCapabilities caps; 96 | 97 | memset(&caps, 0, sizeof(caps)); 98 | caps.can_generate_all_class_hook_events = 1; 99 | 100 | caps.can_get_source_file_name = 1; 101 | caps.can_get_line_numbers = 1; 102 | caps.can_get_bytecodes = 1; 103 | caps.can_get_constant_pool = 1; 104 | 105 | jvmtiCapabilities all_caps; 106 | int error; 107 | 108 | if (JVMTI_ERROR_NONE == 109 | (error = jvmti->GetPotentialCapabilities(&all_caps))) { 110 | // This makes sure that if we need a capability, it is one of the 111 | // potential capabilities. The technique isn't wonderful, but it 112 | // is compact and as likely to be compatible between versions as 113 | // anything else. 114 | char *has = reinterpret_cast(&all_caps); 115 | const char *should_have = reinterpret_cast(&caps); 116 | for (int i = 0; i < sizeof(all_caps); i++) { 117 | if ((should_have[i] != 0) && (has[i] == 0)) { 118 | return false; 119 | } 120 | } 121 | 122 | // This adds the capabilities. 123 | if ((error = jvmti->AddCapabilities(&caps)) != JVMTI_ERROR_NONE) { 124 | fprintf(stderr, "Failed to add capabilities with error %d\n", error); 125 | return false; 126 | } 127 | } 128 | return true; 129 | } 130 | 131 | static bool RegisterJvmti(jvmtiEnv *jvmti) { 132 | // Create the list of callbacks to be called on given events. 133 | jvmtiEventCallbacks *callbacks = new jvmtiEventCallbacks(); 134 | memset(callbacks, 0, sizeof(jvmtiEventCallbacks)); 135 | 136 | callbacks->ThreadStart = &OnThreadStart; 137 | callbacks->ThreadEnd = &OnThreadEnd; 138 | callbacks->VMInit = &OnVMInit; 139 | callbacks->VMDeath = &OnVMDeath; 140 | 141 | callbacks->ClassLoad = &OnClassLoad; 142 | callbacks->ClassPrepare = &OnClassPrepare; 143 | 144 | JVMTI_ERROR_1( 145 | (jvmti->SetEventCallbacks(callbacks, sizeof(jvmtiEventCallbacks))), 146 | false); 147 | 148 | jvmtiEvent events[] = {JVMTI_EVENT_CLASS_LOAD, JVMTI_EVENT_CLASS_PREPARE, 149 | JVMTI_EVENT_THREAD_END, JVMTI_EVENT_THREAD_START, 150 | JVMTI_EVENT_VM_DEATH, JVMTI_EVENT_VM_INIT}; 151 | 152 | size_t num_events = sizeof(events) / sizeof(jvmtiEvent); 153 | 154 | // Enable the callbacks to be triggered when the events occur. 155 | // Events are enumerated in jvmstatagent.h 156 | for (int i = 0; i < num_events; i++) { 157 | JVMTI_ERROR_1( 158 | (jvmti->SetEventNotificationMode(JVMTI_ENABLE, events[i], NULL)), 159 | false); 160 | } 161 | 162 | return true; 163 | } 164 | 165 | #define POSITIVE(x) (static_cast(x > 0 ? x : 0)) 166 | 167 | static void SetFileFromOption(char *equals) { 168 | char *name_begin = equals + 1; 169 | char *name_end; 170 | if ((name_end = strchr(equals, ',')) == NULL) { 171 | name_end = equals + strlen(equals); 172 | } 173 | size_t len = POSITIVE(name_end - name_begin); 174 | char *file_name = new char[len]; 175 | for(int i = 0; i < len; ++i){ 176 | file_name[i] = '\0'; 177 | } 178 | strcpy(file_name, name_begin); 179 | if (strcmp(file_name, "stderr") == 0) { 180 | Globals::OutFile = stderr; 181 | } else if (strcmp(file_name, "stdout") == 0) { 182 | Globals::OutFile = stdout; 183 | } else { 184 | Globals::OutFile = fopen(file_name, "w+"); 185 | if (Globals::OutFile == NULL) { 186 | fprintf(stderr, "Could not open file %s: ", file_name); 187 | perror(NULL); 188 | exit(1); 189 | } 190 | } 191 | 192 | delete[] file_name; 193 | } 194 | 195 | static void ParseArguments(char *options) { 196 | char *key = options; 197 | for (char *next = options; next != NULL; 198 | next = strchr((key = next + 1), ',')) { 199 | char *equals = strchr(key, '='); 200 | if (equals == NULL) { 201 | fprintf(stderr, "No value for key %s\n", key); 202 | continue; 203 | } 204 | if (strncmp(key, "file", POSITIVE(equals - key)) == 0) { 205 | SetFileFromOption(equals); 206 | } 207 | } 208 | 209 | if (Globals::OutFile == NULL) { 210 | char path[PATH_MAX]; 211 | if (getcwd(path, PATH_MAX) == NULL) { 212 | fprintf(stderr, "cwd too long?\n"); 213 | exit(0); 214 | } 215 | size_t pathlen = strlen(path); 216 | strncat(path, "/", PATH_MAX - (pathlen++)); 217 | strncat(path, kDefaultOutFile, PATH_MAX - pathlen); 218 | Globals::OutFile = fopen(path, "w+"); 219 | } 220 | } 221 | 222 | AGENTEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, 223 | void *reserved) { 224 | IMPLICITLY_USE(reserved); 225 | int err; 226 | jvmtiEnv *jvmti; 227 | ParseArguments(options); 228 | 229 | Accessors::Init(); 230 | 231 | if ((err = (vm->GetEnv(reinterpret_cast(&jvmti), JVMTI_VERSION))) != 232 | JNI_OK) { 233 | fprintf(stderr, "JNI Error %d\n", err); 234 | return 1; 235 | } 236 | 237 | if (!PrepareJvmti(jvmti)) { 238 | fprintf(stderr, "Failed to initialize JVMTI. Continuing...\n"); 239 | return 0; 240 | } 241 | 242 | if (!RegisterJvmti(jvmti)) { 243 | fprintf(stderr, "Failed to enable JVMTI events. Continuing...\n"); 244 | // We fail hard here because we may have failed in the middle of 245 | // registering callbacks, which will leave the system in an 246 | // inconsistent state. 247 | return 1; 248 | } 249 | 250 | Asgct::SetAsgct(Accessors::GetJvmFunction("AsyncGetCallTrace")); 251 | 252 | prof = new Profiler(jvmti); 253 | 254 | return 0; 255 | } 256 | 257 | AGENTEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) { 258 | IMPLICITLY_USE(vm); 259 | Accessors::Destroy(); 260 | } 261 | -------------------------------------------------------------------------------- /src/globals.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #ifdef __APPLE__ 7 | #include 8 | #endif 9 | 10 | 11 | #ifndef GLOBALS_H 12 | #define GLOBALS_H 13 | 14 | #define AGENTEXPORT __attribute__((visibility("default"))) JNIEXPORT 15 | 16 | // Gets us around -Wunused-parameter 17 | #define IMPLICITLY_USE(x) (void) x; 18 | 19 | // Wrap JVMTI functions in this in functions that expect a return 20 | // value and require cleanup. 21 | #define JVMTI_ERROR_CLEANUP_1(error, retval, cleanup) \ 22 | { \ 23 | int err; \ 24 | if ((err = (error)) != JVMTI_ERROR_NONE) { \ 25 | fprintf(stderr, "JVMTI error %d\n", err); \ 26 | cleanup; \ 27 | return (retval); \ 28 | } \ 29 | } 30 | 31 | // Wrap JVMTI functions in this in functions that expect a return value. 32 | #define JVMTI_ERROR_1(error, retval) \ 33 | JVMTI_ERROR_CLEANUP_1(error, retval, /* nothing */) 34 | 35 | // Wrap JVMTI functions in this in void functions. 36 | #define JVMTI_ERROR(error) JVMTI_ERROR_CLEANUP(error, /* nothing */) 37 | 38 | // Wrap JVMTI functions in this in void functions that require cleanup. 39 | #define JVMTI_ERROR_CLEANUP(error, cleanup) \ 40 | { \ 41 | int err; \ 42 | if ((err = (error)) != JVMTI_ERROR_NONE) { \ 43 | fprintf(stderr, "JVMTI error %d\n", err); \ 44 | cleanup; \ 45 | return; \ 46 | } \ 47 | } 48 | 49 | #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ 50 | TypeName(const TypeName&); \ 51 | void operator=(const TypeName&) 52 | 53 | #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ 54 | TypeName(); \ 55 | DISALLOW_COPY_AND_ASSIGN(TypeName) 56 | 57 | // Short version: reinterpret_cast produces undefined behavior in many 58 | // cases where memcpy doesn't. 59 | template 60 | inline Dest bit_cast(const Source& source) { 61 | // Compile time assertion: sizeof(Dest) == sizeof(Source) 62 | // A compile error here means your Dest and Source have different sizes. 63 | typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1] 64 | __attribute__ ((unused)); 65 | 66 | Dest dest; 67 | memcpy(&dest, &source, sizeof(dest)); 68 | return dest; 69 | } 70 | 71 | template 72 | class JvmtiScopedPtr { 73 | public: 74 | explicit JvmtiScopedPtr(jvmtiEnv *jvmti) 75 | : jvmti_(jvmti), 76 | ref_(NULL) {} 77 | 78 | JvmtiScopedPtr(jvmtiEnv *jvmti, T *ref) 79 | : jvmti_(jvmti), 80 | ref_(ref) {} 81 | 82 | ~JvmtiScopedPtr() { 83 | if (NULL != ref_) { 84 | JVMTI_ERROR(jvmti_->Deallocate((unsigned char *)ref_)); 85 | } 86 | } 87 | 88 | T **GetRef() { 89 | assert(ref_ == NULL); 90 | return &ref_; 91 | } 92 | 93 | T *Get() { 94 | return ref_; 95 | } 96 | 97 | void AbandonBecauseOfError() { 98 | ref_ = NULL; 99 | } 100 | 101 | private: 102 | jvmtiEnv *jvmti_; 103 | T *ref_; 104 | 105 | DISALLOW_IMPLICIT_CONSTRUCTORS(JvmtiScopedPtr); 106 | }; 107 | 108 | // Accessors for a JNIEnv for this thread. 109 | class Accessors { 110 | public: 111 | #ifdef __APPLE__ 112 | // As of 8/2013, Darwin doesn't support __thread. We love you, 113 | // Darwin! 114 | static void SetCurrentJniEnv(JNIEnv *env) { 115 | static bool once = false; 116 | int err; 117 | if ((err = pthread_setspecific(key_, reinterpret_cast(env))) != 0 && 118 | !once) { 119 | once = true; 120 | perror("Was not able to set JNIEnv for at least one thread: "); 121 | } 122 | } 123 | 124 | static JNIEnv *CurrentJniEnv() { 125 | JNIEnv *p = reinterpret_cast(pthread_getspecific(key_)); 126 | return p; 127 | } 128 | 129 | static void Init() { 130 | if (pthread_key_create(&key_, NULL) != 0) { 131 | perror("Unable to init thread-local storage. Profiling won't work:"); 132 | } 133 | } 134 | 135 | static void Destroy() { 136 | if (pthread_key_delete(key_) != 0) { 137 | // Meh. 138 | } 139 | } 140 | #else 141 | static void SetCurrentJniEnv(JNIEnv *env) { 142 | env_ = env; 143 | } 144 | 145 | static JNIEnv *CurrentJniEnv() { 146 | return env_; 147 | } 148 | 149 | static void Init() { 150 | } 151 | 152 | static void Destroy() { 153 | } 154 | #endif 155 | 156 | template 157 | static inline FunctionType GetJvmFunction(const char *function_name) { 158 | // get handle to library 159 | static void *handle = dlopen("libjvm.so", RTLD_LAZY); 160 | if (handle == NULL) { 161 | return NULL; 162 | } 163 | 164 | // get address of function, return null if not found 165 | return bit_cast(dlsym(handle, function_name)); 166 | } 167 | 168 | private: 169 | #ifdef __APPLE__ 170 | static pthread_key_t key_; 171 | #else 172 | // This is very dangerous. __thread is not async-safe when used in 173 | // a shared library, because it calls malloc the first time a given 174 | // thread accesses it. This is unlikely to cause problems in 175 | // straightforward Java apps, but a real fix involves either a fix 176 | // to glibc or to the Java launcher, and casual users will have a 177 | // hard time with this. 178 | static __thread JNIEnv *env_; 179 | #endif 180 | }; 181 | 182 | #if defined(__GNUC__) && (defined(i386) || defined(__x86_64)) 183 | #if defined(__x86_64__) 184 | #define __CAS_INSTR "lock; cmpxchgq %1,%2" 185 | #define __ADD_INSTR "lock; xaddq %0,%1" 186 | #else // defined(__x86_64__) 187 | #define __CAS_INSTR "lock; cmpxchgl %1,%2" 188 | #define __ADD_INSTR "lock; xaddl %0,%1" 189 | #endif // defined(__x86_64__) 190 | #else // defined(__GNUC__) && (defined(i386) || defined(__x86_64)) 191 | #error \ 192 | "Cannot compile with non-x86. Add support for atomic ops, if you want it" 193 | #endif // defined(__GNUC__) && (defined(i386) || defined(__x86_64)) 194 | 195 | inline intptr_t NoBarrier_CompareAndSwap(volatile intptr_t *ptr, 196 | intptr_t old_value, 197 | intptr_t new_value) { 198 | intptr_t prev; 199 | __asm__ __volatile__(__CAS_INSTR 200 | : "=a"(prev) 201 | : "q"(new_value), "m"(*ptr), "0"(old_value) 202 | : "cc", "memory"); 203 | return prev; 204 | } 205 | 206 | inline intptr_t NoBarrier_AtomicIncrement(volatile intptr_t* ptr, 207 | intptr_t increment) { 208 | intptr_t temp = increment; 209 | __asm__ __volatile__(__ADD_INSTR 210 | : "+r" (temp), "+m" (*ptr) 211 | : : "cc", "memory"); 212 | // temp now contains the previous value of *ptr 213 | return temp + increment; 214 | } 215 | 216 | #undef __CAS_INSTR 217 | #undef __ADD_INSTR 218 | 219 | // Things that should probably be user-configurable 220 | 221 | // Number of times per second that we profile 222 | static const int kNumInterrupts = 100; 223 | 224 | // Maximum number of stack traces 225 | static const int kMaxStackTraces = 3000; 226 | 227 | // Maximum number of frames to store from the stack traces sampled. 228 | static const int kMaxFramesToCapture = 128; 229 | 230 | // Location where the data are dumped. 231 | static const char kDefaultOutFile[] = "traces.txt"; 232 | 233 | class Globals { 234 | public: 235 | static FILE *OutFile; 236 | }; 237 | 238 | #endif // GLOBALS_H 239 | -------------------------------------------------------------------------------- /src/profiler.cc: -------------------------------------------------------------------------------- 1 | #include "profiler.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "display.h" 9 | 10 | #ifdef __APPLE__ 11 | // See comment in Accessors class 12 | pthread_key_t Accessors::key_; 13 | #else 14 | __thread JNIEnv * Accessors::env_; 15 | #endif 16 | 17 | ASGCTType Asgct::asgct_; 18 | 19 | TraceData Profiler::traces_[kMaxStackTraces]; 20 | 21 | JVMPI_CallFrame Profiler::frame_buffer_[kMaxStackTraces][kMaxFramesToCapture]; 22 | 23 | int Profiler::failures_[kNumCallTraceErrors + 1]; 24 | 25 | namespace { 26 | 27 | // Helper class to store and reset errno when in a signal handler. 28 | class ErrnoRaii { 29 | public: 30 | ErrnoRaii() { stored_errno_ = errno; } 31 | ~ErrnoRaii() { errno = stored_errno_; } 32 | 33 | private: 34 | int stored_errno_; 35 | 36 | DISALLOW_COPY_AND_ASSIGN(ErrnoRaii); 37 | }; 38 | } // namespace 39 | 40 | static uint64_t CalculateHash(JVMPI_CallTrace *trace, int skip) { 41 | // Make hash-value 42 | uint64_t h = 0; 43 | for (int i = skip; i < trace->num_frames; i++) { 44 | h += reinterpret_cast(trace->frames[i].method_id); 45 | h += h << 10; 46 | h ^= h >> 6; 47 | h += static_cast(trace->frames[i].lineno); 48 | h += h << 10; 49 | h ^= h >> 6; 50 | } 51 | h += h << 3; 52 | h ^= h >> 11; 53 | return h; 54 | } 55 | 56 | void Profiler::Handle(int signum, siginfo_t *info, void *context) { 57 | IMPLICITLY_USE(signum); 58 | IMPLICITLY_USE(info); 59 | ErrnoRaii err_storage; // stores and resets errno 60 | 61 | JNIEnv *env = Accessors::CurrentJniEnv(); 62 | if (env == NULL) { 63 | // native / JIT / GC thread, which isn't attached to the JVM. 64 | failures_[0]++; 65 | return; 66 | } 67 | 68 | JVMPI_CallTrace trace; 69 | JVMPI_CallFrame frames[kMaxFramesToCapture]; 70 | // We have to set every byte to 0 instead of just initializing the 71 | // individual fields, because the structs might be padded, and we 72 | // use memcmp on it later. We can't use memset, because it isn't 73 | // async-safe. 74 | char *base = reinterpret_cast(frames); 75 | for (char *p = base; p < base + sizeof(JVMPI_CallFrame) * kMaxFramesToCapture; 76 | p++) { 77 | *p = 0; 78 | } 79 | 80 | trace.frames = frames; 81 | trace.env_id = env; 82 | 83 | ASGCTType asgct = Asgct::GetAsgct(); 84 | (*asgct)(&trace, kMaxFramesToCapture, context); 85 | 86 | if (trace.num_frames < 0) { 87 | int idx = -trace.num_frames; 88 | if (idx > kNumCallTraceErrors) { 89 | return; 90 | } 91 | failures_[idx]++; 92 | } 93 | 94 | uint64_t hash_val = CalculateHash(&trace, 0); 95 | uint64_t idx = hash_val % kMaxStackTraces; 96 | 97 | uint64_t i = idx; 98 | 99 | do { 100 | intptr_t *count = &(traces_[i].count); 101 | if (*count == 0 && (NoBarrier_CompareAndSwap(count, 0, 1) == 0)) { 102 | // memcpy is not async safe 103 | JVMPI_CallFrame *fb = frame_buffer_[i]; 104 | for (int frame_num = 0; frame_num < trace.num_frames; ++frame_num) { 105 | base = reinterpret_cast(&(fb[frame_num])); 106 | // Make sure the padding is all set to 0. 107 | for (char *p = base; p < base + sizeof(JVMPI_CallFrame); p++) { 108 | *p = 0; 109 | } 110 | fb[frame_num].lineno = trace.frames[frame_num].lineno; 111 | fb[frame_num].method_id = trace.frames[frame_num].method_id; 112 | } 113 | 114 | traces_[i].trace.frames = fb; 115 | traces_[i].trace.num_frames = trace.num_frames; 116 | return; 117 | } 118 | 119 | if ((traces_[i].trace.num_frames == trace.num_frames) && 120 | (memcmp(traces_[i].trace.frames, trace.frames, 121 | sizeof(JVMPI_CallFrame) * kMaxFramesToCapture) == 0)) { 122 | NoBarrier_AtomicIncrement(&(traces_[i].count), 1); 123 | return; 124 | } 125 | 126 | i = (i + 1) % kMaxStackTraces; 127 | } while (i != idx); 128 | } 129 | 130 | // This method schedules the SIGPROF timer to go off every sec 131 | // seconds, usec microseconds. 132 | bool SignalHandler::SetSigprofInterval(int sec, int usec) { 133 | static struct itimerval timer; 134 | timer.it_interval.tv_sec = sec; 135 | timer.it_interval.tv_usec = usec; 136 | timer.it_value = timer.it_interval; 137 | if (setitimer(ITIMER_PROF, &timer, 0) == -1) { 138 | fprintf(stderr, "Scheduling profiler interval failed with error %d\n", 139 | errno); 140 | return false; 141 | } 142 | return true; 143 | } 144 | 145 | struct sigaction SignalHandler::SetAction(void (*action)(int, siginfo_t *, 146 | void *)) { 147 | struct sigaction sa; 148 | sa.sa_handler = NULL; 149 | sa.sa_sigaction = action; 150 | sa.sa_flags = SA_RESTART | SA_SIGINFO; 151 | 152 | sigemptyset(&sa.sa_mask); 153 | 154 | struct sigaction old_handler; 155 | if (sigaction(SIGPROF, &sa, &old_handler) != 0) { 156 | fprintf(stderr, "Scheduling profiler action failed with error %d\n", errno); 157 | return old_handler; 158 | } 159 | 160 | return old_handler; 161 | } 162 | 163 | bool Profiler::Start() { 164 | int usec_wait = 1000000 / kNumInterrupts; 165 | 166 | memset(traces_, 0, sizeof(traces_)); 167 | memset(frame_buffer_, 0, sizeof(frame_buffer_)); 168 | memset(failures_, 0, sizeof(failures_)); 169 | 170 | // old_action_ is stored, but never used. This is in case of future 171 | // refactorings that need it. 172 | old_action_ = handler_.SetAction(&Profiler::Handle); 173 | return handler_.SetSigprofInterval(0, usec_wait); 174 | } 175 | 176 | void Profiler::Stop() { 177 | handler_.SetSigprofInterval(0, 0); 178 | // Breaks encapsulation, but whatever. 179 | signal(SIGPROF, SIG_IGN); 180 | } 181 | 182 | static int CompareTraceData(const void *v1, const void *v2) { 183 | const TraceData *tr1 = reinterpret_cast(v1); 184 | const TraceData *tr2 = reinterpret_cast(v2); 185 | return tr1->count > tr2->count ? 1 : (tr1->count < tr2->count ? -1 : 0); 186 | } 187 | 188 | void Profiler::DumpToFile(FILE *file) { 189 | qsort(traces_, kMaxStackTraces, sizeof(TraceData), &CompareTraceData); 190 | 191 | StackTracesPrinter printer(file, jvmti_); 192 | 193 | printer.PrintStackTraces(traces_, kMaxStackTraces); 194 | printer.PrintLeafHistogram(traces_, kMaxStackTraces); 195 | 196 | fprintf(file, "Failures:\n" 197 | "Instances Reason\n" 198 | "%-12d Non Java thread (GC/JIT/pure native)\n" 199 | "%-12d Stack walking disabled\n" 200 | "%-12d Java thread doing GC work\n" 201 | "%-12d In native code, unknown frame.\n" 202 | "%-12d In native code, non-walkable frame (you are likely to" 203 | " get this for native code).\n" 204 | "%-12d In Java code, unknown frame.\n" 205 | "%-12d In Java code, non-walkable frame (for example," 206 | " if the frame is being constructed).\n" 207 | "%-12d Unknown thread state.\n" 208 | "%-12d Thread exiting.\n" 209 | "%-12d Thread in deoptimization" 210 | " (for dynamic recompilation).\n" 211 | "%-12d Thread in a safepoint" 212 | " (such as a stop-the-world GC).\n", 213 | failures_[-kNativeStackTrace], failures_[-kNoClassLoad], 214 | failures_[-kGcTraceError], failures_[-kUnknownNotJava], 215 | failures_[-kNotWalkableFrameNotJava], failures_[-kUnknownJava], 216 | failures_[-kNotWalkableFrameJava], failures_[-kUnknownState], 217 | failures_[-kTicksThreadExit], failures_[-kDeoptHandler], 218 | failures_[-kSafepoint]); 219 | } 220 | -------------------------------------------------------------------------------- /src/profiler.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "globals.h" 4 | #include "stacktraces.h" 5 | 6 | #ifndef PROFILER_H 7 | #define PROFILER_H 8 | 9 | class SignalHandler { 10 | public: 11 | SignalHandler() {} 12 | 13 | struct sigaction SetAction(void (*sigaction)(int, siginfo_t *, void *)); 14 | 15 | bool SetSigprofInterval(int sec, int usec); 16 | 17 | private: 18 | DISALLOW_COPY_AND_ASSIGN(SignalHandler); 19 | }; 20 | 21 | struct TraceData { 22 | intptr_t count; 23 | JVMPI_CallTrace trace; 24 | }; 25 | 26 | class Profiler { 27 | public: 28 | explicit Profiler(jvmtiEnv *jvmti) : jvmti_(jvmti) {} 29 | 30 | bool Start(); 31 | 32 | void Stop(); 33 | 34 | void DumpToFile(FILE *file); 35 | 36 | private: 37 | jvmtiEnv *jvmti_; 38 | 39 | SignalHandler handler_; 40 | 41 | struct sigaction old_action_; 42 | 43 | static TraceData traces_[kMaxStackTraces]; 44 | 45 | static JVMPI_CallFrame frame_buffer_[kMaxStackTraces][kMaxFramesToCapture]; 46 | 47 | static int failures_[kNumCallTraceErrors + 1]; // they are indexed from 1 48 | 49 | static void Handle(int signum, siginfo_t *info, void *context); 50 | 51 | DISALLOW_COPY_AND_ASSIGN(Profiler); 52 | }; 53 | 54 | #endif // PROFILER_H 55 | -------------------------------------------------------------------------------- /src/stacktraces.h: -------------------------------------------------------------------------------- 1 | #include "globals.h" 2 | 3 | #ifndef STACKTRACES_H 4 | #define STACKTRACES_H 5 | 6 | // To implement the profiler, we rely on an undocumented function called 7 | // AsyncGetCallTrace in the Java virtual machine, which is used by Sun 8 | // Studio Analyzer, and designed to get stack traces asynchronously. 9 | // It uses the old JVMPI interface, so we must reconstruct the 10 | // neccesary bits of that here. 11 | 12 | // For a Java frame, the lineno is the bci of the method, and the 13 | // method_id is the jmethodID. For a JNI method, the lineno is -3, 14 | // and the method_id is the jmethodID. 15 | typedef struct { 16 | jint lineno; 17 | jmethodID method_id; 18 | } JVMPI_CallFrame; 19 | 20 | typedef struct { 21 | // JNIEnv of the thread from which we grabbed the trace 22 | JNIEnv *env_id; 23 | // < 0 if the frame isn't walkable 24 | jint num_frames; 25 | // The frames, callee first. 26 | JVMPI_CallFrame *frames; 27 | } JVMPI_CallTrace; 28 | 29 | typedef void (*ASGCTType)(JVMPI_CallTrace *, jint, void *); 30 | 31 | const int kNumCallTraceErrors = 10; 32 | 33 | enum CallTraceErrors { 34 | // 0 is reserved for native stack traces. This includes JIT and GC threads. 35 | kNativeStackTrace = 0, 36 | // The JVMTI class load event is disabled (a prereq for AsyncGetCallTrace) 37 | kNoClassLoad = -1, 38 | // For traces in GC 39 | kGcTraceError = -2, 40 | // We can't figure out what the top (non-Java) frame is 41 | kUnknownNotJava = -3, 42 | // The frame is not Java and not walkable 43 | kNotWalkableFrameNotJava = -4, 44 | // We can't figure out what the top Java frame is 45 | kUnknownJava = -5, 46 | // The frame is Java and not walkable 47 | kNotWalkableFrameJava = -6, 48 | // Unknown thread state (not in Java or native or the VM) 49 | kUnknownState = -7, 50 | // The JNIEnv is bad - this likely means the thread has exited 51 | kTicksThreadExit = -8, 52 | // The thread is being deoptimized, so the stack is borked 53 | kDeoptHandler = -9, 54 | // We're in a safepoint, and can't do reporting 55 | kSafepoint = -10, 56 | }; 57 | 58 | class Asgct { 59 | public: 60 | static void SetAsgct(ASGCTType asgct) { 61 | asgct_ = asgct; 62 | } 63 | 64 | // AsyncGetCallTrace function, to be dlsym'd. 65 | static ASGCTType GetAsgct() { return asgct_; } 66 | 67 | private: 68 | static ASGCTType asgct_; 69 | 70 | DISALLOW_IMPLICIT_CONSTRUCTORS(Asgct); 71 | }; 72 | 73 | #endif // STACKTRACES_H 74 | --------------------------------------------------------------------------------