1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"nclude
5 * <android/hardware_buffer_jni.h>);
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include "nativeTestHelper.h"
20 #include "SensorTest.h"
21
22 #include <android/hardware_buffer_jni.h>
23
24 namespace {
readHardwareBuffer(JNIEnv * env,jclass,jobject hardwareBufferObj,jbyteArray buffer,jint srcOffset,jint destOffset,jint count)25 jboolean readHardwareBuffer(JNIEnv* env, jclass,
26 jobject hardwareBufferObj, jbyteArray buffer, jint srcOffset, jint destOffset, jint count) {
27 if (hardwareBufferObj == nullptr || buffer == nullptr ||
28 srcOffset < 0 || destOffset < 0 || count <= 0) {
29 return false;
30 }
31
32 if (env->GetArrayLength(buffer) < destOffset + count) {
33 ALOGE("Byte array is not large enough.");
34 return false;
35 }
36
37 AHardwareBuffer *hardwareBuffer = AHardwareBuffer_fromHardwareBuffer(env, hardwareBufferObj);
38 if (hardwareBuffer == nullptr) {
39 ALOGE("Cannot get AHardwareBuffer from HardwareBuffer");
40 return false;
41 }
42
43 void *address;
44 int32_t fence = -1;
45 jboolean ret = false;
46 if (AHardwareBuffer_lock(hardwareBuffer, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY,
47 fence, nullptr, &address) == 0) {
48 if (address != nullptr) {
49 env->SetByteArrayRegion(buffer, destOffset, count,
50 reinterpret_cast<const jbyte *>(address) + srcOffset);
51 ret = true;
52 } else {
53 ALOGE("AHardwareBuffer locked but address is invalid");
54 }
55 AHardwareBuffer_unlock(hardwareBuffer, &fence);
56 }
57 return ret;
58 }
59
60 JNINativeMethod gMethods[] = {
61 { "nativeReadHardwareBuffer", "(Landroid/hardware/HardwareBuffer;[BIII)Z",
62 (void *) readHardwareBuffer},
63 };
64 } // unamed namespace
65
register_android_hardware_cts_SensorDirectReportTest(JNIEnv * env)66 int register_android_hardware_cts_SensorDirectReportTest(JNIEnv* env) {
67 jclass clazz = env->FindClass("android/hardware/cts/SensorDirectReportTest");
68 return env->RegisterNatives(clazz, gMethods,
69 sizeof(gMethods) / sizeof(JNINativeMethod));
70 }
71