• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 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 import java.lang.reflect.*;
18 
19 class Main {
20     static Object nativeLock = new Object();
21     static int nativeBytes = 0;
22     static Object runtime;
23     static Method register_native_allocation;
24     static Method register_native_free;
25     static int maxMem = 64 * 1024 * 1024;
26 
27     static class NativeAllocation {
28         private int bytes;
29 
NativeAllocation(int bytes)30         NativeAllocation(int bytes) throws Exception {
31             this.bytes = bytes;
32             register_native_allocation.invoke(runtime, bytes);
33             synchronized (nativeLock) {
34                 nativeBytes += bytes;
35                 if (nativeBytes > maxMem) {
36                     throw new OutOfMemoryError();
37                 }
38             }
39         }
40 
finalize()41         protected void finalize() throws Exception {
42             synchronized (nativeLock) {
43                 nativeBytes -= bytes;
44             }
45             register_native_free.invoke(runtime, bytes);
46         }
47     }
48 
main(String[] args)49     public static void main(String[] args) throws Exception {
50         Class<?> vm_runtime = Class.forName("dalvik.system.VMRuntime");
51         Method get_runtime = vm_runtime.getDeclaredMethod("getRuntime");
52         runtime = get_runtime.invoke(null);
53         register_native_allocation = vm_runtime.getDeclaredMethod("registerNativeAllocation", Integer.TYPE);
54         register_native_free = vm_runtime.getDeclaredMethod("registerNativeFree", Integer.TYPE);
55         int count = 16;
56         int size = 512 * 0x400;
57         int allocation_count = 256;
58         NativeAllocation[] allocations = new NativeAllocation[count];
59         for (int i = 0; i < allocation_count; ++i) {
60             allocations[i % count] = new NativeAllocation(size);
61         }
62         System.out.println("Test complete");
63     }
64 }
65 
66