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