trace.h revision 8f4b056427a9d2321e3aa4f21ca8ffb18b3e5ae6
1/*
2 * Copyright (C) 2011 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
17#ifndef ART_RUNTIME_TRACE_H_
18#define ART_RUNTIME_TRACE_H_
19
20#include <bitset>
21#include <map>
22#include <memory>
23#include <ostream>
24#include <set>
25#include <string>
26#include <unordered_map>
27#include <vector>
28
29#include "base/atomic.h"
30#include "base/macros.h"
31#include "base/os.h"
32#include "base/safe_map.h"
33#include "globals.h"
34#include "instrumentation.h"
35
36namespace art {
37
38class ArtField;
39class ArtMethod;
40class DexFile;
41class ShadowFrame;
42class Thread;
43
44using DexIndexBitSet = std::bitset<65536>;
45
46constexpr size_t kMaxThreadIdNumber = kIsTargetBuild ? 65536U : 1048576U;
47using ThreadIDBitSet = std::bitset<kMaxThreadIdNumber>;
48
49enum TracingMode {
50  kTracingInactive,
51  kMethodTracingActive,
52  kSampleProfilingActive,
53};
54
55// File format:
56//     header
57//     record 0
58//     record 1
59//     ...
60//
61// Header format:
62//     u4  magic ('SLOW')
63//     u2  version
64//     u2  offset to data
65//     u8  start date/time in usec
66//     u2  record size in bytes (version >= 2 only)
67//     ... padding to 32 bytes
68//
69// Record format v1:
70//     u1  thread ID
71//     u4  method ID | method action
72//     u4  time delta since start, in usec
73//
74// Record format v2:
75//     u2  thread ID
76//     u4  method ID | method action
77//     u4  time delta since start, in usec
78//
79// Record format v3:
80//     u2  thread ID
81//     u4  method ID | method action
82//     u4  time delta since start, in usec
83//     u4  wall time since start, in usec (when clock == "dual" only)
84//
85// 32 bits of microseconds is 70 minutes.
86//
87// All values are stored in little-endian order.
88
89enum TraceAction {
90    kTraceMethodEnter = 0x00,       // method entry
91    kTraceMethodExit = 0x01,        // method exit
92    kTraceUnroll = 0x02,            // method exited by exception unrolling
93    // 0x03 currently unused
94    kTraceMethodActionMask = 0x03,  // two bits
95};
96
97class Trace FINAL : public instrumentation::InstrumentationListener {
98 public:
99  enum TraceFlag {
100    kTraceCountAllocs = 1,
101  };
102
103  enum class TraceOutputMode {
104    kFile,
105    kDDMS,
106    kStreaming
107  };
108
109  enum class TraceMode {
110    kMethodTracing,
111    kSampling
112  };
113
114  ~Trace();
115
116  static void SetDefaultClockSource(TraceClockSource clock_source);
117
118  static void Start(const char* trace_filename, int trace_fd, size_t buffer_size, int flags,
119                    TraceOutputMode output_mode, TraceMode trace_mode, int interval_us)
120      REQUIRES(!Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_,
121               !Locks::trace_lock_);
122  static void Pause() REQUIRES(!Locks::trace_lock_, !Locks::thread_list_lock_);
123  static void Resume() REQUIRES(!Locks::trace_lock_);
124
125  // Stop tracing. This will finish the trace and write it to file/send it via DDMS.
126  static void Stop()
127      REQUIRES(!Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::trace_lock_);
128  // Abort tracing. This will just stop tracing and *not* write/send the collected data.
129  static void Abort()
130      REQUIRES(!Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::trace_lock_);
131  static void Shutdown()
132      REQUIRES(!Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::trace_lock_);
133  static TracingMode GetMethodTracingMode() REQUIRES(!Locks::trace_lock_);
134
135  bool UseWallClock();
136  bool UseThreadCpuClock();
137  void MeasureClockOverhead();
138  uint32_t GetClockOverheadNanoSeconds();
139
140  void CompareAndUpdateStackTrace(Thread* thread, std::vector<ArtMethod*>* stack_trace)
141      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_);
142
143  // InstrumentationListener implementation.
144  void MethodEntered(Thread* thread,
145                     Handle<mirror::Object> this_object,
146                     ArtMethod* method,
147                     uint32_t dex_pc)
148      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_)
149      OVERRIDE;
150  void MethodExited(Thread* thread,
151                    Handle<mirror::Object> this_object,
152                    ArtMethod* method,
153                    uint32_t dex_pc,
154                    const JValue& return_value)
155      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_)
156      OVERRIDE;
157  void MethodUnwind(Thread* thread,
158                    Handle<mirror::Object> this_object,
159                    ArtMethod* method,
160                    uint32_t dex_pc)
161      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_)
162      OVERRIDE;
163  void DexPcMoved(Thread* thread,
164                  Handle<mirror::Object> this_object,
165                  ArtMethod* method,
166                  uint32_t new_dex_pc)
167      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_)
168      OVERRIDE;
169  void FieldRead(Thread* thread,
170                 Handle<mirror::Object> this_object,
171                 ArtMethod* method,
172                 uint32_t dex_pc,
173                 ArtField* field)
174      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
175  void FieldWritten(Thread* thread,
176                    Handle<mirror::Object> this_object,
177                    ArtMethod* method,
178                    uint32_t dex_pc,
179                    ArtField* field,
180                    const JValue& field_value)
181      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
182  void ExceptionThrown(Thread* thread,
183                       Handle<mirror::Throwable> exception_object)
184      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
185  void ExceptionHandled(Thread* thread, Handle<mirror::Throwable> exception_object)
186      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
187  void Branch(Thread* thread,
188              ArtMethod* method,
189              uint32_t dex_pc,
190              int32_t dex_pc_offset)
191      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
192  void InvokeVirtualOrInterface(Thread* thread,
193                                Handle<mirror::Object> this_object,
194                                ArtMethod* caller,
195                                uint32_t dex_pc,
196                                ArtMethod* callee)
197      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
198  void WatchedFramePop(Thread* thread, const ShadowFrame& frame)
199      REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE;
200  // Reuse an old stack trace if it exists, otherwise allocate a new one.
201  static std::vector<ArtMethod*>* AllocStackTrace();
202  // Clear and store an old stack trace for later use.
203  static void FreeStackTrace(std::vector<ArtMethod*>* stack_trace);
204  // Save id and name of a thread before it exits.
205  static void StoreExitingThreadInfo(Thread* thread);
206
207  static TraceOutputMode GetOutputMode() REQUIRES(!Locks::trace_lock_);
208  static TraceMode GetMode() REQUIRES(!Locks::trace_lock_);
209  static size_t GetBufferSize() REQUIRES(!Locks::trace_lock_);
210
211  // Used by class linker to prevent class unloading.
212  static bool IsTracingEnabled() REQUIRES(!Locks::trace_lock_);
213
214 private:
215  Trace(File* trace_file, const char* trace_name, size_t buffer_size, int flags,
216        TraceOutputMode output_mode, TraceMode trace_mode);
217
218  // The sampling interval in microseconds is passed as an argument.
219  static void* RunSamplingThread(void* arg) REQUIRES(!Locks::trace_lock_);
220
221  static void StopTracing(bool finish_tracing, bool flush_file)
222      REQUIRES(!Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::trace_lock_)
223      // There is an annoying issue with static functions that create a new object and call into
224      // that object that causes them to not be able to tell that we don't currently hold the lock.
225      // This causes the negative annotations to incorrectly have a false positive. TODO: Figure out
226      // how to annotate this.
227      NO_THREAD_SAFETY_ANALYSIS;
228  void FinishTracing()
229      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_);
230
231  void ReadClocks(Thread* thread, uint32_t* thread_clock_diff, uint32_t* wall_clock_diff);
232
233  void LogMethodTraceEvent(Thread* thread, ArtMethod* method,
234                           instrumentation::Instrumentation::InstrumentationEvent event,
235                           uint32_t thread_clock_diff, uint32_t wall_clock_diff)
236      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_);
237
238  // Methods to output traced methods and threads.
239  void GetVisitedMethods(size_t end_offset, std::set<ArtMethod*>* visited_methods)
240      REQUIRES(!*unique_methods_lock_);
241  void DumpMethodList(std::ostream& os, const std::set<ArtMethod*>& visited_methods)
242      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_);
243  void DumpThreadList(std::ostream& os) REQUIRES(!Locks::thread_list_lock_);
244
245  // Methods to register seen entitites in streaming mode. The methods return true if the entity
246  // is newly discovered.
247  bool RegisterMethod(ArtMethod* method)
248      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(streaming_lock_);
249  bool RegisterThread(Thread* thread)
250      REQUIRES(streaming_lock_);
251
252  // Copy a temporary buffer to the main buffer. Used for streaming. Exposed here for lock
253  // annotation.
254  void WriteToBuf(const uint8_t* src, size_t src_size)
255      REQUIRES(streaming_lock_);
256  // Flush the main buffer to file. Used for streaming. Exposed here for lock annotation.
257  void FlushBuf()
258      REQUIRES(streaming_lock_);
259
260  uint32_t EncodeTraceMethod(ArtMethod* method) REQUIRES(!*unique_methods_lock_);
261  uint32_t EncodeTraceMethodAndAction(ArtMethod* method, TraceAction action)
262      REQUIRES(!*unique_methods_lock_);
263  ArtMethod* DecodeTraceMethod(uint32_t tmid) REQUIRES(!*unique_methods_lock_);
264  std::string GetMethodLine(ArtMethod* method) REQUIRES(!*unique_methods_lock_)
265      REQUIRES_SHARED(Locks::mutator_lock_);
266
267  void DumpBuf(uint8_t* buf, size_t buf_size, TraceClockSource clock_source)
268      REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_);
269
270  // Singleton instance of the Trace or null when no method tracing is active.
271  static Trace* volatile the_trace_ GUARDED_BY(Locks::trace_lock_);
272
273  // The default profiler clock source.
274  static TraceClockSource default_clock_source_;
275
276  // Sampling thread, non-zero when sampling.
277  static pthread_t sampling_pthread_;
278
279  // Used to remember an unused stack trace to avoid re-allocation during sampling.
280  static std::unique_ptr<std::vector<ArtMethod*>> temp_stack_trace_;
281
282  // File to write trace data out to, null if direct to ddms.
283  std::unique_ptr<File> trace_file_;
284
285  // Buffer to store trace data.
286  std::unique_ptr<uint8_t[]> buf_;
287
288  // Flags enabling extra tracing of things such as alloc counts.
289  const int flags_;
290
291  // The kind of output for this tracing.
292  const TraceOutputMode trace_output_mode_;
293
294  // The tracing method.
295  const TraceMode trace_mode_;
296
297  const TraceClockSource clock_source_;
298
299  // Size of buf_.
300  const size_t buffer_size_;
301
302  // Time trace was created.
303  const uint64_t start_time_;
304
305  // Clock overhead.
306  const uint32_t clock_overhead_ns_;
307
308  // Offset into buf_.
309  AtomicInteger cur_offset_;
310
311  // Did we overflow the buffer recording traces?
312  bool overflow_;
313
314  // Map of thread ids and names that have already exited.
315  SafeMap<pid_t, std::string> exited_threads_;
316
317  // Sampling profiler sampling interval.
318  int interval_us_;
319
320  // Streaming mode data.
321  std::string streaming_file_name_;
322  Mutex* streaming_lock_;
323  std::map<const DexFile*, DexIndexBitSet*> seen_methods_;
324  std::unique_ptr<ThreadIDBitSet> seen_threads_;
325
326  // Bijective map from ArtMethod* to index.
327  // Map from ArtMethod* to index in unique_methods_;
328  Mutex* unique_methods_lock_ ACQUIRED_AFTER(streaming_lock_);
329  std::unordered_map<ArtMethod*, uint32_t> art_method_id_map_ GUARDED_BY(unique_methods_lock_);
330  std::vector<ArtMethod*> unique_methods_ GUARDED_BY(unique_methods_lock_);
331
332  DISALLOW_COPY_AND_ASSIGN(Trace);
333};
334
335}  // namespace art
336
337#endif  // ART_RUNTIME_TRACE_H_
338