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, mirror::Object* this_object,
144                      ArtMethod* method, uint32_t dex_pc)
145       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_)
146       OVERRIDE;
147   void MethodExited(Thread* thread, mirror::Object* this_object,
148                     ArtMethod* method, uint32_t dex_pc,
149                     const JValue& return_value)
150       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_)
151       OVERRIDE;
152   void MethodUnwind(Thread* thread, mirror::Object* this_object,
153                     ArtMethod* method, uint32_t dex_pc)
154       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_)
155       OVERRIDE;
156   void DexPcMoved(Thread* thread, mirror::Object* this_object,
157                   ArtMethod* method, uint32_t new_dex_pc)
158       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_)
159       OVERRIDE;
160   void FieldRead(Thread* thread, mirror::Object* this_object,
161                  ArtMethod* method, uint32_t dex_pc, ArtField* field)
162       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
163   void FieldWritten(Thread* thread, mirror::Object* this_object,
164                     ArtMethod* method, uint32_t dex_pc, ArtField* field,
165                     const JValue& field_value)
166       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
167   void ExceptionCaught(Thread* thread, mirror::Throwable* exception_object)
168       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
169   void Branch(Thread* thread, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
170       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
171   void InvokeVirtualOrInterface(Thread* thread,
172                                 mirror::Object* this_object,
173                                 ArtMethod* caller,
174                                 uint32_t dex_pc,
175                                 ArtMethod* callee)
176       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_) OVERRIDE;
177   // Reuse an old stack trace if it exists, otherwise allocate a new one.
178   static std::vector<ArtMethod*>* AllocStackTrace();
179   // Clear and store an old stack trace for later use.
180   static void FreeStackTrace(std::vector<ArtMethod*>* stack_trace);
181   // Save id and name of a thread before it exits.
182   static void StoreExitingThreadInfo(Thread* thread);
183 
184   static TraceOutputMode GetOutputMode() REQUIRES(!Locks::trace_lock_);
185   static TraceMode GetMode() REQUIRES(!Locks::trace_lock_);
186   static size_t GetBufferSize() REQUIRES(!Locks::trace_lock_);
187 
188   // Used by class linker to prevent class unloading.
189   static bool IsTracingEnabled() REQUIRES(!Locks::trace_lock_);
190 
191  private:
192   Trace(File* trace_file, const char* trace_name, size_t buffer_size, int flags,
193         TraceOutputMode output_mode, TraceMode trace_mode);
194 
195   // The sampling interval in microseconds is passed as an argument.
196   static void* RunSamplingThread(void* arg) REQUIRES(!Locks::trace_lock_);
197 
198   static void StopTracing(bool finish_tracing, bool flush_file)
199       REQUIRES(!Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::trace_lock_)
200       // There is an annoying issue with static functions that create a new object and call into
201       // that object that causes them to not be able to tell that we don't currently hold the lock.
202       // This causes the negative annotations to incorrectly have a false positive. TODO: Figure out
203       // how to annotate this.
204       NO_THREAD_SAFETY_ANALYSIS;
205   void FinishTracing()
206       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_);
207 
208   void ReadClocks(Thread* thread, uint32_t* thread_clock_diff, uint32_t* wall_clock_diff);
209 
210   void LogMethodTraceEvent(Thread* thread, ArtMethod* method,
211                            instrumentation::Instrumentation::InstrumentationEvent event,
212                            uint32_t thread_clock_diff, uint32_t wall_clock_diff)
213       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_, !*streaming_lock_);
214 
215   // Methods to output traced methods and threads.
216   void GetVisitedMethods(size_t end_offset, std::set<ArtMethod*>* visited_methods)
217       REQUIRES(!*unique_methods_lock_);
218   void DumpMethodList(std::ostream& os, const std::set<ArtMethod*>& visited_methods)
219       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_);
220   void DumpThreadList(std::ostream& os) REQUIRES(!Locks::thread_list_lock_);
221 
222   // Methods to register seen entitites in streaming mode. The methods return true if the entity
223   // is newly discovered.
224   bool RegisterMethod(ArtMethod* method)
225       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(streaming_lock_);
226   bool RegisterThread(Thread* thread)
227       REQUIRES(streaming_lock_);
228 
229   // Copy a temporary buffer to the main buffer. Used for streaming. Exposed here for lock
230   // annotation.
231   void WriteToBuf(const uint8_t* src, size_t src_size)
232       REQUIRES(streaming_lock_);
233   // Flush the main buffer to file. Used for streaming. Exposed here for lock annotation.
234   void FlushBuf()
235       REQUIRES(streaming_lock_);
236 
237   uint32_t EncodeTraceMethod(ArtMethod* method) REQUIRES(!*unique_methods_lock_);
238   uint32_t EncodeTraceMethodAndAction(ArtMethod* method, TraceAction action)
239       REQUIRES(!*unique_methods_lock_);
240   ArtMethod* DecodeTraceMethod(uint32_t tmid) REQUIRES(!*unique_methods_lock_);
241   std::string GetMethodLine(ArtMethod* method) REQUIRES(!*unique_methods_lock_)
242       REQUIRES_SHARED(Locks::mutator_lock_);
243 
244   void DumpBuf(uint8_t* buf, size_t buf_size, TraceClockSource clock_source)
245       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!*unique_methods_lock_);
246 
247   // Singleton instance of the Trace or null when no method tracing is active.
248   static Trace* volatile the_trace_ GUARDED_BY(Locks::trace_lock_);
249 
250   // The default profiler clock source.
251   static TraceClockSource default_clock_source_;
252 
253   // Sampling thread, non-zero when sampling.
254   static pthread_t sampling_pthread_;
255 
256   // Used to remember an unused stack trace to avoid re-allocation during sampling.
257   static std::unique_ptr<std::vector<ArtMethod*>> temp_stack_trace_;
258 
259   // File to write trace data out to, null if direct to ddms.
260   std::unique_ptr<File> trace_file_;
261 
262   // Buffer to store trace data.
263   std::unique_ptr<uint8_t[]> buf_;
264 
265   // Flags enabling extra tracing of things such as alloc counts.
266   const int flags_;
267 
268   // The kind of output for this tracing.
269   const TraceOutputMode trace_output_mode_;
270 
271   // The tracing method.
272   const TraceMode trace_mode_;
273 
274   const TraceClockSource clock_source_;
275 
276   // Size of buf_.
277   const size_t buffer_size_;
278 
279   // Time trace was created.
280   const uint64_t start_time_;
281 
282   // Clock overhead.
283   const uint32_t clock_overhead_ns_;
284 
285   // Offset into buf_.
286   AtomicInteger cur_offset_;
287 
288   // Did we overflow the buffer recording traces?
289   bool overflow_;
290 
291   // Map of thread ids and names that have already exited.
292   SafeMap<pid_t, std::string> exited_threads_;
293 
294   // Sampling profiler sampling interval.
295   int interval_us_;
296 
297   // Streaming mode data.
298   std::string streaming_file_name_;
299   Mutex* streaming_lock_;
300   std::map<const DexFile*, DexIndexBitSet*> seen_methods_;
301   std::unique_ptr<ThreadIDBitSet> seen_threads_;
302 
303   // Bijective map from ArtMethod* to index.
304   // Map from ArtMethod* to index in unique_methods_;
305   Mutex* unique_methods_lock_ ACQUIRED_AFTER(streaming_lock_);
306   std::unordered_map<ArtMethod*, uint32_t> art_method_id_map_ GUARDED_BY(unique_methods_lock_);
307   std::vector<ArtMethod*> unique_methods_ GUARDED_BY(unique_methods_lock_);
308 
309   DISALLOW_COPY_AND_ASSIGN(Trace);
310 };
311 
312 }  // namespace art
313 
314 #endif  // ART_RUNTIME_TRACE_H_
315