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