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_JNI_HELPER_H_ 18#define ART_TEST_TI_AGENT_JNI_HELPER_H_ 19 20#include "jni.h" 21#include "scoped_local_ref.h" 22 23namespace art { 24 25// Create an object array using a lambda that returns a local ref for each element. 26template <typename T> 27static inline jobjectArray CreateObjectArray(JNIEnv* env, 28 jint length, 29 const char* component_type_descriptor, 30 T src) { 31 if (length < 0) { 32 return nullptr; 33 } 34 35 ScopedLocalRef<jclass> obj_class(env, env->FindClass(component_type_descriptor)); 36 if (obj_class.get() == nullptr) { 37 return nullptr; 38 } 39 40 ScopedLocalRef<jobjectArray> ret(env, env->NewObjectArray(length, obj_class.get(), nullptr)); 41 if (ret.get() == nullptr) { 42 return nullptr; 43 } 44 45 for (jint i = 0; i < length; ++i) { 46 jobject element = src(i); 47 env->SetObjectArrayElement(ret.get(), static_cast<jint>(i), element); 48 env->DeleteLocalRef(element); 49 if (env->ExceptionCheck()) { 50 return nullptr; 51 } 52 } 53 54 return ret.release(); 55} 56 57inline bool JniThrowNullPointerException(JNIEnv* env, const char* msg) { 58 if (env->ExceptionCheck()) { 59 env->ExceptionClear(); 60 } 61 62 ScopedLocalRef<jclass> exc_class(env, env->FindClass("java/lang/NullPointerException")); 63 if (exc_class.get() == nullptr) { 64 return -1; 65 } 66 67 return env->ThrowNew(exc_class.get(), msg) == JNI_OK; 68} 69 70} // namespace art 71 72#endif // ART_TEST_TI_AGENT_JNI_HELPER_H_ 73