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