instrumentation.h revision 94f7b49578b6aaa80de8ffed230648d601393905
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_INSTRUMENTATION_H_
18#define ART_RUNTIME_INSTRUMENTATION_H_
19
20#include <stdint.h>
21#include <list>
22#include <map>
23
24#include "atomic.h"
25#include "instruction_set.h"
26#include "base/macros.h"
27#include "base/mutex.h"
28#include "gc_root.h"
29#include "object_callbacks.h"
30
31namespace art {
32namespace mirror {
33  class ArtField;
34  class ArtMethod;
35  class Class;
36  class Object;
37  class Throwable;
38}  // namespace mirror
39union JValue;
40class Thread;
41class ThrowLocation;
42
43namespace instrumentation {
44
45// Interpreter handler tables.
46enum InterpreterHandlerTable {
47  kMainHandlerTable = 0,          // Main handler table: no suspend check, no instrumentation.
48  kAlternativeHandlerTable = 1,   // Alternative handler table: suspend check and/or instrumentation
49                                  // enabled.
50  kNumHandlerTables
51};
52
53// Instrumentation event listener API. Registered listeners will get the appropriate call back for
54// the events they are listening for. The call backs supply the thread, method and dex_pc the event
55// occurred upon. The thread may or may not be Thread::Current().
56struct InstrumentationListener {
57  InstrumentationListener() {}
58  virtual ~InstrumentationListener() {}
59
60  // Call-back for when a method is entered.
61  virtual void MethodEntered(Thread* thread, mirror::Object* this_object,
62                             mirror::ArtMethod* method,
63                             uint32_t dex_pc) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) = 0;
64
65  // Call-back for when a method is exited.
66  // TODO: its likely passing the return value would be useful, however, we may need to get and
67  //       parse the shorty to determine what kind of register holds the result.
68  virtual void MethodExited(Thread* thread, mirror::Object* this_object,
69                            mirror::ArtMethod* method, uint32_t dex_pc,
70                            const JValue& return_value)
71      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) = 0;
72
73  // Call-back for when a method is popped due to an exception throw. A method will either cause a
74  // MethodExited call-back or a MethodUnwind call-back when its activation is removed.
75  virtual void MethodUnwind(Thread* thread, mirror::Object* this_object,
76                            mirror::ArtMethod* method, uint32_t dex_pc)
77      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) = 0;
78
79  // Call-back for when the dex pc moves in a method.
80  virtual void DexPcMoved(Thread* thread, mirror::Object* this_object,
81                          mirror::ArtMethod* method, uint32_t new_dex_pc)
82      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) = 0;
83
84  // Call-back for when we read from a field.
85  virtual void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
86                         uint32_t dex_pc, mirror::ArtField* field) = 0;
87
88  // Call-back for when we write into a field.
89  virtual void FieldWritten(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
90                            uint32_t dex_pc, mirror::ArtField* field, const JValue& field_value) = 0;
91
92  // Call-back when an exception is caught.
93  virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
94                               mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
95                               mirror::Throwable* exception_object)
96      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) = 0;
97};
98
99// Instrumentation is a catch-all for when extra information is required from the runtime. The
100// typical use for instrumentation is for profiling and debugging. Instrumentation may add stubs
101// to method entry and exit, it may also force execution to be switched to the interpreter and
102// trigger deoptimization.
103class Instrumentation {
104 public:
105  enum InstrumentationEvent {
106    kMethodEntered =   1 << 0,
107    kMethodExited =    1 << 1,
108    kMethodUnwind =    1 << 2,
109    kDexPcMoved =      1 << 3,
110    kFieldRead =       1 << 4,
111    kFieldWritten =    1 << 5,
112    kExceptionCaught = 1 << 6,
113  };
114
115  Instrumentation();
116
117  // Add a listener to be notified of the masked together sent of instrumentation events. This
118  // suspend the runtime to install stubs. You are expected to hold the mutator lock as a proxy
119  // for saying you should have suspended all threads (installing stubs while threads are running
120  // will break).
121  void AddListener(InstrumentationListener* listener, uint32_t events)
122      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
123      LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::classlinker_classes_lock_);
124
125  // Removes a listener possibly removing instrumentation stubs.
126  void RemoveListener(InstrumentationListener* listener, uint32_t events)
127      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
128      LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::classlinker_classes_lock_);
129
130  // Deoptimization.
131  void EnableDeoptimization()
132      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
133      LOCKS_EXCLUDED(deoptimized_methods_lock_);
134  void DisableDeoptimization()
135      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
136      LOCKS_EXCLUDED(deoptimized_methods_lock_);
137  bool AreAllMethodsDeoptimized() const {
138    return interpreter_stubs_installed_;
139  }
140  bool ShouldNotifyMethodEnterExitEvents() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
141
142  // Executes everything with interpreter.
143  void DeoptimizeEverything()
144      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
145      LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::classlinker_classes_lock_);
146
147  // Executes everything with compiled code (or interpreter if there is no code).
148  void UndeoptimizeEverything()
149      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
150      LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::classlinker_classes_lock_);
151
152  // Deoptimize a method by forcing its execution with the interpreter. Nevertheless, a static
153  // method (except a class initializer) set to the resolution trampoline will be deoptimized only
154  // once its declaring class is initialized.
155  void Deoptimize(mirror::ArtMethod* method)
156      LOCKS_EXCLUDED(Locks::thread_list_lock_, deoptimized_methods_lock_)
157      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_);
158
159  // Undeoptimze the method by restoring its entrypoints. Nevertheless, a static method
160  // (except a class initializer) set to the resolution trampoline will be updated only once its
161  // declaring class is initialized.
162  void Undeoptimize(mirror::ArtMethod* method)
163      LOCKS_EXCLUDED(Locks::thread_list_lock_, deoptimized_methods_lock_)
164      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_);
165
166  bool IsDeoptimized(mirror::ArtMethod* method)
167      LOCKS_EXCLUDED(deoptimized_methods_lock_)
168      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
169
170  // Enable method tracing by installing instrumentation entry/exit stubs.
171  void EnableMethodTracing()
172      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
173      LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::classlinker_classes_lock_);
174
175  // Disable method tracing by uninstalling instrumentation entry/exit stubs.
176  void DisableMethodTracing()
177      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
178      LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::classlinker_classes_lock_);
179
180  InterpreterHandlerTable GetInterpreterHandlerTable() const {
181    return interpreter_handler_table_;
182  }
183
184  void InstrumentQuickAllocEntryPoints() LOCKS_EXCLUDED(Locks::thread_list_lock_,
185                                                        Locks::runtime_shutdown_lock_);
186  void UninstrumentQuickAllocEntryPoints() LOCKS_EXCLUDED(Locks::thread_list_lock_,
187                                                          Locks::runtime_shutdown_lock_);
188  void ResetQuickAllocEntryPoints() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_);
189
190  // Update the code of a method respecting any installed stubs.
191  void UpdateMethodsCode(mirror::ArtMethod* method, const void* quick_code,
192                         const void* portable_code, bool have_portable_code)
193      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
194
195  // Get the quick code for the given method. More efficient than asking the class linker as it
196  // will short-cut to GetCode if instrumentation and static method resolution stubs aren't
197  // installed.
198  const void* GetQuickCodeFor(mirror::ArtMethod* method) const
199      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
200
201  void ForceInterpretOnly() {
202    interpret_only_ = true;
203    forced_interpret_only_ = true;
204  }
205
206  // Called by ArtMethod::Invoke to determine dispatch mechanism.
207  bool InterpretOnly() const {
208    return interpret_only_;
209  }
210
211  bool IsForcedInterpretOnly() const {
212    return forced_interpret_only_;
213  }
214
215  bool ShouldPortableCodeDeoptimize() const {
216    return instrumentation_stubs_installed_;
217  }
218
219  bool AreExitStubsInstalled() const {
220    return instrumentation_stubs_installed_;
221  }
222
223  bool HasMethodEntryListeners() const {
224    return have_method_entry_listeners_;
225  }
226
227  bool HasMethodExitListeners() const {
228    return have_method_exit_listeners_;
229  }
230
231  bool HasDexPcListeners() const {
232    return have_dex_pc_listeners_;
233  }
234
235  bool HasFieldReadListeners() const {
236    return have_field_read_listeners_;
237  }
238
239  bool HasFieldWriteListeners() const {
240    return have_field_write_listeners_;
241  }
242
243  bool HasExceptionCaughtListeners() const {
244    return have_exception_caught_listeners_;
245  }
246
247  bool IsActive() const {
248    return have_dex_pc_listeners_ || have_method_entry_listeners_ || have_method_exit_listeners_ ||
249        have_field_read_listeners_ || have_field_write_listeners_ ||
250        have_exception_caught_listeners_ || have_method_unwind_listeners_;
251  }
252
253  // Inform listeners that a method has been entered. A dex PC is provided as we may install
254  // listeners into executing code and get method enter events for methods already on the stack.
255  void MethodEnterEvent(Thread* thread, mirror::Object* this_object,
256                        mirror::ArtMethod* method, uint32_t dex_pc) const
257      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
258    if (UNLIKELY(HasMethodEntryListeners())) {
259      MethodEnterEventImpl(thread, this_object, method, dex_pc);
260    }
261  }
262
263  // Inform listeners that a method has been exited.
264  void MethodExitEvent(Thread* thread, mirror::Object* this_object,
265                       mirror::ArtMethod* method, uint32_t dex_pc,
266                       const JValue& return_value) const
267      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
268    if (UNLIKELY(HasMethodExitListeners())) {
269      MethodExitEventImpl(thread, this_object, method, dex_pc, return_value);
270    }
271  }
272
273  // Inform listeners that a method has been exited due to an exception.
274  void MethodUnwindEvent(Thread* thread, mirror::Object* this_object,
275                         mirror::ArtMethod* method, uint32_t dex_pc) const
276      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
277
278  // Inform listeners that the dex pc has moved (only supported by the interpreter).
279  void DexPcMovedEvent(Thread* thread, mirror::Object* this_object,
280                       mirror::ArtMethod* method, uint32_t dex_pc) const
281      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
282    if (UNLIKELY(HasDexPcListeners())) {
283      DexPcMovedEventImpl(thread, this_object, method, dex_pc);
284    }
285  }
286
287  // Inform listeners that we read a field (only supported by the interpreter).
288  void FieldReadEvent(Thread* thread, mirror::Object* this_object,
289                      mirror::ArtMethod* method, uint32_t dex_pc,
290                      mirror::ArtField* field) const
291      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
292    if (UNLIKELY(HasFieldReadListeners())) {
293      FieldReadEventImpl(thread, this_object, method, dex_pc, field);
294    }
295  }
296
297  // Inform listeners that we write a field (only supported by the interpreter).
298  void FieldWriteEvent(Thread* thread, mirror::Object* this_object,
299                       mirror::ArtMethod* method, uint32_t dex_pc,
300                       mirror::ArtField* field, const JValue& field_value) const
301      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
302    if (UNLIKELY(HasFieldWriteListeners())) {
303      FieldWriteEventImpl(thread, this_object, method, dex_pc, field, field_value);
304    }
305  }
306
307  // Inform listeners that an exception was caught.
308  void ExceptionCaughtEvent(Thread* thread, const ThrowLocation& throw_location,
309                            mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
310                            mirror::Throwable* exception_object) const
311      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
312
313  // Called when an instrumented method is entered. The intended link register (lr) is saved so
314  // that returning causes a branch to the method exit stub. Generates method enter events.
315  void PushInstrumentationStackFrame(Thread* self, mirror::Object* this_object,
316                                     mirror::ArtMethod* method, uintptr_t lr,
317                                     bool interpreter_entry)
318      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
319
320  // Called when an instrumented method is exited. Removes the pushed instrumentation frame
321  // returning the intended link register. Generates method exit events.
322  TwoWordReturn PopInstrumentationStackFrame(Thread* self, uintptr_t* return_pc,
323                                             uint64_t gpr_result, uint64_t fpr_result)
324      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
325
326  // Pops an instrumentation frame from the current thread and generate an unwind event.
327  void PopMethodForUnwind(Thread* self, bool is_deoptimization) const
328      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
329
330  // Call back for configure stubs.
331  bool InstallStubsForClass(mirror::Class* klass) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
332
333  void InstallStubsForMethod(mirror::ArtMethod* method)
334      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
335
336  void VisitRoots(RootCallback* callback, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
337      LOCKS_EXCLUDED(deoptimized_methods_lock_);
338
339 private:
340  // Does the job of installing or removing instrumentation code within methods.
341  void ConfigureStubs(bool require_entry_exit_stubs, bool require_interpreter)
342      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
343      LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::classlinker_classes_lock_,
344                     deoptimized_methods_lock_);
345
346  void UpdateInterpreterHandlerTable() {
347    interpreter_handler_table_ = IsActive() ? kAlternativeHandlerTable : kMainHandlerTable;
348  }
349
350  // No thread safety analysis to get around SetQuickAllocEntryPointsInstrumented requiring
351  // exclusive access to mutator lock which you can't get if the runtime isn't started.
352  void SetEntrypointsInstrumented(bool instrumented) NO_THREAD_SAFETY_ANALYSIS;
353
354  void MethodEnterEventImpl(Thread* thread, mirror::Object* this_object,
355                            mirror::ArtMethod* method, uint32_t dex_pc) const
356      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
357  void MethodExitEventImpl(Thread* thread, mirror::Object* this_object,
358                           mirror::ArtMethod* method,
359                           uint32_t dex_pc, const JValue& return_value) const
360      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
361  void DexPcMovedEventImpl(Thread* thread, mirror::Object* this_object,
362                           mirror::ArtMethod* method, uint32_t dex_pc) const
363      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
364  void FieldReadEventImpl(Thread* thread, mirror::Object* this_object,
365                           mirror::ArtMethod* method, uint32_t dex_pc,
366                           mirror::ArtField* field) const
367      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
368  void FieldWriteEventImpl(Thread* thread, mirror::Object* this_object,
369                           mirror::ArtMethod* method, uint32_t dex_pc,
370                           mirror::ArtField* field, const JValue& field_value) const
371      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
372
373  // Read barrier-aware utility functions for accessing deoptimized_methods_
374  bool AddDeoptimizedMethod(mirror::ArtMethod* method)
375      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
376      EXCLUSIVE_LOCKS_REQUIRED(deoptimized_methods_lock_);
377  bool FindDeoptimizedMethod(mirror::ArtMethod* method)
378      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
379      SHARED_LOCKS_REQUIRED(deoptimized_methods_lock_);
380  bool RemoveDeoptimizedMethod(mirror::ArtMethod* method)
381      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
382      EXCLUSIVE_LOCKS_REQUIRED(deoptimized_methods_lock_);
383  mirror::ArtMethod* BeginDeoptimizedMethod()
384      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
385      SHARED_LOCKS_REQUIRED(deoptimized_methods_lock_);
386  bool IsDeoptimizedMethodsEmpty() const
387      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
388      SHARED_LOCKS_REQUIRED(deoptimized_methods_lock_);
389
390  // Have we hijacked ArtMethod::code_ so that it calls instrumentation/interpreter code?
391  bool instrumentation_stubs_installed_;
392
393  // Have we hijacked ArtMethod::code_ to reference the enter/exit stubs?
394  bool entry_exit_stubs_installed_;
395
396  // Have we hijacked ArtMethod::code_ to reference the enter interpreter stub?
397  bool interpreter_stubs_installed_;
398
399  // Do we need the fidelity of events that we only get from running within the interpreter?
400  bool interpret_only_;
401
402  // Did the runtime request we only run in the interpreter? ie -Xint mode.
403  bool forced_interpret_only_;
404
405  // Do we have any listeners for method entry events? Short-cut to avoid taking the
406  // instrumentation_lock_.
407  bool have_method_entry_listeners_;
408
409  // Do we have any listeners for method exit events? Short-cut to avoid taking the
410  // instrumentation_lock_.
411  bool have_method_exit_listeners_;
412
413  // Do we have any listeners for method unwind events? Short-cut to avoid taking the
414  // instrumentation_lock_.
415  bool have_method_unwind_listeners_;
416
417  // Do we have any listeners for dex move events? Short-cut to avoid taking the
418  // instrumentation_lock_.
419  bool have_dex_pc_listeners_;
420
421  // Do we have any listeners for field read events? Short-cut to avoid taking the
422  // instrumentation_lock_.
423  bool have_field_read_listeners_;
424
425  // Do we have any listeners for field write events? Short-cut to avoid taking the
426  // instrumentation_lock_.
427  bool have_field_write_listeners_;
428
429  // Do we have any exception caught listeners? Short-cut to avoid taking the instrumentation_lock_.
430  bool have_exception_caught_listeners_;
431
432  // The event listeners, written to with the mutator_lock_ exclusively held.
433  std::list<InstrumentationListener*> method_entry_listeners_ GUARDED_BY(Locks::mutator_lock_);
434  std::list<InstrumentationListener*> method_exit_listeners_ GUARDED_BY(Locks::mutator_lock_);
435  std::list<InstrumentationListener*> method_unwind_listeners_ GUARDED_BY(Locks::mutator_lock_);
436  std::list<InstrumentationListener*> dex_pc_listeners_ GUARDED_BY(Locks::mutator_lock_);
437  std::list<InstrumentationListener*> field_read_listeners_ GUARDED_BY(Locks::mutator_lock_);
438  std::list<InstrumentationListener*> field_write_listeners_ GUARDED_BY(Locks::mutator_lock_);
439  std::list<InstrumentationListener*> exception_caught_listeners_ GUARDED_BY(Locks::mutator_lock_);
440
441  // The set of methods being deoptimized (by the debugger) which must be executed with interpreter
442  // only.
443  mutable ReaderWriterMutex deoptimized_methods_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
444  std::multimap<int32_t, GcRoot<mirror::ArtMethod>> deoptimized_methods_
445      GUARDED_BY(deoptimized_methods_lock_);
446  bool deoptimization_enabled_;
447
448  // Current interpreter handler table. This is updated each time the thread state flags are
449  // modified.
450  InterpreterHandlerTable interpreter_handler_table_;
451
452  // Greater than 0 if quick alloc entry points instrumented.
453  // TODO: The access and changes to this is racy and should be guarded by a lock.
454  AtomicInteger quick_alloc_entry_points_instrumentation_counter_;
455
456  DISALLOW_COPY_AND_ASSIGN(Instrumentation);
457};
458
459// An element in the instrumentation side stack maintained in art::Thread.
460struct InstrumentationStackFrame {
461  InstrumentationStackFrame(mirror::Object* this_object, mirror::ArtMethod* method,
462                            uintptr_t return_pc, size_t frame_id, bool interpreter_entry)
463      : this_object_(this_object), method_(method), return_pc_(return_pc), frame_id_(frame_id),
464        interpreter_entry_(interpreter_entry) {
465  }
466
467  std::string Dump() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
468
469  mirror::Object* this_object_;
470  mirror::ArtMethod* method_;
471  uintptr_t return_pc_;
472  size_t frame_id_;
473  bool interpreter_entry_;
474};
475
476}  // namespace instrumentation
477}  // namespace art
478
479#endif  // ART_RUNTIME_INSTRUMENTATION_H_
480