1 /* 2 * Copyright 2021 Code Intelligence GmbH 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <jni.h> 20 21 #include <string> 22 23 namespace jazzer { 24 25 void DumpJvmStackTraces(); 26 27 // JVM is a thin wrapper around JNI_CreateJavaVM and DestroyJavaVM. The JVM 28 // instance is created inside the constructor with some default JNI options 29 // + options which can be added to via command line flags. 30 class JVM { 31 private: 32 JavaVM *jvm_; 33 JNIEnv *env_; 34 35 public: 36 // Creates a JVM instance with default options + options that were provided as 37 // command line flags. 38 explicit JVM(const std::string &executable_path); 39 40 // Destroy the running JVM instance. 41 ~JVM(); 42 43 // Get the JNI environment for interaction with the running JVM instance. 44 JNIEnv &GetEnv() const; 45 46 jclass FindClass(std::string class_name) const; 47 jmethodID GetStaticMethodID(jclass class_id, const std::string &method_name, 48 const std::string &signature, 49 bool is_required = true) const; 50 jmethodID GetMethodID(jclass class_id, const std::string &method_name, 51 const std::string &signature) const; 52 jfieldID GetStaticFieldID(jclass jclass, const std::string &field_name, 53 const std::string &type) const; 54 }; 55 56 // Adds convenience methods to convert a jvm exception to std::string 57 // using StringWriter and PrintWriter. The stack trace can be subjected to 58 // further processing, such as deduplication token computation and severity 59 // annotation. 60 class ExceptionPrinter { 61 private: 62 const JVM &jvm_; 63 64 jclass string_writer_class_; 65 jmethodID string_writer_constructor_; 66 jmethodID string_writer_to_string_method_; 67 68 jclass print_writer_class_; 69 jmethodID print_writer_constructor_; 70 jmethodID print_stack_trace_method_; 71 72 jclass exception_utils_; 73 jmethodID compute_dedup_token_method_; 74 jmethodID preprocess_throwable_method_; 75 76 protected: 77 explicit ExceptionPrinter(JVM &jvm); 78 79 // returns the current JVM exception stack trace as a string 80 std::string getStackTrace(jthrowable exception) const; 81 // augments the throwable with additional information such as severity markers 82 jthrowable preprocessException(jthrowable exception) const; 83 // returns a hash of the exception stack trace for deduplication purposes 84 jlong computeDedupToken(jthrowable exception) const; 85 }; 86 87 } /* namespace jazzer */ 88