blob: 57f79487aa646188d3b4082e2dd911b681067279 [file] [log] [blame]
jeffhao725a9572012-11-13 18:20:12 -08001/*
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#include "instrumentation.h"
18
Ian Rogersc7dd2952014-10-21 23:31:19 -070019#include <sstream>
20
Andreas Gampec7d878d2018-11-19 18:42:06 +000021#include <android-base/logging.h>
22
Ian Rogerse63db272014-07-15 15:36:11 -070023#include "arch/context.h"
Alex Lightd7661582017-05-01 13:48:16 -070024#include "art_field-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070025#include "art_method-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080026#include "base/atomic.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070027#include "base/callee_save_type.h"
jeffhao725a9572012-11-13 18:20:12 -080028#include "class_linker.h"
29#include "debugger.h"
David Sehr9e734c72018-01-04 17:56:19 -080030#include "dex/dex_file-inl.h"
31#include "dex/dex_file_types.h"
32#include "dex/dex_instruction-inl.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080033#include "entrypoints/quick/quick_alloc_entrypoints.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070034#include "entrypoints/quick/quick_entrypoints.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070035#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070036#include "gc_root-inl.h"
Sebastien Hertz138dbfc2013-12-04 18:15:25 +010037#include "interpreter/interpreter.h"
Mingyao Yang2ee17902017-08-30 11:37:08 -070038#include "interpreter/interpreter_common.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080039#include "jit/jit.h"
40#include "jit/jit_code_cache.h"
Alex Lightd7661582017-05-01 13:48:16 -070041#include "jvalue-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/class-inl.h"
43#include "mirror/dex_cache.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070044#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070045#include "mirror/object_array-inl.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080046#include "nth_caller_visitor.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010047#include "oat_quick_method_header.h"
David Srbecky28f6cff2018-10-16 15:07:28 +010048#include "runtime-inl.h"
jeffhao725a9572012-11-13 18:20:12 -080049#include "thread.h"
50#include "thread_list.h"
jeffhao725a9572012-11-13 18:20:12 -080051
52namespace art {
Ian Rogers62d6c772013-02-27 08:32:07 -080053namespace instrumentation {
jeffhao725a9572012-11-13 18:20:12 -080054
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020055constexpr bool kVerboseInstrumentation = false;
Sebastien Hertz5bfd5c92013-11-15 11:36:07 +010056
Alex Lightd7661582017-05-01 13:48:16 -070057void InstrumentationListener::MethodExited(Thread* thread,
58 Handle<mirror::Object> this_object,
59 ArtMethod* method,
60 uint32_t dex_pc,
61 Handle<mirror::Object> return_value) {
62 DCHECK_EQ(method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetReturnTypePrimitive(),
63 Primitive::kPrimNot);
64 JValue v;
65 v.SetL(return_value.Get());
66 MethodExited(thread, this_object, method, dex_pc, v);
67}
68
69void InstrumentationListener::FieldWritten(Thread* thread,
70 Handle<mirror::Object> this_object,
71 ArtMethod* method,
72 uint32_t dex_pc,
73 ArtField* field,
74 Handle<mirror::Object> field_value) {
75 DCHECK(!field->IsPrimitiveType());
76 JValue v;
77 v.SetL(field_value.Get());
78 FieldWritten(thread, this_object, method, dex_pc, field, v);
79}
80
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +010081// Instrumentation works on non-inlined frames by updating returned PCs
82// of compiled frames.
83static constexpr StackVisitor::StackWalkKind kInstrumentationStackWalk =
84 StackVisitor::StackWalkKind::kSkipInlinedFrames;
85
Mathieu Chartiere0671ce2015-07-28 17:23:28 -070086class InstallStubsClassVisitor : public ClassVisitor {
87 public:
88 explicit InstallStubsClassVisitor(Instrumentation* instrumentation)
89 : instrumentation_(instrumentation) {}
90
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010091 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -070092 instrumentation_->InstallStubsForClass(klass.Ptr());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -070093 return true; // we visit all classes.
94 }
95
96 private:
97 Instrumentation* const instrumentation_;
98};
99
Alex Light2c8206f2018-06-08 14:51:09 -0700100InstrumentationStackPopper::InstrumentationStackPopper(Thread* self)
101 : self_(self),
102 instrumentation_(Runtime::Current()->GetInstrumentation()),
103 frames_to_remove_(0) {}
104
105InstrumentationStackPopper::~InstrumentationStackPopper() {
106 std::deque<instrumentation::InstrumentationStackFrame>* stack = self_->GetInstrumentationStack();
107 for (size_t i = 0; i < frames_to_remove_; i++) {
108 stack->pop_front();
109 }
110}
111
112bool InstrumentationStackPopper::PopFramesTo(uint32_t desired_pops,
113 MutableHandle<mirror::Throwable>& exception) {
114 std::deque<instrumentation::InstrumentationStackFrame>* stack = self_->GetInstrumentationStack();
115 DCHECK_LE(frames_to_remove_, desired_pops);
116 DCHECK_GE(stack->size(), desired_pops);
117 DCHECK(!self_->IsExceptionPending());
118 if (!instrumentation_->HasMethodUnwindListeners()) {
119 frames_to_remove_ = desired_pops;
120 return true;
121 }
122 if (kVerboseInstrumentation) {
123 LOG(INFO) << "Popping frames for exception " << exception->Dump();
124 }
125 // The instrumentation events expect the exception to be set.
126 self_->SetException(exception.Get());
127 bool new_exception_thrown = false;
128 for (; frames_to_remove_ < desired_pops && !new_exception_thrown; frames_to_remove_++) {
129 InstrumentationStackFrame frame = stack->at(frames_to_remove_);
130 ArtMethod* method = frame.method_;
131 // Notify listeners of method unwind.
132 // TODO: improve the dex_pc information here.
133 uint32_t dex_pc = dex::kDexNoIndex;
134 if (kVerboseInstrumentation) {
135 LOG(INFO) << "Popping for unwind " << method->PrettyMethod();
136 }
137 if (!method->IsRuntimeMethod() && !frame.interpreter_entry_) {
138 instrumentation_->MethodUnwindEvent(self_, frame.this_object_, method, dex_pc);
139 new_exception_thrown = self_->GetException() != exception.Get();
140 }
141 }
142 exception.Assign(self_->GetException());
143 self_->ClearException();
144 if (kVerboseInstrumentation && new_exception_thrown) {
145 LOG(INFO) << "Failed to pop " << (desired_pops - frames_to_remove_)
146 << " frames due to new exception";
147 }
148 return !new_exception_thrown;
149}
Ian Rogers62d6c772013-02-27 08:32:07 -0800150
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700151Instrumentation::Instrumentation()
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000152 : instrumentation_stubs_installed_(false),
153 entry_exit_stubs_installed_(false),
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700154 interpreter_stubs_installed_(false),
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000155 interpret_only_(false),
156 forced_interpret_only_(false),
157 have_method_entry_listeners_(false),
158 have_method_exit_listeners_(false),
159 have_method_unwind_listeners_(false),
160 have_dex_pc_listeners_(false),
161 have_field_read_listeners_(false),
162 have_field_write_listeners_(false),
Alex Light6e1607e2017-08-23 10:06:18 -0700163 have_exception_thrown_listeners_(false),
Alex Lighte814f9d2017-07-31 16:14:39 -0700164 have_watched_frame_pop_listeners_(false),
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000165 have_branch_listeners_(false),
Alex Light9fb1ab12017-09-05 09:32:49 -0700166 have_exception_handled_listeners_(false),
Andreas Gampe7e56a072018-11-29 10:40:06 -0800167 deoptimized_methods_lock_(new ReaderWriterMutex("deoptimized methods lock",
168 kGenericBottomLock)),
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700169 deoptimization_enabled_(false),
170 interpreter_handler_table_(kMainHandlerTable),
Mathieu Chartier50e93312016-03-16 11:25:29 -0700171 quick_alloc_entry_points_instrumentation_counter_(0),
Alex Light40607862019-05-06 18:16:24 +0000172 alloc_entrypoints_instrumented_(false),
173 can_use_instrumentation_trampolines_(true) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700174}
175
Vladimir Marko19711d42019-04-12 14:05:34 +0100176void Instrumentation::InstallStubsForClass(ObjPtr<mirror::Class> klass) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000177 if (!klass->IsResolved()) {
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100178 // We need the class to be resolved to install/uninstall stubs. Otherwise its methods
179 // could not be initialized or linked with regards to class inheritance.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000180 } else if (klass->IsErroneousResolved()) {
181 // We can't execute code in a erroneous class: do nothing.
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100182 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -0700183 for (ArtMethod& method : klass->GetMethods(kRuntimePointerSize)) {
Alex Light51a64d52015-12-17 13:55:59 -0800184 InstallStubsForMethod(&method);
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100185 }
jeffhao725a9572012-11-13 18:20:12 -0800186 }
jeffhao725a9572012-11-13 18:20:12 -0800187}
188
Mathieu Chartiere401d142015-04-22 13:56:20 -0700189static void UpdateEntrypoints(ArtMethod* method, const void* quick_code)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700190 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800191 method->SetEntryPointFromQuickCompiledCode(quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100192}
193
Alex Light0fa17862017-10-24 13:43:05 -0700194bool Instrumentation::NeedDebugVersionFor(ArtMethod* method) const
195 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightf2858632018-04-02 11:28:50 -0700196 art::Runtime* runtime = Runtime::Current();
197 // If anything says we need the debug version or we are debuggable we will need the debug version
198 // of the method.
199 return (runtime->GetRuntimeCallbacks()->MethodNeedsDebugVersion(method) ||
200 runtime->IsJavaDebuggable()) &&
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800201 !method->IsNative() &&
Alex Lightf2858632018-04-02 11:28:50 -0700202 !method->IsProxyMethod();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800203}
204
Mathieu Chartiere401d142015-04-22 13:56:20 -0700205void Instrumentation::InstallStubsForMethod(ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -0700206 if (!method->IsInvokable() || method->IsProxyMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100207 // Do not change stubs for these methods.
208 return;
209 }
Jeff Hao56802772014-08-19 10:17:36 -0700210 // Don't stub Proxy.<init>. Note that the Proxy class itself is not a proxy class.
Alex Light6cae5ea2018-06-07 17:07:02 -0700211 // TODO We should remove the need for this since it means we cannot always correctly detect calls
212 // to Proxy.<init>
213 // Annoyingly this can be called before we have actually initialized WellKnownClasses so therefore
214 // we also need to check this based on the declaring-class descriptor. The check is valid because
215 // Proxy only has a single constructor.
216 ArtMethod* well_known_proxy_init = jni::DecodeArtMethod(
217 WellKnownClasses::java_lang_reflect_Proxy_init);
218 if ((LIKELY(well_known_proxy_init != nullptr) && UNLIKELY(method == well_known_proxy_init)) ||
219 UNLIKELY(method->IsConstructor() &&
220 method->GetDeclaringClass()->DescriptorEquals("Ljava/lang/reflect/Proxy;"))) {
Jeff Haodb8a6642014-08-14 17:18:52 -0700221 return;
222 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800223 const void* new_quick_code;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100224 bool uninstall = !entry_exit_stubs_installed_ && !interpreter_stubs_installed_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800225 Runtime* const runtime = Runtime::Current();
226 ClassLinker* const class_linker = runtime->GetClassLinker();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100227 bool is_class_initialized = method->GetDeclaringClass()->IsInitialized();
228 if (uninstall) {
229 if ((forced_interpret_only_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800230 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100231 } else if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700232 new_quick_code = GetCodeForInvoke(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100233 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700234 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100235 }
236 } else { // !uninstall
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100237 if ((interpreter_stubs_installed_ || forced_interpret_only_ || IsDeoptimized(method)) &&
238 !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800239 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100240 } else {
241 // Do not overwrite resolution trampoline. When the trampoline initializes the method's
242 // class, all its static methods code will be set to the instrumentation entry point.
243 // For more details, see ClassLinker::FixupStaticTrampolines.
244 if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light2d441b12018-06-08 15:33:21 -0700245 if (entry_exit_stubs_installed_) {
246 // This needs to be checked first since the instrumentation entrypoint will be able to
247 // find the actual JIT compiled code that corresponds to this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800248 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700249 } else if (NeedDebugVersionFor(method)) {
250 // It would be great to search the JIT for its implementation here but we cannot due to
251 // the locks we hold. Instead just set to the interpreter bridge and that code will search
252 // the JIT when it gets called and replace the entrypoint then.
253 new_quick_code = GetQuickToInterpreterBridge();
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000254 } else {
Alex Lightfc49fec2018-01-16 22:28:36 +0000255 new_quick_code = class_linker->GetQuickOatCodeFor(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100256 }
257 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700258 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100259 }
260 }
261 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800262 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100263}
264
Ian Rogers62d6c772013-02-27 08:32:07 -0800265// Places the instrumentation exit pc as the return PC for every quick frame. This also allows
266// deoptimization of quick frames to interpreter frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100267// Since we may already have done this previously, we need to push new instrumentation frame before
268// existing instrumentation frames.
Ian Rogers62d6c772013-02-27 08:32:07 -0800269static void InstrumentationInstallStack(Thread* thread, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700270 REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100271 struct InstallStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800272 InstallStackVisitor(Thread* thread_in, Context* context, uintptr_t instrumentation_exit_pc)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100273 : StackVisitor(thread_in, context, kInstrumentationStackWalk),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800274 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100275 instrumentation_exit_pc_(instrumentation_exit_pc),
Alex Lighte9278662018-03-08 16:55:58 -0800276 reached_existing_instrumentation_frames_(false), instrumentation_stack_depth_(0),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100277 last_return_pc_(0) {
278 }
jeffhao725a9572012-11-13 18:20:12 -0800279
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100280 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700281 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700282 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800283 if (kVerboseInstrumentation) {
284 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
285 }
286 last_return_pc_ = 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700287 return true; // Ignore upcalls.
Ian Rogers306057f2012-11-26 12:45:53 -0800288 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700289 if (GetCurrentQuickFrame() == nullptr) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800290 bool interpreter_frame = true;
Sebastien Hertz320deb22014-06-11 19:45:05 +0200291 InstrumentationStackFrame instrumentation_frame(GetThisObject(), m, 0, GetFrameId(),
292 interpreter_frame);
Jeff Haoa15a81b2014-05-27 18:25:47 -0700293 if (kVerboseInstrumentation) {
294 LOG(INFO) << "Pushing shadow frame " << instrumentation_frame.Dump();
295 }
296 shadow_stack_.push_back(instrumentation_frame);
297 return true; // Continue.
298 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800299 uintptr_t return_pc = GetReturnPc();
Sebastien Hertz320deb22014-06-11 19:45:05 +0200300 if (kVerboseInstrumentation) {
301 LOG(INFO) << " Installing exit stub in " << DescribeLocation();
302 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100303 if (return_pc == instrumentation_exit_pc_) {
Mingyao Yang2ee17902017-08-30 11:37:08 -0700304 CHECK_LT(instrumentation_stack_depth_, instrumentation_stack_->size());
305
306 if (m->IsRuntimeMethod()) {
307 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100308 (*instrumentation_stack_)[instrumentation_stack_depth_];
Mingyao Yang2ee17902017-08-30 11:37:08 -0700309 if (frame.interpreter_entry_) {
310 // This instrumentation frame is for an interpreter bridge and is
311 // pushed when executing the instrumented interpreter bridge. So method
312 // enter event must have been reported. However we need to push a DEX pc
313 // into the dex_pcs_ list to match size of instrumentation stack.
Andreas Gampee2abbc62017-09-15 11:59:26 -0700314 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700315 dex_pcs_.push_back(dex_pc);
316 last_return_pc_ = frame.return_pc_;
317 ++instrumentation_stack_depth_;
318 return true;
319 }
320 }
321
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100322 // We've reached a frame which has already been installed with instrumentation exit stub.
Alex Light74c91c92018-03-08 14:01:44 -0800323 // We should have already installed instrumentation or be interpreter on previous frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100324 reached_existing_instrumentation_frames_ = true;
325
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200326 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100327 (*instrumentation_stack_)[instrumentation_stack_depth_];
Alex Lightfc81d802018-12-07 13:39:05 -0800328 CHECK_EQ(m->GetNonObsoleteMethod(), frame.method_->GetNonObsoleteMethod())
329 << "Expected " << ArtMethod::PrettyMethod(m)
330 << ", Found " << ArtMethod::PrettyMethod(frame.method_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100331 return_pc = frame.return_pc_;
332 if (kVerboseInstrumentation) {
333 LOG(INFO) << "Ignoring already instrumented " << frame.Dump();
334 }
335 } else {
336 CHECK_NE(return_pc, 0U);
Alex Light74c91c92018-03-08 14:01:44 -0800337 if (UNLIKELY(reached_existing_instrumentation_frames_ && !m->IsRuntimeMethod())) {
338 // We already saw an existing instrumentation frame so this should be a runtime-method
339 // inserted by the interpreter or runtime.
Alex Lighte9278662018-03-08 16:55:58 -0800340 std::string thread_name;
341 GetThread()->GetThreadName(thread_name);
342 uint32_t dex_pc = dex::kDexNoIndex;
343 if (last_return_pc_ != 0 &&
344 GetCurrentOatQuickMethodHeader() != nullptr) {
345 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
346 }
Alex Light74c91c92018-03-08 14:01:44 -0800347 LOG(FATAL) << "While walking " << thread_name << " found unexpected non-runtime method"
348 << " without instrumentation exit return or interpreter frame."
Alex Lighte9278662018-03-08 16:55:58 -0800349 << " method is " << GetMethod()->PrettyMethod()
350 << " return_pc is " << std::hex << return_pc
351 << " dex pc: " << dex_pc;
352 UNREACHABLE();
353 }
Mingyao Yang2ee17902017-08-30 11:37:08 -0700354 InstrumentationStackFrame instrumentation_frame(
355 m->IsRuntimeMethod() ? nullptr : GetThisObject(),
356 m,
357 return_pc,
358 GetFrameId(), // A runtime method still gets a frame id.
359 false);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100360 if (kVerboseInstrumentation) {
361 LOG(INFO) << "Pushing frame " << instrumentation_frame.Dump();
362 }
363
Sebastien Hertz320deb22014-06-11 19:45:05 +0200364 // Insert frame at the right position so we do not corrupt the instrumentation stack.
365 // Instrumentation stack frames are in descending frame id order.
366 auto it = instrumentation_stack_->begin();
367 for (auto end = instrumentation_stack_->end(); it != end; ++it) {
368 const InstrumentationStackFrame& current = *it;
369 if (instrumentation_frame.frame_id_ >= current.frame_id_) {
370 break;
371 }
372 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100373 instrumentation_stack_->insert(it, instrumentation_frame);
374 SetReturnPc(instrumentation_exit_pc_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800375 }
Andreas Gampee2abbc62017-09-15 11:59:26 -0700376 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700377 if (last_return_pc_ != 0 &&
378 GetCurrentOatQuickMethodHeader() != nullptr) {
379 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
380 }
381 dex_pcs_.push_back(dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800382 last_return_pc_ = return_pc;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100383 ++instrumentation_stack_depth_;
Ian Rogers306057f2012-11-26 12:45:53 -0800384 return true; // Continue.
385 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800386 std::deque<InstrumentationStackFrame>* const instrumentation_stack_;
Jeff Haoa15a81b2014-05-27 18:25:47 -0700387 std::vector<InstrumentationStackFrame> shadow_stack_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800388 std::vector<uint32_t> dex_pcs_;
Ian Rogers306057f2012-11-26 12:45:53 -0800389 const uintptr_t instrumentation_exit_pc_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100390 bool reached_existing_instrumentation_frames_;
391 size_t instrumentation_stack_depth_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800392 uintptr_t last_return_pc_;
Ian Rogers306057f2012-11-26 12:45:53 -0800393 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800394 if (kVerboseInstrumentation) {
395 std::string thread_name;
396 thread->GetThreadName(thread_name);
397 LOG(INFO) << "Installing exit stubs in " << thread_name;
Ian Rogers306057f2012-11-26 12:45:53 -0800398 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100399
400 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers700a4022014-05-19 16:49:03 -0700401 std::unique_ptr<Context> context(Context::Create());
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700402 uintptr_t instrumentation_exit_pc = reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100403 InstallStackVisitor visitor(thread, context.get(), instrumentation_exit_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800404 visitor.WalkStack(true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100405 CHECK_EQ(visitor.dex_pcs_.size(), thread->GetInstrumentationStack()->size());
Ian Rogers62d6c772013-02-27 08:32:07 -0800406
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100407 if (instrumentation->ShouldNotifyMethodEnterExitEvents()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100408 // Create method enter events for all methods currently on the thread's stack. We only do this
409 // if no debugger is attached to prevent from posting events twice.
Jeff Haoa15a81b2014-05-27 18:25:47 -0700410 auto ssi = visitor.shadow_stack_.rbegin();
411 for (auto isi = thread->GetInstrumentationStack()->rbegin(),
412 end = thread->GetInstrumentationStack()->rend(); isi != end; ++isi) {
413 while (ssi != visitor.shadow_stack_.rend() && (*ssi).frame_id_ < (*isi).frame_id_) {
414 instrumentation->MethodEnterEvent(thread, (*ssi).this_object_, (*ssi).method_, 0);
415 ++ssi;
416 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100417 uint32_t dex_pc = visitor.dex_pcs_.back();
418 visitor.dex_pcs_.pop_back();
Alex Lightdc5423f2018-06-08 10:43:38 -0700419 if (!isi->interpreter_entry_ && !isi->method_->IsRuntimeMethod()) {
Sebastien Hertz320deb22014-06-11 19:45:05 +0200420 instrumentation->MethodEnterEvent(thread, (*isi).this_object_, (*isi).method_, dex_pc);
421 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100422 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800423 }
424 thread->VerifyStack();
Ian Rogers306057f2012-11-26 12:45:53 -0800425}
426
Mingyao Yang99170c62015-07-06 11:10:37 -0700427void Instrumentation::InstrumentThreadStack(Thread* thread) {
428 instrumentation_stubs_installed_ = true;
429 InstrumentationInstallStack(thread, this);
430}
431
Ian Rogers62d6c772013-02-27 08:32:07 -0800432// Removes the instrumentation exit pc as the return PC for every quick frame.
433static void InstrumentationRestoreStack(Thread* thread, void* arg)
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000434 REQUIRES(Locks::mutator_lock_) {
435 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
436
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100437 struct RestoreStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800438 RestoreStackVisitor(Thread* thread_in, uintptr_t instrumentation_exit_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800439 Instrumentation* instrumentation)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100440 : StackVisitor(thread_in, nullptr, kInstrumentationStackWalk),
441 thread_(thread_in),
Ian Rogers62d6c772013-02-27 08:32:07 -0800442 instrumentation_exit_pc_(instrumentation_exit_pc),
443 instrumentation_(instrumentation),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800444 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Ian Rogers62d6c772013-02-27 08:32:07 -0800445 frames_removed_(0) {}
Ian Rogers306057f2012-11-26 12:45:53 -0800446
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100447 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800448 if (instrumentation_stack_->size() == 0) {
jeffhao725a9572012-11-13 18:20:12 -0800449 return false; // Stop.
450 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700451 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700452 if (GetCurrentQuickFrame() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800453 if (kVerboseInstrumentation) {
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200454 LOG(INFO) << " Ignoring a shadow frame. Frame " << GetFrameId()
David Sehr709b0702016-10-13 09:12:37 -0700455 << " Method=" << ArtMethod::PrettyMethod(m);
Ian Rogers62d6c772013-02-27 08:32:07 -0800456 }
457 return true; // Ignore shadow frames.
458 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700459 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800460 if (kVerboseInstrumentation) {
461 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
462 }
Ian Rogers306057f2012-11-26 12:45:53 -0800463 return true; // Ignore upcalls.
464 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800465 bool removed_stub = false;
466 // TODO: make this search more efficient?
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100467 const size_t frameId = GetFrameId();
468 for (const InstrumentationStackFrame& instrumentation_frame : *instrumentation_stack_) {
469 if (instrumentation_frame.frame_id_ == frameId) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800470 if (kVerboseInstrumentation) {
471 LOG(INFO) << " Removing exit stub in " << DescribeLocation();
472 }
Jeff Hao9a916d32013-06-27 18:45:37 -0700473 if (instrumentation_frame.interpreter_entry_) {
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700474 CHECK(m == Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
Jeff Hao9a916d32013-06-27 18:45:37 -0700475 } else {
Alex Lightfc81d802018-12-07 13:39:05 -0800476 CHECK_EQ(m->GetNonObsoleteMethod(),
477 instrumentation_frame.method_->GetNonObsoleteMethod())
478 << ArtMethod::PrettyMethod(m);
Jeff Hao9a916d32013-06-27 18:45:37 -0700479 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800480 SetReturnPc(instrumentation_frame.return_pc_);
Mingyao Yang2ee17902017-08-30 11:37:08 -0700481 if (instrumentation_->ShouldNotifyMethodEnterExitEvents() &&
482 !m->IsRuntimeMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100483 // Create the method exit events. As the methods didn't really exit the result is 0.
484 // We only do this if no debugger is attached to prevent from posting events twice.
485 instrumentation_->MethodExitEvent(thread_, instrumentation_frame.this_object_, m,
486 GetDexPc(), JValue());
487 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800488 frames_removed_++;
489 removed_stub = true;
490 break;
491 }
492 }
493 if (!removed_stub) {
494 if (kVerboseInstrumentation) {
495 LOG(INFO) << " No exit stub in " << DescribeLocation();
Ian Rogers306057f2012-11-26 12:45:53 -0800496 }
jeffhao725a9572012-11-13 18:20:12 -0800497 }
498 return true; // Continue.
499 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800500 Thread* const thread_;
Ian Rogers306057f2012-11-26 12:45:53 -0800501 const uintptr_t instrumentation_exit_pc_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800502 Instrumentation* const instrumentation_;
503 std::deque<instrumentation::InstrumentationStackFrame>* const instrumentation_stack_;
504 size_t frames_removed_;
jeffhao725a9572012-11-13 18:20:12 -0800505 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800506 if (kVerboseInstrumentation) {
507 std::string thread_name;
508 thread->GetThreadName(thread_name);
509 LOG(INFO) << "Removing exit stubs in " << thread_name;
510 }
511 std::deque<instrumentation::InstrumentationStackFrame>* stack = thread->GetInstrumentationStack();
512 if (stack->size() > 0) {
513 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700514 uintptr_t instrumentation_exit_pc =
515 reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Ian Rogers62d6c772013-02-27 08:32:07 -0800516 RestoreStackVisitor visitor(thread, instrumentation_exit_pc, instrumentation);
517 visitor.WalkStack(true);
518 CHECK_EQ(visitor.frames_removed_, stack->size());
519 while (stack->size() > 0) {
520 stack->pop_front();
521 }
jeffhao725a9572012-11-13 18:20:12 -0800522 }
523}
524
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200525static bool HasEvent(Instrumentation::InstrumentationEvent expected, uint32_t events) {
526 return (events & expected) != 0;
527}
528
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000529static void PotentiallyAddListenerTo(Instrumentation::InstrumentationEvent event,
530 uint32_t events,
531 std::list<InstrumentationListener*>& list,
532 InstrumentationListener* listener,
533 bool* has_listener)
534 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
535 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
536 if (!HasEvent(event, events)) {
537 return;
538 }
539 // If there is a free slot in the list, we insert the listener in that slot.
540 // Otherwise we add it to the end of the list.
541 auto it = std::find(list.begin(), list.end(), nullptr);
542 if (it != list.end()) {
543 *it = listener;
544 } else {
545 list.push_back(listener);
546 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100547 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000548}
549
Ian Rogers62d6c772013-02-27 08:32:07 -0800550void Instrumentation::AddListener(InstrumentationListener* listener, uint32_t events) {
551 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000552 PotentiallyAddListenerTo(kMethodEntered,
553 events,
554 method_entry_listeners_,
555 listener,
556 &have_method_entry_listeners_);
557 PotentiallyAddListenerTo(kMethodExited,
558 events,
559 method_exit_listeners_,
560 listener,
561 &have_method_exit_listeners_);
562 PotentiallyAddListenerTo(kMethodUnwind,
563 events,
564 method_unwind_listeners_,
565 listener,
566 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000567 PotentiallyAddListenerTo(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000568 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000569 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000570 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000571 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000572 PotentiallyAddListenerTo(kDexPcMoved,
573 events,
574 dex_pc_listeners_,
575 listener,
576 &have_dex_pc_listeners_);
577 PotentiallyAddListenerTo(kFieldRead,
578 events,
579 field_read_listeners_,
580 listener,
581 &have_field_read_listeners_);
582 PotentiallyAddListenerTo(kFieldWritten,
583 events,
584 field_write_listeners_,
585 listener,
586 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700587 PotentiallyAddListenerTo(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000588 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700589 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000590 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700591 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700592 PotentiallyAddListenerTo(kWatchedFramePop,
593 events,
594 watched_frame_pop_listeners_,
595 listener,
596 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700597 PotentiallyAddListenerTo(kExceptionHandled,
598 events,
599 exception_handled_listeners_,
600 listener,
601 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200602 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800603}
604
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000605static void PotentiallyRemoveListenerFrom(Instrumentation::InstrumentationEvent event,
606 uint32_t events,
607 std::list<InstrumentationListener*>& list,
608 InstrumentationListener* listener,
609 bool* has_listener)
610 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
611 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
612 if (!HasEvent(event, events)) {
613 return;
614 }
615 auto it = std::find(list.begin(), list.end(), listener);
616 if (it != list.end()) {
617 // Just update the entry, do not remove from the list. Removing entries in the list
618 // is unsafe when mutators are iterating over it.
619 *it = nullptr;
620 }
621
622 // Check if the list contains any non-null listener, and update 'has_listener'.
623 for (InstrumentationListener* l : list) {
624 if (l != nullptr) {
David Srbecky28f6cff2018-10-16 15:07:28 +0100625 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000626 return;
627 }
628 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100629 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = false; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000630}
631
Ian Rogers62d6c772013-02-27 08:32:07 -0800632void Instrumentation::RemoveListener(InstrumentationListener* listener, uint32_t events) {
633 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000634 PotentiallyRemoveListenerFrom(kMethodEntered,
635 events,
636 method_entry_listeners_,
637 listener,
638 &have_method_entry_listeners_);
639 PotentiallyRemoveListenerFrom(kMethodExited,
640 events,
641 method_exit_listeners_,
642 listener,
643 &have_method_exit_listeners_);
644 PotentiallyRemoveListenerFrom(kMethodUnwind,
645 events,
646 method_unwind_listeners_,
647 listener,
648 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000649 PotentiallyRemoveListenerFrom(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000650 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000651 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000652 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000653 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000654 PotentiallyRemoveListenerFrom(kDexPcMoved,
655 events,
656 dex_pc_listeners_,
657 listener,
658 &have_dex_pc_listeners_);
659 PotentiallyRemoveListenerFrom(kFieldRead,
660 events,
661 field_read_listeners_,
662 listener,
663 &have_field_read_listeners_);
664 PotentiallyRemoveListenerFrom(kFieldWritten,
665 events,
666 field_write_listeners_,
667 listener,
668 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700669 PotentiallyRemoveListenerFrom(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000670 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700671 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000672 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700673 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700674 PotentiallyRemoveListenerFrom(kWatchedFramePop,
675 events,
676 watched_frame_pop_listeners_,
677 listener,
678 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700679 PotentiallyRemoveListenerFrom(kExceptionHandled,
680 events,
681 exception_handled_listeners_,
682 listener,
683 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200684 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800685}
686
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200687Instrumentation::InstrumentationLevel Instrumentation::GetCurrentInstrumentationLevel() const {
Alex Light4ba388a2017-01-27 10:26:49 -0800688 if (interpreter_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200689 return InstrumentationLevel::kInstrumentWithInterpreter;
Ian Rogers62d6c772013-02-27 08:32:07 -0800690 } else if (entry_exit_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200691 return InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Ian Rogers62d6c772013-02-27 08:32:07 -0800692 } else {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200693 return InstrumentationLevel::kInstrumentNothing;
Ian Rogers62d6c772013-02-27 08:32:07 -0800694 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200695}
696
Alex Lightdba61482016-12-21 08:20:29 -0800697bool Instrumentation::RequiresInstrumentationInstallation(InstrumentationLevel new_level) const {
Alex Light4ba388a2017-01-27 10:26:49 -0800698 // We need to reinstall instrumentation if we go to a different level.
699 return GetCurrentInstrumentationLevel() != new_level;
Alex Lightdba61482016-12-21 08:20:29 -0800700}
701
Alex Light40607862019-05-06 18:16:24 +0000702void Instrumentation::UpdateInstrumentationLevels(InstrumentationLevel level) {
703 if (level == InstrumentationLevel::kInstrumentWithInterpreter) {
704 can_use_instrumentation_trampolines_ = false;
705 }
706 if (UNLIKELY(!can_use_instrumentation_trampolines_)) {
707 for (auto& p : requested_instrumentation_levels_) {
708 if (p.second == InstrumentationLevel::kInstrumentWithInstrumentationStubs) {
709 p.second = InstrumentationLevel::kInstrumentWithInterpreter;
710 }
711 }
712 }
713}
714
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200715void Instrumentation::ConfigureStubs(const char* key, InstrumentationLevel desired_level) {
716 // Store the instrumentation level for this key or remove it.
717 if (desired_level == InstrumentationLevel::kInstrumentNothing) {
718 // The client no longer needs instrumentation.
719 requested_instrumentation_levels_.erase(key);
720 } else {
721 // The client needs instrumentation.
722 requested_instrumentation_levels_.Overwrite(key, desired_level);
723 }
724
Alex Light40607862019-05-06 18:16:24 +0000725 UpdateInstrumentationLevels(desired_level);
726 UpdateStubs();
727}
728
729void Instrumentation::EnableSingleThreadDeopt() {
730 // Single-thread deopt only uses interpreter.
731 can_use_instrumentation_trampolines_ = false;
732 UpdateInstrumentationLevels(InstrumentationLevel::kInstrumentWithInterpreter);
733 UpdateStubs();
734}
735
736void Instrumentation::UpdateStubs() {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200737 // Look for the highest required instrumentation level.
738 InstrumentationLevel requested_level = InstrumentationLevel::kInstrumentNothing;
739 for (const auto& v : requested_instrumentation_levels_) {
740 requested_level = std::max(requested_level, v.second);
741 }
742
Alex Light40607862019-05-06 18:16:24 +0000743 DCHECK(can_use_instrumentation_trampolines_ ||
744 requested_level != InstrumentationLevel::kInstrumentWithInstrumentationStubs)
745 << "Use trampolines: " << can_use_instrumentation_trampolines_ << " level "
746 << requested_level;
747
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200748 interpret_only_ = (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) ||
749 forced_interpret_only_;
750
Alex Lightdba61482016-12-21 08:20:29 -0800751 if (!RequiresInstrumentationInstallation(requested_level)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800752 // We're already set.
753 return;
754 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100755 Thread* const self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800756 Runtime* runtime = Runtime::Current();
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100757 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800758 Locks::thread_list_lock_->AssertNotHeld(self);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200759 if (requested_level > InstrumentationLevel::kInstrumentNothing) {
Alex Light4ba388a2017-01-27 10:26:49 -0800760 if (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800761 interpreter_stubs_installed_ = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800762 entry_exit_stubs_installed_ = true;
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200763 } else {
764 CHECK_EQ(requested_level, InstrumentationLevel::kInstrumentWithInstrumentationStubs);
765 entry_exit_stubs_installed_ = true;
766 interpreter_stubs_installed_ = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800767 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700768 InstallStubsClassVisitor visitor(this);
769 runtime->GetClassLinker()->VisitClasses(&visitor);
Ian Rogers62d6c772013-02-27 08:32:07 -0800770 instrumentation_stubs_installed_ = true;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100771 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800772 runtime->GetThreadList()->ForEach(InstrumentationInstallStack, this);
773 } else {
774 interpreter_stubs_installed_ = false;
775 entry_exit_stubs_installed_ = false;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700776 InstallStubsClassVisitor visitor(this);
777 runtime->GetClassLinker()->VisitClasses(&visitor);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100778 // Restore stack only if there is no method currently deoptimized.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700779 bool empty;
780 {
Andreas Gampe7e56a072018-11-29 10:40:06 -0800781 ReaderMutexLock mu(self, *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700782 empty = IsDeoptimizedMethodsEmpty(); // Avoid lock violation.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700783 }
784 if (empty) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100785 MutexLock mu(self, *Locks::thread_list_lock_);
786 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000787 // Only do this after restoring, as walking the stack when restoring will see
788 // the instrumentation exit pc.
789 instrumentation_stubs_installed_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100790 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800791 }
jeffhao725a9572012-11-13 18:20:12 -0800792}
793
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200794static void ResetQuickAllocEntryPointsForThread(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -0800795 thread->ResetQuickAllocEntryPointsForThread(kUseReadBarrier && thread->GetIsGcMarking());
Ian Rogersfa824272013-11-05 16:12:57 -0800796}
797
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700798void Instrumentation::SetEntrypointsInstrumented(bool instrumented) {
799 Thread* self = Thread::Current();
Mathieu Chartier661974a2014-01-09 11:23:53 -0800800 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700801 Locks::mutator_lock_->AssertNotHeld(self);
802 Locks::instrument_entrypoints_lock_->AssertHeld(self);
803 if (runtime->IsStarted()) {
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700804 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700805 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier661974a2014-01-09 11:23:53 -0800806 SetQuickAllocEntryPointsInstrumented(instrumented);
807 ResetQuickAllocEntryPoints();
Mathieu Chartier50e93312016-03-16 11:25:29 -0700808 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700809 } else {
810 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
811 SetQuickAllocEntryPointsInstrumented(instrumented);
Andreas Gampe157c77e2016-10-17 17:44:41 -0700812
813 // Note: ResetQuickAllocEntryPoints only works when the runtime is started. Manually run the
814 // update for just this thread.
Andreas Gampe162ae502016-10-18 10:03:42 -0700815 // Note: self may be null. One of those paths is setting instrumentation in the Heap
816 // constructor for gcstress mode.
817 if (self != nullptr) {
818 ResetQuickAllocEntryPointsForThread(self, nullptr);
819 }
Andreas Gampe157c77e2016-10-17 17:44:41 -0700820
Mathieu Chartier50e93312016-03-16 11:25:29 -0700821 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier661974a2014-01-09 11:23:53 -0800822 }
823}
824
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700825void Instrumentation::InstrumentQuickAllocEntryPoints() {
826 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
827 InstrumentQuickAllocEntryPointsLocked();
Ian Rogersfa824272013-11-05 16:12:57 -0800828}
829
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700830void Instrumentation::UninstrumentQuickAllocEntryPoints() {
831 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
832 UninstrumentQuickAllocEntryPointsLocked();
833}
834
835void Instrumentation::InstrumentQuickAllocEntryPointsLocked() {
836 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
837 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
838 SetEntrypointsInstrumented(true);
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800839 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700840 ++quick_alloc_entry_points_instrumentation_counter_;
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700841}
842
843void Instrumentation::UninstrumentQuickAllocEntryPointsLocked() {
844 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
845 CHECK_GT(quick_alloc_entry_points_instrumentation_counter_, 0U);
846 --quick_alloc_entry_points_instrumentation_counter_;
847 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
848 SetEntrypointsInstrumented(false);
849 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800850}
851
852void Instrumentation::ResetQuickAllocEntryPoints() {
853 Runtime* runtime = Runtime::Current();
854 if (runtime->IsStarted()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800855 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700856 runtime->GetThreadList()->ForEach(ResetQuickAllocEntryPointsForThread, nullptr);
Ian Rogersfa824272013-11-05 16:12:57 -0800857 }
858}
859
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700860void Instrumentation::UpdateMethodsCodeImpl(ArtMethod* method, const void* quick_code) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800861 const void* new_quick_code;
Ian Rogers62d6c772013-02-27 08:32:07 -0800862 if (LIKELY(!instrumentation_stubs_installed_)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800863 new_quick_code = quick_code;
Jeff Hao65d15d92013-07-16 16:39:33 -0700864 } else {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100865 if ((interpreter_stubs_installed_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800866 new_quick_code = GetQuickToInterpreterBridge();
Jeff Hao65d15d92013-07-16 16:39:33 -0700867 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700868 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700869 if (class_linker->IsQuickResolutionStub(quick_code) ||
870 class_linker->IsQuickToInterpreterBridge(quick_code)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700871 new_quick_code = quick_code;
Alex Light6cae5ea2018-06-07 17:07:02 -0700872 } else if (entry_exit_stubs_installed_ &&
873 // We need to make sure not to replace anything that InstallStubsForMethod
874 // wouldn't. Specifically we cannot stub out Proxy.<init> since subtypes copy the
875 // implementation directly and this will confuse the instrumentation trampolines.
876 // TODO We should remove the need for this since it makes it impossible to profile
877 // Proxy.<init> correctly in all cases.
878 method != jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700879 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700880 if (!method->IsNative() && Runtime::Current()->GetJit() != nullptr) {
881 // Native methods use trampoline entrypoints during interpreter tracing.
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000882 DCHECK(!Runtime::Current()->GetJit()->GetCodeCache()->GetGarbageCollectCodeUnsafe());
Alex Light2d441b12018-06-08 15:33:21 -0700883 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
884 // Tracing will look at the saved entry point in the profiling info to know the actual
885 // entrypoint, so we store it here.
886 if (profiling_info != nullptr) {
887 profiling_info->SetSavedEntryPoint(quick_code);
888 }
889 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700890 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700891 new_quick_code = quick_code;
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700892 }
Jeff Hao65d15d92013-07-16 16:39:33 -0700893 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800894 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800895 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100896}
897
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +0000898void Instrumentation::UpdateNativeMethodsCodeToJitCode(ArtMethod* method, const void* quick_code) {
899 // We don't do any read barrier on `method`'s declaring class in this code, as the JIT might
900 // enter here on a soon-to-be deleted ArtMethod. Updating the entrypoint is OK though, as
901 // the ArtMethod is still in memory.
902 const void* new_quick_code = quick_code;
903 if (UNLIKELY(instrumentation_stubs_installed_) && entry_exit_stubs_installed_) {
904 new_quick_code = GetQuickInstrumentationEntryPoint();
905 }
906 UpdateEntrypoints(method, new_quick_code);
907}
908
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700909void Instrumentation::UpdateMethodsCode(ArtMethod* method, const void* quick_code) {
910 DCHECK(method->GetDeclaringClass()->IsResolved());
911 UpdateMethodsCodeImpl(method, quick_code);
912}
913
Alex Light0a5ec3d2017-07-25 16:50:26 -0700914void Instrumentation::UpdateMethodsCodeToInterpreterEntryPoint(ArtMethod* method) {
915 UpdateMethodsCodeImpl(method, GetQuickToInterpreterBridge());
916}
917
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000918void Instrumentation::UpdateMethodsCodeForJavaDebuggable(ArtMethod* method,
919 const void* quick_code) {
920 // When the runtime is set to Java debuggable, we may update the entry points of
921 // all methods of a class to the interpreter bridge. A method's declaring class
922 // might not be in resolved state yet in that case, so we bypass the DCHECK in
923 // UpdateMethodsCode.
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700924 UpdateMethodsCodeImpl(method, quick_code);
925}
926
Mathieu Chartiere401d142015-04-22 13:56:20 -0700927bool Instrumentation::AddDeoptimizedMethod(ArtMethod* method) {
928 if (IsDeoptimizedMethod(method)) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700929 // Already in the map. Return.
930 return false;
931 }
932 // Not found. Add it.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700933 deoptimized_methods_.insert(method);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700934 return true;
935}
936
Mathieu Chartiere401d142015-04-22 13:56:20 -0700937bool Instrumentation::IsDeoptimizedMethod(ArtMethod* method) {
938 return deoptimized_methods_.find(method) != deoptimized_methods_.end();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700939}
940
Mathieu Chartiere401d142015-04-22 13:56:20 -0700941ArtMethod* Instrumentation::BeginDeoptimizedMethod() {
942 if (deoptimized_methods_.empty()) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700943 // Empty.
944 return nullptr;
945 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700946 return *deoptimized_methods_.begin();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700947}
948
Mathieu Chartiere401d142015-04-22 13:56:20 -0700949bool Instrumentation::RemoveDeoptimizedMethod(ArtMethod* method) {
950 auto it = deoptimized_methods_.find(method);
951 if (it == deoptimized_methods_.end()) {
952 return false;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700953 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700954 deoptimized_methods_.erase(it);
955 return true;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700956}
957
958bool Instrumentation::IsDeoptimizedMethodsEmpty() const {
959 return deoptimized_methods_.empty();
960}
961
Mathieu Chartiere401d142015-04-22 13:56:20 -0700962void Instrumentation::Deoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100963 CHECK(!method->IsNative());
964 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700965 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100966
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700967 Thread* self = Thread::Current();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700968 {
Andreas Gampe7e56a072018-11-29 10:40:06 -0800969 WriterMutexLock mu(self, *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700970 bool has_not_been_deoptimized = AddDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700971 CHECK(has_not_been_deoptimized) << "Method " << ArtMethod::PrettyMethod(method)
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200972 << " is already deoptimized";
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700973 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100974 if (!interpreter_stubs_installed_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800975 UpdateEntrypoints(method, GetQuickInstrumentationEntryPoint());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100976
977 // Install instrumentation exit stub and instrumentation frames. We may already have installed
978 // these previously so it will only cover the newly created frames.
979 instrumentation_stubs_installed_ = true;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700980 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100981 Runtime::Current()->GetThreadList()->ForEach(InstrumentationInstallStack, this);
982 }
983}
984
Mathieu Chartiere401d142015-04-22 13:56:20 -0700985void Instrumentation::Undeoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100986 CHECK(!method->IsNative());
987 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700988 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100989
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700990 Thread* self = Thread::Current();
991 bool empty;
992 {
Andreas Gampe7e56a072018-11-29 10:40:06 -0800993 WriterMutexLock mu(self, *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700994 bool found_and_erased = RemoveDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700995 CHECK(found_and_erased) << "Method " << ArtMethod::PrettyMethod(method)
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700996 << " is not deoptimized";
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700997 empty = IsDeoptimizedMethodsEmpty();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700998 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100999
1000 // Restore code and possibly stack only if we did not deoptimize everything.
1001 if (!interpreter_stubs_installed_) {
1002 // Restore its code or resolution trampoline.
1003 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001004 if (method->IsStatic() && !method->IsConstructor() &&
1005 !method->GetDeclaringClass()->IsInitialized()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001006 UpdateEntrypoints(method, GetQuickResolutionStub());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001007 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001008 const void* quick_code = NeedDebugVersionFor(method)
1009 ? GetQuickToInterpreterBridge()
Alex Lightfc49fec2018-01-16 22:28:36 +00001010 : class_linker->GetQuickOatCodeFor(method);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001011 UpdateEntrypoints(method, quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001012 }
1013
1014 // If there is no deoptimized method left, we can restore the stack of each thread.
Alex Lightf244a572018-06-08 13:56:51 -07001015 if (empty && !entry_exit_stubs_installed_) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001016 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001017 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
1018 instrumentation_stubs_installed_ = false;
1019 }
1020 }
1021}
1022
Mathieu Chartiere401d142015-04-22 13:56:20 -07001023bool Instrumentation::IsDeoptimized(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001024 DCHECK(method != nullptr);
Andreas Gampe7e56a072018-11-29 10:40:06 -08001025 ReaderMutexLock mu(Thread::Current(), *GetDeoptimizedMethodsLock());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001026 return IsDeoptimizedMethod(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001027}
1028
1029void Instrumentation::EnableDeoptimization() {
Andreas Gampe7e56a072018-11-29 10:40:06 -08001030 ReaderMutexLock mu(Thread::Current(), *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001031 CHECK(IsDeoptimizedMethodsEmpty());
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001032 CHECK_EQ(deoptimization_enabled_, false);
1033 deoptimization_enabled_ = true;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001034}
1035
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001036void Instrumentation::DisableDeoptimization(const char* key) {
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001037 CHECK_EQ(deoptimization_enabled_, true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001038 // If we deoptimized everything, undo it.
Alex Lightdba61482016-12-21 08:20:29 -08001039 InstrumentationLevel level = GetCurrentInstrumentationLevel();
1040 if (level == InstrumentationLevel::kInstrumentWithInterpreter) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001041 UndeoptimizeEverything(key);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001042 }
1043 // Undeoptimized selected methods.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001044 while (true) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001045 ArtMethod* method;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001046 {
Andreas Gampe7e56a072018-11-29 10:40:06 -08001047 ReaderMutexLock mu(Thread::Current(), *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001048 if (IsDeoptimizedMethodsEmpty()) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001049 break;
1050 }
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001051 method = BeginDeoptimizedMethod();
1052 CHECK(method != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001053 }
1054 Undeoptimize(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001055 }
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001056 deoptimization_enabled_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001057}
1058
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001059// Indicates if instrumentation should notify method enter/exit events to the listeners.
1060bool Instrumentation::ShouldNotifyMethodEnterExitEvents() const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001061 if (!HasMethodEntryListeners() && !HasMethodExitListeners()) {
1062 return false;
1063 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01001064 return !deoptimization_enabled_ && !interpreter_stubs_installed_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001065}
1066
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001067void Instrumentation::DeoptimizeEverything(const char* key) {
1068 CHECK(deoptimization_enabled_);
1069 ConfigureStubs(key, InstrumentationLevel::kInstrumentWithInterpreter);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001070}
1071
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001072void Instrumentation::UndeoptimizeEverything(const char* key) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001073 CHECK(interpreter_stubs_installed_);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001074 CHECK(deoptimization_enabled_);
1075 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001076}
1077
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001078void Instrumentation::EnableMethodTracing(const char* key, bool needs_interpreter) {
1079 InstrumentationLevel level;
1080 if (needs_interpreter) {
1081 level = InstrumentationLevel::kInstrumentWithInterpreter;
1082 } else {
1083 level = InstrumentationLevel::kInstrumentWithInstrumentationStubs;
1084 }
1085 ConfigureStubs(key, level);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001086}
1087
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001088void Instrumentation::DisableMethodTracing(const char* key) {
1089 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
jeffhao725a9572012-11-13 18:20:12 -08001090}
1091
Alex Light2d441b12018-06-08 15:33:21 -07001092const void* Instrumentation::GetCodeForInvoke(ArtMethod* method) const {
1093 // This is called by instrumentation entry only and that should never be getting proxy methods.
1094 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
1095 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1096 if (LIKELY(!instrumentation_stubs_installed_ && !interpreter_stubs_installed_)) {
1097 // In general we just return whatever the method thinks its entrypoint is here. The only
1098 // exception is if it still has the instrumentation entrypoint. That means we are racing another
1099 // thread getting rid of instrumentation which is unexpected but possible. In that case we want
1100 // to wait and try to get it from the oat file or jit.
1101 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(kRuntimePointerSize);
1102 DCHECK(code != nullptr);
1103 if (code != GetQuickInstrumentationEntryPoint()) {
1104 return code;
1105 } else if (method->IsNative()) {
1106 return class_linker->GetQuickOatCodeFor(method);
1107 }
1108 // We don't know what it is. Fallthough to try to find the code from the JIT or Oat file.
1109 } else if (method->IsNative()) {
1110 // TODO We could have JIT compiled native entrypoints. It might be worth it to find these.
1111 return class_linker->GetQuickOatCodeFor(method);
1112 } else if (UNLIKELY(interpreter_stubs_installed_)) {
1113 return GetQuickToInterpreterBridge();
1114 }
1115 // Since the method cannot be native due to ifs above we can always fall back to interpreter
1116 // bridge.
1117 const void* result = GetQuickToInterpreterBridge();
1118 if (!NeedDebugVersionFor(method)) {
1119 // If we don't need a debug version we should see what the oat file/class linker has to say.
1120 result = class_linker->GetQuickOatCodeFor(method);
1121 }
1122 // If both those fail try the jit.
1123 if (result == GetQuickToInterpreterBridge()) {
1124 jit::Jit* jit = Runtime::Current()->GetJit();
1125 if (jit != nullptr) {
1126 const void* res = jit->GetCodeCache()->FindCompiledCodeForInstrumentation(method);
1127 if (res != nullptr) {
1128 result = res;
1129 }
1130 }
1131 }
1132 return result;
1133}
1134
Andreas Gampe542451c2016-07-26 09:02:02 -07001135const void* Instrumentation::GetQuickCodeFor(ArtMethod* method, PointerSize pointer_size) const {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001136 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers62d6c772013-02-27 08:32:07 -08001137 if (LIKELY(!instrumentation_stubs_installed_)) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08001138 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size);
Vladimir Marko8a630572014-04-09 18:45:35 +01001139 DCHECK(code != nullptr);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001140 if (LIKELY(!class_linker->IsQuickResolutionStub(code) &&
1141 !class_linker->IsQuickToInterpreterBridge(code)) &&
1142 !class_linker->IsQuickResolutionStub(code) &&
1143 !class_linker->IsQuickToInterpreterBridge(code)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001144 return code;
1145 }
1146 }
Alex Lightfc49fec2018-01-16 22:28:36 +00001147 return class_linker->GetQuickOatCodeFor(method);
jeffhao725a9572012-11-13 18:20:12 -08001148}
1149
Alex Lightd7661582017-05-01 13:48:16 -07001150void Instrumentation::MethodEnterEventImpl(Thread* thread,
1151 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001152 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001153 uint32_t dex_pc) const {
Mingyao Yang2ee17902017-08-30 11:37:08 -07001154 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001155 if (HasMethodEntryListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001156 Thread* self = Thread::Current();
1157 StackHandleScope<1> hs(self);
1158 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001159 for (InstrumentationListener* listener : method_entry_listeners_) {
1160 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001161 listener->MethodEntered(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001162 }
1163 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001164 }
1165}
1166
Alex Lightd7661582017-05-01 13:48:16 -07001167void Instrumentation::MethodExitEventImpl(Thread* thread,
1168 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001169 ArtMethod* method,
Alex Lightd7661582017-05-01 13:48:16 -07001170 uint32_t dex_pc,
1171 const JValue& return_value) const {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001172 if (HasMethodExitListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001173 Thread* self = Thread::Current();
1174 StackHandleScope<2> hs(self);
1175 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1176 if (method->GetInterfaceMethodIfProxy(kRuntimePointerSize)
1177 ->GetReturnTypePrimitive() != Primitive::kPrimNot) {
1178 for (InstrumentationListener* listener : method_exit_listeners_) {
1179 if (listener != nullptr) {
1180 listener->MethodExited(thread, thiz, method, dex_pc, return_value);
1181 }
1182 }
1183 } else {
1184 Handle<mirror::Object> ret(hs.NewHandle(return_value.GetL()));
1185 for (InstrumentationListener* listener : method_exit_listeners_) {
1186 if (listener != nullptr) {
1187 listener->MethodExited(thread, thiz, method, dex_pc, ret);
1188 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001189 }
1190 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001191 }
1192}
1193
Alex Lightd7661582017-05-01 13:48:16 -07001194void Instrumentation::MethodUnwindEvent(Thread* thread,
Vladimir Marko19711d42019-04-12 14:05:34 +01001195 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001196 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001197 uint32_t dex_pc) const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001198 if (HasMethodUnwindListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001199 Thread* self = Thread::Current();
1200 StackHandleScope<1> hs(self);
1201 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Mathieu Chartier02e25112013-08-14 16:14:24 -07001202 for (InstrumentationListener* listener : method_unwind_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001203 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001204 listener->MethodUnwind(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001205 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001206 }
1207 }
1208}
1209
Alex Lightd7661582017-05-01 13:48:16 -07001210void Instrumentation::DexPcMovedEventImpl(Thread* thread,
1211 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001212 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001213 uint32_t dex_pc) const {
Alex Lightd7661582017-05-01 13:48:16 -07001214 Thread* self = Thread::Current();
1215 StackHandleScope<1> hs(self);
1216 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001217 for (InstrumentationListener* listener : dex_pc_listeners_) {
1218 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001219 listener->DexPcMoved(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001220 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001221 }
1222}
1223
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001224void Instrumentation::BranchImpl(Thread* thread,
1225 ArtMethod* method,
1226 uint32_t dex_pc,
1227 int32_t offset) const {
1228 for (InstrumentationListener* listener : branch_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001229 if (listener != nullptr) {
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001230 listener->Branch(thread, method, dex_pc, offset);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001231 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001232 }
1233}
1234
Alex Lighte814f9d2017-07-31 16:14:39 -07001235void Instrumentation::WatchedFramePopImpl(Thread* thread, const ShadowFrame& frame) const {
1236 for (InstrumentationListener* listener : watched_frame_pop_listeners_) {
1237 if (listener != nullptr) {
1238 listener->WatchedFramePop(thread, frame);
1239 }
1240 }
1241}
1242
Alex Lightd7661582017-05-01 13:48:16 -07001243void Instrumentation::FieldReadEventImpl(Thread* thread,
1244 ObjPtr<mirror::Object> this_object,
1245 ArtMethod* method,
1246 uint32_t dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001247 ArtField* field) const {
Alex Lightd7661582017-05-01 13:48:16 -07001248 Thread* self = Thread::Current();
1249 StackHandleScope<1> hs(self);
1250 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001251 for (InstrumentationListener* listener : field_read_listeners_) {
1252 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001253 listener->FieldRead(thread, thiz, method, dex_pc, field);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001254 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001255 }
1256}
1257
Alex Lightd7661582017-05-01 13:48:16 -07001258void Instrumentation::FieldWriteEventImpl(Thread* thread,
1259 ObjPtr<mirror::Object> this_object,
1260 ArtMethod* method,
1261 uint32_t dex_pc,
1262 ArtField* field,
1263 const JValue& field_value) const {
1264 Thread* self = Thread::Current();
1265 StackHandleScope<2> hs(self);
1266 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1267 if (field->IsPrimitiveType()) {
1268 for (InstrumentationListener* listener : field_write_listeners_) {
1269 if (listener != nullptr) {
1270 listener->FieldWritten(thread, thiz, method, dex_pc, field, field_value);
1271 }
1272 }
1273 } else {
1274 Handle<mirror::Object> val(hs.NewHandle(field_value.GetL()));
1275 for (InstrumentationListener* listener : field_write_listeners_) {
1276 if (listener != nullptr) {
1277 listener->FieldWritten(thread, thiz, method, dex_pc, field, val);
1278 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001279 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001280 }
1281}
1282
Alex Light6e1607e2017-08-23 10:06:18 -07001283void Instrumentation::ExceptionThrownEvent(Thread* thread,
Vladimir Marko19711d42019-04-12 14:05:34 +01001284 ObjPtr<mirror::Throwable> exception_object) const {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001285 Thread* self = Thread::Current();
1286 StackHandleScope<1> hs(self);
1287 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
Alex Light6e1607e2017-08-23 10:06:18 -07001288 if (HasExceptionThrownListeners()) {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001289 DCHECK_EQ(thread->GetException(), h_exception.Get());
Jeff Haoc0bd4da2013-04-11 15:52:28 -07001290 thread->ClearException();
Alex Light6e1607e2017-08-23 10:06:18 -07001291 for (InstrumentationListener* listener : exception_thrown_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001292 if (listener != nullptr) {
Alex Light6e1607e2017-08-23 10:06:18 -07001293 listener->ExceptionThrown(thread, h_exception);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001294 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001295 }
Alex Light9fb1ab12017-09-05 09:32:49 -07001296 // See b/65049545 for discussion about this behavior.
1297 thread->AssertNoPendingException();
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001298 thread->SetException(h_exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08001299 }
1300}
1301
Alex Light9fb1ab12017-09-05 09:32:49 -07001302void Instrumentation::ExceptionHandledEvent(Thread* thread,
Vladimir Marko19711d42019-04-12 14:05:34 +01001303 ObjPtr<mirror::Throwable> exception_object) const {
Alex Light9fb1ab12017-09-05 09:32:49 -07001304 Thread* self = Thread::Current();
1305 StackHandleScope<1> hs(self);
1306 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
1307 if (HasExceptionHandledListeners()) {
1308 // We should have cleared the exception so that callers can detect a new one.
1309 DCHECK(thread->GetException() == nullptr);
1310 for (InstrumentationListener* listener : exception_handled_listeners_) {
1311 if (listener != nullptr) {
1312 listener->ExceptionHandled(thread, h_exception);
1313 }
1314 }
1315 }
1316}
1317
Sebastien Hertzb2feaaf2015-10-12 13:40:10 +00001318// Computes a frame ID by ignoring inlined frames.
1319size_t Instrumentation::ComputeFrameId(Thread* self,
1320 size_t frame_depth,
1321 size_t inlined_frames_before_frame) {
1322 CHECK_GE(frame_depth, inlined_frames_before_frame);
1323 size_t no_inline_depth = frame_depth - inlined_frames_before_frame;
1324 return StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) - no_inline_depth;
1325}
1326
Ian Rogers62d6c772013-02-27 08:32:07 -08001327static void CheckStackDepth(Thread* self, const InstrumentationStackFrame& instrumentation_frame,
1328 int delta)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001329 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001330 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) + delta;
Ian Rogers62d6c772013-02-27 08:32:07 -08001331 if (frame_id != instrumentation_frame.frame_id_) {
1332 LOG(ERROR) << "Expected frame_id=" << frame_id << " but found "
1333 << instrumentation_frame.frame_id_;
1334 StackVisitor::DescribeStack(self);
1335 CHECK_EQ(frame_id, instrumentation_frame.frame_id_);
1336 }
1337}
1338
Vladimir Marko19711d42019-04-12 14:05:34 +01001339void Instrumentation::PushInstrumentationStackFrame(Thread* self,
1340 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001341 ArtMethod* method,
Vladimir Marko19711d42019-04-12 14:05:34 +01001342 uintptr_t lr,
1343 bool interpreter_entry) {
Alex Lightb7edcda2017-04-27 13:20:31 -07001344 DCHECK(!self->IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001345 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1346 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001347 LOG(INFO) << "Entering " << ArtMethod::PrettyMethod(method) << " from PC "
1348 << reinterpret_cast<void*>(lr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001349 }
Alex Lightb7edcda2017-04-27 13:20:31 -07001350
1351 // We send the enter event before pushing the instrumentation frame to make cleanup easier. If the
1352 // event causes an exception we can simply send the unwind event and return.
1353 StackHandleScope<1> hs(self);
1354 Handle<mirror::Object> h_this(hs.NewHandle(this_object));
1355 if (!interpreter_entry) {
1356 MethodEnterEvent(self, h_this.Get(), method, 0);
1357 if (self->IsExceptionPending()) {
1358 MethodUnwindEvent(self, h_this.Get(), method, 0);
1359 return;
1360 }
1361 }
1362
1363 // We have a callee-save frame meaning this value is guaranteed to never be 0.
1364 DCHECK(!self->IsExceptionPending());
1365 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk);
1366
1367 instrumentation::InstrumentationStackFrame instrumentation_frame(h_this.Get(), method, lr,
Jeff Hao9a916d32013-06-27 18:45:37 -07001368 frame_id, interpreter_entry);
Ian Rogers62d6c772013-02-27 08:32:07 -08001369 stack->push_front(instrumentation_frame);
Ian Rogers62d6c772013-02-27 08:32:07 -08001370}
1371
Mingyao Yang2ee17902017-08-30 11:37:08 -07001372DeoptimizationMethodType Instrumentation::GetDeoptimizationMethodType(ArtMethod* method) {
1373 if (method->IsRuntimeMethod()) {
1374 // Certain methods have strict requirement on whether the dex instruction
1375 // should be re-executed upon deoptimization.
1376 if (method == Runtime::Current()->GetCalleeSaveMethod(
1377 CalleeSaveType::kSaveEverythingForClinit)) {
1378 return DeoptimizationMethodType::kKeepDexPc;
1379 }
1380 if (method == Runtime::Current()->GetCalleeSaveMethod(
1381 CalleeSaveType::kSaveEverythingForSuspendCheck)) {
1382 return DeoptimizationMethodType::kKeepDexPc;
1383 }
1384 }
1385 return DeoptimizationMethodType::kDefault;
1386}
1387
1388// Try to get the shorty of a runtime method if it's an invocation stub.
Andreas Gampec7d878d2018-11-19 18:42:06 +00001389static char GetRuntimeMethodShorty(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
1390 char shorty = 'V';
1391 StackVisitor::WalkStack(
1392 [&shorty](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1393 ArtMethod* m = stack_visitor->GetMethod();
1394 if (m == nullptr || m->IsRuntimeMethod()) {
1395 return true;
Andreas Gampe3d477f32018-11-16 16:40:45 +00001396 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00001397 // The first Java method.
1398 if (m->IsNative()) {
1399 // Use JNI method's shorty for the jni stub.
1400 shorty = m->GetShorty()[0];
1401 } else if (m->IsProxyMethod()) {
1402 // Proxy method just invokes its proxied method via
1403 // art_quick_proxy_invoke_handler.
1404 shorty = m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty()[0];
1405 } else {
1406 const Instruction& instr = m->DexInstructions().InstructionAt(stack_visitor->GetDexPc());
1407 if (instr.IsInvoke()) {
1408 auto get_method_index_fn = [](ArtMethod* caller,
1409 const Instruction& inst,
1410 uint32_t dex_pc)
1411 REQUIRES_SHARED(Locks::mutator_lock_) {
1412 switch (inst.Opcode()) {
1413 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
1414 case Instruction::INVOKE_VIRTUAL_QUICK: {
1415 uint16_t method_idx = caller->GetIndexFromQuickening(dex_pc);
1416 CHECK_NE(method_idx, DexFile::kDexNoIndex16);
1417 return method_idx;
1418 }
1419 default: {
1420 return static_cast<uint16_t>(inst.VRegB());
1421 }
1422 }
1423 };
Nicolas Geoffrayec43a012018-11-17 13:10:40 +00001424
Andreas Gampec7d878d2018-11-19 18:42:06 +00001425 uint16_t method_index = get_method_index_fn(m, instr, stack_visitor->GetDexPc());
1426 const DexFile* dex_file = m->GetDexFile();
1427 if (interpreter::IsStringInit(dex_file, method_index)) {
1428 // Invoking string init constructor is turned into invoking
1429 // StringFactory.newStringFromChars() which returns a string.
1430 shorty = 'L';
1431 } else {
1432 shorty = dex_file->GetMethodShorty(method_index)[0];
1433 }
1434
1435 } else {
1436 // It could be that a non-invoke opcode invokes a stub, which in turn
1437 // invokes Java code. In such cases, we should never expect a return
1438 // value from the stub.
1439 }
1440 }
1441 // Stop stack walking since we've seen a Java frame.
1442 return false;
1443 },
1444 thread,
1445 /* context= */ nullptr,
1446 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
1447 return shorty;
1448}
Mingyao Yang2ee17902017-08-30 11:37:08 -07001449
Alex Lightb7edcda2017-04-27 13:20:31 -07001450TwoWordReturn Instrumentation::PopInstrumentationStackFrame(Thread* self,
1451 uintptr_t* return_pc,
1452 uint64_t* gpr_result,
1453 uint64_t* fpr_result) {
1454 DCHECK(gpr_result != nullptr);
1455 DCHECK(fpr_result != nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001456 // Do the pop.
1457 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1458 CHECK_GT(stack->size(), 0U);
1459 InstrumentationStackFrame instrumentation_frame = stack->front();
1460 stack->pop_front();
1461
1462 // Set return PC and check the sanity of the stack.
1463 *return_pc = instrumentation_frame.return_pc_;
1464 CheckStackDepth(self, instrumentation_frame, 0);
Ian Rogers1d8cdbc2014-09-22 22:51:09 -07001465 self->VerifyStack();
Ian Rogers62d6c772013-02-27 08:32:07 -08001466
Mathieu Chartiere401d142015-04-22 13:56:20 -07001467 ArtMethod* method = instrumentation_frame.method_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001468 uint32_t length;
Andreas Gampe542451c2016-07-26 09:02:02 -07001469 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001470 char return_shorty;
1471
1472 // Runtime method does not call into MethodExitEvent() so there should not be
1473 // suspension point below.
1474 ScopedAssertNoThreadSuspension ants(__FUNCTION__, method->IsRuntimeMethod());
1475 if (method->IsRuntimeMethod()) {
1476 if (method != Runtime::Current()->GetCalleeSaveMethod(
1477 CalleeSaveType::kSaveEverythingForClinit)) {
1478 // If the caller is at an invocation point and the runtime method is not
1479 // for clinit, we need to pass return results to the caller.
1480 // We need the correct shorty to decide whether we need to pass the return
1481 // result for deoptimization below.
Andreas Gampec7d878d2018-11-19 18:42:06 +00001482 return_shorty = GetRuntimeMethodShorty(self);
Mingyao Yang2ee17902017-08-30 11:37:08 -07001483 } else {
1484 // Some runtime methods such as allocations, unresolved field getters, etc.
1485 // have return value. We don't need to set return_value since MethodExitEvent()
1486 // below isn't called for runtime methods. Deoptimization doesn't need the
1487 // value either since the dex instruction will be re-executed by the
1488 // interpreter, except these two cases:
1489 // (1) For an invoke, which is handled above to get the correct shorty.
1490 // (2) For MONITOR_ENTER/EXIT, which cannot be re-executed since it's not
1491 // idempotent. However there is no return value for it anyway.
1492 return_shorty = 'V';
1493 }
1494 } else {
1495 return_shorty = method->GetInterfaceMethodIfProxy(pointer_size)->GetShorty(&length)[0];
1496 }
1497
Alex Lightb7edcda2017-04-27 13:20:31 -07001498 bool is_ref = return_shorty == '[' || return_shorty == 'L';
1499 StackHandleScope<1> hs(self);
1500 MutableHandle<mirror::Object> res(hs.NewHandle<mirror::Object>(nullptr));
Ian Rogers62d6c772013-02-27 08:32:07 -08001501 JValue return_value;
1502 if (return_shorty == 'V') {
1503 return_value.SetJ(0);
1504 } else if (return_shorty == 'F' || return_shorty == 'D') {
Alex Lightb7edcda2017-04-27 13:20:31 -07001505 return_value.SetJ(*fpr_result);
Ian Rogers62d6c772013-02-27 08:32:07 -08001506 } else {
Alex Lightb7edcda2017-04-27 13:20:31 -07001507 return_value.SetJ(*gpr_result);
1508 }
1509 if (is_ref) {
1510 // Take a handle to the return value so we won't lose it if we suspend.
1511 res.Assign(return_value.GetL());
Ian Rogers62d6c772013-02-27 08:32:07 -08001512 }
1513 // TODO: improve the dex pc information here, requires knowledge of current PC as opposed to
1514 // return_pc.
Andreas Gampee2abbc62017-09-15 11:59:26 -07001515 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -07001516 if (!method->IsRuntimeMethod() && !instrumentation_frame.interpreter_entry_) {
Vladimir Marko19711d42019-04-12 14:05:34 +01001517 ObjPtr<mirror::Object> this_object = instrumentation_frame.this_object_;
Sebastien Hertz320deb22014-06-11 19:45:05 +02001518 MethodExitEvent(self, this_object, instrumentation_frame.method_, dex_pc, return_value);
1519 }
jeffhao725a9572012-11-13 18:20:12 -08001520
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001521 // Deoptimize if the caller needs to continue execution in the interpreter. Do nothing if we get
1522 // back to an upcall.
1523 NthCallerVisitor visitor(self, 1, true);
1524 visitor.WalkStack(true);
Sebastien Hertz270a0e12015-01-16 19:49:09 +01001525 bool deoptimize = (visitor.caller != nullptr) &&
Daniel Mihalyieb076692014-08-22 17:33:31 +02001526 (interpreter_stubs_installed_ || IsDeoptimized(visitor.caller) ||
Alex Light3dacdd62019-03-12 15:45:47 +00001527 self->IsForceInterpreter() ||
Daniel Mihalyieb076692014-08-22 17:33:31 +02001528 Dbg::IsForcedInterpreterNeededForUpcall(self, visitor.caller));
Alex Lightb7edcda2017-04-27 13:20:31 -07001529 if (is_ref) {
1530 // Restore the return value if it's a reference since it might have moved.
1531 *reinterpret_cast<mirror::Object**>(gpr_result) = res.Get();
1532 }
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001533 if (deoptimize && Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001534 if (kVerboseInstrumentation) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -08001535 LOG(INFO) << "Deoptimizing "
1536 << visitor.caller->PrettyMethod()
1537 << " by returning from "
1538 << method->PrettyMethod()
1539 << " with result "
1540 << std::hex << return_value.GetJ() << std::dec
1541 << " in "
1542 << *self;
Ian Rogers62d6c772013-02-27 08:32:07 -08001543 }
Mingyao Yang2ee17902017-08-30 11:37:08 -07001544 DeoptimizationMethodType deopt_method_type = GetDeoptimizationMethodType(method);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001545 self->PushDeoptimizationContext(return_value,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001546 return_shorty == 'L' || return_shorty == '[',
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001547 /* exception= */ nullptr ,
1548 /* from_code= */ false,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001549 deopt_method_type);
Andreas Gamped58342c2014-06-05 14:18:08 -07001550 return GetTwoWordSuccessValue(*return_pc,
1551 reinterpret_cast<uintptr_t>(GetQuickDeoptimizationEntryPoint()));
Ian Rogers62d6c772013-02-27 08:32:07 -08001552 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001553 if (deoptimize && !Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Alex Lightd8eb6732018-01-29 15:16:02 -08001554 VLOG(deopt) << "Got a deoptimization request on un-deoptimizable " << method->PrettyMethod()
1555 << " at PC " << reinterpret_cast<void*>(*return_pc);
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001556 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001557 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001558 LOG(INFO) << "Returning from " << method->PrettyMethod()
Brian Carlstrom2d888622013-07-18 17:02:00 -07001559 << " to PC " << reinterpret_cast<void*>(*return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001560 }
Andreas Gamped58342c2014-06-05 14:18:08 -07001561 return GetTwoWordSuccessValue(0, *return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001562 }
jeffhao725a9572012-11-13 18:20:12 -08001563}
1564
Alex Light2c8206f2018-06-08 14:51:09 -07001565uintptr_t Instrumentation::PopFramesForDeoptimization(Thread* self, size_t nframes) const {
Ian Rogers62d6c772013-02-27 08:32:07 -08001566 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
Alex Light2c8206f2018-06-08 14:51:09 -07001567 CHECK_GE(stack->size(), nframes);
1568 if (nframes == 0) {
1569 return 0u;
1570 }
1571 // Only need to send instrumentation events if it's not for deopt (do give the log messages if we
1572 // have verbose-instrumentation anyway though).
1573 if (kVerboseInstrumentation) {
1574 for (size_t i = 0; i < nframes; i++) {
1575 LOG(INFO) << "Popping for deoptimization " << stack->at(i).method_->PrettyMethod();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001576 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001577 }
Alex Light2c8206f2018-06-08 14:51:09 -07001578 // Now that we've sent all the instrumentation events we can actually modify the
1579 // instrumentation-stack. We cannot do this earlier since MethodUnwindEvent can re-enter java and
1580 // do other things that require the instrumentation stack to be in a consistent state with the
1581 // actual stack.
1582 for (size_t i = 0; i < nframes - 1; i++) {
1583 stack->pop_front();
1584 }
1585 uintptr_t return_pc = stack->front().return_pc_;
Alex Lightb7edcda2017-04-27 13:20:31 -07001586 stack->pop_front();
Alex Light2c8206f2018-06-08 14:51:09 -07001587 return return_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -08001588}
1589
1590std::string InstrumentationStackFrame::Dump() const {
1591 std::ostringstream os;
David Sehr709b0702016-10-13 09:12:37 -07001592 os << "Frame " << frame_id_ << " " << ArtMethod::PrettyMethod(method_) << ":"
Ian Rogers62d6c772013-02-27 08:32:07 -08001593 << reinterpret_cast<void*>(return_pc_) << " this=" << reinterpret_cast<void*>(this_object_);
1594 return os.str();
1595}
1596
1597} // namespace instrumentation
jeffhao725a9572012-11-13 18:20:12 -08001598} // namespace art