1 /* 2 * Copyright (C) 2017 The Android Open Source Project 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 #ifndef ART_TEST_TI_AGENT_JVMTI_HELPER_H_ 18 #define ART_TEST_TI_AGENT_JVMTI_HELPER_H_ 19 20 #include "jni.h" 21 #include "jvmti.h" 22 #include <memory> 23 #include <ostream> 24 25 #include "android-base/logging.h" 26 27 namespace art { 28 29 // Add all capabilities to the given env. 30 void SetAllCapabilities(jvmtiEnv* env); 31 32 // Check whether the given error is NONE. If not, print out the corresponding error message 33 // and abort. 34 void CheckJvmtiError(jvmtiEnv* env, jvmtiError error); 35 36 // Convert the given error to a RuntimeException with a message derived from the error. Returns 37 // true on error, false if error is JVMTI_ERROR_NONE. 38 bool JvmtiErrorToException(JNIEnv* env, jvmtiEnv* jvmti_env, jvmtiError error); 39 40 class JvmtiDeleter { 41 public: 42 JvmtiDeleter() : env_(nullptr) {} 43 explicit JvmtiDeleter(jvmtiEnv* env) : env_(env) {} 44 45 JvmtiDeleter(JvmtiDeleter&) = default; 46 JvmtiDeleter(JvmtiDeleter&&) = default; 47 JvmtiDeleter& operator=(const JvmtiDeleter&) = default; 48 49 void operator()(unsigned char* ptr) const { 50 CHECK(env_ != nullptr); 51 jvmtiError ret = env_->Deallocate(ptr); 52 CheckJvmtiError(env_, ret); 53 } 54 55 private: 56 mutable jvmtiEnv* env_; 57 }; 58 59 using JvmtiUniquePtr = std::unique_ptr<unsigned char, JvmtiDeleter>; 60 61 template <typename T> 62 static inline JvmtiUniquePtr MakeJvmtiUniquePtr(jvmtiEnv* env, T* mem) { 63 return JvmtiUniquePtr(reinterpret_cast<unsigned char*>(mem), JvmtiDeleter(env)); 64 } 65 66 template <typename T> 67 static inline jvmtiError Deallocate(jvmtiEnv* env, T* mem) { 68 return env->Deallocate(reinterpret_cast<unsigned char*>(mem)); 69 } 70 71 // To print jvmtiError. Does not rely on GetErrorName, so is an approximation. 72 std::ostream& operator<<(std::ostream& os, const jvmtiError& rhs); 73 74 } // namespace art 75 76 #endif // ART_TEST_TI_AGENT_JVMTI_HELPER_H_ 77