1 package org.coolreader.crengine;
2 
3 import java.lang.reflect.InvocationTargetException;
4 import java.lang.reflect.Method;
5 
6 import android.util.Log;
7 
8 public class VMRuntimeHack {
9 	private Object runtime = null;
10 	private Method trackAllocation = null;
11 	private Method trackFree = null;
12 	private static int totalSize = 0;
13 
trackAlloc(long size)14 	public boolean trackAlloc(long size) {
15 		if (runtime == null)
16 			return false;
17 		totalSize += size;
18 		L.v("trackAlloc(" + size + ")  total=" + totalSize);
19 		try {
20 			Object res = trackAllocation.invoke(runtime, Long.valueOf(size));
21 			return (res instanceof Boolean) ? (Boolean)res : true;
22 		} catch (IllegalArgumentException e) {
23 			return false;
24 		} catch (IllegalAccessException e) {
25 			return false;
26 		} catch (InvocationTargetException e) {
27 			return false;
28 		}
29 	}
trackFree(long size)30 	public boolean trackFree(long size) {
31 		if (runtime == null)
32 			return false;
33 		totalSize -= size;
34 		L.v("trackFree(" + size + ")  total=" + totalSize);
35 		try {
36 			Object res = trackFree.invoke(runtime, Long.valueOf(size));
37 			return (res instanceof Boolean) ? (Boolean)res : true;
38 		} catch (IllegalArgumentException e) {
39 			return false;
40 		} catch (IllegalAccessException e) {
41 			return false;
42 		} catch (InvocationTargetException e) {
43 			return false;
44 		}
45 	}
VMRuntimeHack()46 	public VMRuntimeHack() {
47 		if (!DeviceInfo.USE_BITMAP_MEMORY_HACK)
48 			return;
49 		boolean success = false;
50 		try {
51 			Class<?> cl = Class.forName("dalvik.system.VMRuntime");
52 			Method getRt = cl.getMethod("getRuntime", new Class[0]);
53 			runtime = getRt.invoke(null, new Object[0]);
54 			trackAllocation = cl.getMethod("trackExternalAllocation", new Class[] {long.class});
55 			trackFree = cl.getMethod("trackExternalFree", new Class[] {long.class});
56 			success = true;
57 		} catch (ClassNotFoundException e) {
58 		} catch (SecurityException e) {
59 		} catch (NoSuchMethodException e) {
60 		} catch (IllegalArgumentException e) {
61 		} catch (IllegalAccessException e) {
62 		} catch (InvocationTargetException e) {
63 		}
64 		if (!success) {
65 			Log.i("cr3", "VMRuntime hack does not work!");
66 			runtime = null;
67 			trackAllocation = null;
68 			trackFree = null;
69 		}
70 	}
71 }
72