Repository: odnoklassniki/jvmti-tools Branch: master Commit: 477d2391b02f Files: 10 Total size: 45.3 KB Directory structure: gitextract_hu58l01j/ ├── .gitignore ├── LICENSE ├── README.md ├── antimodule/ │ └── antimodule.cpp ├── faketime/ │ └── faketime.cpp ├── heapsampler/ │ └── heapsampler.cpp ├── richNPE/ │ └── richNPE.cpp ├── stackframe/ │ ├── StackFrame.java │ └── stackframe.cpp └── vmtrace/ └── vmtrace.cpp ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Compiled class file *.class # Log file *.log # BlueJ files *.ctxt # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.jar *.war *.nar *.ear *.zip *.tar.gz *.rar # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # JVM TI tools Collection of small Java serviceability improvements based on [JVM Tool Interface](https://docs.oracle.com/en/java/javase/11/docs/specs/jvmti.html). - [richNPE](#richnpe) - [vmtrace](#vmtrace) - [antimodule](#antimodule) - [heapsampler](#heapsampler) - [faketime](#faketime) ## richNPE Enhances `NullPointerException` thrown by JVM with a detailed error message. For example, there are several reasons why the following code may throw `NullPointerException`: long value = source.map().get(key); Either - `source` is null, or - `map()` returns null, or - `get()` returns null and the subsequent unboxing fails. The standard JDK exception message does not give a clue which expression exactly caused NPE, but when using this tool, the message will look like java.lang.NullPointerException: Called method 'get()' on null object at bci 19 While [JDK-8218628](https://bugs.openjdk.java.net/browse/JDK-8218628) is going to be implemented in JDK 13, the given agent improves NPE messages for existing JDK 8-12. #### Compilation # Linux g++ -O2 -fPIC -shared -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -olibrichNPE.so richNPE.cpp # Windows cl /O2 /LD /I "%JAVA_HOME%/include" -I "%JAVA_HOME%/include/win32" richNPE.cpp #### Usage java -agentpath:/path/to/librichNPE.so MainClass ## vmtrace Traces basic JVM events like - Thread started / terminated - GC started / finished - Class loading / class prepared - Method compiled / unloaded - Dynamic code generated #### Example output ```text [0.05588] Method compiled: java/lang/String. (1056 bytes) [0.05597] Loading class: java/io/FileOutputStream$1 (557 bytes) [0.05600] Class prepared: java/io/FileOutputStream$1 [0.05602] Method compiled: java/lang/String.hashCode (512 bytes) [0.05618] Thread started: main [0.05622] Loading class: sun/launcher/LauncherHelper (14692 bytes) [0.05640] Dynamic code generated: I2C/C2I adapters(0xabbebebea0000000)@0x00000000032c38a0 (392 bytes) [0.05642] Dynamic code generated: I2C/C2I adapters(0xbebebea0)@0x00000000032c36a0 (376 bytes) ... ``` #### Compilation # Linux g++ -O2 -fPIC -shared -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -olibvmtrace.so vmtrace.cpp # Windows cl /O2 /LD /I "%JAVA_HOME%/include" -I "%JAVA_HOME%/include/win32" vmtrace.cpp #### Usage java -agentpath:/path/to/libvmtrace.so[=output.log] MainClass The log will be written to the file specified in the agent arguments, or to `stderr` if no arguments given. ## antimodule Removes Jigsaw restrictions in JDK 9+ by opening and exporting all JDK modules to the unnamed module. This allows Reflection access to all JDK private fields and methods with no warnings, even when `--illegal-access=deny` option specified. This also makes all JDK internal classes like `sun.nio.ch.DirectBuffer` accessible by the unnamed module. The agent is helpful for running older Java applications on JDK 9+ when application uses private APIs. #### Compilation # Linux g++ -O2 -fPIC -shared -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -olibantimodule.so antimodule.cpp # Windows cl /O2 /LD /I "%JAVA_HOME%/include" -I "%JAVA_HOME%/include/win32" antimodule.cpp #### Usage java -agentpath:/path/to/libantimodule.so MainClass ## heapsampler The example of low-overhead heap allocation profiler based on [JEP 331](https://openjdk.java.net/jeps/331). Requires JDK 11 or later. #### Example output The output is generated in collapsed stacktraces format suitable for generating [Flame Graphs](https://github.com/brendangregg/FlameGraph/). ```text Allocate.main;java.lang.Long.valueOf;java.lang.Long 49 Allocate.main;java.lang.Object[] 31 java.lang.Thread.run;jdk.internal.misc.Signal$1.run;java.lang.Terminator$1.handle;java.lang.Class 1 jdk.internal.misc.Signal.dispatch;java.lang.Class 1 ``` See [async-profiler](https://github.com/jvm-profiling-tools/async-profiler) for more information about allocation profiling and Flame Graphs. Note that `heapsampler` works only on JDK 11+, while `async-profiler` is capable of generating allocation profiles on JDK 7+. #### Compilation # Linux g++ -O2 -fPIC -shared -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -olibheapsampler.so heapsampler.cpp # Windows cl /O2 /LD /I "%JAVA_HOME%/include" -I "%JAVA_HOME%/include/win32" heapsampler.cpp #### Usage java -agentpath:/path/to/libheapsampler.so[=interval] MainClass > output.txt The agent can be also loaded dynamically in run-time: jcmd JVMTI.agent_load /path/to/libheapsampler.so [interval] The optional `interval` argument specifies the sampling interval in bytes. The default value is 512 KB. The output is printed on `stdout`. ## faketime Changes current date/time for a Java application without affecting system date/time. The agent rebinds the native entry for `System.currentTimeMillis` and related methods and adds the specified offset to the times returned by these methods. #### Compilation # Linux g++ -O2 -fPIC -shared -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -olibfaketime.so faketime.cpp # Windows cl /O2 /LD /I "%JAVA_HOME%/include" -I "%JAVA_HOME%/include/win32" faketime.cpp #### Usage java -agentpath:/path/to/libfaketime.so=timestamp|+-offset MainClass where the agent argument is either - absolute `timestamp` in milliseconds from Epoch, or - relative `offset` in milliseconds, if `offset` starts with `+` or `-` Since `System.currentTimeMillis` is a JVM intrinsic method, it's also required to disable the corresponding intrinsic to make sure the JNI method is called: java -XX:+UnlockDiagnosticVMOptions -XX:DisableIntrinsic=_currentTimeMillis -XX:CompileCommand=dontinline,java.lang.System::currentTimeMillis ================================================ FILE: antimodule/antimodule.cpp ================================================ /* * Copyright 2019 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include void JNICALL VMInit(jvmtiEnv* jvmti, JNIEnv* env, jthread thread) { jclass Module = env->FindClass("java/lang/Module"); if (Module == NULL) { // Seems like pre-module JDK env->ExceptionClear(); return; } jmethodID getPackages = env->GetMethodID(Module, "getPackages", "()Ljava/util/Set;"); jmethodID getUnnamedModule = env->GetMethodID( env->FindClass("java/lang/ClassLoader"), "getUnnamedModule", "()Ljava/lang/Module;"); jmethodID toString = env->GetMethodID( env->FindClass("java/lang/Object"), "toString", "()Ljava/lang/String;"); // Get unnamed module of the current thread's ClassLoader jvmtiThreadInfo thread_info; jvmti->GetThreadInfo(NULL, &thread_info); jobject unnamed_module = env->CallObjectMethod(thread_info.context_class_loader, getUnnamedModule); jint module_count = 0; jobject* modules = NULL; jvmti->GetAllModules(&module_count, &modules); // Scan all loaded modules for (int i = 0; i < module_count; i++) { jvmti->AddModuleReads(modules[i], unnamed_module); // Get all module packages as one string: "[java.lang, java.io, ...]" jobject packages = env->CallObjectMethod(modules[i], getPackages); jstring str = (jstring) env->CallObjectMethod(packages, toString); char* c_str = (char*) env->GetStringUTFChars(str, NULL); if (c_str == NULL) continue; // Export and open every package to the unnamed module char* package = strtok(c_str + 1, ", ]"); while (package != NULL) { jvmti->AddModuleExports(modules[i], package, unnamed_module); jvmti->AddModuleOpens(modules[i], package, unnamed_module); package = strtok(NULL, ", ]"); } env->ReleaseStringUTFChars(str, c_str); } jvmti->Deallocate((unsigned char*) modules); } JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { jvmtiEnv* jvmti; vm->GetEnv((void**) &jvmti, JVMTI_VERSION_1_0); jvmtiEventCallbacks callbacks = {0}; callbacks.VMInit = VMInit; jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL); return 0; } ================================================ FILE: faketime/faketime.cpp ================================================ /* * Copyright 2020 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include static jlong (*real_time_millis)(JNIEnv*, jclass) = NULL; static jlong (*real_nano_time_adjustment)(JNIEnv*, jclass, jlong) = NULL; static jlong offset_millis = 0; jlong JNICALL fake_time_millis(JNIEnv* env, jclass cls) { return real_time_millis(env, cls) + offset_millis; } jlong JNICALL fake_nano_time_adjustment(JNIEnv* env, jclass cls, jlong offset_seconds) { return real_nano_time_adjustment(env, cls, offset_seconds) + offset_millis * 1000000; } void JNICALL NativeMethodBind(jvmtiEnv* jvmti, JNIEnv* env, jthread thread, jmethodID method, void* address, void** new_address_ptr) { char* name; if (jvmti->GetMethodName(method, &name, NULL, NULL) == 0) { if (real_time_millis == NULL && strcmp(name, "currentTimeMillis") == 0) { real_time_millis = (jlong (*)(JNIEnv*, jclass)) address; *new_address_ptr = (void*) fake_time_millis; } else if (real_nano_time_adjustment == NULL && strcmp(name, "getNanoTimeAdjustment") == 0) { real_nano_time_adjustment = (jlong (*)(JNIEnv*, jclass, jlong)) address; *new_address_ptr = (void*) fake_nano_time_adjustment; } jvmti->Deallocate((unsigned char*) name); } } JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { if (options != NULL) { if (options[0] == '+' || options[0] == '-') { offset_millis = atoll(options); // time offset } else { offset_millis = atoll(options) - time(NULL) * 1000LL; // absolute time } } jvmtiEnv* jvmti; vm->GetEnv((void**) &jvmti, JVMTI_VERSION_1_0); jvmtiCapabilities capabilities = {0}; capabilities.can_generate_native_method_bind_events = 1; #if JNI_VERSION_9 jvmtiCapabilities potential_capabilities; jvmti->GetPotentialCapabilities(&potential_capabilities); capabilities.can_generate_early_vmstart = potential_capabilities.can_generate_early_vmstart; #endif jvmti->AddCapabilities(&capabilities); jvmtiEventCallbacks callbacks = {0}; callbacks.NativeMethodBind = NativeMethodBind; jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_NATIVE_METHOD_BIND, NULL); return 0; } ================================================ FILE: heapsampler/heapsampler.cpp ================================================ /* * Copyright 2019 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include #include #include #define MAX_STACK_DEPTH 1024 struct Frame { jlong samples; jlong bytes; std::map children; }; static jvmtiEnv* jvmti = NULL; static jrawMonitorID tree_lock; static std::map root; // Converts JVM internal class signature to human readable name static std::string decode_class_signature(char* class_sig) { switch (class_sig[0]) { case 'B': return "byte"; case 'C': return "char"; case 'S': return "short"; case 'I': return "int"; case 'J': return "long"; case 'F': return "float"; case 'D': return "double"; case 'Z': return "boolean"; case '[': return decode_class_signature(class_sig + 1) + "[]"; } // Strip 'L' and ';' class_sig++; class_sig[std::strlen(class_sig) - 1] = 0; // Replace '/' with '.' for (char* c = class_sig; *c; c++) { if (*c == '/') *c = '.'; } return class_sig; } static std::string get_method_name(jmethodID method) { jclass method_class; char* class_sig = NULL; char* method_name = NULL; std::string result; if (jvmti->GetMethodDeclaringClass(method, &method_class) == 0 && jvmti->GetClassSignature(method_class, &class_sig, NULL) == 0 && jvmti->GetMethodName(method, &method_name, NULL, NULL) == 0) { result.assign(decode_class_signature(class_sig) + "." + method_name); } else { result.assign("[unknown]"); } jvmti->Deallocate((unsigned char*) method_name); jvmti->Deallocate((unsigned char*) class_sig); return result; } static void dump_tree(const std::string stack_line, const std::string& class_name, const Frame* f) { if (f->samples > 0) { // Output sample in 'collapsed stack traces' format understood by flamegraph.pl std::cout << stack_line << class_name << "_[i] " << f->samples << std::endl; } for (auto it = f->children.begin(); it != f->children.end(); ++it) { dump_tree(stack_line + get_method_name(it->first) + ";", class_name, &it->second); } } static void dump_profile() { for (auto it = root.begin(); it != root.end(); ++it) { dump_tree("", it->first, &it->second); } } static void record_stack_trace(char* class_sig, jvmtiFrameInfo* frames, jint count, jlong size) { Frame* f = &root[decode_class_signature(class_sig)]; while (--count >= 0) { f = &f->children[frames[count].method]; } f->samples++; f->bytes += size; } void JNICALL SampledObjectAlloc(jvmtiEnv* jvmti, JNIEnv* env, jthread thread, jobject object, jclass object_klass, jlong size) { jvmtiFrameInfo frames[MAX_STACK_DEPTH]; jint count; if (jvmti->GetStackTrace(thread, 0, MAX_STACK_DEPTH, frames, &count) != 0) { return; } char* class_sig; if (jvmti->GetClassSignature(object_klass, &class_sig, NULL) != 0) { return; } jvmti->RawMonitorEnter(tree_lock); record_stack_trace(class_sig, frames, count, size); jvmti->RawMonitorExit(tree_lock); jvmti->Deallocate((unsigned char*) class_sig); } void JNICALL DataDumpRequest(jvmtiEnv* jvmti) { jvmti->RawMonitorEnter(tree_lock); dump_profile(); jvmti->RawMonitorExit(tree_lock); } void JNICALL VMDeath(jvmtiEnv* jvmti, JNIEnv* env) { DataDumpRequest(jvmti); } JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { vm->GetEnv((void**) &jvmti, JVMTI_VERSION_1_0); jvmti->CreateRawMonitor("tree_lock", &tree_lock); jvmtiCapabilities capabilities = {0}; capabilities.can_generate_sampled_object_alloc_events = 1; jvmti->AddCapabilities(&capabilities); if (options != NULL && options[0] >= '0' && options[0] <= '9') { jvmti->SetHeapSamplingInterval(std::atoi(options)); } jvmtiEventCallbacks callbacks = {0}; callbacks.SampledObjectAlloc = SampledObjectAlloc; callbacks.DataDumpRequest = DataDumpRequest; callbacks.VMDeath = VMDeath; jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DATA_DUMP_REQUEST, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL); return 0; } JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char* options, void* reserved) { // Protect against repeated load if (jvmti != NULL) { return 0; } return Agent_OnLoad(vm, options, reserved); } ================================================ FILE: richNPE/richNPE.cpp ================================================ /* * Copyright 2019 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include #include typedef unsigned char u1; typedef unsigned short u2; static const char* get_exception_message(u1 bytecode) { switch (bytecode) { case JVM_OPC_iaload: return "Load from null int array at bci %d"; case JVM_OPC_laload: return "Load from null long array at bci %d"; case JVM_OPC_faload: return "Load from null float array at bci %d"; case JVM_OPC_daload: return "Load from null double array at bci %d"; case JVM_OPC_aaload: return "Load from null Object array at bci %d"; case JVM_OPC_baload: return "Load from null byte/boolean array at bci %d"; case JVM_OPC_caload: return "Load from null char array at bci %d"; case JVM_OPC_saload: return "Load from null short array at bci %d"; case JVM_OPC_iastore: return "Store into null int array at bci %d"; case JVM_OPC_lastore: return "Store into null long array at bci %d"; case JVM_OPC_fastore: return "Store into null float array at bci %d"; case JVM_OPC_dastore: return "Store into null double array at bci %d"; case JVM_OPC_aastore: return "Store into null Object array at bci %d"; case JVM_OPC_bastore: return "Store into null byte/boolean array at bci %d"; case JVM_OPC_castore: return "Store into null char array at bci %d"; case JVM_OPC_sastore: return "Store into null short array at bci %d"; case JVM_OPC_arraylength: return "Get .length of null array"; case JVM_OPC_getfield: return "Get field '%s' of null object at bci %d"; case JVM_OPC_putfield: return "Put field '%s' of null object at bci %d"; case JVM_OPC_invokevirtual: // fall through case JVM_OPC_invokespecial: // fall through case JVM_OPC_invokeinterface: return "Called method '%s' on null object at bci %d"; case JVM_OPC_monitorenter: // fall through case JVM_OPC_monitorexit: return "Synchronized on null monitor at bci %d"; default: return NULL; } } static u2 get_u2(const u1* bytes) { return bytes[0] << 8 | bytes[1]; } static u1* get_cpool_at(u1* cpool, u2 index) { // Length in bytes of a constant pool item with the given tag static u1 cp_item_size[] = {0, 3, 0, 5, 5, 9, 9, 3, 3, 5, 5, 5, 5, 4, 3, 5, 5, 3, 3}; for (unsigned int i = 1; i < index; i++) { u1 tag = cpool[0]; cpool += tag == JVM_CONSTANT_Utf8 ? 3 + get_u2(cpool + 1) : cp_item_size[tag]; } return cpool; } static char* get_name_from_cpool(jvmtiEnv* jvmti, jmethodID method, const u1* bytecodes) { jclass holder; jvmti->GetMethodDeclaringClass(method, &holder); jint cpool_count; jint cpool_bytes; u1* cpool; if (jvmti->GetConstantPool(holder, &cpool_count, &cpool_bytes, &cpool) != 0) { return strdup(""); } u1* ref = get_cpool_at(cpool, get_u2(bytecodes + 1)); // CONSTANT_Fieldref / Methodref u1* name_and_type = get_cpool_at(cpool, get_u2(ref + 3)); // CONSTANT_NameAndType u1* name = get_cpool_at(cpool, get_u2(name_and_type + 1)); // CONSTANT_Utf8 size_t name_length = get_u2(name + 1); char* result = (char*) malloc(name_length + 1); memcpy(result, name + 3, name_length); result[name_length] = 0; jvmti->Deallocate(cpool); return result; } // Cache JNI handles as soon as VM initializes static jclass NullPointerException = NULL; static jfieldID detailMessage = NULL; void JNICALL VMInit(jvmtiEnv* jvmti, JNIEnv* env, jthread thread) { jclass localNPE = env->FindClass("java/lang/NullPointerException"); NullPointerException = (jclass) env->NewGlobalRef(localNPE); jclass Throwable = env->FindClass("java/lang/Throwable"); detailMessage = env->GetFieldID(Throwable, "detailMessage", "Ljava/lang/String;"); } void JNICALL ExceptionCallback(jvmtiEnv* jvmti, JNIEnv* env, jthread thread, jmethodID method, jlocation location, jobject exception, jmethodID catch_method, jlocation catch_location) { if (NullPointerException == NULL || detailMessage == NULL || !env->IsInstanceOf(exception, NullPointerException)) { return; } jint bytecode_count; u1* bytecodes; if (jvmti->GetBytecodes(method, &bytecode_count, &bytecodes) != 0) { return; } if (location >= 0 && location < bytecode_count) { const char* message = get_exception_message(bytecodes[location]); if (message != NULL) { char buf[400]; if (strstr(message, "%s") != NULL) { char* name = get_name_from_cpool(jvmti, method, bytecodes + location); snprintf(buf, sizeof(buf), message, name, (int) location); free(name); } else { sprintf(buf, message, (int) location); } env->SetObjectField(exception, detailMessage, env->NewStringUTF(buf)); } } jvmti->Deallocate(bytecodes); } JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { jvmtiEnv* jvmti; vm->GetEnv((void**) &jvmti, JVMTI_VERSION_1_0); jvmtiCapabilities capabilities = {0}; capabilities.can_generate_exception_events = 1; capabilities.can_get_bytecodes = 1; capabilities.can_get_constant_pool = 1; jvmti->AddCapabilities(&capabilities); jvmtiEventCallbacks callbacks = {0}; callbacks.VMInit = VMInit; callbacks.Exception = ExceptionCallback; jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_EXCEPTION, NULL); return 0; } ================================================ FILE: stackframe/StackFrame.java ================================================ /* * Copyright 2019 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class StackFrame { static { System.loadLibrary("stackframe"); } public static native String getLocation(int depth); } ================================================ FILE: stackframe/stackframe.cpp ================================================ /* * Copyright 2019 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include class MethodInfo { private: char* _file = NULL; jvmtiLineNumberEntry* _line_number_table = NULL; jint _table_size = 0; bool _initialized = false; public: bool initialized() { return _initialized; } void initialize(jvmtiEnv* jvmti, jmethodID method) { jclass method_class; if (jvmti->GetMethodDeclaringClass(method, &method_class) == 0) { jvmti->GetSourceFileName(method_class, &_file); } jvmti->GetLineNumberTable(method, &_table_size, &_line_number_table); _initialized = true; } char* file() { return _file; } int line(jlocation location) { int line = 0; jlocation min = 0xffff; for (int i = 0; i < _table_size; i++) { jlocation start = _line_number_table[i].start_location; if (location >= start && start < min) { line = _line_number_table[i].line_number; min = start; } } return line; } }; static jvmtiEnv* jvmti; static std::map method_cache; extern "C" JNIEXPORT jstring JNICALL Java_StackFrame_getLocation(JNIEnv* env, jclass unused, jint depth) { jvmtiFrameInfo frame; jint count; if (jvmti->GetStackTrace(NULL, depth, 1, &frame, &count) != 0) { return NULL; } MethodInfo* info = &method_cache[frame.method]; if (!info->initialized()) { info->initialize(jvmti, frame.method); } char buf[1024]; std::snprintf(buf, sizeof(buf), "%s:%d", info->file(), info->line(frame.location)); return env->NewStringUTF(buf); } jint JNI_OnLoad(JavaVM* vm, void* reserved) { vm->GetEnv((void**) &jvmti, JVMTI_VERSION_1_0); jvmtiCapabilities capabilities = {0}; capabilities.can_get_source_file_name = 1; capabilities.can_get_line_numbers = 1; jvmti->AddCapabilities(&capabilities); return JNI_VERSION_1_6; } ================================================ FILE: vmtrace/vmtrace.cpp ================================================ /* * Copyright 2019 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include static FILE* out; static jrawMonitorID vmtrace_lock; static jlong start_time; static void trace(jvmtiEnv* jvmti, const char* fmt, ...) { jlong current_time; jvmti->GetTime(¤t_time); char buf[1024]; va_list args; va_start(args, fmt); vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); jvmti->RawMonitorEnter(vmtrace_lock); fprintf(out, "[%.5f] %s\n", (current_time - start_time) / 1000000000.0, buf); jvmti->RawMonitorExit(vmtrace_lock); } static char* fix_class_name(char* class_name) { // Strip 'L' and ';' from class signature class_name[strlen(class_name) - 1] = 0; return class_name + 1; } class ClassName { private: jvmtiEnv* _jvmti; char* _name; public: ClassName(jvmtiEnv* jvmti, jclass klass) : _jvmti(jvmti), _name(NULL) { _jvmti->GetClassSignature(klass, &_name, NULL); } ~ClassName() { _jvmti->Deallocate((unsigned char*) _name); } char* name() { return _name == NULL ? NULL : fix_class_name(_name); } }; class MethodName { private: jvmtiEnv* _jvmti; char* _holder_name; char* _method_name; public: MethodName(jvmtiEnv* jvmti, jmethodID method) : _jvmti(jvmti), _holder_name(NULL), _method_name(NULL) { jclass holder; if (_jvmti->GetMethodDeclaringClass(method, &holder) == 0) { _jvmti->GetClassSignature(holder, &_holder_name, NULL); _jvmti->GetMethodName(method, &_method_name, NULL, NULL); } } ~MethodName() { _jvmti->Deallocate((unsigned char*) _method_name); _jvmti->Deallocate((unsigned char*) _holder_name); } char* holder() { return _holder_name == NULL ? NULL : fix_class_name(_holder_name); } char* name() { return _method_name; } }; class ThreadName { private: jvmtiEnv* _jvmti; char* _name; public: ThreadName(jvmtiEnv* jvmti, jthread thread) : _jvmti(jvmti), _name(NULL) { jvmtiThreadInfo info; _name = _jvmti->GetThreadInfo(thread, &info) == 0 ? info.name : NULL; } ~ThreadName() { _jvmti->Deallocate((unsigned char*) _name); } char* name() { return _name; } }; void JNICALL VMStart(jvmtiEnv* jvmti, JNIEnv* env) { trace(jvmti, "VM started"); } void JNICALL VMInit(jvmtiEnv* jvmti, JNIEnv* env, jthread thread) { trace(jvmti, "VM initialized"); } void JNICALL VMDeath(jvmtiEnv* jvmti, JNIEnv* env) { trace(jvmti, "VM destroyed"); } void JNICALL ClassFileLoadHook(jvmtiEnv* jvmti, JNIEnv* env, jclass class_being_redefined, jobject loader, const char* name, jobject protection_domain, jint data_len, const unsigned char* data, jint* new_data_len, unsigned char** new_data) { trace(jvmti, "Loading class: %s (%d bytes)", name, data_len); } void JNICALL ClassPrepare(jvmtiEnv* jvmti, JNIEnv* env, jthread thread, jclass klass) { ClassName cn(jvmti, klass); trace(jvmti, "Class prepared: %s", cn.name()); } void JNICALL DynamicCodeGenerated(jvmtiEnv* jvmti, const char* name, const void* address, jint length) { trace(jvmti, "Dynamic code generated: %s (%d bytes)", name, length); } void JNICALL CompiledMethodLoad(jvmtiEnv* jvmti, jmethodID method, jint code_size, const void* code_addr, jint map_length, const jvmtiAddrLocationMap* map, const void* compile_info) { MethodName mn(jvmti, method); trace(jvmti, "Method compiled: %s.%s (%d bytes)", mn.holder(), mn.name(), code_size); } void JNICALL CompiledMethodUnload(jvmtiEnv* jvmti, jmethodID method, const void* code_addr) { MethodName mn(jvmti, method); trace(jvmti, "Method flushed: %s.%s", mn.holder(), mn.name()); } void JNICALL ThreadStart(jvmtiEnv* jvmti, JNIEnv* env, jthread thread) { ThreadName tn(jvmti, thread); trace(jvmti, "Thread started: %s", tn.name()); } void JNICALL ThreadEnd(jvmtiEnv* jvmti, JNIEnv* env, jthread thread) { ThreadName tn(jvmti, thread); trace(jvmti, "Thread finished: %s", tn.name()); } void JNICALL GarbageCollectionStart(jvmtiEnv* jvmti) { trace(jvmti, "GC started"); } void JNICALL GarbageCollectionFinish(jvmtiEnv* jvmti) { trace(jvmti, "GC finished"); } JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { if (options == NULL || !options[0]) { out = stderr; } else if ((out = fopen(options, "w")) == NULL) { fprintf(stderr, "Cannot open output file: %s\n", options); return 1; } jvmtiEnv* jvmti; vm->GetEnv((void**) &jvmti, JVMTI_VERSION_1_0); jvmti->CreateRawMonitor("vmtrace_lock", &vmtrace_lock); jvmti->GetTime(&start_time); trace(jvmti, "VMTrace started"); jvmtiCapabilities capabilities = {0}; capabilities.can_generate_all_class_hook_events = 1; capabilities.can_generate_compiled_method_load_events = 1; capabilities.can_generate_garbage_collection_events = 1; jvmti->AddCapabilities(&capabilities); jvmtiEventCallbacks callbacks = {0}; callbacks.VMStart = VMStart; callbacks.VMInit = VMInit; callbacks.VMDeath = VMDeath; callbacks.ClassFileLoadHook = ClassFileLoadHook; callbacks.ClassPrepare = ClassPrepare; callbacks.DynamicCodeGenerated = DynamicCodeGenerated; callbacks.CompiledMethodLoad = CompiledMethodLoad; callbacks.CompiledMethodUnload = CompiledMethodUnload; callbacks.ThreadStart = ThreadStart; callbacks.ThreadEnd = ThreadEnd; callbacks.GarbageCollectionStart = GarbageCollectionStart; callbacks.GarbageCollectionFinish = GarbageCollectionFinish; jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_START, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_UNLOAD, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_THREAD_START, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_THREAD_END, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_GARBAGE_COLLECTION_START, NULL); jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, NULL); return 0; } JNIEXPORT void JNICALL Agent_OnUnload(JavaVM* vm) { if (out != NULL && out != stderr) { fclose(out); } }