Trace.java revision 461ac24b8c2b400656a0bcd72743f03720af2fd0
1/*
2 * Copyright (C) 2012 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
17package android.os;
18
19import android.util.Log;
20
21/**
22 * Writes trace events to the system trace buffer.  These trace events can be
23 * collected and visualized using the Systrace tool.
24 *
25 * <p>This tracing mechanism is independent of the method tracing mechanism
26 * offered by {@link Debug#startMethodTracing}.  In particular, it enables
27 * tracing of events that occur across multiple processes.
28 * <p>For information about using the Systrace tool, read <a
29 * href="{@docRoot}tools/debugging/systrace.html">Analyzing Display and Performance
30 * with Systrace</a>.
31 */
32public final class Trace {
33    /*
34     * Writes trace events to the kernel trace buffer.  These trace events can be
35     * collected using the "atrace" program for offline analysis.
36     */
37
38    private static final String TAG = "Trace";
39
40    // These tags must be kept in sync with system/core/include/cutils/trace.h.
41    /** @hide */
42    public static final long TRACE_TAG_NEVER = 0;
43    /** @hide */
44    public static final long TRACE_TAG_ALWAYS = 1L << 0;
45    /** @hide */
46    public static final long TRACE_TAG_GRAPHICS = 1L << 1;
47    /** @hide */
48    public static final long TRACE_TAG_INPUT = 1L << 2;
49    /** @hide */
50    public static final long TRACE_TAG_VIEW = 1L << 3;
51    /** @hide */
52    public static final long TRACE_TAG_WEBVIEW = 1L << 4;
53    /** @hide */
54    public static final long TRACE_TAG_WINDOW_MANAGER = 1L << 5;
55    /** @hide */
56    public static final long TRACE_TAG_ACTIVITY_MANAGER = 1L << 6;
57    /** @hide */
58    public static final long TRACE_TAG_SYNC_MANAGER = 1L << 7;
59    /** @hide */
60    public static final long TRACE_TAG_AUDIO = 1L << 8;
61    /** @hide */
62    public static final long TRACE_TAG_VIDEO = 1L << 9;
63    /** @hide */
64    public static final long TRACE_TAG_CAMERA = 1L << 10;
65    /** @hide */
66    public static final long TRACE_TAG_HAL = 1L << 11;
67    /** @hide */
68    public static final long TRACE_TAG_APP = 1L << 12;
69    /** @hide */
70    public static final long TRACE_TAG_RESOURCES = 1L << 13;
71    /** @hide */
72    public static final long TRACE_TAG_DALVIK = 1L << 14;
73    /** @hide */
74    public static final long TRACE_TAG_RS = 1L << 15;
75    /** @hide */
76    public static final long TRACE_TAG_BIONIC = 1L << 16;
77
78    private static final long TRACE_TAG_NOT_READY = 1L << 63;
79    private static final int MAX_SECTION_NAME_LEN = 127;
80
81    // Must be volatile to avoid word tearing.
82    private static volatile long sEnabledTags = TRACE_TAG_NOT_READY;
83
84    private static native long nativeGetEnabledTags();
85    private static native void nativeTraceCounter(long tag, String name, int value);
86    private static native void nativeTraceBegin(long tag, String name);
87    private static native void nativeTraceEnd(long tag);
88    private static native void nativeAsyncTraceBegin(long tag, String name, int cookie);
89    private static native void nativeAsyncTraceEnd(long tag, String name, int cookie);
90    private static native void nativeSetAppTracingAllowed(boolean allowed);
91    private static native void nativeSetTracingEnabled(boolean allowed);
92
93    static {
94        // We configure two separate change callbacks, one in Trace.cpp and one here.  The
95        // native callback reads the tags from the system property, and this callback
96        // reads the value that the native code retrieved.  It's essential that the native
97        // callback executes first.
98        //
99        // The system provides ordering through a priority level.  Callbacks made through
100        // SystemProperties.addChangeCallback currently have a negative priority, while
101        // our native code is using a priority of zero.
102        SystemProperties.addChangeCallback(new Runnable() {
103            @Override public void run() {
104                cacheEnabledTags();
105            }
106        });
107    }
108
109    private Trace() {
110    }
111
112    /**
113     * Caches a copy of the enabled-tag bits.  The "master" copy is held by the native code,
114     * and comes from the PROPERTY_TRACE_TAG_ENABLEFLAGS property.
115     * <p>
116     * If the native code hasn't yet read the property, we will cause it to do one-time
117     * initialization.  We don't want to do this during class init, because this class is
118     * preloaded, so all apps would be stuck with whatever the zygote saw.  (The zygote
119     * doesn't see the system-property update broadcasts.)
120     * <p>
121     * We want to defer initialization until the first use by an app, post-zygote.
122     * <p>
123     * We're okay if multiple threads call here simultaneously -- the native state is
124     * synchronized, and sEnabledTags is volatile (prevents word tearing).
125     */
126    private static long cacheEnabledTags() {
127        long tags = nativeGetEnabledTags();
128        sEnabledTags = tags;
129        return tags;
130    }
131
132    /**
133     * Returns true if a trace tag is enabled.
134     *
135     * @param traceTag The trace tag to check.
136     * @return True if the trace tag is valid.
137     *
138     * @hide
139     */
140    public static boolean isTagEnabled(long traceTag) {
141        long tags = sEnabledTags;
142        if (tags == TRACE_TAG_NOT_READY) {
143            tags = cacheEnabledTags();
144        }
145        return (tags & traceTag) != 0;
146    }
147
148    /**
149     * Writes trace message to indicate the value of a given counter.
150     *
151     * @param traceTag The trace tag.
152     * @param counterName The counter name to appear in the trace.
153     * @param counterValue The counter value.
154     *
155     * @hide
156     */
157    public static void traceCounter(long traceTag, String counterName, int counterValue) {
158        if (isTagEnabled(traceTag)) {
159            nativeTraceCounter(traceTag, counterName, counterValue);
160        }
161    }
162
163    /**
164     * Set whether application tracing is allowed for this process.  This is intended to be set
165     * once at application start-up time based on whether the application is debuggable.
166     *
167     * @hide
168     */
169    public static void setAppTracingAllowed(boolean allowed) {
170        nativeSetAppTracingAllowed(allowed);
171
172        // Setting whether app tracing is allowed may change the tags, so we update the cached
173        // tags here.
174        cacheEnabledTags();
175    }
176
177    /**
178     * Set whether tracing is enabled in this process.  Tracing is disabled shortly after Zygote
179     * initializes and re-enabled after processes fork from Zygote.  This is done because Zygote
180     * has no way to be notified about changes to the tracing tags, and if Zygote ever reads and
181     * caches the tracing tags, forked processes will inherit those stale tags.
182     *
183     * @hide
184     */
185    public static void setTracingEnabled(boolean enabled) {
186        nativeSetTracingEnabled(enabled);
187
188        // Setting whether tracing is enabled may change the tags, so we update the cached tags
189        // here.
190        cacheEnabledTags();
191    }
192
193    /**
194     * Writes a trace message to indicate that a given section of code has
195     * begun. Must be followed by a call to {@link #traceEnd} using the same
196     * tag.
197     *
198     * @param traceTag The trace tag.
199     * @param methodName The method name to appear in the trace.
200     *
201     * @hide
202     */
203    public static void traceBegin(long traceTag, String methodName) {
204        if (isTagEnabled(traceTag)) {
205            nativeTraceBegin(traceTag, methodName);
206        }
207    }
208
209    /**
210     * Writes a trace message to indicate that the current method has ended.
211     * Must be called exactly once for each call to {@link #traceBegin} using the same tag.
212     *
213     * @param traceTag The trace tag.
214     *
215     * @hide
216     */
217    public static void traceEnd(long traceTag) {
218        if (isTagEnabled(traceTag)) {
219            nativeTraceEnd(traceTag);
220        }
221    }
222
223    /**
224     * Writes a trace message to indicate that a given section of code has
225     * begun. Must be followed by a call to {@link #asyncTraceEnd} using the same
226     * tag. Unlike {@link #traceBegin(long, String)} and {@link #traceEnd(long)},
227     * asynchronous events do not need to be nested. The name and cookie used to
228     * begin an event must be used to end it.
229     *
230     * @param traceTag The trace tag.
231     * @param methodName The method name to appear in the trace.
232     * @param cookie Unique identifier for distinguishing simultaneous events
233     *
234     * @hide
235     */
236    public static void asyncTraceBegin(long traceTag, String methodName, int cookie) {
237        if (isTagEnabled(traceTag)) {
238            nativeAsyncTraceBegin(traceTag, methodName, cookie);
239        }
240    }
241
242    /**
243     * Writes a trace message to indicate that the current method has ended.
244     * Must be called exactly once for each call to {@link #asyncTraceBegin(long, String, int)}
245     * using the same tag, name and cookie.
246     *
247     * @param traceTag The trace tag.
248     * @param methodName The method name to appear in the trace.
249     * @param cookie Unique identifier for distinguishing simultaneous events
250     *
251     * @hide
252     */
253    public static void asyncTraceEnd(long traceTag, String methodName, int cookie) {
254        if (isTagEnabled(traceTag)) {
255            nativeAsyncTraceEnd(traceTag, methodName, cookie);
256        }
257    }
258
259    /**
260     * Writes a trace message to indicate that a given section of code has begun. This call must
261     * be followed by a corresponding call to {@link #endSection()} on the same thread.
262     *
263     * <p class="note"> At this time the vertical bar character '|', newline character '\n', and
264     * null character '\0' are used internally by the tracing mechanism.  If sectionName contains
265     * these characters they will be replaced with a space character in the trace.
266     *
267     * @param sectionName The name of the code section to appear in the trace.  This may be at
268     * most 127 Unicode code units long.
269     */
270    public static void beginSection(String sectionName) {
271        if (isTagEnabled(TRACE_TAG_APP)) {
272            if (sectionName.length() > MAX_SECTION_NAME_LEN) {
273                throw new IllegalArgumentException("sectionName is too long");
274            }
275            nativeTraceBegin(TRACE_TAG_APP, sectionName);
276        }
277    }
278
279    /**
280     * Writes a trace message to indicate that a given section of code has ended. This call must
281     * be preceeded by a corresponding call to {@link #beginSection(String)}. Calling this method
282     * will mark the end of the most recently begun section of code, so care must be taken to
283     * ensure that beginSection / endSection pairs are properly nested and called from the same
284     * thread.
285     */
286    public static void endSection() {
287        if (isTagEnabled(TRACE_TAG_APP)) {
288            nativeTraceEnd(TRACE_TAG_APP);
289        }
290    }
291}
292