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