1 /*
2  * Copyright (C) 2016 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 #include <sys/stat.h>
18 #include <stdio.h>
19 #include <string.h>
20 
21 #include <atomic>
22 #include <string>
23 
24 #include <android-base/macros.h>
25 #include <jni.h>
26 #include <nativehelper/JNIHelp.h>
27 #include <nativehelper/ScopedUtfChars.h>
28 
29 #if defined(__BIONIC__)
30 #include <sys/system_properties.h>
31 #endif
32 
33 extern "C"
Java_libcore_libcore_util_NativeAllocationRegistryTest_isNativeBridgedABI(JNIEnv *,jclass)34 jboolean Java_libcore_libcore_util_NativeAllocationRegistryTest_isNativeBridgedABI(JNIEnv*, jclass) {
35 #if defined(__BIONIC__)
36   return __system_property_find("ro.dalvik.vm.isa." ABI_STRING) != nullptr;
37 #else
38   return false;
39 #endif
40 }
41 
42 std::atomic<uint64_t> gNumNativeBytesAllocated = 0;
43 
finalize(uint64_t * ptr)44 static void finalize(uint64_t* ptr) {
45   gNumNativeBytesAllocated -= *ptr;
46   delete ptr;
47 }
48 
49 extern "C"
Java_libcore_libcore_util_NativeAllocationRegistryTest_getNativeFinalizer(JNIEnv *,jclass)50 jlong Java_libcore_libcore_util_NativeAllocationRegistryTest_getNativeFinalizer(JNIEnv*, jclass) {
51   return static_cast<jlong>(reinterpret_cast<uintptr_t>(&finalize));
52 }
53 
54 extern "C"
Java_libcore_libcore_util_NativeAllocationRegistryTest_doNativeAllocation(JNIEnv *,jclass,jlong size)55 jlong Java_libcore_libcore_util_NativeAllocationRegistryTest_doNativeAllocation(JNIEnv*,
56                                                                         jclass,
57                                                                         jlong size) {
58   gNumNativeBytesAllocated += size;
59 
60   // The actual allocation is a pointer to the pretend size of the allocation.
61   uint64_t* ptr = new uint64_t;
62   *ptr = static_cast<uint64_t>(size);
63   return static_cast<jlong>(reinterpret_cast<uintptr_t>(ptr));
64 }
65 
66 extern "C"
Java_libcore_libcore_util_NativeAllocationRegistryTest_getNumNativeBytesAllocated(JNIEnv *,jclass)67 jlong Java_libcore_libcore_util_NativeAllocationRegistryTest_getNumNativeBytesAllocated(JNIEnv*, jclass) {
68   return static_cast<jlong>(gNumNativeBytesAllocated);
69 }
70