/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.os; import com.android.internal.util.FastPrintWriter; import com.android.internal.util.TypedProperties; import android.util.Log; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Map; import org.apache.harmony.dalvik.ddmc.Chunk; import org.apache.harmony.dalvik.ddmc.ChunkHandler; import org.apache.harmony.dalvik.ddmc.DdmServer; import dalvik.bytecode.OpcodeInfo; import dalvik.system.VMDebug; /** * Provides various debugging methods for Android applications, including * tracing and allocation counts. *
Logging Trace Files
*Debug can create log files that give details about an application, such as
* a call stack and start/stop times for any running methods. See Traceview: A Graphical Log Viewer for
* information about reading trace files. To start logging trace files, call one
* of the startMethodTracing() methods. To stop tracing, call
* {@link #stopMethodTracing()}.
*/
public final class Debug
{
private static final String TAG = "Debug";
/**
* Flags for startMethodTracing(). These can be ORed together.
*
* TRACE_COUNT_ALLOCS adds the results from startAllocCounting to the
* trace key file.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static final int TRACE_COUNT_ALLOCS = VMDebug.TRACE_COUNT_ALLOCS;
/**
* Flags for printLoadedClasses(). Default behavior is to only show
* the class name.
*/
public static final int SHOW_FULL_DETAIL = 1;
public static final int SHOW_CLASSLOADER = (1 << 1);
public static final int SHOW_INITIALIZED = (1 << 2);
// set/cleared by waitForDebugger()
private static volatile boolean mWaiting = false;
private Debug() {}
/*
* How long to wait for the debugger to finish sending requests. I've
* seen this hit 800msec on the device while waiting for a response
* to travel over USB and get processed, so we take that and add
* half a second.
*/
private static final int MIN_DEBUGGER_IDLE = 1300; // msec
/* how long to sleep when polling for activity */
private static final int SPIN_DELAY = 200; // msec
/**
* Default trace file path and file
*/
private static final String DEFAULT_TRACE_PATH_PREFIX =
Environment.getLegacyExternalStorageDirectory().getPath() + "/";
private static final String DEFAULT_TRACE_BODY = "dmtrace";
private static final String DEFAULT_TRACE_EXTENSION = ".trace";
private static final String DEFAULT_TRACE_FILE_PATH =
DEFAULT_TRACE_PATH_PREFIX + DEFAULT_TRACE_BODY
+ DEFAULT_TRACE_EXTENSION;
/**
* This class is used to retrieved various statistics about the memory mappings for this
* process. The returned info is broken down by dalvik, native, and other. All results are in kB.
*/
public static class MemoryInfo implements Parcelable {
/** The proportional set size for dalvik heap. (Doesn't include other Dalvik overhead.) */
public int dalvikPss;
/** The proportional set size that is swappable for dalvik heap. */
/** @hide We may want to expose this, eventually. */
public int dalvikSwappablePss;
/** The private dirty pages used by dalvik heap. */
public int dalvikPrivateDirty;
/** The shared dirty pages used by dalvik heap. */
public int dalvikSharedDirty;
/** The private clean pages used by dalvik heap. */
/** @hide We may want to expose this, eventually. */
public int dalvikPrivateClean;
/** The shared clean pages used by dalvik heap. */
/** @hide We may want to expose this, eventually. */
public int dalvikSharedClean;
/** The dirty dalvik pages that have been swapped out. */
/** @hide We may want to expose this, eventually. */
public int dalvikSwappedOut;
/** The proportional set size for the native heap. */
public int nativePss;
/** The proportional set size that is swappable for the native heap. */
/** @hide We may want to expose this, eventually. */
public int nativeSwappablePss;
/** The private dirty pages used by the native heap. */
public int nativePrivateDirty;
/** The shared dirty pages used by the native heap. */
public int nativeSharedDirty;
/** The private clean pages used by the native heap. */
/** @hide We may want to expose this, eventually. */
public int nativePrivateClean;
/** The shared clean pages used by the native heap. */
/** @hide We may want to expose this, eventually. */
public int nativeSharedClean;
/** The dirty native pages that have been swapped out. */
/** @hide We may want to expose this, eventually. */
public int nativeSwappedOut;
/** The proportional set size for everything else. */
public int otherPss;
/** The proportional set size that is swappable for everything else. */
/** @hide We may want to expose this, eventually. */
public int otherSwappablePss;
/** The private dirty pages used by everything else. */
public int otherPrivateDirty;
/** The shared dirty pages used by everything else. */
public int otherSharedDirty;
/** The private clean pages used by everything else. */
/** @hide We may want to expose this, eventually. */
public int otherPrivateClean;
/** The shared clean pages used by everything else. */
/** @hide We may want to expose this, eventually. */
public int otherSharedClean;
/** The dirty pages used by anyting else that have been swapped out. */
/** @hide We may want to expose this, eventually. */
public int otherSwappedOut;
/** @hide */
public static final int HEAP_UNKNOWN = 0;
/** @hide */
public static final int HEAP_DALVIK = 1;
/** @hide */
public static final int HEAP_NATIVE = 2;
/** @hide */
public static final int OTHER_DALVIK_OTHER = 0;
/** @hide */
public static final int OTHER_STACK = 1;
/** @hide */
public static final int OTHER_CURSOR = 2;
/** @hide */
public static final int OTHER_ASHMEM = 3;
/** @hide */
public static final int OTHER_GL_DEV = 4;
/** @hide */
public static final int OTHER_UNKNOWN_DEV = 5;
/** @hide */
public static final int OTHER_SO = 6;
/** @hide */
public static final int OTHER_JAR = 7;
/** @hide */
public static final int OTHER_APK = 8;
/** @hide */
public static final int OTHER_TTF = 9;
/** @hide */
public static final int OTHER_DEX = 10;
/** @hide */
public static final int OTHER_OAT = 11;
/** @hide */
public static final int OTHER_ART = 12;
/** @hide */
public static final int OTHER_UNKNOWN_MAP = 13;
/** @hide */
public static final int OTHER_GRAPHICS = 14;
/** @hide */
public static final int OTHER_GL = 15;
/** @hide */
public static final int OTHER_OTHER_MEMTRACK = 16;
/** @hide */
public static final int OTHER_DALVIK_NORMAL = 17;
/** @hide */
public static final int OTHER_DALVIK_LARGE = 18;
/** @hide */
public static final int OTHER_DALVIK_LINEARALLOC = 19;
/** @hide */
public static final int OTHER_DALVIK_ACCOUNTING = 20;
/** @hide */
public static final int OTHER_DALVIK_CODE_CACHE = 21;
/** @hide */
public static final int OTHER_DALVIK_ZYGOTE = 22;
/** @hide */
public static final int OTHER_DALVIK_NON_MOVING = 23;
/** @hide */
public static final int OTHER_DALVIK_INDIRECT_REFERENCE_TABLE = 24;
/** @hide */
public static final int NUM_OTHER_STATS = 17;
/** @hide */
public static final int NUM_DVK_STATS = 8;
/** @hide */
public static final int NUM_CATEGORIES = 7;
/** @hide */
public static final int offsetPss = 0;
/** @hide */
public static final int offsetSwappablePss = 1;
/** @hide */
public static final int offsetPrivateDirty = 2;
/** @hide */
public static final int offsetSharedDirty = 3;
/** @hide */
public static final int offsetPrivateClean = 4;
/** @hide */
public static final int offsetSharedClean = 5;
/** @hide */
public static final int offsetSwappedOut = 6;
private int[] otherStats = new int[(NUM_OTHER_STATS+NUM_DVK_STATS)*NUM_CATEGORIES];
public MemoryInfo() {
}
/**
* Return total PSS memory usage in kB.
*/
public int getTotalPss() {
return dalvikPss + nativePss + otherPss;
}
/**
* @hide Return total PSS memory usage in kB.
*/
public int getTotalUss() {
return dalvikPrivateClean + dalvikPrivateDirty
+ nativePrivateClean + nativePrivateDirty
+ otherPrivateClean + otherPrivateDirty;
}
/**
* Return total PSS memory usage in kB.
*/
public int getTotalSwappablePss() {
return dalvikSwappablePss + nativeSwappablePss + otherSwappablePss;
}
/**
* Return total private dirty memory usage in kB.
*/
public int getTotalPrivateDirty() {
return dalvikPrivateDirty + nativePrivateDirty + otherPrivateDirty;
}
/**
* Return total shared dirty memory usage in kB.
*/
public int getTotalSharedDirty() {
return dalvikSharedDirty + nativeSharedDirty + otherSharedDirty;
}
/**
* Return total shared clean memory usage in kB.
*/
public int getTotalPrivateClean() {
return dalvikPrivateClean + nativePrivateClean + otherPrivateClean;
}
/**
* Return total shared clean memory usage in kB.
*/
public int getTotalSharedClean() {
return dalvikSharedClean + nativeSharedClean + otherSharedClean;
}
/**
* Return total swapped out memory in kB.
* @hide
*/
public int getTotalSwappedOut() {
return dalvikSwappedOut + nativeSwappedOut + otherSwappedOut;
}
/** @hide */
public int getOtherPss(int which) {
return otherStats[which*NUM_CATEGORIES + offsetPss];
}
/** @hide */
public int getOtherSwappablePss(int which) {
return otherStats[which*NUM_CATEGORIES + offsetSwappablePss];
}
/** @hide */
public int getOtherPrivateDirty(int which) {
return otherStats[which*NUM_CATEGORIES + offsetPrivateDirty];
}
/** @hide */
public int getOtherSharedDirty(int which) {
return otherStats[which*NUM_CATEGORIES + offsetSharedDirty];
}
/** @hide */
public int getOtherPrivateClean(int which) {
return otherStats[which*NUM_CATEGORIES + offsetPrivateClean];
}
/** @hide */
public int getOtherPrivate(int which) {
return getOtherPrivateClean(which) + getOtherPrivateDirty(which);
}
/** @hide */
public int getOtherSharedClean(int which) {
return otherStats[which*NUM_CATEGORIES + offsetSharedClean];
}
/** @hide */
public int getOtherSwappedOut(int which) {
return otherStats[which*NUM_CATEGORIES + offsetSwappedOut];
}
/** @hide */
public static String getOtherLabel(int which) {
switch (which) {
case OTHER_DALVIK_OTHER: return "Dalvik Other";
case OTHER_STACK: return "Stack";
case OTHER_CURSOR: return "Cursor";
case OTHER_ASHMEM: return "Ashmem";
case OTHER_GL_DEV: return "Gfx dev";
case OTHER_UNKNOWN_DEV: return "Other dev";
case OTHER_SO: return ".so mmap";
case OTHER_JAR: return ".jar mmap";
case OTHER_APK: return ".apk mmap";
case OTHER_TTF: return ".ttf mmap";
case OTHER_DEX: return ".dex mmap";
case OTHER_OAT: return ".oat mmap";
case OTHER_ART: return ".art mmap";
case OTHER_UNKNOWN_MAP: return "Other mmap";
case OTHER_GRAPHICS: return "EGL mtrack";
case OTHER_GL: return "GL mtrack";
case OTHER_OTHER_MEMTRACK: return "Other mtrack";
case OTHER_DALVIK_NORMAL: return ".Heap";
case OTHER_DALVIK_LARGE: return ".LOS";
case OTHER_DALVIK_LINEARALLOC: return ".LinearAlloc";
case OTHER_DALVIK_ACCOUNTING: return ".GC";
case OTHER_DALVIK_CODE_CACHE: return ".JITCache";
case OTHER_DALVIK_ZYGOTE: return ".Zygote";
case OTHER_DALVIK_NON_MOVING: return ".NonMoving";
case OTHER_DALVIK_INDIRECT_REFERENCE_TABLE: return ".IndirectRef";
default: return "????";
}
}
/**
* Pss of Java Heap bytes in KB due to the application.
* Notes:
* * OTHER_ART is the boot image. Anything private here is blamed on
* the application, not the system.
* * dalvikPrivateDirty includes private zygote, which means the
* application dirtied something allocated by the zygote. We blame
* the application for that memory, not the system.
* * Does not include OTHER_DALVIK_OTHER, which is considered VM
* Overhead and lumped into Private Other.
* * We don't include dalvikPrivateClean, because there should be no
* such thing as private clean for the Java Heap.
* @hide
*/
public int getSummaryJavaHeap() {
return dalvikPrivateDirty + getOtherPrivate(OTHER_ART);
}
/**
* Pss of Native Heap bytes in KB due to the application.
* Notes:
* * Includes private dirty malloc space.
* * We don't include nativePrivateClean, because there should be no
* such thing as private clean for the Native Heap.
* @hide
*/
public int getSummaryNativeHeap() {
return nativePrivateDirty;
}
/**
* Pss of code and other static resource bytes in KB due to
* the application.
* @hide
*/
public int getSummaryCode() {
return getOtherPrivate(OTHER_SO)
+ getOtherPrivate(OTHER_JAR)
+ getOtherPrivate(OTHER_APK)
+ getOtherPrivate(OTHER_TTF)
+ getOtherPrivate(OTHER_DEX)
+ getOtherPrivate(OTHER_OAT);
}
/**
* Pss in KB of the stack due to the application.
* Notes:
* * Includes private dirty stack, which includes both Java and Native
* stack.
* * Does not include private clean stack, because there should be no
* such thing as private clean for the stack.
* @hide
*/
public int getSummaryStack() {
return getOtherPrivateDirty(OTHER_STACK);
}
/**
* Pss in KB of graphics due to the application.
* Notes:
* * Includes private Gfx, EGL, and GL.
* * Warning: These numbers can be misreported by the graphics drivers.
* * We don't include shared graphics. It may make sense to, because
* shared graphics are likely buffers due to the application
* anyway, but it's simpler to implement to just group all shared
* memory into the System category.
* @hide
*/
public int getSummaryGraphics() {
return getOtherPrivate(OTHER_GL_DEV)
+ getOtherPrivate(OTHER_GRAPHICS)
+ getOtherPrivate(OTHER_GL);
}
/**
* Pss in KB due to the application that haven't otherwise been
* accounted for.
* @hide
*/
public int getSummaryPrivateOther() {
return getTotalPrivateClean()
+ getTotalPrivateDirty()
- getSummaryJavaHeap()
- getSummaryNativeHeap()
- getSummaryCode()
- getSummaryStack()
- getSummaryGraphics();
}
/**
* Pss in KB due to the system.
* Notes:
* * Includes all shared memory.
* @hide
*/
public int getSummarySystem() {
return getTotalPss()
- getTotalPrivateClean()
- getTotalPrivateDirty();
}
/**
* Total Pss in KB.
* @hide
*/
public int getSummaryTotalPss() {
return getTotalPss();
}
/**
* Total Swap in KB.
* Notes:
* * Some of this memory belongs in other categories, but we don't
* know if the Swap memory is shared or private, so we don't know
* what to blame on the application and what on the system.
* For now, just lump all the Swap in one place.
* @hide
*/
public int getSummaryTotalSwap() {
return getTotalSwappedOut();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(dalvikPss);
dest.writeInt(dalvikSwappablePss);
dest.writeInt(dalvikPrivateDirty);
dest.writeInt(dalvikSharedDirty);
dest.writeInt(dalvikPrivateClean);
dest.writeInt(dalvikSharedClean);
dest.writeInt(dalvikSwappedOut);
dest.writeInt(nativePss);
dest.writeInt(nativeSwappablePss);
dest.writeInt(nativePrivateDirty);
dest.writeInt(nativeSharedDirty);
dest.writeInt(nativePrivateClean);
dest.writeInt(nativeSharedClean);
dest.writeInt(nativeSwappedOut);
dest.writeInt(otherPss);
dest.writeInt(otherSwappablePss);
dest.writeInt(otherPrivateDirty);
dest.writeInt(otherSharedDirty);
dest.writeInt(otherPrivateClean);
dest.writeInt(otherSharedClean);
dest.writeInt(otherSwappedOut);
dest.writeIntArray(otherStats);
}
public void readFromParcel(Parcel source) {
dalvikPss = source.readInt();
dalvikSwappablePss = source.readInt();
dalvikPrivateDirty = source.readInt();
dalvikSharedDirty = source.readInt();
dalvikPrivateClean = source.readInt();
dalvikSharedClean = source.readInt();
dalvikSwappedOut = source.readInt();
nativePss = source.readInt();
nativeSwappablePss = source.readInt();
nativePrivateDirty = source.readInt();
nativeSharedDirty = source.readInt();
nativePrivateClean = source.readInt();
nativeSharedClean = source.readInt();
nativeSwappedOut = source.readInt();
otherPss = source.readInt();
otherSwappablePss = source.readInt();
otherPrivateDirty = source.readInt();
otherSharedDirty = source.readInt();
otherPrivateClean = source.readInt();
otherSharedClean = source.readInt();
otherSwappedOut = source.readInt();
otherStats = source.createIntArray();
}
public static final Creator
* The main differences between this and {@link #startMethodTracing()} are
* that tracing in the qemu emulator traces every cpu instruction of every
* process, including kernel code, so we have more complete information,
* including all context switches. We can also get more detailed information
* such as cache misses. The sequence of calls is determined by
* post-processing the instruction trace. The qemu tracing is also done
* without modifying the application or perturbing the timing of calls
* because no instrumentation is added to the application being traced.
*
* One limitation of using this method compared to using
* {@link #startMethodTracing()} on the real device is that the emulator
* does not model all of the real hardware effects such as memory and
* bus contention. The emulator also has a simple cache model and cannot
* capture all the complexities of a real cache.
* Tracing can be started and stopped as many times as desired. When
* the qemu emulator itself is stopped then the buffered trace records
* are flushed and written to the trace file. In fact, it is not necessary
* to call this method at all; simply killing qemu is sufficient. But
* starting and stopping a trace is useful for examining a specific
* region of code.
* When method tracing is enabled, the VM will run more slowly than
* usual, so the timings from the trace files should only be considered
* in relative terms (e.g. was run #1 faster than run #2). The times
* for native methods will not change, so don't try to use this to
* compare the performance of interpreted and native implementations of the
* same method. As an alternative, consider using sampling-based method
* tracing via {@link #startMethodTracingSampling(String, int, int)} or
* "native" tracing in the emulator via {@link #startNativeTracing()}.
* The {@link #startAllocCounting() start} method resets the counts and enables counting.
* The {@link #stopAllocCounting() stop} method disables the counting so that the analysis
* code doesn't cause additional allocations. The various Counts are kept for the system as a whole (global) and for each thread.
* The per-thread counts for threads other than the current thread
* are not cleared by the "reset" or "start" calls. The following table lists the runtime statistics that the runtime supports.
* Note runtime statistics may be added or removed in a future API level.
* NOTE TO APPLICATION DEVELOPERS: false will
* always be false in release builds. This API is typically only useful
* for platform developers.
*
* These properties are only set during platform debugging, and are not
* meant to be used as a general-purpose properties store.
*
* {@hide}
*
* @param cl The class to (possibly) modify
* @param partial If false, sets all static fields, otherwise, only set
* fields with the {@link android.os.Debug.DebugProperty}
* annotation
* @throws IllegalArgumentException if any fields are final or non-static,
* or if the type of the field does not match the type of
* the internal debugging property value.
*/
public static void setFieldsOn(Class> cl, boolean partial) {
if (false) {
if (debugProperties != null) {
/* Only look for fields declared directly by the class,
* so we don't mysteriously change static fields in superclasses.
*/
for (Field field : cl.getDeclaredFields()) {
if (!partial || field.getAnnotation(DebugProperty.class) != null) {
final String propertyName = cl.getName() + "." + field.getName();
boolean isStatic = Modifier.isStatic(field.getModifiers());
boolean isFinal = Modifier.isFinal(field.getModifiers());
if (!isStatic || isFinal) {
throw new IllegalArgumentException(propertyName +
" must be static and non-final");
}
modifyFieldIfSet(field, debugProperties, propertyName);
}
}
}
} else {
Log.wtf(TAG,
"setFieldsOn(" + (cl == null ? "null" : cl.getName()) +
") called in non-DEBUG build");
}
}
/**
* Annotation to put on fields you want to set with
* {@link Debug#setFieldsOn(Class, boolean)}.
*
* @hide
*/
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface DebugProperty {
}
/**
* Get a debugging dump of a system service by name.
*
* Most services require the caller to hold android.permission.DUMP.
*
* @param name of the service to dump
* @param fd to write dump output to (usually an output log file)
* @param args to pass to the service's dump method, may be null
* @return true if the service was dumped successfully, false if
* the service could not be found or had an error while dumping
*/
public static boolean dumpService(String name, FileDescriptor fd, String[] args) {
IBinder service = ServiceManager.getService(name);
if (service == null) {
Log.e(TAG, "Can't find service to dump: " + name);
return false;
}
try {
service.dump(fd, args);
return true;
} catch (RemoteException e) {
Log.e(TAG, "Can't dump service: " + name, e);
return false;
}
}
/**
* Have the stack traces of the given native process dumped to the
* specified file. Will be appended to the file.
* @hide
*/
public static native void dumpNativeBacktraceToFile(int pid, String file);
/**
* Return a String describing the calling method and location at a particular stack depth.
* @param callStack the Thread stack
* @param depth the depth of stack to return information for.
* @return the String describing the caller at that depth.
*/
private static String getCaller(StackTraceElement callStack[], int depth) {
// callStack[4] is the caller of the method that called getCallers()
if (4 + depth >= callStack.length) {
return "
* emulator -trace foo
* will start running the emulator and create a trace file named "foo". This
* method simply enables writing the trace records to the trace file.
*
* get
methods return
* the specified value. And the various reset
methods reset the specified
* count.
*
*
*
* @param statName
* the name of the runtime statistic to look up.
* @return the value of the specified runtime statistic or {@code null} if the
* runtime statistic doesn't exist.
*/
public static String getRuntimeStat(String statName) {
return VMDebug.getRuntimeStat(statName);
}
/**
* Returns a map of the names/values of the runtime statistics
* that {@link #getRuntimeStat(String)} supports.
*
* @return a map of the names/values of the supported runtime statistics.
*/
public static Map
*
*
*
* Runtime statistic name
* Meaning
* Example
* Supported (API Levels)
*
*
* art.gc.gc-count
* The number of garbage collection runs.
* {@code 164}
* 23
*
*
* art.gc.gc-time
* The total duration of garbage collection runs in ms.
* {@code 62364}
* 23
*
*
* art.gc.bytes-allocated
* The total number of bytes that the application allocated.
* {@code 1463948408}
* 23
*
*
* art.gc.bytes-freed
* The total number of bytes that garbage collection reclaimed.
* {@code 1313493084}
* 23
*
*
* art.gc.blocking-gc-count
* The number of blocking garbage collection runs.
* {@code 2}
* 23
*
*
* art.gc.blocking-gc-time
* The total duration of blocking garbage collection runs in ms.
* {@code 804}
* 23
*
*
* art.gc.gc-count-rate-histogram
* The histogram of the number of garbage collection runs per 10 seconds.
* {@code 0:34503,1:45350,2:11281,3:8088,4:43,5:8}
* 23
*
*
*
* art.gc.blocking-gc-count-rate-histogram
* The histogram of the number of garbage collection runs per 10 seconds.
* {@code 0:99269,1:1,2:1}
* 23
*
* Debug.InstructionCount icount = new Debug.InstructionCount();
* icount.resetAndStart();
* [... do lots of stuff ...]
* if (icount.collect()) {
* System.out.println("Total instructions executed: "
* + icount.globalTotal());
* System.out.println("Method invocations: "
* + icount.globalMethodInvocations());
* }
*
*
* @deprecated Instruction counting is no longer supported.
*/
@Deprecated
public static class InstructionCount {
private static final int NUM_INSTR =
OpcodeInfo.MAXIMUM_PACKED_VALUE + 1;
private int[] mCounts;
public InstructionCount() {
mCounts = new int[NUM_INSTR];
}
/**
* Reset counters and ensure counts are running. Counts may
* have already been running.
*
* @return true if counting was started
*/
public boolean resetAndStart() {
try {
VMDebug.startInstructionCounting();
VMDebug.resetInstructionCount();
} catch (UnsupportedOperationException uoe) {
return false;
}
return true;
}
/**
* Collect instruction counts. May or may not stop the
* counting process.
*/
public boolean collect() {
try {
VMDebug.stopInstructionCounting();
VMDebug.getInstructionCount(mCounts);
} catch (UnsupportedOperationException uoe) {
return false;
}
return true;
}
/**
* Return the total number of instructions executed globally (i.e. in
* all threads).
*/
public int globalTotal() {
int count = 0;
for (int i = 0; i < NUM_INSTR; i++) {
count += mCounts[i];
}
return count;
}
/**
* Return the total number of method-invocation instructions
* executed globally.
*/
public int globalMethodInvocations() {
int count = 0;
for (int i = 0; i < NUM_INSTR; i++) {
if (OpcodeInfo.isInvoke(i)) {
count += mCounts[i];
}
}
return count;
}
}
/**
* A Map of typed debug properties.
*/
private static final TypedProperties debugProperties;
/*
* Load the debug properties from the standard files into debugProperties.
*/
static {
if (false) {
final String TAG = "DebugProperties";
final String[] files = { "/system/debug.prop", "/debug.prop", "/data/debug.prop" };
final TypedProperties tp = new TypedProperties();
// Read the properties from each of the files, if present.
for (String file : files) {
Reader r;
try {
r = new FileReader(file);
} catch (FileNotFoundException ex) {
// It's ok if a file is missing.
continue;
}
try {
tp.load(r);
} catch (Exception ex) {
throw new RuntimeException("Problem loading " + file, ex);
} finally {
try {
r.close();
} catch (IOException ex) {
// Ignore this error.
}
}
}
debugProperties = tp.isEmpty() ? null : tp;
} else {
debugProperties = null;
}
}
/**
* Returns true if the type of the field matches the specified class.
* Handles the case where the class is, e.g., java.lang.Boolean, but
* the field is of the primitive "boolean" type. Also handles all of
* the java.lang.Number subclasses.
*/
private static boolean fieldTypeMatches(Field field, Class> cl) {
Class> fieldClass = field.getType();
if (fieldClass == cl) {
return true;
}
Field primitiveTypeField;
try {
/* All of the classes we care about (Boolean, Integer, etc.)
* have a Class field called "TYPE" that points to the corresponding
* primitive class.
*/
primitiveTypeField = cl.getField("TYPE");
} catch (NoSuchFieldException ex) {
return false;
}
try {
return fieldClass == (Class>) primitiveTypeField.get(null);
} catch (IllegalAccessException ex) {
return false;
}
}
/**
* Looks up the property that corresponds to the field, and sets the field's value
* if the types match.
*/
private static void modifyFieldIfSet(final Field field, final TypedProperties properties,
final String propertyName) {
if (field.getType() == java.lang.String.class) {
int stringInfo = properties.getStringInfo(propertyName);
switch (stringInfo) {
case TypedProperties.STRING_SET:
// Handle as usual below.
break;
case TypedProperties.STRING_NULL:
try {
field.set(null, null); // null object for static fields; null string
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Cannot set field for " + propertyName, ex);
}
return;
case TypedProperties.STRING_NOT_SET:
return;
case TypedProperties.STRING_TYPE_MISMATCH:
throw new IllegalArgumentException(
"Type of " + propertyName + " " +
" does not match field type (" + field.getType() + ")");
default:
throw new IllegalStateException(
"Unexpected getStringInfo(" + propertyName + ") return value " +
stringInfo);
}
}
Object value = properties.get(propertyName);
if (value != null) {
if (!fieldTypeMatches(field, value.getClass())) {
throw new IllegalArgumentException(
"Type of " + propertyName + " (" + value.getClass() + ") " +
" does not match field type (" + field.getType() + ")");
}
try {
field.set(null, value); // null object for static fields
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Cannot set field for " + propertyName, ex);
}
}
}
/**
* Equivalent to setFieldsOn(cl, false)
.
*
* @see #setFieldsOn(Class, boolean)
*
* @hide
*/
public static void setFieldsOn(Class> cl) {
setFieldsOn(cl, false);
}
/**
* Reflectively sets static fields of a class based on internal debugging
* properties. This method is a no-op if false is
* false.
*
* package com.example;
*
* import android.os.Debug;
*
* public class MyDebugVars {
* public static String s = "a string";
* public static String s2 = "second string";
* public static String ns = null;
* public static boolean b = false;
* public static int i = 5;
* @Debug.DebugProperty
* public static float f = 0.1f;
* @@Debug.DebugProperty
* public static double d = 0.5d;
*
* // This MUST appear AFTER all fields are defined and initialized!
* static {
* // Sets all the fields
* Debug.setFieldsOn(MyDebugVars.class);
*
* // Sets only the fields annotated with @Debug.DebugProperty
* // Debug.setFieldsOn(MyDebugVars.class, true);
* }
* }
*
* setFieldsOn() may override the value of any field in the class based
* on internal properties that are fixed at boot time.
*