blob: fc2143f11e17a8d65e4291fcac6e7023dd03fdbc [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
Alex Lightb7c640d2019-03-20 15:52:13 -070019#include <functional>
20#include <optional>
Ian Rogersc7dd2952014-10-21 23:31:19 -070021#include <sstream>
22
Andreas Gampec7d878d2018-11-19 18:42:06 +000023#include <android-base/logging.h>
24
Ian Rogerse63db272014-07-15 15:36:11 -070025#include "arch/context.h"
Alex Lightd7661582017-05-01 13:48:16 -070026#include "art_field-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070027#include "art_method-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080028#include "base/atomic.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070029#include "base/callee_save_type.h"
jeffhao725a9572012-11-13 18:20:12 -080030#include "class_linker.h"
31#include "debugger.h"
David Sehr9e734c72018-01-04 17:56:19 -080032#include "dex/dex_file-inl.h"
33#include "dex/dex_file_types.h"
34#include "dex/dex_instruction-inl.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080035#include "entrypoints/quick/quick_alloc_entrypoints.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070036#include "entrypoints/quick/quick_entrypoints.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070037#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070038#include "gc_root-inl.h"
Sebastien Hertz138dbfc2013-12-04 18:15:25 +010039#include "interpreter/interpreter.h"
Mingyao Yang2ee17902017-08-30 11:37:08 -070040#include "interpreter/interpreter_common.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080041#include "jit/jit.h"
42#include "jit/jit_code_cache.h"
Alex Lightd7661582017-05-01 13:48:16 -070043#include "jvalue-inl.h"
Alex Lightb7c640d2019-03-20 15:52:13 -070044#include "jvalue.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#include "mirror/class-inl.h"
46#include "mirror/dex_cache.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070047#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070048#include "mirror/object_array-inl.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080049#include "nth_caller_visitor.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010050#include "oat_quick_method_header.h"
David Srbecky28f6cff2018-10-16 15:07:28 +010051#include "runtime-inl.h"
jeffhao725a9572012-11-13 18:20:12 -080052#include "thread.h"
53#include "thread_list.h"
jeffhao725a9572012-11-13 18:20:12 -080054
55namespace art {
Ian Rogers62d6c772013-02-27 08:32:07 -080056namespace instrumentation {
jeffhao725a9572012-11-13 18:20:12 -080057
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020058constexpr bool kVerboseInstrumentation = false;
Sebastien Hertz5bfd5c92013-11-15 11:36:07 +010059
Alex Lightb7c640d2019-03-20 15:52:13 -070060void InstrumentationListener::MethodExited(
61 Thread* thread,
62 Handle<mirror::Object> this_object,
63 ArtMethod* method,
64 uint32_t dex_pc,
65 OptionalFrame frame,
66 MutableHandle<mirror::Object>& return_value) {
Alex Lightd7661582017-05-01 13:48:16 -070067 DCHECK_EQ(method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetReturnTypePrimitive(),
68 Primitive::kPrimNot);
Alex Lightb7c640d2019-03-20 15:52:13 -070069 const void* original_ret = return_value.Get();
Alex Lightd7661582017-05-01 13:48:16 -070070 JValue v;
71 v.SetL(return_value.Get());
Alex Lightb7c640d2019-03-20 15:52:13 -070072 MethodExited(thread, this_object, method, dex_pc, frame, v);
73 DCHECK(original_ret == v.GetL()) << "Return value changed";
Alex Lightd7661582017-05-01 13:48:16 -070074}
75
76void InstrumentationListener::FieldWritten(Thread* thread,
77 Handle<mirror::Object> this_object,
78 ArtMethod* method,
79 uint32_t dex_pc,
80 ArtField* field,
81 Handle<mirror::Object> field_value) {
82 DCHECK(!field->IsPrimitiveType());
83 JValue v;
84 v.SetL(field_value.Get());
85 FieldWritten(thread, this_object, method, dex_pc, field, v);
86}
87
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +010088// Instrumentation works on non-inlined frames by updating returned PCs
89// of compiled frames.
90static constexpr StackVisitor::StackWalkKind kInstrumentationStackWalk =
91 StackVisitor::StackWalkKind::kSkipInlinedFrames;
92
Mathieu Chartiere0671ce2015-07-28 17:23:28 -070093class InstallStubsClassVisitor : public ClassVisitor {
94 public:
95 explicit InstallStubsClassVisitor(Instrumentation* instrumentation)
96 : instrumentation_(instrumentation) {}
97
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010098 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -070099 instrumentation_->InstallStubsForClass(klass.Ptr());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700100 return true; // we visit all classes.
101 }
102
103 private:
104 Instrumentation* const instrumentation_;
105};
106
Alex Light2c8206f2018-06-08 14:51:09 -0700107InstrumentationStackPopper::InstrumentationStackPopper(Thread* self)
108 : self_(self),
109 instrumentation_(Runtime::Current()->GetInstrumentation()),
110 frames_to_remove_(0) {}
111
112InstrumentationStackPopper::~InstrumentationStackPopper() {
113 std::deque<instrumentation::InstrumentationStackFrame>* stack = self_->GetInstrumentationStack();
114 for (size_t i = 0; i < frames_to_remove_; i++) {
115 stack->pop_front();
116 }
117}
118
119bool InstrumentationStackPopper::PopFramesTo(uint32_t desired_pops,
120 MutableHandle<mirror::Throwable>& exception) {
121 std::deque<instrumentation::InstrumentationStackFrame>* stack = self_->GetInstrumentationStack();
122 DCHECK_LE(frames_to_remove_, desired_pops);
123 DCHECK_GE(stack->size(), desired_pops);
124 DCHECK(!self_->IsExceptionPending());
125 if (!instrumentation_->HasMethodUnwindListeners()) {
126 frames_to_remove_ = desired_pops;
127 return true;
128 }
129 if (kVerboseInstrumentation) {
130 LOG(INFO) << "Popping frames for exception " << exception->Dump();
131 }
132 // The instrumentation events expect the exception to be set.
133 self_->SetException(exception.Get());
134 bool new_exception_thrown = false;
135 for (; frames_to_remove_ < desired_pops && !new_exception_thrown; frames_to_remove_++) {
136 InstrumentationStackFrame frame = stack->at(frames_to_remove_);
137 ArtMethod* method = frame.method_;
138 // Notify listeners of method unwind.
139 // TODO: improve the dex_pc information here.
140 uint32_t dex_pc = dex::kDexNoIndex;
141 if (kVerboseInstrumentation) {
142 LOG(INFO) << "Popping for unwind " << method->PrettyMethod();
143 }
144 if (!method->IsRuntimeMethod() && !frame.interpreter_entry_) {
145 instrumentation_->MethodUnwindEvent(self_, frame.this_object_, method, dex_pc);
146 new_exception_thrown = self_->GetException() != exception.Get();
147 }
148 }
149 exception.Assign(self_->GetException());
150 self_->ClearException();
151 if (kVerboseInstrumentation && new_exception_thrown) {
152 LOG(INFO) << "Failed to pop " << (desired_pops - frames_to_remove_)
153 << " frames due to new exception";
154 }
155 return !new_exception_thrown;
156}
Ian Rogers62d6c772013-02-27 08:32:07 -0800157
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700158Instrumentation::Instrumentation()
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000159 : instrumentation_stubs_installed_(false),
160 entry_exit_stubs_installed_(false),
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700161 interpreter_stubs_installed_(false),
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000162 interpret_only_(false),
163 forced_interpret_only_(false),
164 have_method_entry_listeners_(false),
165 have_method_exit_listeners_(false),
166 have_method_unwind_listeners_(false),
167 have_dex_pc_listeners_(false),
168 have_field_read_listeners_(false),
169 have_field_write_listeners_(false),
Alex Light6e1607e2017-08-23 10:06:18 -0700170 have_exception_thrown_listeners_(false),
Alex Lighte814f9d2017-07-31 16:14:39 -0700171 have_watched_frame_pop_listeners_(false),
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000172 have_branch_listeners_(false),
Alex Light9fb1ab12017-09-05 09:32:49 -0700173 have_exception_handled_listeners_(false),
Andreas Gampe7e56a072018-11-29 10:40:06 -0800174 deoptimized_methods_lock_(new ReaderWriterMutex("deoptimized methods lock",
175 kGenericBottomLock)),
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700176 deoptimization_enabled_(false),
177 interpreter_handler_table_(kMainHandlerTable),
Mathieu Chartier50e93312016-03-16 11:25:29 -0700178 quick_alloc_entry_points_instrumentation_counter_(0),
Alex Light40607862019-05-06 18:16:24 +0000179 alloc_entrypoints_instrumented_(false),
180 can_use_instrumentation_trampolines_(true) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700181}
182
Vladimir Marko19711d42019-04-12 14:05:34 +0100183void Instrumentation::InstallStubsForClass(ObjPtr<mirror::Class> klass) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000184 if (!klass->IsResolved()) {
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100185 // We need the class to be resolved to install/uninstall stubs. Otherwise its methods
186 // could not be initialized or linked with regards to class inheritance.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000187 } else if (klass->IsErroneousResolved()) {
188 // We can't execute code in a erroneous class: do nothing.
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100189 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -0700190 for (ArtMethod& method : klass->GetMethods(kRuntimePointerSize)) {
Alex Light51a64d52015-12-17 13:55:59 -0800191 InstallStubsForMethod(&method);
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100192 }
jeffhao725a9572012-11-13 18:20:12 -0800193 }
jeffhao725a9572012-11-13 18:20:12 -0800194}
195
Mathieu Chartiere401d142015-04-22 13:56:20 -0700196static void UpdateEntrypoints(ArtMethod* method, const void* quick_code)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700197 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800198 method->SetEntryPointFromQuickCompiledCode(quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100199}
200
Alex Light0fa17862017-10-24 13:43:05 -0700201bool Instrumentation::NeedDebugVersionFor(ArtMethod* method) const
202 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightf2858632018-04-02 11:28:50 -0700203 art::Runtime* runtime = Runtime::Current();
204 // If anything says we need the debug version or we are debuggable we will need the debug version
205 // of the method.
206 return (runtime->GetRuntimeCallbacks()->MethodNeedsDebugVersion(method) ||
207 runtime->IsJavaDebuggable()) &&
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800208 !method->IsNative() &&
Alex Lightf2858632018-04-02 11:28:50 -0700209 !method->IsProxyMethod();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800210}
211
Mathieu Chartiere401d142015-04-22 13:56:20 -0700212void Instrumentation::InstallStubsForMethod(ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -0700213 if (!method->IsInvokable() || method->IsProxyMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100214 // Do not change stubs for these methods.
215 return;
216 }
Jeff Hao56802772014-08-19 10:17:36 -0700217 // Don't stub Proxy.<init>. Note that the Proxy class itself is not a proxy class.
Alex Light6cae5ea2018-06-07 17:07:02 -0700218 // TODO We should remove the need for this since it means we cannot always correctly detect calls
219 // to Proxy.<init>
220 // Annoyingly this can be called before we have actually initialized WellKnownClasses so therefore
221 // we also need to check this based on the declaring-class descriptor. The check is valid because
222 // Proxy only has a single constructor.
223 ArtMethod* well_known_proxy_init = jni::DecodeArtMethod(
224 WellKnownClasses::java_lang_reflect_Proxy_init);
225 if ((LIKELY(well_known_proxy_init != nullptr) && UNLIKELY(method == well_known_proxy_init)) ||
226 UNLIKELY(method->IsConstructor() &&
227 method->GetDeclaringClass()->DescriptorEquals("Ljava/lang/reflect/Proxy;"))) {
Jeff Haodb8a6642014-08-14 17:18:52 -0700228 return;
229 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800230 const void* new_quick_code;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100231 bool uninstall = !entry_exit_stubs_installed_ && !interpreter_stubs_installed_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800232 Runtime* const runtime = Runtime::Current();
233 ClassLinker* const class_linker = runtime->GetClassLinker();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100234 bool is_class_initialized = method->GetDeclaringClass()->IsInitialized();
235 if (uninstall) {
236 if ((forced_interpret_only_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800237 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100238 } else if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700239 new_quick_code = GetCodeForInvoke(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100240 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700241 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100242 }
243 } else { // !uninstall
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100244 if ((interpreter_stubs_installed_ || forced_interpret_only_ || IsDeoptimized(method)) &&
245 !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800246 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100247 } else {
248 // Do not overwrite resolution trampoline. When the trampoline initializes the method's
249 // class, all its static methods code will be set to the instrumentation entry point.
250 // For more details, see ClassLinker::FixupStaticTrampolines.
251 if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light2d441b12018-06-08 15:33:21 -0700252 if (entry_exit_stubs_installed_) {
253 // This needs to be checked first since the instrumentation entrypoint will be able to
254 // find the actual JIT compiled code that corresponds to this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800255 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700256 } else if (NeedDebugVersionFor(method)) {
257 // It would be great to search the JIT for its implementation here but we cannot due to
258 // the locks we hold. Instead just set to the interpreter bridge and that code will search
259 // the JIT when it gets called and replace the entrypoint then.
260 new_quick_code = GetQuickToInterpreterBridge();
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000261 } else {
Alex Lightfc49fec2018-01-16 22:28:36 +0000262 new_quick_code = class_linker->GetQuickOatCodeFor(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100263 }
264 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700265 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100266 }
267 }
268 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800269 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100270}
271
Ian Rogers62d6c772013-02-27 08:32:07 -0800272// Places the instrumentation exit pc as the return PC for every quick frame. This also allows
273// deoptimization of quick frames to interpreter frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100274// Since we may already have done this previously, we need to push new instrumentation frame before
275// existing instrumentation frames.
Ian Rogers62d6c772013-02-27 08:32:07 -0800276static void InstrumentationInstallStack(Thread* thread, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700277 REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100278 struct InstallStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800279 InstallStackVisitor(Thread* thread_in, Context* context, uintptr_t instrumentation_exit_pc)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100280 : StackVisitor(thread_in, context, kInstrumentationStackWalk),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800281 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100282 instrumentation_exit_pc_(instrumentation_exit_pc),
Alex Lighte9278662018-03-08 16:55:58 -0800283 reached_existing_instrumentation_frames_(false), instrumentation_stack_depth_(0),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100284 last_return_pc_(0) {
285 }
jeffhao725a9572012-11-13 18:20:12 -0800286
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100287 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700288 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700289 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800290 if (kVerboseInstrumentation) {
291 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
292 }
293 last_return_pc_ = 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700294 return true; // Ignore upcalls.
Ian Rogers306057f2012-11-26 12:45:53 -0800295 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700296 if (GetCurrentQuickFrame() == nullptr) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800297 bool interpreter_frame = true;
Vladimir Markoabedfca2019-05-23 14:07:47 +0100298 InstrumentationStackFrame instrumentation_frame(GetThisObject().Ptr(),
299 m,
300 /*return_pc=*/ 0,
301 GetFrameId(),
Sebastien Hertz320deb22014-06-11 19:45:05 +0200302 interpreter_frame);
Jeff Haoa15a81b2014-05-27 18:25:47 -0700303 if (kVerboseInstrumentation) {
304 LOG(INFO) << "Pushing shadow frame " << instrumentation_frame.Dump();
305 }
306 shadow_stack_.push_back(instrumentation_frame);
307 return true; // Continue.
308 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800309 uintptr_t return_pc = GetReturnPc();
Sebastien Hertz320deb22014-06-11 19:45:05 +0200310 if (kVerboseInstrumentation) {
311 LOG(INFO) << " Installing exit stub in " << DescribeLocation();
312 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100313 if (return_pc == instrumentation_exit_pc_) {
Mingyao Yang2ee17902017-08-30 11:37:08 -0700314 CHECK_LT(instrumentation_stack_depth_, instrumentation_stack_->size());
315
316 if (m->IsRuntimeMethod()) {
317 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100318 (*instrumentation_stack_)[instrumentation_stack_depth_];
Mingyao Yang2ee17902017-08-30 11:37:08 -0700319 if (frame.interpreter_entry_) {
320 // This instrumentation frame is for an interpreter bridge and is
321 // pushed when executing the instrumented interpreter bridge. So method
322 // enter event must have been reported. However we need to push a DEX pc
323 // into the dex_pcs_ list to match size of instrumentation stack.
Andreas Gampee2abbc62017-09-15 11:59:26 -0700324 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700325 dex_pcs_.push_back(dex_pc);
326 last_return_pc_ = frame.return_pc_;
327 ++instrumentation_stack_depth_;
328 return true;
329 }
330 }
331
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100332 // We've reached a frame which has already been installed with instrumentation exit stub.
Alex Light74c91c92018-03-08 14:01:44 -0800333 // We should have already installed instrumentation or be interpreter on previous frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100334 reached_existing_instrumentation_frames_ = true;
335
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200336 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100337 (*instrumentation_stack_)[instrumentation_stack_depth_];
Alex Lightfc81d802018-12-07 13:39:05 -0800338 CHECK_EQ(m->GetNonObsoleteMethod(), frame.method_->GetNonObsoleteMethod())
339 << "Expected " << ArtMethod::PrettyMethod(m)
340 << ", Found " << ArtMethod::PrettyMethod(frame.method_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100341 return_pc = frame.return_pc_;
342 if (kVerboseInstrumentation) {
343 LOG(INFO) << "Ignoring already instrumented " << frame.Dump();
344 }
345 } else {
346 CHECK_NE(return_pc, 0U);
Alex Light74c91c92018-03-08 14:01:44 -0800347 if (UNLIKELY(reached_existing_instrumentation_frames_ && !m->IsRuntimeMethod())) {
348 // We already saw an existing instrumentation frame so this should be a runtime-method
349 // inserted by the interpreter or runtime.
Alex Lighte9278662018-03-08 16:55:58 -0800350 std::string thread_name;
351 GetThread()->GetThreadName(thread_name);
352 uint32_t dex_pc = dex::kDexNoIndex;
353 if (last_return_pc_ != 0 &&
354 GetCurrentOatQuickMethodHeader() != nullptr) {
355 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
356 }
Alex Light74c91c92018-03-08 14:01:44 -0800357 LOG(FATAL) << "While walking " << thread_name << " found unexpected non-runtime method"
358 << " without instrumentation exit return or interpreter frame."
Alex Lighte9278662018-03-08 16:55:58 -0800359 << " method is " << GetMethod()->PrettyMethod()
360 << " return_pc is " << std::hex << return_pc
361 << " dex pc: " << dex_pc;
362 UNREACHABLE();
363 }
Mingyao Yang2ee17902017-08-30 11:37:08 -0700364 InstrumentationStackFrame instrumentation_frame(
Vladimir Markoabedfca2019-05-23 14:07:47 +0100365 m->IsRuntimeMethod() ? nullptr : GetThisObject().Ptr(),
Mingyao Yang2ee17902017-08-30 11:37:08 -0700366 m,
367 return_pc,
368 GetFrameId(), // A runtime method still gets a frame id.
369 false);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100370 if (kVerboseInstrumentation) {
371 LOG(INFO) << "Pushing frame " << instrumentation_frame.Dump();
372 }
373
Sebastien Hertz320deb22014-06-11 19:45:05 +0200374 // Insert frame at the right position so we do not corrupt the instrumentation stack.
375 // Instrumentation stack frames are in descending frame id order.
376 auto it = instrumentation_stack_->begin();
377 for (auto end = instrumentation_stack_->end(); it != end; ++it) {
378 const InstrumentationStackFrame& current = *it;
379 if (instrumentation_frame.frame_id_ >= current.frame_id_) {
380 break;
381 }
382 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100383 instrumentation_stack_->insert(it, instrumentation_frame);
384 SetReturnPc(instrumentation_exit_pc_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800385 }
Andreas Gampee2abbc62017-09-15 11:59:26 -0700386 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700387 if (last_return_pc_ != 0 &&
388 GetCurrentOatQuickMethodHeader() != nullptr) {
389 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
390 }
391 dex_pcs_.push_back(dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800392 last_return_pc_ = return_pc;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100393 ++instrumentation_stack_depth_;
Ian Rogers306057f2012-11-26 12:45:53 -0800394 return true; // Continue.
395 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800396 std::deque<InstrumentationStackFrame>* const instrumentation_stack_;
Jeff Haoa15a81b2014-05-27 18:25:47 -0700397 std::vector<InstrumentationStackFrame> shadow_stack_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800398 std::vector<uint32_t> dex_pcs_;
Ian Rogers306057f2012-11-26 12:45:53 -0800399 const uintptr_t instrumentation_exit_pc_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100400 bool reached_existing_instrumentation_frames_;
401 size_t instrumentation_stack_depth_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800402 uintptr_t last_return_pc_;
Ian Rogers306057f2012-11-26 12:45:53 -0800403 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800404 if (kVerboseInstrumentation) {
405 std::string thread_name;
406 thread->GetThreadName(thread_name);
407 LOG(INFO) << "Installing exit stubs in " << thread_name;
Ian Rogers306057f2012-11-26 12:45:53 -0800408 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100409
410 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers700a4022014-05-19 16:49:03 -0700411 std::unique_ptr<Context> context(Context::Create());
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700412 uintptr_t instrumentation_exit_pc = reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100413 InstallStackVisitor visitor(thread, context.get(), instrumentation_exit_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800414 visitor.WalkStack(true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100415 CHECK_EQ(visitor.dex_pcs_.size(), thread->GetInstrumentationStack()->size());
Ian Rogers62d6c772013-02-27 08:32:07 -0800416
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100417 if (instrumentation->ShouldNotifyMethodEnterExitEvents()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100418 // Create method enter events for all methods currently on the thread's stack. We only do this
419 // if no debugger is attached to prevent from posting events twice.
Jeff Haoa15a81b2014-05-27 18:25:47 -0700420 auto ssi = visitor.shadow_stack_.rbegin();
421 for (auto isi = thread->GetInstrumentationStack()->rbegin(),
422 end = thread->GetInstrumentationStack()->rend(); isi != end; ++isi) {
423 while (ssi != visitor.shadow_stack_.rend() && (*ssi).frame_id_ < (*isi).frame_id_) {
424 instrumentation->MethodEnterEvent(thread, (*ssi).this_object_, (*ssi).method_, 0);
425 ++ssi;
426 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100427 uint32_t dex_pc = visitor.dex_pcs_.back();
428 visitor.dex_pcs_.pop_back();
Alex Lightdc5423f2018-06-08 10:43:38 -0700429 if (!isi->interpreter_entry_ && !isi->method_->IsRuntimeMethod()) {
Sebastien Hertz320deb22014-06-11 19:45:05 +0200430 instrumentation->MethodEnterEvent(thread, (*isi).this_object_, (*isi).method_, dex_pc);
431 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100432 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800433 }
434 thread->VerifyStack();
Ian Rogers306057f2012-11-26 12:45:53 -0800435}
436
Mingyao Yang99170c62015-07-06 11:10:37 -0700437void Instrumentation::InstrumentThreadStack(Thread* thread) {
438 instrumentation_stubs_installed_ = true;
439 InstrumentationInstallStack(thread, this);
440}
441
Ian Rogers62d6c772013-02-27 08:32:07 -0800442// Removes the instrumentation exit pc as the return PC for every quick frame.
443static void InstrumentationRestoreStack(Thread* thread, void* arg)
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000444 REQUIRES(Locks::mutator_lock_) {
445 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
446
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100447 struct RestoreStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800448 RestoreStackVisitor(Thread* thread_in, uintptr_t instrumentation_exit_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800449 Instrumentation* instrumentation)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100450 : StackVisitor(thread_in, nullptr, kInstrumentationStackWalk),
451 thread_(thread_in),
Ian Rogers62d6c772013-02-27 08:32:07 -0800452 instrumentation_exit_pc_(instrumentation_exit_pc),
453 instrumentation_(instrumentation),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800454 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Ian Rogers62d6c772013-02-27 08:32:07 -0800455 frames_removed_(0) {}
Ian Rogers306057f2012-11-26 12:45:53 -0800456
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100457 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800458 if (instrumentation_stack_->size() == 0) {
jeffhao725a9572012-11-13 18:20:12 -0800459 return false; // Stop.
460 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700461 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700462 if (GetCurrentQuickFrame() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800463 if (kVerboseInstrumentation) {
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200464 LOG(INFO) << " Ignoring a shadow frame. Frame " << GetFrameId()
David Sehr709b0702016-10-13 09:12:37 -0700465 << " Method=" << ArtMethod::PrettyMethod(m);
Ian Rogers62d6c772013-02-27 08:32:07 -0800466 }
467 return true; // Ignore shadow frames.
468 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700469 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800470 if (kVerboseInstrumentation) {
471 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
472 }
Ian Rogers306057f2012-11-26 12:45:53 -0800473 return true; // Ignore upcalls.
474 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800475 bool removed_stub = false;
476 // TODO: make this search more efficient?
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100477 const size_t frameId = GetFrameId();
478 for (const InstrumentationStackFrame& instrumentation_frame : *instrumentation_stack_) {
479 if (instrumentation_frame.frame_id_ == frameId) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800480 if (kVerboseInstrumentation) {
481 LOG(INFO) << " Removing exit stub in " << DescribeLocation();
482 }
Jeff Hao9a916d32013-06-27 18:45:37 -0700483 if (instrumentation_frame.interpreter_entry_) {
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700484 CHECK(m == Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
Jeff Hao9a916d32013-06-27 18:45:37 -0700485 } else {
Alex Lightfc81d802018-12-07 13:39:05 -0800486 CHECK_EQ(m->GetNonObsoleteMethod(),
487 instrumentation_frame.method_->GetNonObsoleteMethod())
488 << ArtMethod::PrettyMethod(m);
Jeff Hao9a916d32013-06-27 18:45:37 -0700489 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800490 SetReturnPc(instrumentation_frame.return_pc_);
Mingyao Yang2ee17902017-08-30 11:37:08 -0700491 if (instrumentation_->ShouldNotifyMethodEnterExitEvents() &&
492 !m->IsRuntimeMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100493 // Create the method exit events. As the methods didn't really exit the result is 0.
494 // We only do this if no debugger is attached to prevent from posting events twice.
Alex Lightb7c640d2019-03-20 15:52:13 -0700495 JValue val;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100496 instrumentation_->MethodExitEvent(thread_, instrumentation_frame.this_object_, m,
Alex Lightb7c640d2019-03-20 15:52:13 -0700497 GetDexPc(), OptionalFrame{}, val);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100498 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800499 frames_removed_++;
500 removed_stub = true;
501 break;
502 }
503 }
504 if (!removed_stub) {
505 if (kVerboseInstrumentation) {
506 LOG(INFO) << " No exit stub in " << DescribeLocation();
Ian Rogers306057f2012-11-26 12:45:53 -0800507 }
jeffhao725a9572012-11-13 18:20:12 -0800508 }
509 return true; // Continue.
510 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800511 Thread* const thread_;
Ian Rogers306057f2012-11-26 12:45:53 -0800512 const uintptr_t instrumentation_exit_pc_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800513 Instrumentation* const instrumentation_;
514 std::deque<instrumentation::InstrumentationStackFrame>* const instrumentation_stack_;
515 size_t frames_removed_;
jeffhao725a9572012-11-13 18:20:12 -0800516 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800517 if (kVerboseInstrumentation) {
518 std::string thread_name;
519 thread->GetThreadName(thread_name);
520 LOG(INFO) << "Removing exit stubs in " << thread_name;
521 }
522 std::deque<instrumentation::InstrumentationStackFrame>* stack = thread->GetInstrumentationStack();
523 if (stack->size() > 0) {
524 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700525 uintptr_t instrumentation_exit_pc =
526 reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Ian Rogers62d6c772013-02-27 08:32:07 -0800527 RestoreStackVisitor visitor(thread, instrumentation_exit_pc, instrumentation);
528 visitor.WalkStack(true);
529 CHECK_EQ(visitor.frames_removed_, stack->size());
530 while (stack->size() > 0) {
531 stack->pop_front();
532 }
jeffhao725a9572012-11-13 18:20:12 -0800533 }
534}
535
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200536static bool HasEvent(Instrumentation::InstrumentationEvent expected, uint32_t events) {
537 return (events & expected) != 0;
538}
539
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000540static void PotentiallyAddListenerTo(Instrumentation::InstrumentationEvent event,
541 uint32_t events,
542 std::list<InstrumentationListener*>& list,
543 InstrumentationListener* listener,
544 bool* has_listener)
545 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
546 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
547 if (!HasEvent(event, events)) {
548 return;
549 }
550 // If there is a free slot in the list, we insert the listener in that slot.
551 // Otherwise we add it to the end of the list.
552 auto it = std::find(list.begin(), list.end(), nullptr);
553 if (it != list.end()) {
554 *it = listener;
555 } else {
556 list.push_back(listener);
557 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100558 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000559}
560
Ian Rogers62d6c772013-02-27 08:32:07 -0800561void Instrumentation::AddListener(InstrumentationListener* listener, uint32_t events) {
562 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000563 PotentiallyAddListenerTo(kMethodEntered,
564 events,
565 method_entry_listeners_,
566 listener,
567 &have_method_entry_listeners_);
568 PotentiallyAddListenerTo(kMethodExited,
569 events,
570 method_exit_listeners_,
571 listener,
572 &have_method_exit_listeners_);
573 PotentiallyAddListenerTo(kMethodUnwind,
574 events,
575 method_unwind_listeners_,
576 listener,
577 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000578 PotentiallyAddListenerTo(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000579 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000580 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000581 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000582 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000583 PotentiallyAddListenerTo(kDexPcMoved,
584 events,
585 dex_pc_listeners_,
586 listener,
587 &have_dex_pc_listeners_);
588 PotentiallyAddListenerTo(kFieldRead,
589 events,
590 field_read_listeners_,
591 listener,
592 &have_field_read_listeners_);
593 PotentiallyAddListenerTo(kFieldWritten,
594 events,
595 field_write_listeners_,
596 listener,
597 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700598 PotentiallyAddListenerTo(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000599 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700600 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000601 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700602 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700603 PotentiallyAddListenerTo(kWatchedFramePop,
604 events,
605 watched_frame_pop_listeners_,
606 listener,
607 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700608 PotentiallyAddListenerTo(kExceptionHandled,
609 events,
610 exception_handled_listeners_,
611 listener,
612 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200613 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800614}
615
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000616static void PotentiallyRemoveListenerFrom(Instrumentation::InstrumentationEvent event,
617 uint32_t events,
618 std::list<InstrumentationListener*>& list,
619 InstrumentationListener* listener,
620 bool* has_listener)
621 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
622 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
623 if (!HasEvent(event, events)) {
624 return;
625 }
626 auto it = std::find(list.begin(), list.end(), listener);
627 if (it != list.end()) {
628 // Just update the entry, do not remove from the list. Removing entries in the list
629 // is unsafe when mutators are iterating over it.
630 *it = nullptr;
631 }
632
633 // Check if the list contains any non-null listener, and update 'has_listener'.
634 for (InstrumentationListener* l : list) {
635 if (l != nullptr) {
David Srbecky28f6cff2018-10-16 15:07:28 +0100636 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000637 return;
638 }
639 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100640 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = false; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000641}
642
Ian Rogers62d6c772013-02-27 08:32:07 -0800643void Instrumentation::RemoveListener(InstrumentationListener* listener, uint32_t events) {
644 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000645 PotentiallyRemoveListenerFrom(kMethodEntered,
646 events,
647 method_entry_listeners_,
648 listener,
649 &have_method_entry_listeners_);
650 PotentiallyRemoveListenerFrom(kMethodExited,
651 events,
652 method_exit_listeners_,
653 listener,
654 &have_method_exit_listeners_);
655 PotentiallyRemoveListenerFrom(kMethodUnwind,
656 events,
657 method_unwind_listeners_,
658 listener,
659 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000660 PotentiallyRemoveListenerFrom(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000661 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000662 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000663 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000664 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000665 PotentiallyRemoveListenerFrom(kDexPcMoved,
666 events,
667 dex_pc_listeners_,
668 listener,
669 &have_dex_pc_listeners_);
670 PotentiallyRemoveListenerFrom(kFieldRead,
671 events,
672 field_read_listeners_,
673 listener,
674 &have_field_read_listeners_);
675 PotentiallyRemoveListenerFrom(kFieldWritten,
676 events,
677 field_write_listeners_,
678 listener,
679 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700680 PotentiallyRemoveListenerFrom(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000681 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700682 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000683 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700684 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700685 PotentiallyRemoveListenerFrom(kWatchedFramePop,
686 events,
687 watched_frame_pop_listeners_,
688 listener,
689 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700690 PotentiallyRemoveListenerFrom(kExceptionHandled,
691 events,
692 exception_handled_listeners_,
693 listener,
694 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200695 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800696}
697
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200698Instrumentation::InstrumentationLevel Instrumentation::GetCurrentInstrumentationLevel() const {
Alex Light4ba388a2017-01-27 10:26:49 -0800699 if (interpreter_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200700 return InstrumentationLevel::kInstrumentWithInterpreter;
Ian Rogers62d6c772013-02-27 08:32:07 -0800701 } else if (entry_exit_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200702 return InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Ian Rogers62d6c772013-02-27 08:32:07 -0800703 } else {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200704 return InstrumentationLevel::kInstrumentNothing;
Ian Rogers62d6c772013-02-27 08:32:07 -0800705 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200706}
707
Alex Lightdba61482016-12-21 08:20:29 -0800708bool Instrumentation::RequiresInstrumentationInstallation(InstrumentationLevel new_level) const {
Alex Light4ba388a2017-01-27 10:26:49 -0800709 // We need to reinstall instrumentation if we go to a different level.
710 return GetCurrentInstrumentationLevel() != new_level;
Alex Lightdba61482016-12-21 08:20:29 -0800711}
712
Alex Light40607862019-05-06 18:16:24 +0000713void Instrumentation::UpdateInstrumentationLevels(InstrumentationLevel level) {
714 if (level == InstrumentationLevel::kInstrumentWithInterpreter) {
715 can_use_instrumentation_trampolines_ = false;
716 }
717 if (UNLIKELY(!can_use_instrumentation_trampolines_)) {
718 for (auto& p : requested_instrumentation_levels_) {
719 if (p.second == InstrumentationLevel::kInstrumentWithInstrumentationStubs) {
720 p.second = InstrumentationLevel::kInstrumentWithInterpreter;
721 }
722 }
723 }
724}
725
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200726void Instrumentation::ConfigureStubs(const char* key, InstrumentationLevel desired_level) {
727 // Store the instrumentation level for this key or remove it.
728 if (desired_level == InstrumentationLevel::kInstrumentNothing) {
729 // The client no longer needs instrumentation.
730 requested_instrumentation_levels_.erase(key);
731 } else {
732 // The client needs instrumentation.
733 requested_instrumentation_levels_.Overwrite(key, desired_level);
734 }
735
Alex Light40607862019-05-06 18:16:24 +0000736 UpdateInstrumentationLevels(desired_level);
737 UpdateStubs();
738}
739
740void Instrumentation::EnableSingleThreadDeopt() {
741 // Single-thread deopt only uses interpreter.
742 can_use_instrumentation_trampolines_ = false;
743 UpdateInstrumentationLevels(InstrumentationLevel::kInstrumentWithInterpreter);
744 UpdateStubs();
745}
746
747void Instrumentation::UpdateStubs() {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200748 // Look for the highest required instrumentation level.
749 InstrumentationLevel requested_level = InstrumentationLevel::kInstrumentNothing;
750 for (const auto& v : requested_instrumentation_levels_) {
751 requested_level = std::max(requested_level, v.second);
752 }
753
Alex Light40607862019-05-06 18:16:24 +0000754 DCHECK(can_use_instrumentation_trampolines_ ||
755 requested_level != InstrumentationLevel::kInstrumentWithInstrumentationStubs)
756 << "Use trampolines: " << can_use_instrumentation_trampolines_ << " level "
757 << requested_level;
758
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200759 interpret_only_ = (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) ||
760 forced_interpret_only_;
761
Alex Lightdba61482016-12-21 08:20:29 -0800762 if (!RequiresInstrumentationInstallation(requested_level)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800763 // We're already set.
764 return;
765 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100766 Thread* const self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800767 Runtime* runtime = Runtime::Current();
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100768 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800769 Locks::thread_list_lock_->AssertNotHeld(self);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200770 if (requested_level > InstrumentationLevel::kInstrumentNothing) {
Alex Light4ba388a2017-01-27 10:26:49 -0800771 if (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800772 interpreter_stubs_installed_ = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800773 entry_exit_stubs_installed_ = true;
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200774 } else {
775 CHECK_EQ(requested_level, InstrumentationLevel::kInstrumentWithInstrumentationStubs);
776 entry_exit_stubs_installed_ = true;
777 interpreter_stubs_installed_ = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800778 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700779 InstallStubsClassVisitor visitor(this);
780 runtime->GetClassLinker()->VisitClasses(&visitor);
Ian Rogers62d6c772013-02-27 08:32:07 -0800781 instrumentation_stubs_installed_ = true;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100782 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800783 runtime->GetThreadList()->ForEach(InstrumentationInstallStack, this);
784 } else {
785 interpreter_stubs_installed_ = false;
786 entry_exit_stubs_installed_ = false;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700787 InstallStubsClassVisitor visitor(this);
788 runtime->GetClassLinker()->VisitClasses(&visitor);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100789 // Restore stack only if there is no method currently deoptimized.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700790 bool empty;
791 {
Andreas Gampe7e56a072018-11-29 10:40:06 -0800792 ReaderMutexLock mu(self, *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700793 empty = IsDeoptimizedMethodsEmpty(); // Avoid lock violation.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700794 }
795 if (empty) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100796 MutexLock mu(self, *Locks::thread_list_lock_);
797 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000798 // Only do this after restoring, as walking the stack when restoring will see
799 // the instrumentation exit pc.
800 instrumentation_stubs_installed_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100801 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800802 }
jeffhao725a9572012-11-13 18:20:12 -0800803}
804
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200805static void ResetQuickAllocEntryPointsForThread(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -0800806 thread->ResetQuickAllocEntryPointsForThread(kUseReadBarrier && thread->GetIsGcMarking());
Ian Rogersfa824272013-11-05 16:12:57 -0800807}
808
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700809void Instrumentation::SetEntrypointsInstrumented(bool instrumented) {
810 Thread* self = Thread::Current();
Mathieu Chartier661974a2014-01-09 11:23:53 -0800811 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700812 Locks::mutator_lock_->AssertNotHeld(self);
813 Locks::instrument_entrypoints_lock_->AssertHeld(self);
814 if (runtime->IsStarted()) {
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700815 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700816 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier661974a2014-01-09 11:23:53 -0800817 SetQuickAllocEntryPointsInstrumented(instrumented);
818 ResetQuickAllocEntryPoints();
Mathieu Chartier50e93312016-03-16 11:25:29 -0700819 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700820 } else {
821 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
822 SetQuickAllocEntryPointsInstrumented(instrumented);
Andreas Gampe157c77e2016-10-17 17:44:41 -0700823
824 // Note: ResetQuickAllocEntryPoints only works when the runtime is started. Manually run the
825 // update for just this thread.
Andreas Gampe162ae502016-10-18 10:03:42 -0700826 // Note: self may be null. One of those paths is setting instrumentation in the Heap
827 // constructor for gcstress mode.
828 if (self != nullptr) {
829 ResetQuickAllocEntryPointsForThread(self, nullptr);
830 }
Andreas Gampe157c77e2016-10-17 17:44:41 -0700831
Mathieu Chartier50e93312016-03-16 11:25:29 -0700832 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier661974a2014-01-09 11:23:53 -0800833 }
834}
835
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700836void Instrumentation::InstrumentQuickAllocEntryPoints() {
837 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
838 InstrumentQuickAllocEntryPointsLocked();
Ian Rogersfa824272013-11-05 16:12:57 -0800839}
840
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700841void Instrumentation::UninstrumentQuickAllocEntryPoints() {
842 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
843 UninstrumentQuickAllocEntryPointsLocked();
844}
845
846void Instrumentation::InstrumentQuickAllocEntryPointsLocked() {
847 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
848 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
849 SetEntrypointsInstrumented(true);
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800850 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700851 ++quick_alloc_entry_points_instrumentation_counter_;
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700852}
853
854void Instrumentation::UninstrumentQuickAllocEntryPointsLocked() {
855 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
856 CHECK_GT(quick_alloc_entry_points_instrumentation_counter_, 0U);
857 --quick_alloc_entry_points_instrumentation_counter_;
858 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
859 SetEntrypointsInstrumented(false);
860 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800861}
862
863void Instrumentation::ResetQuickAllocEntryPoints() {
864 Runtime* runtime = Runtime::Current();
865 if (runtime->IsStarted()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800866 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700867 runtime->GetThreadList()->ForEach(ResetQuickAllocEntryPointsForThread, nullptr);
Ian Rogersfa824272013-11-05 16:12:57 -0800868 }
869}
870
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700871void Instrumentation::UpdateMethodsCodeImpl(ArtMethod* method, const void* quick_code) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800872 const void* new_quick_code;
Ian Rogers62d6c772013-02-27 08:32:07 -0800873 if (LIKELY(!instrumentation_stubs_installed_)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800874 new_quick_code = quick_code;
Jeff Hao65d15d92013-07-16 16:39:33 -0700875 } else {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100876 if ((interpreter_stubs_installed_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800877 new_quick_code = GetQuickToInterpreterBridge();
Jeff Hao65d15d92013-07-16 16:39:33 -0700878 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700879 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700880 if (class_linker->IsQuickResolutionStub(quick_code) ||
881 class_linker->IsQuickToInterpreterBridge(quick_code)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700882 new_quick_code = quick_code;
Alex Light6cae5ea2018-06-07 17:07:02 -0700883 } else if (entry_exit_stubs_installed_ &&
884 // We need to make sure not to replace anything that InstallStubsForMethod
885 // wouldn't. Specifically we cannot stub out Proxy.<init> since subtypes copy the
886 // implementation directly and this will confuse the instrumentation trampolines.
887 // TODO We should remove the need for this since it makes it impossible to profile
888 // Proxy.<init> correctly in all cases.
889 method != jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700890 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700891 if (!method->IsNative() && Runtime::Current()->GetJit() != nullptr) {
892 // Native methods use trampoline entrypoints during interpreter tracing.
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000893 DCHECK(!Runtime::Current()->GetJit()->GetCodeCache()->GetGarbageCollectCodeUnsafe());
Alex Light2d441b12018-06-08 15:33:21 -0700894 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
895 // Tracing will look at the saved entry point in the profiling info to know the actual
896 // entrypoint, so we store it here.
897 if (profiling_info != nullptr) {
898 profiling_info->SetSavedEntryPoint(quick_code);
899 }
900 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700901 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700902 new_quick_code = quick_code;
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700903 }
Jeff Hao65d15d92013-07-16 16:39:33 -0700904 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800905 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800906 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100907}
908
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +0000909void Instrumentation::UpdateNativeMethodsCodeToJitCode(ArtMethod* method, const void* quick_code) {
910 // We don't do any read barrier on `method`'s declaring class in this code, as the JIT might
911 // enter here on a soon-to-be deleted ArtMethod. Updating the entrypoint is OK though, as
912 // the ArtMethod is still in memory.
913 const void* new_quick_code = quick_code;
914 if (UNLIKELY(instrumentation_stubs_installed_) && entry_exit_stubs_installed_) {
915 new_quick_code = GetQuickInstrumentationEntryPoint();
916 }
917 UpdateEntrypoints(method, new_quick_code);
918}
919
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700920void Instrumentation::UpdateMethodsCode(ArtMethod* method, const void* quick_code) {
921 DCHECK(method->GetDeclaringClass()->IsResolved());
922 UpdateMethodsCodeImpl(method, quick_code);
923}
924
Alex Light0a5ec3d2017-07-25 16:50:26 -0700925void Instrumentation::UpdateMethodsCodeToInterpreterEntryPoint(ArtMethod* method) {
926 UpdateMethodsCodeImpl(method, GetQuickToInterpreterBridge());
927}
928
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000929void Instrumentation::UpdateMethodsCodeForJavaDebuggable(ArtMethod* method,
930 const void* quick_code) {
931 // When the runtime is set to Java debuggable, we may update the entry points of
932 // all methods of a class to the interpreter bridge. A method's declaring class
933 // might not be in resolved state yet in that case, so we bypass the DCHECK in
934 // UpdateMethodsCode.
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700935 UpdateMethodsCodeImpl(method, quick_code);
936}
937
Mathieu Chartiere401d142015-04-22 13:56:20 -0700938bool Instrumentation::AddDeoptimizedMethod(ArtMethod* method) {
939 if (IsDeoptimizedMethod(method)) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700940 // Already in the map. Return.
941 return false;
942 }
943 // Not found. Add it.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700944 deoptimized_methods_.insert(method);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700945 return true;
946}
947
Mathieu Chartiere401d142015-04-22 13:56:20 -0700948bool Instrumentation::IsDeoptimizedMethod(ArtMethod* method) {
949 return deoptimized_methods_.find(method) != deoptimized_methods_.end();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700950}
951
Mathieu Chartiere401d142015-04-22 13:56:20 -0700952ArtMethod* Instrumentation::BeginDeoptimizedMethod() {
953 if (deoptimized_methods_.empty()) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700954 // Empty.
955 return nullptr;
956 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700957 return *deoptimized_methods_.begin();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700958}
959
Mathieu Chartiere401d142015-04-22 13:56:20 -0700960bool Instrumentation::RemoveDeoptimizedMethod(ArtMethod* method) {
961 auto it = deoptimized_methods_.find(method);
962 if (it == deoptimized_methods_.end()) {
963 return false;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700964 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700965 deoptimized_methods_.erase(it);
966 return true;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700967}
968
969bool Instrumentation::IsDeoptimizedMethodsEmpty() const {
970 return deoptimized_methods_.empty();
971}
972
Mathieu Chartiere401d142015-04-22 13:56:20 -0700973void Instrumentation::Deoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100974 CHECK(!method->IsNative());
975 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700976 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100977
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700978 Thread* self = Thread::Current();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700979 {
Andreas Gampe7e56a072018-11-29 10:40:06 -0800980 WriterMutexLock mu(self, *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700981 bool has_not_been_deoptimized = AddDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700982 CHECK(has_not_been_deoptimized) << "Method " << ArtMethod::PrettyMethod(method)
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200983 << " is already deoptimized";
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700984 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100985 if (!interpreter_stubs_installed_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800986 UpdateEntrypoints(method, GetQuickInstrumentationEntryPoint());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100987
988 // Install instrumentation exit stub and instrumentation frames. We may already have installed
989 // these previously so it will only cover the newly created frames.
990 instrumentation_stubs_installed_ = true;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700991 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100992 Runtime::Current()->GetThreadList()->ForEach(InstrumentationInstallStack, this);
993 }
994}
995
Mathieu Chartiere401d142015-04-22 13:56:20 -0700996void Instrumentation::Undeoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100997 CHECK(!method->IsNative());
998 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700999 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001000
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001001 Thread* self = Thread::Current();
1002 bool empty;
1003 {
Andreas Gampe7e56a072018-11-29 10:40:06 -08001004 WriterMutexLock mu(self, *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001005 bool found_and_erased = RemoveDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -07001006 CHECK(found_and_erased) << "Method " << ArtMethod::PrettyMethod(method)
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001007 << " is not deoptimized";
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001008 empty = IsDeoptimizedMethodsEmpty();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001009 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001010
1011 // Restore code and possibly stack only if we did not deoptimize everything.
1012 if (!interpreter_stubs_installed_) {
1013 // Restore its code or resolution trampoline.
1014 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001015 if (method->IsStatic() && !method->IsConstructor() &&
1016 !method->GetDeclaringClass()->IsInitialized()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001017 UpdateEntrypoints(method, GetQuickResolutionStub());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001018 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001019 const void* quick_code = NeedDebugVersionFor(method)
1020 ? GetQuickToInterpreterBridge()
Alex Lightfc49fec2018-01-16 22:28:36 +00001021 : class_linker->GetQuickOatCodeFor(method);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001022 UpdateEntrypoints(method, quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001023 }
1024
1025 // If there is no deoptimized method left, we can restore the stack of each thread.
Alex Lightf244a572018-06-08 13:56:51 -07001026 if (empty && !entry_exit_stubs_installed_) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001027 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001028 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
1029 instrumentation_stubs_installed_ = false;
1030 }
1031 }
1032}
1033
Mathieu Chartiere401d142015-04-22 13:56:20 -07001034bool Instrumentation::IsDeoptimized(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001035 DCHECK(method != nullptr);
Andreas Gampe7e56a072018-11-29 10:40:06 -08001036 ReaderMutexLock mu(Thread::Current(), *GetDeoptimizedMethodsLock());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001037 return IsDeoptimizedMethod(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001038}
1039
1040void Instrumentation::EnableDeoptimization() {
Andreas Gampe7e56a072018-11-29 10:40:06 -08001041 ReaderMutexLock mu(Thread::Current(), *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001042 CHECK(IsDeoptimizedMethodsEmpty());
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001043 CHECK_EQ(deoptimization_enabled_, false);
1044 deoptimization_enabled_ = true;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001045}
1046
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001047void Instrumentation::DisableDeoptimization(const char* key) {
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001048 CHECK_EQ(deoptimization_enabled_, true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001049 // If we deoptimized everything, undo it.
Alex Lightdba61482016-12-21 08:20:29 -08001050 InstrumentationLevel level = GetCurrentInstrumentationLevel();
1051 if (level == InstrumentationLevel::kInstrumentWithInterpreter) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001052 UndeoptimizeEverything(key);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001053 }
1054 // Undeoptimized selected methods.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001055 while (true) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001056 ArtMethod* method;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001057 {
Andreas Gampe7e56a072018-11-29 10:40:06 -08001058 ReaderMutexLock mu(Thread::Current(), *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001059 if (IsDeoptimizedMethodsEmpty()) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001060 break;
1061 }
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001062 method = BeginDeoptimizedMethod();
1063 CHECK(method != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001064 }
1065 Undeoptimize(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001066 }
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001067 deoptimization_enabled_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001068}
1069
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001070// Indicates if instrumentation should notify method enter/exit events to the listeners.
1071bool Instrumentation::ShouldNotifyMethodEnterExitEvents() const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001072 if (!HasMethodEntryListeners() && !HasMethodExitListeners()) {
1073 return false;
1074 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01001075 return !deoptimization_enabled_ && !interpreter_stubs_installed_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001076}
1077
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001078void Instrumentation::DeoptimizeEverything(const char* key) {
1079 CHECK(deoptimization_enabled_);
1080 ConfigureStubs(key, InstrumentationLevel::kInstrumentWithInterpreter);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001081}
1082
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001083void Instrumentation::UndeoptimizeEverything(const char* key) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001084 CHECK(interpreter_stubs_installed_);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001085 CHECK(deoptimization_enabled_);
1086 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001087}
1088
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001089void Instrumentation::EnableMethodTracing(const char* key, bool needs_interpreter) {
1090 InstrumentationLevel level;
1091 if (needs_interpreter) {
1092 level = InstrumentationLevel::kInstrumentWithInterpreter;
1093 } else {
1094 level = InstrumentationLevel::kInstrumentWithInstrumentationStubs;
1095 }
1096 ConfigureStubs(key, level);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001097}
1098
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001099void Instrumentation::DisableMethodTracing(const char* key) {
1100 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
jeffhao725a9572012-11-13 18:20:12 -08001101}
1102
Alex Light2d441b12018-06-08 15:33:21 -07001103const void* Instrumentation::GetCodeForInvoke(ArtMethod* method) const {
1104 // This is called by instrumentation entry only and that should never be getting proxy methods.
1105 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
1106 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1107 if (LIKELY(!instrumentation_stubs_installed_ && !interpreter_stubs_installed_)) {
1108 // In general we just return whatever the method thinks its entrypoint is here. The only
1109 // exception is if it still has the instrumentation entrypoint. That means we are racing another
1110 // thread getting rid of instrumentation which is unexpected but possible. In that case we want
1111 // to wait and try to get it from the oat file or jit.
1112 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(kRuntimePointerSize);
1113 DCHECK(code != nullptr);
1114 if (code != GetQuickInstrumentationEntryPoint()) {
1115 return code;
1116 } else if (method->IsNative()) {
1117 return class_linker->GetQuickOatCodeFor(method);
1118 }
1119 // We don't know what it is. Fallthough to try to find the code from the JIT or Oat file.
1120 } else if (method->IsNative()) {
1121 // TODO We could have JIT compiled native entrypoints. It might be worth it to find these.
1122 return class_linker->GetQuickOatCodeFor(method);
1123 } else if (UNLIKELY(interpreter_stubs_installed_)) {
1124 return GetQuickToInterpreterBridge();
1125 }
1126 // Since the method cannot be native due to ifs above we can always fall back to interpreter
1127 // bridge.
1128 const void* result = GetQuickToInterpreterBridge();
1129 if (!NeedDebugVersionFor(method)) {
1130 // If we don't need a debug version we should see what the oat file/class linker has to say.
1131 result = class_linker->GetQuickOatCodeFor(method);
1132 }
1133 // If both those fail try the jit.
1134 if (result == GetQuickToInterpreterBridge()) {
1135 jit::Jit* jit = Runtime::Current()->GetJit();
1136 if (jit != nullptr) {
1137 const void* res = jit->GetCodeCache()->FindCompiledCodeForInstrumentation(method);
1138 if (res != nullptr) {
1139 result = res;
1140 }
1141 }
1142 }
1143 return result;
1144}
1145
Andreas Gampe542451c2016-07-26 09:02:02 -07001146const void* Instrumentation::GetQuickCodeFor(ArtMethod* method, PointerSize pointer_size) const {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001147 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers62d6c772013-02-27 08:32:07 -08001148 if (LIKELY(!instrumentation_stubs_installed_)) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08001149 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size);
Vladimir Marko8a630572014-04-09 18:45:35 +01001150 DCHECK(code != nullptr);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001151 if (LIKELY(!class_linker->IsQuickResolutionStub(code) &&
1152 !class_linker->IsQuickToInterpreterBridge(code)) &&
1153 !class_linker->IsQuickResolutionStub(code) &&
1154 !class_linker->IsQuickToInterpreterBridge(code)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001155 return code;
1156 }
1157 }
Alex Lightfc49fec2018-01-16 22:28:36 +00001158 return class_linker->GetQuickOatCodeFor(method);
jeffhao725a9572012-11-13 18:20:12 -08001159}
1160
Alex Lightd7661582017-05-01 13:48:16 -07001161void Instrumentation::MethodEnterEventImpl(Thread* thread,
1162 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001163 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001164 uint32_t dex_pc) const {
Mingyao Yang2ee17902017-08-30 11:37:08 -07001165 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001166 if (HasMethodEntryListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001167 Thread* self = Thread::Current();
1168 StackHandleScope<1> hs(self);
1169 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001170 for (InstrumentationListener* listener : method_entry_listeners_) {
1171 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001172 listener->MethodEntered(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001173 }
1174 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001175 }
1176}
1177
Alex Lightb7c640d2019-03-20 15:52:13 -07001178template <>
Alex Lightd7661582017-05-01 13:48:16 -07001179void Instrumentation::MethodExitEventImpl(Thread* thread,
1180 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001181 ArtMethod* method,
Alex Lightd7661582017-05-01 13:48:16 -07001182 uint32_t dex_pc,
Alex Lightb7c640d2019-03-20 15:52:13 -07001183 OptionalFrame frame,
1184 MutableHandle<mirror::Object>& return_value) const {
1185 if (HasMethodExitListeners()) {
1186 Thread* self = Thread::Current();
1187 StackHandleScope<1> hs(self);
1188 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1189 for (InstrumentationListener* listener : method_exit_listeners_) {
1190 if (listener != nullptr) {
1191 listener->MethodExited(thread, thiz, method, dex_pc, frame, return_value);
1192 }
1193 }
1194 }
1195}
1196
1197template<> void Instrumentation::MethodExitEventImpl(Thread* thread,
1198 ObjPtr<mirror::Object> this_object,
1199 ArtMethod* method,
1200 uint32_t dex_pc,
1201 OptionalFrame frame,
1202 JValue& return_value) const {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001203 if (HasMethodExitListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001204 Thread* self = Thread::Current();
1205 StackHandleScope<2> hs(self);
1206 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Alex Lightb7c640d2019-03-20 15:52:13 -07001207 if (method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetReturnTypePrimitive() !=
1208 Primitive::kPrimNot) {
Alex Lightd7661582017-05-01 13:48:16 -07001209 for (InstrumentationListener* listener : method_exit_listeners_) {
1210 if (listener != nullptr) {
Alex Lightb7c640d2019-03-20 15:52:13 -07001211 listener->MethodExited(thread, thiz, method, dex_pc, frame, return_value);
Alex Lightd7661582017-05-01 13:48:16 -07001212 }
1213 }
1214 } else {
Alex Lightb7c640d2019-03-20 15:52:13 -07001215 MutableHandle<mirror::Object> ret(hs.NewHandle(return_value.GetL()));
1216 MethodExitEventImpl(thread, thiz.Get(), method, dex_pc, frame, ret);
1217 return_value.SetL(ret.Get());
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001218 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001219 }
1220}
1221
Alex Lightd7661582017-05-01 13:48:16 -07001222void Instrumentation::MethodUnwindEvent(Thread* thread,
Vladimir Marko19711d42019-04-12 14:05:34 +01001223 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001224 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001225 uint32_t dex_pc) const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001226 if (HasMethodUnwindListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001227 Thread* self = Thread::Current();
1228 StackHandleScope<1> hs(self);
1229 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Mathieu Chartier02e25112013-08-14 16:14:24 -07001230 for (InstrumentationListener* listener : method_unwind_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001231 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001232 listener->MethodUnwind(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001233 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001234 }
1235 }
1236}
1237
Alex Lightd7661582017-05-01 13:48:16 -07001238void Instrumentation::DexPcMovedEventImpl(Thread* thread,
1239 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001240 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001241 uint32_t dex_pc) const {
Alex Lightd7661582017-05-01 13:48:16 -07001242 Thread* self = Thread::Current();
1243 StackHandleScope<1> hs(self);
1244 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001245 for (InstrumentationListener* listener : dex_pc_listeners_) {
1246 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001247 listener->DexPcMoved(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001248 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001249 }
1250}
1251
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001252void Instrumentation::BranchImpl(Thread* thread,
1253 ArtMethod* method,
1254 uint32_t dex_pc,
1255 int32_t offset) const {
1256 for (InstrumentationListener* listener : branch_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001257 if (listener != nullptr) {
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001258 listener->Branch(thread, method, dex_pc, offset);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001259 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001260 }
1261}
1262
Alex Lighte814f9d2017-07-31 16:14:39 -07001263void Instrumentation::WatchedFramePopImpl(Thread* thread, const ShadowFrame& frame) const {
1264 for (InstrumentationListener* listener : watched_frame_pop_listeners_) {
1265 if (listener != nullptr) {
1266 listener->WatchedFramePop(thread, frame);
1267 }
1268 }
1269}
1270
Alex Lightd7661582017-05-01 13:48:16 -07001271void Instrumentation::FieldReadEventImpl(Thread* thread,
1272 ObjPtr<mirror::Object> this_object,
1273 ArtMethod* method,
1274 uint32_t dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001275 ArtField* field) const {
Alex Lightd7661582017-05-01 13:48:16 -07001276 Thread* self = Thread::Current();
1277 StackHandleScope<1> hs(self);
1278 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001279 for (InstrumentationListener* listener : field_read_listeners_) {
1280 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001281 listener->FieldRead(thread, thiz, method, dex_pc, field);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001282 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001283 }
1284}
1285
Alex Lightd7661582017-05-01 13:48:16 -07001286void Instrumentation::FieldWriteEventImpl(Thread* thread,
1287 ObjPtr<mirror::Object> this_object,
1288 ArtMethod* method,
1289 uint32_t dex_pc,
1290 ArtField* field,
1291 const JValue& field_value) const {
1292 Thread* self = Thread::Current();
1293 StackHandleScope<2> hs(self);
1294 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1295 if (field->IsPrimitiveType()) {
1296 for (InstrumentationListener* listener : field_write_listeners_) {
1297 if (listener != nullptr) {
1298 listener->FieldWritten(thread, thiz, method, dex_pc, field, field_value);
1299 }
1300 }
1301 } else {
1302 Handle<mirror::Object> val(hs.NewHandle(field_value.GetL()));
1303 for (InstrumentationListener* listener : field_write_listeners_) {
1304 if (listener != nullptr) {
1305 listener->FieldWritten(thread, thiz, method, dex_pc, field, val);
1306 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001307 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001308 }
1309}
1310
Alex Light6e1607e2017-08-23 10:06:18 -07001311void Instrumentation::ExceptionThrownEvent(Thread* thread,
Vladimir Marko19711d42019-04-12 14:05:34 +01001312 ObjPtr<mirror::Throwable> exception_object) const {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001313 Thread* self = Thread::Current();
1314 StackHandleScope<1> hs(self);
1315 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
Alex Light6e1607e2017-08-23 10:06:18 -07001316 if (HasExceptionThrownListeners()) {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001317 DCHECK_EQ(thread->GetException(), h_exception.Get());
Jeff Haoc0bd4da2013-04-11 15:52:28 -07001318 thread->ClearException();
Alex Light6e1607e2017-08-23 10:06:18 -07001319 for (InstrumentationListener* listener : exception_thrown_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001320 if (listener != nullptr) {
Alex Light6e1607e2017-08-23 10:06:18 -07001321 listener->ExceptionThrown(thread, h_exception);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001322 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001323 }
Alex Light9fb1ab12017-09-05 09:32:49 -07001324 // See b/65049545 for discussion about this behavior.
1325 thread->AssertNoPendingException();
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001326 thread->SetException(h_exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08001327 }
1328}
1329
Alex Light9fb1ab12017-09-05 09:32:49 -07001330void Instrumentation::ExceptionHandledEvent(Thread* thread,
Vladimir Marko19711d42019-04-12 14:05:34 +01001331 ObjPtr<mirror::Throwable> exception_object) const {
Alex Light9fb1ab12017-09-05 09:32:49 -07001332 Thread* self = Thread::Current();
1333 StackHandleScope<1> hs(self);
1334 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
1335 if (HasExceptionHandledListeners()) {
1336 // We should have cleared the exception so that callers can detect a new one.
1337 DCHECK(thread->GetException() == nullptr);
1338 for (InstrumentationListener* listener : exception_handled_listeners_) {
1339 if (listener != nullptr) {
1340 listener->ExceptionHandled(thread, h_exception);
1341 }
1342 }
1343 }
1344}
1345
Sebastien Hertzb2feaaf2015-10-12 13:40:10 +00001346// Computes a frame ID by ignoring inlined frames.
1347size_t Instrumentation::ComputeFrameId(Thread* self,
1348 size_t frame_depth,
1349 size_t inlined_frames_before_frame) {
1350 CHECK_GE(frame_depth, inlined_frames_before_frame);
1351 size_t no_inline_depth = frame_depth - inlined_frames_before_frame;
1352 return StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) - no_inline_depth;
1353}
1354
Ian Rogers62d6c772013-02-27 08:32:07 -08001355static void CheckStackDepth(Thread* self, const InstrumentationStackFrame& instrumentation_frame,
1356 int delta)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001357 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001358 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) + delta;
Ian Rogers62d6c772013-02-27 08:32:07 -08001359 if (frame_id != instrumentation_frame.frame_id_) {
1360 LOG(ERROR) << "Expected frame_id=" << frame_id << " but found "
1361 << instrumentation_frame.frame_id_;
1362 StackVisitor::DescribeStack(self);
1363 CHECK_EQ(frame_id, instrumentation_frame.frame_id_);
1364 }
1365}
1366
Vladimir Marko19711d42019-04-12 14:05:34 +01001367void Instrumentation::PushInstrumentationStackFrame(Thread* self,
1368 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001369 ArtMethod* method,
Vladimir Marko19711d42019-04-12 14:05:34 +01001370 uintptr_t lr,
1371 bool interpreter_entry) {
Alex Lightb7edcda2017-04-27 13:20:31 -07001372 DCHECK(!self->IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001373 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1374 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001375 LOG(INFO) << "Entering " << ArtMethod::PrettyMethod(method) << " from PC "
1376 << reinterpret_cast<void*>(lr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001377 }
Alex Lightb7edcda2017-04-27 13:20:31 -07001378
1379 // We send the enter event before pushing the instrumentation frame to make cleanup easier. If the
1380 // event causes an exception we can simply send the unwind event and return.
1381 StackHandleScope<1> hs(self);
1382 Handle<mirror::Object> h_this(hs.NewHandle(this_object));
1383 if (!interpreter_entry) {
1384 MethodEnterEvent(self, h_this.Get(), method, 0);
1385 if (self->IsExceptionPending()) {
1386 MethodUnwindEvent(self, h_this.Get(), method, 0);
1387 return;
1388 }
1389 }
1390
1391 // We have a callee-save frame meaning this value is guaranteed to never be 0.
1392 DCHECK(!self->IsExceptionPending());
1393 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk);
1394
1395 instrumentation::InstrumentationStackFrame instrumentation_frame(h_this.Get(), method, lr,
Jeff Hao9a916d32013-06-27 18:45:37 -07001396 frame_id, interpreter_entry);
Ian Rogers62d6c772013-02-27 08:32:07 -08001397 stack->push_front(instrumentation_frame);
Ian Rogers62d6c772013-02-27 08:32:07 -08001398}
1399
Mingyao Yang2ee17902017-08-30 11:37:08 -07001400DeoptimizationMethodType Instrumentation::GetDeoptimizationMethodType(ArtMethod* method) {
1401 if (method->IsRuntimeMethod()) {
1402 // Certain methods have strict requirement on whether the dex instruction
1403 // should be re-executed upon deoptimization.
1404 if (method == Runtime::Current()->GetCalleeSaveMethod(
1405 CalleeSaveType::kSaveEverythingForClinit)) {
1406 return DeoptimizationMethodType::kKeepDexPc;
1407 }
1408 if (method == Runtime::Current()->GetCalleeSaveMethod(
1409 CalleeSaveType::kSaveEverythingForSuspendCheck)) {
1410 return DeoptimizationMethodType::kKeepDexPc;
1411 }
1412 }
1413 return DeoptimizationMethodType::kDefault;
1414}
1415
1416// Try to get the shorty of a runtime method if it's an invocation stub.
Andreas Gampec7d878d2018-11-19 18:42:06 +00001417static char GetRuntimeMethodShorty(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
1418 char shorty = 'V';
1419 StackVisitor::WalkStack(
1420 [&shorty](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1421 ArtMethod* m = stack_visitor->GetMethod();
1422 if (m == nullptr || m->IsRuntimeMethod()) {
1423 return true;
Andreas Gampe3d477f32018-11-16 16:40:45 +00001424 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00001425 // The first Java method.
1426 if (m->IsNative()) {
1427 // Use JNI method's shorty for the jni stub.
1428 shorty = m->GetShorty()[0];
1429 } else if (m->IsProxyMethod()) {
1430 // Proxy method just invokes its proxied method via
1431 // art_quick_proxy_invoke_handler.
1432 shorty = m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty()[0];
1433 } else {
1434 const Instruction& instr = m->DexInstructions().InstructionAt(stack_visitor->GetDexPc());
1435 if (instr.IsInvoke()) {
1436 auto get_method_index_fn = [](ArtMethod* caller,
1437 const Instruction& inst,
1438 uint32_t dex_pc)
1439 REQUIRES_SHARED(Locks::mutator_lock_) {
1440 switch (inst.Opcode()) {
1441 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
1442 case Instruction::INVOKE_VIRTUAL_QUICK: {
1443 uint16_t method_idx = caller->GetIndexFromQuickening(dex_pc);
1444 CHECK_NE(method_idx, DexFile::kDexNoIndex16);
1445 return method_idx;
1446 }
1447 default: {
1448 return static_cast<uint16_t>(inst.VRegB());
1449 }
1450 }
1451 };
Nicolas Geoffrayec43a012018-11-17 13:10:40 +00001452
Andreas Gampec7d878d2018-11-19 18:42:06 +00001453 uint16_t method_index = get_method_index_fn(m, instr, stack_visitor->GetDexPc());
1454 const DexFile* dex_file = m->GetDexFile();
1455 if (interpreter::IsStringInit(dex_file, method_index)) {
1456 // Invoking string init constructor is turned into invoking
1457 // StringFactory.newStringFromChars() which returns a string.
1458 shorty = 'L';
1459 } else {
1460 shorty = dex_file->GetMethodShorty(method_index)[0];
1461 }
1462
1463 } else {
1464 // It could be that a non-invoke opcode invokes a stub, which in turn
1465 // invokes Java code. In such cases, we should never expect a return
1466 // value from the stub.
1467 }
1468 }
1469 // Stop stack walking since we've seen a Java frame.
1470 return false;
1471 },
1472 thread,
1473 /* context= */ nullptr,
1474 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
1475 return shorty;
1476}
Mingyao Yang2ee17902017-08-30 11:37:08 -07001477
Alex Lightb7edcda2017-04-27 13:20:31 -07001478TwoWordReturn Instrumentation::PopInstrumentationStackFrame(Thread* self,
1479 uintptr_t* return_pc,
1480 uint64_t* gpr_result,
1481 uint64_t* fpr_result) {
1482 DCHECK(gpr_result != nullptr);
1483 DCHECK(fpr_result != nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001484 // Do the pop.
1485 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1486 CHECK_GT(stack->size(), 0U);
1487 InstrumentationStackFrame instrumentation_frame = stack->front();
1488 stack->pop_front();
1489
1490 // Set return PC and check the sanity of the stack.
1491 *return_pc = instrumentation_frame.return_pc_;
1492 CheckStackDepth(self, instrumentation_frame, 0);
Ian Rogers1d8cdbc2014-09-22 22:51:09 -07001493 self->VerifyStack();
Ian Rogers62d6c772013-02-27 08:32:07 -08001494
Mathieu Chartiere401d142015-04-22 13:56:20 -07001495 ArtMethod* method = instrumentation_frame.method_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001496 uint32_t length;
Andreas Gampe542451c2016-07-26 09:02:02 -07001497 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001498 char return_shorty;
1499
1500 // Runtime method does not call into MethodExitEvent() so there should not be
1501 // suspension point below.
1502 ScopedAssertNoThreadSuspension ants(__FUNCTION__, method->IsRuntimeMethod());
1503 if (method->IsRuntimeMethod()) {
1504 if (method != Runtime::Current()->GetCalleeSaveMethod(
1505 CalleeSaveType::kSaveEverythingForClinit)) {
1506 // If the caller is at an invocation point and the runtime method is not
1507 // for clinit, we need to pass return results to the caller.
1508 // We need the correct shorty to decide whether we need to pass the return
1509 // result for deoptimization below.
Andreas Gampec7d878d2018-11-19 18:42:06 +00001510 return_shorty = GetRuntimeMethodShorty(self);
Mingyao Yang2ee17902017-08-30 11:37:08 -07001511 } else {
1512 // Some runtime methods such as allocations, unresolved field getters, etc.
1513 // have return value. We don't need to set return_value since MethodExitEvent()
1514 // below isn't called for runtime methods. Deoptimization doesn't need the
1515 // value either since the dex instruction will be re-executed by the
1516 // interpreter, except these two cases:
1517 // (1) For an invoke, which is handled above to get the correct shorty.
1518 // (2) For MONITOR_ENTER/EXIT, which cannot be re-executed since it's not
1519 // idempotent. However there is no return value for it anyway.
1520 return_shorty = 'V';
1521 }
1522 } else {
1523 return_shorty = method->GetInterfaceMethodIfProxy(pointer_size)->GetShorty(&length)[0];
1524 }
1525
Alex Lightb7edcda2017-04-27 13:20:31 -07001526 bool is_ref = return_shorty == '[' || return_shorty == 'L';
1527 StackHandleScope<1> hs(self);
1528 MutableHandle<mirror::Object> res(hs.NewHandle<mirror::Object>(nullptr));
Ian Rogers62d6c772013-02-27 08:32:07 -08001529 JValue return_value;
1530 if (return_shorty == 'V') {
1531 return_value.SetJ(0);
1532 } else if (return_shorty == 'F' || return_shorty == 'D') {
Alex Lightb7edcda2017-04-27 13:20:31 -07001533 return_value.SetJ(*fpr_result);
Ian Rogers62d6c772013-02-27 08:32:07 -08001534 } else {
Alex Lightb7edcda2017-04-27 13:20:31 -07001535 return_value.SetJ(*gpr_result);
1536 }
1537 if (is_ref) {
1538 // Take a handle to the return value so we won't lose it if we suspend.
1539 res.Assign(return_value.GetL());
Ian Rogers62d6c772013-02-27 08:32:07 -08001540 }
1541 // TODO: improve the dex pc information here, requires knowledge of current PC as opposed to
1542 // return_pc.
Andreas Gampee2abbc62017-09-15 11:59:26 -07001543 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -07001544 if (!method->IsRuntimeMethod() && !instrumentation_frame.interpreter_entry_) {
Vladimir Marko19711d42019-04-12 14:05:34 +01001545 ObjPtr<mirror::Object> this_object = instrumentation_frame.this_object_;
Alex Lightb7c640d2019-03-20 15:52:13 -07001546 MethodExitEvent(
1547 self, this_object, instrumentation_frame.method_, dex_pc, OptionalFrame{}, return_value);
Sebastien Hertz320deb22014-06-11 19:45:05 +02001548 }
jeffhao725a9572012-11-13 18:20:12 -08001549
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001550 // Deoptimize if the caller needs to continue execution in the interpreter. Do nothing if we get
1551 // back to an upcall.
1552 NthCallerVisitor visitor(self, 1, true);
1553 visitor.WalkStack(true);
Sebastien Hertz270a0e12015-01-16 19:49:09 +01001554 bool deoptimize = (visitor.caller != nullptr) &&
Daniel Mihalyieb076692014-08-22 17:33:31 +02001555 (interpreter_stubs_installed_ || IsDeoptimized(visitor.caller) ||
Alex Light3dacdd62019-03-12 15:45:47 +00001556 self->IsForceInterpreter() ||
Daniel Mihalyieb076692014-08-22 17:33:31 +02001557 Dbg::IsForcedInterpreterNeededForUpcall(self, visitor.caller));
Alex Lightb7edcda2017-04-27 13:20:31 -07001558 if (is_ref) {
1559 // Restore the return value if it's a reference since it might have moved.
1560 *reinterpret_cast<mirror::Object**>(gpr_result) = res.Get();
1561 }
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001562 if (deoptimize && Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001563 if (kVerboseInstrumentation) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -08001564 LOG(INFO) << "Deoptimizing "
1565 << visitor.caller->PrettyMethod()
1566 << " by returning from "
1567 << method->PrettyMethod()
1568 << " with result "
1569 << std::hex << return_value.GetJ() << std::dec
1570 << " in "
1571 << *self;
Ian Rogers62d6c772013-02-27 08:32:07 -08001572 }
Mingyao Yang2ee17902017-08-30 11:37:08 -07001573 DeoptimizationMethodType deopt_method_type = GetDeoptimizationMethodType(method);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001574 self->PushDeoptimizationContext(return_value,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001575 return_shorty == 'L' || return_shorty == '[',
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001576 /* exception= */ nullptr ,
1577 /* from_code= */ false,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001578 deopt_method_type);
Andreas Gamped58342c2014-06-05 14:18:08 -07001579 return GetTwoWordSuccessValue(*return_pc,
1580 reinterpret_cast<uintptr_t>(GetQuickDeoptimizationEntryPoint()));
Ian Rogers62d6c772013-02-27 08:32:07 -08001581 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001582 if (deoptimize && !Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Alex Lightd8eb6732018-01-29 15:16:02 -08001583 VLOG(deopt) << "Got a deoptimization request on un-deoptimizable " << method->PrettyMethod()
1584 << " at PC " << reinterpret_cast<void*>(*return_pc);
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001585 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001586 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001587 LOG(INFO) << "Returning from " << method->PrettyMethod()
Brian Carlstrom2d888622013-07-18 17:02:00 -07001588 << " to PC " << reinterpret_cast<void*>(*return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001589 }
Andreas Gamped58342c2014-06-05 14:18:08 -07001590 return GetTwoWordSuccessValue(0, *return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001591 }
jeffhao725a9572012-11-13 18:20:12 -08001592}
1593
Alex Light2c8206f2018-06-08 14:51:09 -07001594uintptr_t Instrumentation::PopFramesForDeoptimization(Thread* self, size_t nframes) const {
Ian Rogers62d6c772013-02-27 08:32:07 -08001595 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
Alex Light2c8206f2018-06-08 14:51:09 -07001596 CHECK_GE(stack->size(), nframes);
1597 if (nframes == 0) {
1598 return 0u;
1599 }
1600 // Only need to send instrumentation events if it's not for deopt (do give the log messages if we
1601 // have verbose-instrumentation anyway though).
1602 if (kVerboseInstrumentation) {
1603 for (size_t i = 0; i < nframes; i++) {
1604 LOG(INFO) << "Popping for deoptimization " << stack->at(i).method_->PrettyMethod();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001605 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001606 }
Alex Light2c8206f2018-06-08 14:51:09 -07001607 // Now that we've sent all the instrumentation events we can actually modify the
1608 // instrumentation-stack. We cannot do this earlier since MethodUnwindEvent can re-enter java and
1609 // do other things that require the instrumentation stack to be in a consistent state with the
1610 // actual stack.
1611 for (size_t i = 0; i < nframes - 1; i++) {
1612 stack->pop_front();
1613 }
1614 uintptr_t return_pc = stack->front().return_pc_;
Alex Lightb7edcda2017-04-27 13:20:31 -07001615 stack->pop_front();
Alex Light2c8206f2018-06-08 14:51:09 -07001616 return return_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -08001617}
1618
1619std::string InstrumentationStackFrame::Dump() const {
1620 std::ostringstream os;
David Sehr709b0702016-10-13 09:12:37 -07001621 os << "Frame " << frame_id_ << " " << ArtMethod::PrettyMethod(method_) << ":"
Ian Rogers62d6c772013-02-27 08:32:07 -08001622 << reinterpret_cast<void*>(return_pc_) << " this=" << reinterpret_cast<void*>(this_object_);
1623 return os.str();
1624}
1625
1626} // namespace instrumentation
jeffhao725a9572012-11-13 18:20:12 -08001627} // namespace art