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