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