blob: 27c47bc701cc5e5fecaa8c61b8cff65af4ad4644 [file] [log] [blame]
jeffhao725a9572012-11-13 18:20:12 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "instrumentation.h"
18
Ian Rogersc7dd2952014-10-21 23:31:19 -070019#include <sstream>
20
Andreas Gampec7d878d2018-11-19 18:42:06 +000021#include <android-base/logging.h>
22
Ian Rogerse63db272014-07-15 15:36:11 -070023#include "arch/context.h"
Alex Lightd7661582017-05-01 13:48:16 -070024#include "art_field-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070025#include "art_method-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080026#include "base/atomic.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070027#include "base/callee_save_type.h"
jeffhao725a9572012-11-13 18:20:12 -080028#include "class_linker.h"
29#include "debugger.h"
David Sehr9e734c72018-01-04 17:56:19 -080030#include "dex/dex_file-inl.h"
31#include "dex/dex_file_types.h"
32#include "dex/dex_instruction-inl.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080033#include "entrypoints/quick/quick_alloc_entrypoints.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070034#include "entrypoints/quick/quick_entrypoints.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070035#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070036#include "gc_root-inl.h"
Sebastien Hertz138dbfc2013-12-04 18:15:25 +010037#include "interpreter/interpreter.h"
Mingyao Yang2ee17902017-08-30 11:37:08 -070038#include "interpreter/interpreter_common.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080039#include "jit/jit.h"
40#include "jit/jit_code_cache.h"
Alex Lightd7661582017-05-01 13:48:16 -070041#include "jvalue-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/class-inl.h"
43#include "mirror/dex_cache.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070044#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070045#include "mirror/object_array-inl.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080046#include "nth_caller_visitor.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010047#include "oat_quick_method_header.h"
David Srbecky28f6cff2018-10-16 15:07:28 +010048#include "runtime-inl.h"
jeffhao725a9572012-11-13 18:20:12 -080049#include "thread.h"
50#include "thread_list.h"
jeffhao725a9572012-11-13 18:20:12 -080051
52namespace art {
Ian Rogers62d6c772013-02-27 08:32:07 -080053namespace instrumentation {
jeffhao725a9572012-11-13 18:20:12 -080054
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020055constexpr bool kVerboseInstrumentation = false;
Sebastien Hertz5bfd5c92013-11-15 11:36:07 +010056
Alex Lightd7661582017-05-01 13:48:16 -070057void InstrumentationListener::MethodExited(Thread* thread,
58 Handle<mirror::Object> this_object,
59 ArtMethod* method,
60 uint32_t dex_pc,
61 Handle<mirror::Object> return_value) {
62 DCHECK_EQ(method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetReturnTypePrimitive(),
63 Primitive::kPrimNot);
64 JValue v;
65 v.SetL(return_value.Get());
66 MethodExited(thread, this_object, method, dex_pc, v);
67}
68
69void InstrumentationListener::FieldWritten(Thread* thread,
70 Handle<mirror::Object> this_object,
71 ArtMethod* method,
72 uint32_t dex_pc,
73 ArtField* field,
74 Handle<mirror::Object> field_value) {
75 DCHECK(!field->IsPrimitiveType());
76 JValue v;
77 v.SetL(field_value.Get());
78 FieldWritten(thread, this_object, method, dex_pc, field, v);
79}
80
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +010081// Instrumentation works on non-inlined frames by updating returned PCs
82// of compiled frames.
83static constexpr StackVisitor::StackWalkKind kInstrumentationStackWalk =
84 StackVisitor::StackWalkKind::kSkipInlinedFrames;
85
Mathieu Chartiere0671ce2015-07-28 17:23:28 -070086class InstallStubsClassVisitor : public ClassVisitor {
87 public:
88 explicit InstallStubsClassVisitor(Instrumentation* instrumentation)
89 : instrumentation_(instrumentation) {}
90
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010091 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -070092 instrumentation_->InstallStubsForClass(klass.Ptr());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -070093 return true; // we visit all classes.
94 }
95
96 private:
97 Instrumentation* const instrumentation_;
98};
99
Alex Light2c8206f2018-06-08 14:51:09 -0700100InstrumentationStackPopper::InstrumentationStackPopper(Thread* self)
101 : self_(self),
102 instrumentation_(Runtime::Current()->GetInstrumentation()),
103 frames_to_remove_(0) {}
104
105InstrumentationStackPopper::~InstrumentationStackPopper() {
106 std::deque<instrumentation::InstrumentationStackFrame>* stack = self_->GetInstrumentationStack();
107 for (size_t i = 0; i < frames_to_remove_; i++) {
108 stack->pop_front();
109 }
110}
111
112bool InstrumentationStackPopper::PopFramesTo(uint32_t desired_pops,
113 MutableHandle<mirror::Throwable>& exception) {
114 std::deque<instrumentation::InstrumentationStackFrame>* stack = self_->GetInstrumentationStack();
115 DCHECK_LE(frames_to_remove_, desired_pops);
116 DCHECK_GE(stack->size(), desired_pops);
117 DCHECK(!self_->IsExceptionPending());
118 if (!instrumentation_->HasMethodUnwindListeners()) {
119 frames_to_remove_ = desired_pops;
120 return true;
121 }
122 if (kVerboseInstrumentation) {
123 LOG(INFO) << "Popping frames for exception " << exception->Dump();
124 }
125 // The instrumentation events expect the exception to be set.
126 self_->SetException(exception.Get());
127 bool new_exception_thrown = false;
128 for (; frames_to_remove_ < desired_pops && !new_exception_thrown; frames_to_remove_++) {
129 InstrumentationStackFrame frame = stack->at(frames_to_remove_);
130 ArtMethod* method = frame.method_;
131 // Notify listeners of method unwind.
132 // TODO: improve the dex_pc information here.
133 uint32_t dex_pc = dex::kDexNoIndex;
134 if (kVerboseInstrumentation) {
135 LOG(INFO) << "Popping for unwind " << method->PrettyMethod();
136 }
137 if (!method->IsRuntimeMethod() && !frame.interpreter_entry_) {
138 instrumentation_->MethodUnwindEvent(self_, frame.this_object_, method, dex_pc);
139 new_exception_thrown = self_->GetException() != exception.Get();
140 }
141 }
142 exception.Assign(self_->GetException());
143 self_->ClearException();
144 if (kVerboseInstrumentation && new_exception_thrown) {
145 LOG(INFO) << "Failed to pop " << (desired_pops - frames_to_remove_)
146 << " frames due to new exception";
147 }
148 return !new_exception_thrown;
149}
Ian Rogers62d6c772013-02-27 08:32:07 -0800150
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700151Instrumentation::Instrumentation()
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000152 : instrumentation_stubs_installed_(false),
153 entry_exit_stubs_installed_(false),
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700154 interpreter_stubs_installed_(false),
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000155 interpret_only_(false),
156 forced_interpret_only_(false),
157 have_method_entry_listeners_(false),
158 have_method_exit_listeners_(false),
159 have_method_unwind_listeners_(false),
160 have_dex_pc_listeners_(false),
161 have_field_read_listeners_(false),
162 have_field_write_listeners_(false),
Alex Light6e1607e2017-08-23 10:06:18 -0700163 have_exception_thrown_listeners_(false),
Alex Lighte814f9d2017-07-31 16:14:39 -0700164 have_watched_frame_pop_listeners_(false),
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000165 have_branch_listeners_(false),
Alex Light9fb1ab12017-09-05 09:32:49 -0700166 have_exception_handled_listeners_(false),
Andreas Gampe7e56a072018-11-29 10:40:06 -0800167 deoptimized_methods_lock_(new ReaderWriterMutex("deoptimized methods lock",
168 kGenericBottomLock)),
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700169 deoptimization_enabled_(false),
170 interpreter_handler_table_(kMainHandlerTable),
Mathieu Chartier50e93312016-03-16 11:25:29 -0700171 quick_alloc_entry_points_instrumentation_counter_(0),
172 alloc_entrypoints_instrumented_(false) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700173}
174
Sebastien Hertza10aa372015-01-21 17:30:58 +0100175void Instrumentation::InstallStubsForClass(mirror::Class* klass) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000176 if (!klass->IsResolved()) {
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100177 // We need the class to be resolved to install/uninstall stubs. Otherwise its methods
178 // could not be initialized or linked with regards to class inheritance.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000179 } else if (klass->IsErroneousResolved()) {
180 // We can't execute code in a erroneous class: do nothing.
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100181 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -0700182 for (ArtMethod& method : klass->GetMethods(kRuntimePointerSize)) {
Alex Light51a64d52015-12-17 13:55:59 -0800183 InstallStubsForMethod(&method);
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100184 }
jeffhao725a9572012-11-13 18:20:12 -0800185 }
jeffhao725a9572012-11-13 18:20:12 -0800186}
187
Mathieu Chartiere401d142015-04-22 13:56:20 -0700188static void UpdateEntrypoints(ArtMethod* method, const void* quick_code)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700189 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800190 method->SetEntryPointFromQuickCompiledCode(quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100191}
192
Alex Light0fa17862017-10-24 13:43:05 -0700193bool Instrumentation::NeedDebugVersionFor(ArtMethod* method) const
194 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightf2858632018-04-02 11:28:50 -0700195 art::Runtime* runtime = Runtime::Current();
196 // If anything says we need the debug version or we are debuggable we will need the debug version
197 // of the method.
198 return (runtime->GetRuntimeCallbacks()->MethodNeedsDebugVersion(method) ||
199 runtime->IsJavaDebuggable()) &&
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800200 !method->IsNative() &&
Alex Lightf2858632018-04-02 11:28:50 -0700201 !method->IsProxyMethod();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800202}
203
Mathieu Chartiere401d142015-04-22 13:56:20 -0700204void Instrumentation::InstallStubsForMethod(ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -0700205 if (!method->IsInvokable() || method->IsProxyMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100206 // Do not change stubs for these methods.
207 return;
208 }
Jeff Hao56802772014-08-19 10:17:36 -0700209 // Don't stub Proxy.<init>. Note that the Proxy class itself is not a proxy class.
Alex Light6cae5ea2018-06-07 17:07:02 -0700210 // TODO We should remove the need for this since it means we cannot always correctly detect calls
211 // to Proxy.<init>
212 // Annoyingly this can be called before we have actually initialized WellKnownClasses so therefore
213 // we also need to check this based on the declaring-class descriptor. The check is valid because
214 // Proxy only has a single constructor.
215 ArtMethod* well_known_proxy_init = jni::DecodeArtMethod(
216 WellKnownClasses::java_lang_reflect_Proxy_init);
217 if ((LIKELY(well_known_proxy_init != nullptr) && UNLIKELY(method == well_known_proxy_init)) ||
218 UNLIKELY(method->IsConstructor() &&
219 method->GetDeclaringClass()->DescriptorEquals("Ljava/lang/reflect/Proxy;"))) {
Jeff Haodb8a6642014-08-14 17:18:52 -0700220 return;
221 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800222 const void* new_quick_code;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100223 bool uninstall = !entry_exit_stubs_installed_ && !interpreter_stubs_installed_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800224 Runtime* const runtime = Runtime::Current();
225 ClassLinker* const class_linker = runtime->GetClassLinker();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100226 bool is_class_initialized = method->GetDeclaringClass()->IsInitialized();
227 if (uninstall) {
228 if ((forced_interpret_only_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800229 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100230 } else if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700231 new_quick_code = GetCodeForInvoke(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100232 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700233 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100234 }
235 } else { // !uninstall
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100236 if ((interpreter_stubs_installed_ || forced_interpret_only_ || IsDeoptimized(method)) &&
237 !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800238 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100239 } else {
240 // Do not overwrite resolution trampoline. When the trampoline initializes the method's
241 // class, all its static methods code will be set to the instrumentation entry point.
242 // For more details, see ClassLinker::FixupStaticTrampolines.
243 if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light2d441b12018-06-08 15:33:21 -0700244 if (entry_exit_stubs_installed_) {
245 // This needs to be checked first since the instrumentation entrypoint will be able to
246 // find the actual JIT compiled code that corresponds to this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800247 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700248 } else if (NeedDebugVersionFor(method)) {
249 // It would be great to search the JIT for its implementation here but we cannot due to
250 // the locks we hold. Instead just set to the interpreter bridge and that code will search
251 // the JIT when it gets called and replace the entrypoint then.
252 new_quick_code = GetQuickToInterpreterBridge();
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000253 } else {
Alex Lightfc49fec2018-01-16 22:28:36 +0000254 new_quick_code = class_linker->GetQuickOatCodeFor(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100255 }
256 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700257 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100258 }
259 }
260 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800261 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100262}
263
Ian Rogers62d6c772013-02-27 08:32:07 -0800264// Places the instrumentation exit pc as the return PC for every quick frame. This also allows
265// deoptimization of quick frames to interpreter frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100266// Since we may already have done this previously, we need to push new instrumentation frame before
267// existing instrumentation frames.
Ian Rogers62d6c772013-02-27 08:32:07 -0800268static void InstrumentationInstallStack(Thread* thread, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700269 REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100270 struct InstallStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800271 InstallStackVisitor(Thread* thread_in, Context* context, uintptr_t instrumentation_exit_pc)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100272 : StackVisitor(thread_in, context, kInstrumentationStackWalk),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800273 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100274 instrumentation_exit_pc_(instrumentation_exit_pc),
Alex Lighte9278662018-03-08 16:55:58 -0800275 reached_existing_instrumentation_frames_(false), instrumentation_stack_depth_(0),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100276 last_return_pc_(0) {
277 }
jeffhao725a9572012-11-13 18:20:12 -0800278
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100279 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700280 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700281 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800282 if (kVerboseInstrumentation) {
283 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
284 }
285 last_return_pc_ = 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700286 return true; // Ignore upcalls.
Ian Rogers306057f2012-11-26 12:45:53 -0800287 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700288 if (GetCurrentQuickFrame() == nullptr) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800289 bool interpreter_frame = true;
Sebastien Hertz320deb22014-06-11 19:45:05 +0200290 InstrumentationStackFrame instrumentation_frame(GetThisObject(), m, 0, GetFrameId(),
291 interpreter_frame);
Jeff Haoa15a81b2014-05-27 18:25:47 -0700292 if (kVerboseInstrumentation) {
293 LOG(INFO) << "Pushing shadow frame " << instrumentation_frame.Dump();
294 }
295 shadow_stack_.push_back(instrumentation_frame);
296 return true; // Continue.
297 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800298 uintptr_t return_pc = GetReturnPc();
Sebastien Hertz320deb22014-06-11 19:45:05 +0200299 if (kVerboseInstrumentation) {
300 LOG(INFO) << " Installing exit stub in " << DescribeLocation();
301 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100302 if (return_pc == instrumentation_exit_pc_) {
Mingyao Yang2ee17902017-08-30 11:37:08 -0700303 CHECK_LT(instrumentation_stack_depth_, instrumentation_stack_->size());
304
305 if (m->IsRuntimeMethod()) {
306 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100307 (*instrumentation_stack_)[instrumentation_stack_depth_];
Mingyao Yang2ee17902017-08-30 11:37:08 -0700308 if (frame.interpreter_entry_) {
309 // This instrumentation frame is for an interpreter bridge and is
310 // pushed when executing the instrumented interpreter bridge. So method
311 // enter event must have been reported. However we need to push a DEX pc
312 // into the dex_pcs_ list to match size of instrumentation stack.
Andreas Gampee2abbc62017-09-15 11:59:26 -0700313 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700314 dex_pcs_.push_back(dex_pc);
315 last_return_pc_ = frame.return_pc_;
316 ++instrumentation_stack_depth_;
317 return true;
318 }
319 }
320
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100321 // We've reached a frame which has already been installed with instrumentation exit stub.
Alex Light74c91c92018-03-08 14:01:44 -0800322 // We should have already installed instrumentation or be interpreter on previous frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100323 reached_existing_instrumentation_frames_ = true;
324
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200325 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100326 (*instrumentation_stack_)[instrumentation_stack_depth_];
Alex Lightfc81d802018-12-07 13:39:05 -0800327 CHECK_EQ(m->GetNonObsoleteMethod(), frame.method_->GetNonObsoleteMethod())
328 << "Expected " << ArtMethod::PrettyMethod(m)
329 << ", Found " << ArtMethod::PrettyMethod(frame.method_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100330 return_pc = frame.return_pc_;
331 if (kVerboseInstrumentation) {
332 LOG(INFO) << "Ignoring already instrumented " << frame.Dump();
333 }
334 } else {
335 CHECK_NE(return_pc, 0U);
Alex Light74c91c92018-03-08 14:01:44 -0800336 if (UNLIKELY(reached_existing_instrumentation_frames_ && !m->IsRuntimeMethod())) {
337 // We already saw an existing instrumentation frame so this should be a runtime-method
338 // inserted by the interpreter or runtime.
Alex Lighte9278662018-03-08 16:55:58 -0800339 std::string thread_name;
340 GetThread()->GetThreadName(thread_name);
341 uint32_t dex_pc = dex::kDexNoIndex;
342 if (last_return_pc_ != 0 &&
343 GetCurrentOatQuickMethodHeader() != nullptr) {
344 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
345 }
Alex Light74c91c92018-03-08 14:01:44 -0800346 LOG(FATAL) << "While walking " << thread_name << " found unexpected non-runtime method"
347 << " without instrumentation exit return or interpreter frame."
Alex Lighte9278662018-03-08 16:55:58 -0800348 << " method is " << GetMethod()->PrettyMethod()
349 << " return_pc is " << std::hex << return_pc
350 << " dex pc: " << dex_pc;
351 UNREACHABLE();
352 }
Mingyao Yang2ee17902017-08-30 11:37:08 -0700353 InstrumentationStackFrame instrumentation_frame(
354 m->IsRuntimeMethod() ? nullptr : GetThisObject(),
355 m,
356 return_pc,
357 GetFrameId(), // A runtime method still gets a frame id.
358 false);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100359 if (kVerboseInstrumentation) {
360 LOG(INFO) << "Pushing frame " << instrumentation_frame.Dump();
361 }
362
Sebastien Hertz320deb22014-06-11 19:45:05 +0200363 // Insert frame at the right position so we do not corrupt the instrumentation stack.
364 // Instrumentation stack frames are in descending frame id order.
365 auto it = instrumentation_stack_->begin();
366 for (auto end = instrumentation_stack_->end(); it != end; ++it) {
367 const InstrumentationStackFrame& current = *it;
368 if (instrumentation_frame.frame_id_ >= current.frame_id_) {
369 break;
370 }
371 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100372 instrumentation_stack_->insert(it, instrumentation_frame);
373 SetReturnPc(instrumentation_exit_pc_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800374 }
Andreas Gampee2abbc62017-09-15 11:59:26 -0700375 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700376 if (last_return_pc_ != 0 &&
377 GetCurrentOatQuickMethodHeader() != nullptr) {
378 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
379 }
380 dex_pcs_.push_back(dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800381 last_return_pc_ = return_pc;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100382 ++instrumentation_stack_depth_;
Ian Rogers306057f2012-11-26 12:45:53 -0800383 return true; // Continue.
384 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800385 std::deque<InstrumentationStackFrame>* const instrumentation_stack_;
Jeff Haoa15a81b2014-05-27 18:25:47 -0700386 std::vector<InstrumentationStackFrame> shadow_stack_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800387 std::vector<uint32_t> dex_pcs_;
Ian Rogers306057f2012-11-26 12:45:53 -0800388 const uintptr_t instrumentation_exit_pc_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100389 bool reached_existing_instrumentation_frames_;
390 size_t instrumentation_stack_depth_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800391 uintptr_t last_return_pc_;
Ian Rogers306057f2012-11-26 12:45:53 -0800392 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800393 if (kVerboseInstrumentation) {
394 std::string thread_name;
395 thread->GetThreadName(thread_name);
396 LOG(INFO) << "Installing exit stubs in " << thread_name;
Ian Rogers306057f2012-11-26 12:45:53 -0800397 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100398
399 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers700a4022014-05-19 16:49:03 -0700400 std::unique_ptr<Context> context(Context::Create());
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700401 uintptr_t instrumentation_exit_pc = reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100402 InstallStackVisitor visitor(thread, context.get(), instrumentation_exit_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800403 visitor.WalkStack(true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100404 CHECK_EQ(visitor.dex_pcs_.size(), thread->GetInstrumentationStack()->size());
Ian Rogers62d6c772013-02-27 08:32:07 -0800405
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100406 if (instrumentation->ShouldNotifyMethodEnterExitEvents()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100407 // Create method enter events for all methods currently on the thread's stack. We only do this
408 // if no debugger is attached to prevent from posting events twice.
Jeff Haoa15a81b2014-05-27 18:25:47 -0700409 auto ssi = visitor.shadow_stack_.rbegin();
410 for (auto isi = thread->GetInstrumentationStack()->rbegin(),
411 end = thread->GetInstrumentationStack()->rend(); isi != end; ++isi) {
412 while (ssi != visitor.shadow_stack_.rend() && (*ssi).frame_id_ < (*isi).frame_id_) {
413 instrumentation->MethodEnterEvent(thread, (*ssi).this_object_, (*ssi).method_, 0);
414 ++ssi;
415 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100416 uint32_t dex_pc = visitor.dex_pcs_.back();
417 visitor.dex_pcs_.pop_back();
Alex Lightdc5423f2018-06-08 10:43:38 -0700418 if (!isi->interpreter_entry_ && !isi->method_->IsRuntimeMethod()) {
Sebastien Hertz320deb22014-06-11 19:45:05 +0200419 instrumentation->MethodEnterEvent(thread, (*isi).this_object_, (*isi).method_, dex_pc);
420 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100421 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800422 }
423 thread->VerifyStack();
Ian Rogers306057f2012-11-26 12:45:53 -0800424}
425
Mingyao Yang99170c62015-07-06 11:10:37 -0700426void Instrumentation::InstrumentThreadStack(Thread* thread) {
427 instrumentation_stubs_installed_ = true;
428 InstrumentationInstallStack(thread, this);
429}
430
Ian Rogers62d6c772013-02-27 08:32:07 -0800431// Removes the instrumentation exit pc as the return PC for every quick frame.
432static void InstrumentationRestoreStack(Thread* thread, void* arg)
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000433 REQUIRES(Locks::mutator_lock_) {
434 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
435
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100436 struct RestoreStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800437 RestoreStackVisitor(Thread* thread_in, uintptr_t instrumentation_exit_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800438 Instrumentation* instrumentation)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100439 : StackVisitor(thread_in, nullptr, kInstrumentationStackWalk),
440 thread_(thread_in),
Ian Rogers62d6c772013-02-27 08:32:07 -0800441 instrumentation_exit_pc_(instrumentation_exit_pc),
442 instrumentation_(instrumentation),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800443 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Ian Rogers62d6c772013-02-27 08:32:07 -0800444 frames_removed_(0) {}
Ian Rogers306057f2012-11-26 12:45:53 -0800445
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100446 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800447 if (instrumentation_stack_->size() == 0) {
jeffhao725a9572012-11-13 18:20:12 -0800448 return false; // Stop.
449 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700450 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700451 if (GetCurrentQuickFrame() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800452 if (kVerboseInstrumentation) {
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200453 LOG(INFO) << " Ignoring a shadow frame. Frame " << GetFrameId()
David Sehr709b0702016-10-13 09:12:37 -0700454 << " Method=" << ArtMethod::PrettyMethod(m);
Ian Rogers62d6c772013-02-27 08:32:07 -0800455 }
456 return true; // Ignore shadow frames.
457 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700458 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800459 if (kVerboseInstrumentation) {
460 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
461 }
Ian Rogers306057f2012-11-26 12:45:53 -0800462 return true; // Ignore upcalls.
463 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800464 bool removed_stub = false;
465 // TODO: make this search more efficient?
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100466 const size_t frameId = GetFrameId();
467 for (const InstrumentationStackFrame& instrumentation_frame : *instrumentation_stack_) {
468 if (instrumentation_frame.frame_id_ == frameId) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800469 if (kVerboseInstrumentation) {
470 LOG(INFO) << " Removing exit stub in " << DescribeLocation();
471 }
Jeff Hao9a916d32013-06-27 18:45:37 -0700472 if (instrumentation_frame.interpreter_entry_) {
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700473 CHECK(m == Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
Jeff Hao9a916d32013-06-27 18:45:37 -0700474 } else {
Alex Lightfc81d802018-12-07 13:39:05 -0800475 CHECK_EQ(m->GetNonObsoleteMethod(),
476 instrumentation_frame.method_->GetNonObsoleteMethod())
477 << ArtMethod::PrettyMethod(m);
Jeff Hao9a916d32013-06-27 18:45:37 -0700478 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800479 SetReturnPc(instrumentation_frame.return_pc_);
Mingyao Yang2ee17902017-08-30 11:37:08 -0700480 if (instrumentation_->ShouldNotifyMethodEnterExitEvents() &&
481 !m->IsRuntimeMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100482 // Create the method exit events. As the methods didn't really exit the result is 0.
483 // We only do this if no debugger is attached to prevent from posting events twice.
484 instrumentation_->MethodExitEvent(thread_, instrumentation_frame.this_object_, m,
485 GetDexPc(), JValue());
486 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800487 frames_removed_++;
488 removed_stub = true;
489 break;
490 }
491 }
492 if (!removed_stub) {
493 if (kVerboseInstrumentation) {
494 LOG(INFO) << " No exit stub in " << DescribeLocation();
Ian Rogers306057f2012-11-26 12:45:53 -0800495 }
jeffhao725a9572012-11-13 18:20:12 -0800496 }
497 return true; // Continue.
498 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800499 Thread* const thread_;
Ian Rogers306057f2012-11-26 12:45:53 -0800500 const uintptr_t instrumentation_exit_pc_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800501 Instrumentation* const instrumentation_;
502 std::deque<instrumentation::InstrumentationStackFrame>* const instrumentation_stack_;
503 size_t frames_removed_;
jeffhao725a9572012-11-13 18:20:12 -0800504 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800505 if (kVerboseInstrumentation) {
506 std::string thread_name;
507 thread->GetThreadName(thread_name);
508 LOG(INFO) << "Removing exit stubs in " << thread_name;
509 }
510 std::deque<instrumentation::InstrumentationStackFrame>* stack = thread->GetInstrumentationStack();
511 if (stack->size() > 0) {
512 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700513 uintptr_t instrumentation_exit_pc =
514 reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Ian Rogers62d6c772013-02-27 08:32:07 -0800515 RestoreStackVisitor visitor(thread, instrumentation_exit_pc, instrumentation);
516 visitor.WalkStack(true);
517 CHECK_EQ(visitor.frames_removed_, stack->size());
518 while (stack->size() > 0) {
519 stack->pop_front();
520 }
jeffhao725a9572012-11-13 18:20:12 -0800521 }
522}
523
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200524static bool HasEvent(Instrumentation::InstrumentationEvent expected, uint32_t events) {
525 return (events & expected) != 0;
526}
527
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000528static void PotentiallyAddListenerTo(Instrumentation::InstrumentationEvent event,
529 uint32_t events,
530 std::list<InstrumentationListener*>& list,
531 InstrumentationListener* listener,
532 bool* has_listener)
533 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
534 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
535 if (!HasEvent(event, events)) {
536 return;
537 }
538 // If there is a free slot in the list, we insert the listener in that slot.
539 // Otherwise we add it to the end of the list.
540 auto it = std::find(list.begin(), list.end(), nullptr);
541 if (it != list.end()) {
542 *it = listener;
543 } else {
544 list.push_back(listener);
545 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100546 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000547}
548
Ian Rogers62d6c772013-02-27 08:32:07 -0800549void Instrumentation::AddListener(InstrumentationListener* listener, uint32_t events) {
550 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000551 PotentiallyAddListenerTo(kMethodEntered,
552 events,
553 method_entry_listeners_,
554 listener,
555 &have_method_entry_listeners_);
556 PotentiallyAddListenerTo(kMethodExited,
557 events,
558 method_exit_listeners_,
559 listener,
560 &have_method_exit_listeners_);
561 PotentiallyAddListenerTo(kMethodUnwind,
562 events,
563 method_unwind_listeners_,
564 listener,
565 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000566 PotentiallyAddListenerTo(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000567 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000568 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000569 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000570 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000571 PotentiallyAddListenerTo(kDexPcMoved,
572 events,
573 dex_pc_listeners_,
574 listener,
575 &have_dex_pc_listeners_);
576 PotentiallyAddListenerTo(kFieldRead,
577 events,
578 field_read_listeners_,
579 listener,
580 &have_field_read_listeners_);
581 PotentiallyAddListenerTo(kFieldWritten,
582 events,
583 field_write_listeners_,
584 listener,
585 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700586 PotentiallyAddListenerTo(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000587 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700588 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000589 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700590 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700591 PotentiallyAddListenerTo(kWatchedFramePop,
592 events,
593 watched_frame_pop_listeners_,
594 listener,
595 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700596 PotentiallyAddListenerTo(kExceptionHandled,
597 events,
598 exception_handled_listeners_,
599 listener,
600 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200601 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800602}
603
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000604static void PotentiallyRemoveListenerFrom(Instrumentation::InstrumentationEvent event,
605 uint32_t events,
606 std::list<InstrumentationListener*>& list,
607 InstrumentationListener* listener,
608 bool* has_listener)
609 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
610 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
611 if (!HasEvent(event, events)) {
612 return;
613 }
614 auto it = std::find(list.begin(), list.end(), listener);
615 if (it != list.end()) {
616 // Just update the entry, do not remove from the list. Removing entries in the list
617 // is unsafe when mutators are iterating over it.
618 *it = nullptr;
619 }
620
621 // Check if the list contains any non-null listener, and update 'has_listener'.
622 for (InstrumentationListener* l : list) {
623 if (l != nullptr) {
David Srbecky28f6cff2018-10-16 15:07:28 +0100624 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000625 return;
626 }
627 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100628 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = false; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000629}
630
Ian Rogers62d6c772013-02-27 08:32:07 -0800631void Instrumentation::RemoveListener(InstrumentationListener* listener, uint32_t events) {
632 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000633 PotentiallyRemoveListenerFrom(kMethodEntered,
634 events,
635 method_entry_listeners_,
636 listener,
637 &have_method_entry_listeners_);
638 PotentiallyRemoveListenerFrom(kMethodExited,
639 events,
640 method_exit_listeners_,
641 listener,
642 &have_method_exit_listeners_);
643 PotentiallyRemoveListenerFrom(kMethodUnwind,
644 events,
645 method_unwind_listeners_,
646 listener,
647 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000648 PotentiallyRemoveListenerFrom(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000649 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000650 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000651 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000652 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000653 PotentiallyRemoveListenerFrom(kDexPcMoved,
654 events,
655 dex_pc_listeners_,
656 listener,
657 &have_dex_pc_listeners_);
658 PotentiallyRemoveListenerFrom(kFieldRead,
659 events,
660 field_read_listeners_,
661 listener,
662 &have_field_read_listeners_);
663 PotentiallyRemoveListenerFrom(kFieldWritten,
664 events,
665 field_write_listeners_,
666 listener,
667 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700668 PotentiallyRemoveListenerFrom(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000669 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700670 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000671 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700672 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700673 PotentiallyRemoveListenerFrom(kWatchedFramePop,
674 events,
675 watched_frame_pop_listeners_,
676 listener,
677 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700678 PotentiallyRemoveListenerFrom(kExceptionHandled,
679 events,
680 exception_handled_listeners_,
681 listener,
682 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200683 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800684}
685
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200686Instrumentation::InstrumentationLevel Instrumentation::GetCurrentInstrumentationLevel() const {
Alex Light4ba388a2017-01-27 10:26:49 -0800687 if (interpreter_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200688 return InstrumentationLevel::kInstrumentWithInterpreter;
Ian Rogers62d6c772013-02-27 08:32:07 -0800689 } else if (entry_exit_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200690 return InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Ian Rogers62d6c772013-02-27 08:32:07 -0800691 } else {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200692 return InstrumentationLevel::kInstrumentNothing;
Ian Rogers62d6c772013-02-27 08:32:07 -0800693 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200694}
695
Alex Lightdba61482016-12-21 08:20:29 -0800696bool Instrumentation::RequiresInstrumentationInstallation(InstrumentationLevel new_level) const {
Alex Light4ba388a2017-01-27 10:26:49 -0800697 // We need to reinstall instrumentation if we go to a different level.
698 return GetCurrentInstrumentationLevel() != new_level;
Alex Lightdba61482016-12-21 08:20:29 -0800699}
700
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200701void Instrumentation::ConfigureStubs(const char* key, InstrumentationLevel desired_level) {
702 // Store the instrumentation level for this key or remove it.
703 if (desired_level == InstrumentationLevel::kInstrumentNothing) {
704 // The client no longer needs instrumentation.
705 requested_instrumentation_levels_.erase(key);
706 } else {
707 // The client needs instrumentation.
708 requested_instrumentation_levels_.Overwrite(key, desired_level);
709 }
710
711 // Look for the highest required instrumentation level.
712 InstrumentationLevel requested_level = InstrumentationLevel::kInstrumentNothing;
713 for (const auto& v : requested_instrumentation_levels_) {
714 requested_level = std::max(requested_level, v.second);
715 }
716
717 interpret_only_ = (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) ||
718 forced_interpret_only_;
719
Alex Lightdba61482016-12-21 08:20:29 -0800720 if (!RequiresInstrumentationInstallation(requested_level)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800721 // We're already set.
722 return;
723 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100724 Thread* const self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800725 Runtime* runtime = Runtime::Current();
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100726 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800727 Locks::thread_list_lock_->AssertNotHeld(self);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200728 if (requested_level > InstrumentationLevel::kInstrumentNothing) {
Alex Light4ba388a2017-01-27 10:26:49 -0800729 if (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800730 interpreter_stubs_installed_ = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800731 entry_exit_stubs_installed_ = true;
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200732 } else {
733 CHECK_EQ(requested_level, InstrumentationLevel::kInstrumentWithInstrumentationStubs);
734 entry_exit_stubs_installed_ = true;
735 interpreter_stubs_installed_ = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800736 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700737 InstallStubsClassVisitor visitor(this);
738 runtime->GetClassLinker()->VisitClasses(&visitor);
Ian Rogers62d6c772013-02-27 08:32:07 -0800739 instrumentation_stubs_installed_ = true;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100740 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800741 runtime->GetThreadList()->ForEach(InstrumentationInstallStack, this);
742 } else {
743 interpreter_stubs_installed_ = false;
744 entry_exit_stubs_installed_ = false;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700745 InstallStubsClassVisitor visitor(this);
746 runtime->GetClassLinker()->VisitClasses(&visitor);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100747 // Restore stack only if there is no method currently deoptimized.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700748 bool empty;
749 {
Andreas Gampe7e56a072018-11-29 10:40:06 -0800750 ReaderMutexLock mu(self, *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700751 empty = IsDeoptimizedMethodsEmpty(); // Avoid lock violation.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700752 }
753 if (empty) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100754 MutexLock mu(self, *Locks::thread_list_lock_);
755 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000756 // Only do this after restoring, as walking the stack when restoring will see
757 // the instrumentation exit pc.
758 instrumentation_stubs_installed_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100759 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800760 }
jeffhao725a9572012-11-13 18:20:12 -0800761}
762
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200763static void ResetQuickAllocEntryPointsForThread(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -0800764 thread->ResetQuickAllocEntryPointsForThread(kUseReadBarrier && thread->GetIsGcMarking());
Ian Rogersfa824272013-11-05 16:12:57 -0800765}
766
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700767void Instrumentation::SetEntrypointsInstrumented(bool instrumented) {
768 Thread* self = Thread::Current();
Mathieu Chartier661974a2014-01-09 11:23:53 -0800769 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700770 Locks::mutator_lock_->AssertNotHeld(self);
771 Locks::instrument_entrypoints_lock_->AssertHeld(self);
772 if (runtime->IsStarted()) {
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700773 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700774 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier661974a2014-01-09 11:23:53 -0800775 SetQuickAllocEntryPointsInstrumented(instrumented);
776 ResetQuickAllocEntryPoints();
Mathieu Chartier50e93312016-03-16 11:25:29 -0700777 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700778 } else {
779 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
780 SetQuickAllocEntryPointsInstrumented(instrumented);
Andreas Gampe157c77e2016-10-17 17:44:41 -0700781
782 // Note: ResetQuickAllocEntryPoints only works when the runtime is started. Manually run the
783 // update for just this thread.
Andreas Gampe162ae502016-10-18 10:03:42 -0700784 // Note: self may be null. One of those paths is setting instrumentation in the Heap
785 // constructor for gcstress mode.
786 if (self != nullptr) {
787 ResetQuickAllocEntryPointsForThread(self, nullptr);
788 }
Andreas Gampe157c77e2016-10-17 17:44:41 -0700789
Mathieu Chartier50e93312016-03-16 11:25:29 -0700790 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier661974a2014-01-09 11:23:53 -0800791 }
792}
793
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700794void Instrumentation::InstrumentQuickAllocEntryPoints() {
795 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
796 InstrumentQuickAllocEntryPointsLocked();
Ian Rogersfa824272013-11-05 16:12:57 -0800797}
798
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700799void Instrumentation::UninstrumentQuickAllocEntryPoints() {
800 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
801 UninstrumentQuickAllocEntryPointsLocked();
802}
803
804void Instrumentation::InstrumentQuickAllocEntryPointsLocked() {
805 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
806 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
807 SetEntrypointsInstrumented(true);
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800808 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700809 ++quick_alloc_entry_points_instrumentation_counter_;
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700810}
811
812void Instrumentation::UninstrumentQuickAllocEntryPointsLocked() {
813 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
814 CHECK_GT(quick_alloc_entry_points_instrumentation_counter_, 0U);
815 --quick_alloc_entry_points_instrumentation_counter_;
816 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
817 SetEntrypointsInstrumented(false);
818 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800819}
820
821void Instrumentation::ResetQuickAllocEntryPoints() {
822 Runtime* runtime = Runtime::Current();
823 if (runtime->IsStarted()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800824 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700825 runtime->GetThreadList()->ForEach(ResetQuickAllocEntryPointsForThread, nullptr);
Ian Rogersfa824272013-11-05 16:12:57 -0800826 }
827}
828
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700829void Instrumentation::UpdateMethodsCodeImpl(ArtMethod* method, const void* quick_code) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800830 const void* new_quick_code;
Ian Rogers62d6c772013-02-27 08:32:07 -0800831 if (LIKELY(!instrumentation_stubs_installed_)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800832 new_quick_code = quick_code;
Jeff Hao65d15d92013-07-16 16:39:33 -0700833 } else {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100834 if ((interpreter_stubs_installed_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800835 new_quick_code = GetQuickToInterpreterBridge();
Jeff Hao65d15d92013-07-16 16:39:33 -0700836 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700837 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700838 if (class_linker->IsQuickResolutionStub(quick_code) ||
839 class_linker->IsQuickToInterpreterBridge(quick_code)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700840 new_quick_code = quick_code;
Alex Light6cae5ea2018-06-07 17:07:02 -0700841 } else if (entry_exit_stubs_installed_ &&
842 // We need to make sure not to replace anything that InstallStubsForMethod
843 // wouldn't. Specifically we cannot stub out Proxy.<init> since subtypes copy the
844 // implementation directly and this will confuse the instrumentation trampolines.
845 // TODO We should remove the need for this since it makes it impossible to profile
846 // Proxy.<init> correctly in all cases.
847 method != jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700848 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700849 if (!method->IsNative() && Runtime::Current()->GetJit() != nullptr) {
850 // Native methods use trampoline entrypoints during interpreter tracing.
851 DCHECK(!Runtime::Current()->GetJit()->GetCodeCache()->GetGarbageCollectCode());
852 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
853 // Tracing will look at the saved entry point in the profiling info to know the actual
854 // entrypoint, so we store it here.
855 if (profiling_info != nullptr) {
856 profiling_info->SetSavedEntryPoint(quick_code);
857 }
858 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700859 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700860 new_quick_code = quick_code;
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700861 }
Jeff Hao65d15d92013-07-16 16:39:33 -0700862 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800863 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800864 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100865}
866
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +0000867void Instrumentation::UpdateNativeMethodsCodeToJitCode(ArtMethod* method, const void* quick_code) {
868 // We don't do any read barrier on `method`'s declaring class in this code, as the JIT might
869 // enter here on a soon-to-be deleted ArtMethod. Updating the entrypoint is OK though, as
870 // the ArtMethod is still in memory.
871 const void* new_quick_code = quick_code;
872 if (UNLIKELY(instrumentation_stubs_installed_) && entry_exit_stubs_installed_) {
873 new_quick_code = GetQuickInstrumentationEntryPoint();
874 }
875 UpdateEntrypoints(method, new_quick_code);
876}
877
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700878void Instrumentation::UpdateMethodsCode(ArtMethod* method, const void* quick_code) {
879 DCHECK(method->GetDeclaringClass()->IsResolved());
880 UpdateMethodsCodeImpl(method, quick_code);
881}
882
Alex Light0a5ec3d2017-07-25 16:50:26 -0700883void Instrumentation::UpdateMethodsCodeToInterpreterEntryPoint(ArtMethod* method) {
884 UpdateMethodsCodeImpl(method, GetQuickToInterpreterBridge());
885}
886
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000887void Instrumentation::UpdateMethodsCodeForJavaDebuggable(ArtMethod* method,
888 const void* quick_code) {
889 // When the runtime is set to Java debuggable, we may update the entry points of
890 // all methods of a class to the interpreter bridge. A method's declaring class
891 // might not be in resolved state yet in that case, so we bypass the DCHECK in
892 // UpdateMethodsCode.
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700893 UpdateMethodsCodeImpl(method, quick_code);
894}
895
Mathieu Chartiere401d142015-04-22 13:56:20 -0700896bool Instrumentation::AddDeoptimizedMethod(ArtMethod* method) {
897 if (IsDeoptimizedMethod(method)) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700898 // Already in the map. Return.
899 return false;
900 }
901 // Not found. Add it.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700902 deoptimized_methods_.insert(method);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700903 return true;
904}
905
Mathieu Chartiere401d142015-04-22 13:56:20 -0700906bool Instrumentation::IsDeoptimizedMethod(ArtMethod* method) {
907 return deoptimized_methods_.find(method) != deoptimized_methods_.end();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700908}
909
Mathieu Chartiere401d142015-04-22 13:56:20 -0700910ArtMethod* Instrumentation::BeginDeoptimizedMethod() {
911 if (deoptimized_methods_.empty()) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700912 // Empty.
913 return nullptr;
914 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700915 return *deoptimized_methods_.begin();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700916}
917
Mathieu Chartiere401d142015-04-22 13:56:20 -0700918bool Instrumentation::RemoveDeoptimizedMethod(ArtMethod* method) {
919 auto it = deoptimized_methods_.find(method);
920 if (it == deoptimized_methods_.end()) {
921 return false;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700922 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700923 deoptimized_methods_.erase(it);
924 return true;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700925}
926
927bool Instrumentation::IsDeoptimizedMethodsEmpty() const {
928 return deoptimized_methods_.empty();
929}
930
Mathieu Chartiere401d142015-04-22 13:56:20 -0700931void Instrumentation::Deoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100932 CHECK(!method->IsNative());
933 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700934 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100935
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700936 Thread* self = Thread::Current();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700937 {
Andreas Gampe7e56a072018-11-29 10:40:06 -0800938 WriterMutexLock mu(self, *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700939 bool has_not_been_deoptimized = AddDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700940 CHECK(has_not_been_deoptimized) << "Method " << ArtMethod::PrettyMethod(method)
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200941 << " is already deoptimized";
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700942 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100943 if (!interpreter_stubs_installed_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800944 UpdateEntrypoints(method, GetQuickInstrumentationEntryPoint());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100945
946 // Install instrumentation exit stub and instrumentation frames. We may already have installed
947 // these previously so it will only cover the newly created frames.
948 instrumentation_stubs_installed_ = true;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700949 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100950 Runtime::Current()->GetThreadList()->ForEach(InstrumentationInstallStack, this);
951 }
952}
953
Mathieu Chartiere401d142015-04-22 13:56:20 -0700954void Instrumentation::Undeoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100955 CHECK(!method->IsNative());
956 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700957 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100958
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700959 Thread* self = Thread::Current();
960 bool empty;
961 {
Andreas Gampe7e56a072018-11-29 10:40:06 -0800962 WriterMutexLock mu(self, *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700963 bool found_and_erased = RemoveDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700964 CHECK(found_and_erased) << "Method " << ArtMethod::PrettyMethod(method)
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700965 << " is not deoptimized";
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700966 empty = IsDeoptimizedMethodsEmpty();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700967 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100968
969 // Restore code and possibly stack only if we did not deoptimize everything.
970 if (!interpreter_stubs_installed_) {
971 // Restore its code or resolution trampoline.
972 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800973 if (method->IsStatic() && !method->IsConstructor() &&
974 !method->GetDeclaringClass()->IsInitialized()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800975 UpdateEntrypoints(method, GetQuickResolutionStub());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100976 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000977 const void* quick_code = NeedDebugVersionFor(method)
978 ? GetQuickToInterpreterBridge()
Alex Lightfc49fec2018-01-16 22:28:36 +0000979 : class_linker->GetQuickOatCodeFor(method);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800980 UpdateEntrypoints(method, quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100981 }
982
983 // If there is no deoptimized method left, we can restore the stack of each thread.
Alex Lightf244a572018-06-08 13:56:51 -0700984 if (empty && !entry_exit_stubs_installed_) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700985 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100986 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
987 instrumentation_stubs_installed_ = false;
988 }
989 }
990}
991
Mathieu Chartiere401d142015-04-22 13:56:20 -0700992bool Instrumentation::IsDeoptimized(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100993 DCHECK(method != nullptr);
Andreas Gampe7e56a072018-11-29 10:40:06 -0800994 ReaderMutexLock mu(Thread::Current(), *GetDeoptimizedMethodsLock());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700995 return IsDeoptimizedMethod(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100996}
997
998void Instrumentation::EnableDeoptimization() {
Andreas Gampe7e56a072018-11-29 10:40:06 -0800999 ReaderMutexLock mu(Thread::Current(), *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001000 CHECK(IsDeoptimizedMethodsEmpty());
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001001 CHECK_EQ(deoptimization_enabled_, false);
1002 deoptimization_enabled_ = true;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001003}
1004
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001005void Instrumentation::DisableDeoptimization(const char* key) {
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001006 CHECK_EQ(deoptimization_enabled_, true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001007 // If we deoptimized everything, undo it.
Alex Lightdba61482016-12-21 08:20:29 -08001008 InstrumentationLevel level = GetCurrentInstrumentationLevel();
1009 if (level == InstrumentationLevel::kInstrumentWithInterpreter) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001010 UndeoptimizeEverything(key);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001011 }
1012 // Undeoptimized selected methods.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001013 while (true) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001014 ArtMethod* method;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001015 {
Andreas Gampe7e56a072018-11-29 10:40:06 -08001016 ReaderMutexLock mu(Thread::Current(), *GetDeoptimizedMethodsLock());
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001017 if (IsDeoptimizedMethodsEmpty()) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001018 break;
1019 }
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001020 method = BeginDeoptimizedMethod();
1021 CHECK(method != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001022 }
1023 Undeoptimize(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001024 }
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001025 deoptimization_enabled_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001026}
1027
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001028// Indicates if instrumentation should notify method enter/exit events to the listeners.
1029bool Instrumentation::ShouldNotifyMethodEnterExitEvents() const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001030 if (!HasMethodEntryListeners() && !HasMethodExitListeners()) {
1031 return false;
1032 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01001033 return !deoptimization_enabled_ && !interpreter_stubs_installed_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001034}
1035
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001036void Instrumentation::DeoptimizeEverything(const char* key) {
1037 CHECK(deoptimization_enabled_);
1038 ConfigureStubs(key, InstrumentationLevel::kInstrumentWithInterpreter);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001039}
1040
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001041void Instrumentation::UndeoptimizeEverything(const char* key) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001042 CHECK(interpreter_stubs_installed_);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001043 CHECK(deoptimization_enabled_);
1044 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001045}
1046
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001047void Instrumentation::EnableMethodTracing(const char* key, bool needs_interpreter) {
1048 InstrumentationLevel level;
1049 if (needs_interpreter) {
1050 level = InstrumentationLevel::kInstrumentWithInterpreter;
1051 } else {
1052 level = InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Alex Light2d441b12018-06-08 15:33:21 -07001053 if (Runtime::Current()->GetJit() != nullptr) {
1054 // TODO b/110263880 It would be better if we didn't need to do this.
1055 // Since we need to hold the method entrypoint across a suspend to ensure instrumentation
1056 // hooks are called correctly we have to disable jit-gc to ensure that the entrypoint doesn't
1057 // go away. Furthermore we need to leave this off permanently since one could get the same
1058 // effect by causing this to be toggled on and off.
1059 Runtime::Current()->GetJit()->GetCodeCache()->SetGarbageCollectCode(false);
1060 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001061 }
1062 ConfigureStubs(key, level);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001063}
1064
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001065void Instrumentation::DisableMethodTracing(const char* key) {
1066 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
jeffhao725a9572012-11-13 18:20:12 -08001067}
1068
Alex Light2d441b12018-06-08 15:33:21 -07001069const void* Instrumentation::GetCodeForInvoke(ArtMethod* method) const {
1070 // This is called by instrumentation entry only and that should never be getting proxy methods.
1071 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
1072 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1073 if (LIKELY(!instrumentation_stubs_installed_ && !interpreter_stubs_installed_)) {
1074 // In general we just return whatever the method thinks its entrypoint is here. The only
1075 // exception is if it still has the instrumentation entrypoint. That means we are racing another
1076 // thread getting rid of instrumentation which is unexpected but possible. In that case we want
1077 // to wait and try to get it from the oat file or jit.
1078 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(kRuntimePointerSize);
1079 DCHECK(code != nullptr);
1080 if (code != GetQuickInstrumentationEntryPoint()) {
1081 return code;
1082 } else if (method->IsNative()) {
1083 return class_linker->GetQuickOatCodeFor(method);
1084 }
1085 // We don't know what it is. Fallthough to try to find the code from the JIT or Oat file.
1086 } else if (method->IsNative()) {
1087 // TODO We could have JIT compiled native entrypoints. It might be worth it to find these.
1088 return class_linker->GetQuickOatCodeFor(method);
1089 } else if (UNLIKELY(interpreter_stubs_installed_)) {
1090 return GetQuickToInterpreterBridge();
1091 }
1092 // Since the method cannot be native due to ifs above we can always fall back to interpreter
1093 // bridge.
1094 const void* result = GetQuickToInterpreterBridge();
1095 if (!NeedDebugVersionFor(method)) {
1096 // If we don't need a debug version we should see what the oat file/class linker has to say.
1097 result = class_linker->GetQuickOatCodeFor(method);
1098 }
1099 // If both those fail try the jit.
1100 if (result == GetQuickToInterpreterBridge()) {
1101 jit::Jit* jit = Runtime::Current()->GetJit();
1102 if (jit != nullptr) {
1103 const void* res = jit->GetCodeCache()->FindCompiledCodeForInstrumentation(method);
1104 if (res != nullptr) {
1105 result = res;
1106 }
1107 }
1108 }
1109 return result;
1110}
1111
Andreas Gampe542451c2016-07-26 09:02:02 -07001112const void* Instrumentation::GetQuickCodeFor(ArtMethod* method, PointerSize pointer_size) const {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001113 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers62d6c772013-02-27 08:32:07 -08001114 if (LIKELY(!instrumentation_stubs_installed_)) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08001115 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size);
Vladimir Marko8a630572014-04-09 18:45:35 +01001116 DCHECK(code != nullptr);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001117 if (LIKELY(!class_linker->IsQuickResolutionStub(code) &&
1118 !class_linker->IsQuickToInterpreterBridge(code)) &&
1119 !class_linker->IsQuickResolutionStub(code) &&
1120 !class_linker->IsQuickToInterpreterBridge(code)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001121 return code;
1122 }
1123 }
Alex Lightfc49fec2018-01-16 22:28:36 +00001124 return class_linker->GetQuickOatCodeFor(method);
jeffhao725a9572012-11-13 18:20:12 -08001125}
1126
Alex Lightd7661582017-05-01 13:48:16 -07001127void Instrumentation::MethodEnterEventImpl(Thread* thread,
1128 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001129 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001130 uint32_t dex_pc) const {
Mingyao Yang2ee17902017-08-30 11:37:08 -07001131 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001132 if (HasMethodEntryListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001133 Thread* self = Thread::Current();
1134 StackHandleScope<1> hs(self);
1135 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001136 for (InstrumentationListener* listener : method_entry_listeners_) {
1137 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001138 listener->MethodEntered(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001139 }
1140 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001141 }
1142}
1143
Alex Lightd7661582017-05-01 13:48:16 -07001144void Instrumentation::MethodExitEventImpl(Thread* thread,
1145 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001146 ArtMethod* method,
Alex Lightd7661582017-05-01 13:48:16 -07001147 uint32_t dex_pc,
1148 const JValue& return_value) const {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001149 if (HasMethodExitListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001150 Thread* self = Thread::Current();
1151 StackHandleScope<2> hs(self);
1152 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1153 if (method->GetInterfaceMethodIfProxy(kRuntimePointerSize)
1154 ->GetReturnTypePrimitive() != Primitive::kPrimNot) {
1155 for (InstrumentationListener* listener : method_exit_listeners_) {
1156 if (listener != nullptr) {
1157 listener->MethodExited(thread, thiz, method, dex_pc, return_value);
1158 }
1159 }
1160 } else {
1161 Handle<mirror::Object> ret(hs.NewHandle(return_value.GetL()));
1162 for (InstrumentationListener* listener : method_exit_listeners_) {
1163 if (listener != nullptr) {
1164 listener->MethodExited(thread, thiz, method, dex_pc, ret);
1165 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001166 }
1167 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001168 }
1169}
1170
Alex Lightd7661582017-05-01 13:48:16 -07001171void Instrumentation::MethodUnwindEvent(Thread* thread,
1172 mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001173 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001174 uint32_t dex_pc) const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001175 if (HasMethodUnwindListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001176 Thread* self = Thread::Current();
1177 StackHandleScope<1> hs(self);
1178 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Mathieu Chartier02e25112013-08-14 16:14:24 -07001179 for (InstrumentationListener* listener : method_unwind_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001180 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001181 listener->MethodUnwind(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001182 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001183 }
1184 }
1185}
1186
Alex Lightd7661582017-05-01 13:48:16 -07001187void Instrumentation::DexPcMovedEventImpl(Thread* thread,
1188 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001189 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001190 uint32_t dex_pc) const {
Alex Lightd7661582017-05-01 13:48:16 -07001191 Thread* self = Thread::Current();
1192 StackHandleScope<1> hs(self);
1193 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001194 for (InstrumentationListener* listener : dex_pc_listeners_) {
1195 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001196 listener->DexPcMoved(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001197 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001198 }
1199}
1200
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001201void Instrumentation::BranchImpl(Thread* thread,
1202 ArtMethod* method,
1203 uint32_t dex_pc,
1204 int32_t offset) const {
1205 for (InstrumentationListener* listener : branch_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001206 if (listener != nullptr) {
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001207 listener->Branch(thread, method, dex_pc, offset);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001208 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001209 }
1210}
1211
Alex Lighte814f9d2017-07-31 16:14:39 -07001212void Instrumentation::WatchedFramePopImpl(Thread* thread, const ShadowFrame& frame) const {
1213 for (InstrumentationListener* listener : watched_frame_pop_listeners_) {
1214 if (listener != nullptr) {
1215 listener->WatchedFramePop(thread, frame);
1216 }
1217 }
1218}
1219
Alex Lightd7661582017-05-01 13:48:16 -07001220void Instrumentation::FieldReadEventImpl(Thread* thread,
1221 ObjPtr<mirror::Object> this_object,
1222 ArtMethod* method,
1223 uint32_t dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001224 ArtField* field) const {
Alex Lightd7661582017-05-01 13:48:16 -07001225 Thread* self = Thread::Current();
1226 StackHandleScope<1> hs(self);
1227 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001228 for (InstrumentationListener* listener : field_read_listeners_) {
1229 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001230 listener->FieldRead(thread, thiz, method, dex_pc, field);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001231 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001232 }
1233}
1234
Alex Lightd7661582017-05-01 13:48:16 -07001235void Instrumentation::FieldWriteEventImpl(Thread* thread,
1236 ObjPtr<mirror::Object> this_object,
1237 ArtMethod* method,
1238 uint32_t dex_pc,
1239 ArtField* field,
1240 const JValue& field_value) const {
1241 Thread* self = Thread::Current();
1242 StackHandleScope<2> hs(self);
1243 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1244 if (field->IsPrimitiveType()) {
1245 for (InstrumentationListener* listener : field_write_listeners_) {
1246 if (listener != nullptr) {
1247 listener->FieldWritten(thread, thiz, method, dex_pc, field, field_value);
1248 }
1249 }
1250 } else {
1251 Handle<mirror::Object> val(hs.NewHandle(field_value.GetL()));
1252 for (InstrumentationListener* listener : field_write_listeners_) {
1253 if (listener != nullptr) {
1254 listener->FieldWritten(thread, thiz, method, dex_pc, field, val);
1255 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001256 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001257 }
1258}
1259
Alex Light6e1607e2017-08-23 10:06:18 -07001260void Instrumentation::ExceptionThrownEvent(Thread* thread,
Sebastien Hertz947ff082013-09-17 14:10:13 +02001261 mirror::Throwable* exception_object) const {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001262 Thread* self = Thread::Current();
1263 StackHandleScope<1> hs(self);
1264 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
Alex Light6e1607e2017-08-23 10:06:18 -07001265 if (HasExceptionThrownListeners()) {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001266 DCHECK_EQ(thread->GetException(), h_exception.Get());
Jeff Haoc0bd4da2013-04-11 15:52:28 -07001267 thread->ClearException();
Alex Light6e1607e2017-08-23 10:06:18 -07001268 for (InstrumentationListener* listener : exception_thrown_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001269 if (listener != nullptr) {
Alex Light6e1607e2017-08-23 10:06:18 -07001270 listener->ExceptionThrown(thread, h_exception);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001271 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001272 }
Alex Light9fb1ab12017-09-05 09:32:49 -07001273 // See b/65049545 for discussion about this behavior.
1274 thread->AssertNoPendingException();
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001275 thread->SetException(h_exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08001276 }
1277}
1278
Alex Light9fb1ab12017-09-05 09:32:49 -07001279void Instrumentation::ExceptionHandledEvent(Thread* thread,
1280 mirror::Throwable* exception_object) const {
1281 Thread* self = Thread::Current();
1282 StackHandleScope<1> hs(self);
1283 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
1284 if (HasExceptionHandledListeners()) {
1285 // We should have cleared the exception so that callers can detect a new one.
1286 DCHECK(thread->GetException() == nullptr);
1287 for (InstrumentationListener* listener : exception_handled_listeners_) {
1288 if (listener != nullptr) {
1289 listener->ExceptionHandled(thread, h_exception);
1290 }
1291 }
1292 }
1293}
1294
Sebastien Hertzb2feaaf2015-10-12 13:40:10 +00001295// Computes a frame ID by ignoring inlined frames.
1296size_t Instrumentation::ComputeFrameId(Thread* self,
1297 size_t frame_depth,
1298 size_t inlined_frames_before_frame) {
1299 CHECK_GE(frame_depth, inlined_frames_before_frame);
1300 size_t no_inline_depth = frame_depth - inlined_frames_before_frame;
1301 return StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) - no_inline_depth;
1302}
1303
Ian Rogers62d6c772013-02-27 08:32:07 -08001304static void CheckStackDepth(Thread* self, const InstrumentationStackFrame& instrumentation_frame,
1305 int delta)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001306 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001307 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) + delta;
Ian Rogers62d6c772013-02-27 08:32:07 -08001308 if (frame_id != instrumentation_frame.frame_id_) {
1309 LOG(ERROR) << "Expected frame_id=" << frame_id << " but found "
1310 << instrumentation_frame.frame_id_;
1311 StackVisitor::DescribeStack(self);
1312 CHECK_EQ(frame_id, instrumentation_frame.frame_id_);
1313 }
1314}
1315
1316void Instrumentation::PushInstrumentationStackFrame(Thread* self, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001317 ArtMethod* method,
Jeff Hao9a916d32013-06-27 18:45:37 -07001318 uintptr_t lr, bool interpreter_entry) {
Alex Lightb7edcda2017-04-27 13:20:31 -07001319 DCHECK(!self->IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001320 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1321 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001322 LOG(INFO) << "Entering " << ArtMethod::PrettyMethod(method) << " from PC "
1323 << reinterpret_cast<void*>(lr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001324 }
Alex Lightb7edcda2017-04-27 13:20:31 -07001325
1326 // We send the enter event before pushing the instrumentation frame to make cleanup easier. If the
1327 // event causes an exception we can simply send the unwind event and return.
1328 StackHandleScope<1> hs(self);
1329 Handle<mirror::Object> h_this(hs.NewHandle(this_object));
1330 if (!interpreter_entry) {
1331 MethodEnterEvent(self, h_this.Get(), method, 0);
1332 if (self->IsExceptionPending()) {
1333 MethodUnwindEvent(self, h_this.Get(), method, 0);
1334 return;
1335 }
1336 }
1337
1338 // We have a callee-save frame meaning this value is guaranteed to never be 0.
1339 DCHECK(!self->IsExceptionPending());
1340 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk);
1341
1342 instrumentation::InstrumentationStackFrame instrumentation_frame(h_this.Get(), method, lr,
Jeff Hao9a916d32013-06-27 18:45:37 -07001343 frame_id, interpreter_entry);
Ian Rogers62d6c772013-02-27 08:32:07 -08001344 stack->push_front(instrumentation_frame);
Ian Rogers62d6c772013-02-27 08:32:07 -08001345}
1346
Mingyao Yang2ee17902017-08-30 11:37:08 -07001347DeoptimizationMethodType Instrumentation::GetDeoptimizationMethodType(ArtMethod* method) {
1348 if (method->IsRuntimeMethod()) {
1349 // Certain methods have strict requirement on whether the dex instruction
1350 // should be re-executed upon deoptimization.
1351 if (method == Runtime::Current()->GetCalleeSaveMethod(
1352 CalleeSaveType::kSaveEverythingForClinit)) {
1353 return DeoptimizationMethodType::kKeepDexPc;
1354 }
1355 if (method == Runtime::Current()->GetCalleeSaveMethod(
1356 CalleeSaveType::kSaveEverythingForSuspendCheck)) {
1357 return DeoptimizationMethodType::kKeepDexPc;
1358 }
1359 }
1360 return DeoptimizationMethodType::kDefault;
1361}
1362
1363// Try to get the shorty of a runtime method if it's an invocation stub.
Andreas Gampec7d878d2018-11-19 18:42:06 +00001364static char GetRuntimeMethodShorty(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
1365 char shorty = 'V';
1366 StackVisitor::WalkStack(
1367 [&shorty](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1368 ArtMethod* m = stack_visitor->GetMethod();
1369 if (m == nullptr || m->IsRuntimeMethod()) {
1370 return true;
Andreas Gampe3d477f32018-11-16 16:40:45 +00001371 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00001372 // The first Java method.
1373 if (m->IsNative()) {
1374 // Use JNI method's shorty for the jni stub.
1375 shorty = m->GetShorty()[0];
1376 } else if (m->IsProxyMethod()) {
1377 // Proxy method just invokes its proxied method via
1378 // art_quick_proxy_invoke_handler.
1379 shorty = m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty()[0];
1380 } else {
1381 const Instruction& instr = m->DexInstructions().InstructionAt(stack_visitor->GetDexPc());
1382 if (instr.IsInvoke()) {
1383 auto get_method_index_fn = [](ArtMethod* caller,
1384 const Instruction& inst,
1385 uint32_t dex_pc)
1386 REQUIRES_SHARED(Locks::mutator_lock_) {
1387 switch (inst.Opcode()) {
1388 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
1389 case Instruction::INVOKE_VIRTUAL_QUICK: {
1390 uint16_t method_idx = caller->GetIndexFromQuickening(dex_pc);
1391 CHECK_NE(method_idx, DexFile::kDexNoIndex16);
1392 return method_idx;
1393 }
1394 default: {
1395 return static_cast<uint16_t>(inst.VRegB());
1396 }
1397 }
1398 };
Nicolas Geoffrayec43a012018-11-17 13:10:40 +00001399
Andreas Gampec7d878d2018-11-19 18:42:06 +00001400 uint16_t method_index = get_method_index_fn(m, instr, stack_visitor->GetDexPc());
1401 const DexFile* dex_file = m->GetDexFile();
1402 if (interpreter::IsStringInit(dex_file, method_index)) {
1403 // Invoking string init constructor is turned into invoking
1404 // StringFactory.newStringFromChars() which returns a string.
1405 shorty = 'L';
1406 } else {
1407 shorty = dex_file->GetMethodShorty(method_index)[0];
1408 }
1409
1410 } else {
1411 // It could be that a non-invoke opcode invokes a stub, which in turn
1412 // invokes Java code. In such cases, we should never expect a return
1413 // value from the stub.
1414 }
1415 }
1416 // Stop stack walking since we've seen a Java frame.
1417 return false;
1418 },
1419 thread,
1420 /* context= */ nullptr,
1421 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
1422 return shorty;
1423}
Mingyao Yang2ee17902017-08-30 11:37:08 -07001424
Alex Lightb7edcda2017-04-27 13:20:31 -07001425TwoWordReturn Instrumentation::PopInstrumentationStackFrame(Thread* self,
1426 uintptr_t* return_pc,
1427 uint64_t* gpr_result,
1428 uint64_t* fpr_result) {
1429 DCHECK(gpr_result != nullptr);
1430 DCHECK(fpr_result != nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001431 // Do the pop.
1432 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1433 CHECK_GT(stack->size(), 0U);
1434 InstrumentationStackFrame instrumentation_frame = stack->front();
1435 stack->pop_front();
1436
1437 // Set return PC and check the sanity of the stack.
1438 *return_pc = instrumentation_frame.return_pc_;
1439 CheckStackDepth(self, instrumentation_frame, 0);
Ian Rogers1d8cdbc2014-09-22 22:51:09 -07001440 self->VerifyStack();
Ian Rogers62d6c772013-02-27 08:32:07 -08001441
Mathieu Chartiere401d142015-04-22 13:56:20 -07001442 ArtMethod* method = instrumentation_frame.method_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001443 uint32_t length;
Andreas Gampe542451c2016-07-26 09:02:02 -07001444 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001445 char return_shorty;
1446
1447 // Runtime method does not call into MethodExitEvent() so there should not be
1448 // suspension point below.
1449 ScopedAssertNoThreadSuspension ants(__FUNCTION__, method->IsRuntimeMethod());
1450 if (method->IsRuntimeMethod()) {
1451 if (method != Runtime::Current()->GetCalleeSaveMethod(
1452 CalleeSaveType::kSaveEverythingForClinit)) {
1453 // If the caller is at an invocation point and the runtime method is not
1454 // for clinit, we need to pass return results to the caller.
1455 // We need the correct shorty to decide whether we need to pass the return
1456 // result for deoptimization below.
Andreas Gampec7d878d2018-11-19 18:42:06 +00001457 return_shorty = GetRuntimeMethodShorty(self);
Mingyao Yang2ee17902017-08-30 11:37:08 -07001458 } else {
1459 // Some runtime methods such as allocations, unresolved field getters, etc.
1460 // have return value. We don't need to set return_value since MethodExitEvent()
1461 // below isn't called for runtime methods. Deoptimization doesn't need the
1462 // value either since the dex instruction will be re-executed by the
1463 // interpreter, except these two cases:
1464 // (1) For an invoke, which is handled above to get the correct shorty.
1465 // (2) For MONITOR_ENTER/EXIT, which cannot be re-executed since it's not
1466 // idempotent. However there is no return value for it anyway.
1467 return_shorty = 'V';
1468 }
1469 } else {
1470 return_shorty = method->GetInterfaceMethodIfProxy(pointer_size)->GetShorty(&length)[0];
1471 }
1472
Alex Lightb7edcda2017-04-27 13:20:31 -07001473 bool is_ref = return_shorty == '[' || return_shorty == 'L';
1474 StackHandleScope<1> hs(self);
1475 MutableHandle<mirror::Object> res(hs.NewHandle<mirror::Object>(nullptr));
Ian Rogers62d6c772013-02-27 08:32:07 -08001476 JValue return_value;
1477 if (return_shorty == 'V') {
1478 return_value.SetJ(0);
1479 } else if (return_shorty == 'F' || return_shorty == 'D') {
Alex Lightb7edcda2017-04-27 13:20:31 -07001480 return_value.SetJ(*fpr_result);
Ian Rogers62d6c772013-02-27 08:32:07 -08001481 } else {
Alex Lightb7edcda2017-04-27 13:20:31 -07001482 return_value.SetJ(*gpr_result);
1483 }
1484 if (is_ref) {
1485 // Take a handle to the return value so we won't lose it if we suspend.
1486 res.Assign(return_value.GetL());
Ian Rogers62d6c772013-02-27 08:32:07 -08001487 }
1488 // TODO: improve the dex pc information here, requires knowledge of current PC as opposed to
1489 // return_pc.
Andreas Gampee2abbc62017-09-15 11:59:26 -07001490 uint32_t dex_pc = dex::kDexNoIndex;
Ian Rogers62d6c772013-02-27 08:32:07 -08001491 mirror::Object* this_object = instrumentation_frame.this_object_;
Mingyao Yang2ee17902017-08-30 11:37:08 -07001492 if (!method->IsRuntimeMethod() && !instrumentation_frame.interpreter_entry_) {
Sebastien Hertz320deb22014-06-11 19:45:05 +02001493 MethodExitEvent(self, this_object, instrumentation_frame.method_, dex_pc, return_value);
1494 }
jeffhao725a9572012-11-13 18:20:12 -08001495
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001496 // Deoptimize if the caller needs to continue execution in the interpreter. Do nothing if we get
1497 // back to an upcall.
1498 NthCallerVisitor visitor(self, 1, true);
1499 visitor.WalkStack(true);
Sebastien Hertz270a0e12015-01-16 19:49:09 +01001500 bool deoptimize = (visitor.caller != nullptr) &&
Daniel Mihalyieb076692014-08-22 17:33:31 +02001501 (interpreter_stubs_installed_ || IsDeoptimized(visitor.caller) ||
1502 Dbg::IsForcedInterpreterNeededForUpcall(self, visitor.caller));
Alex Lightb7edcda2017-04-27 13:20:31 -07001503 if (is_ref) {
1504 // Restore the return value if it's a reference since it might have moved.
1505 *reinterpret_cast<mirror::Object**>(gpr_result) = res.Get();
1506 }
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001507 if (deoptimize && Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001508 if (kVerboseInstrumentation) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -08001509 LOG(INFO) << "Deoptimizing "
1510 << visitor.caller->PrettyMethod()
1511 << " by returning from "
1512 << method->PrettyMethod()
1513 << " with result "
1514 << std::hex << return_value.GetJ() << std::dec
1515 << " in "
1516 << *self;
Ian Rogers62d6c772013-02-27 08:32:07 -08001517 }
Mingyao Yang2ee17902017-08-30 11:37:08 -07001518 DeoptimizationMethodType deopt_method_type = GetDeoptimizationMethodType(method);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001519 self->PushDeoptimizationContext(return_value,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001520 return_shorty == 'L' || return_shorty == '[',
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001521 /* exception= */ nullptr ,
1522 /* from_code= */ false,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001523 deopt_method_type);
Andreas Gamped58342c2014-06-05 14:18:08 -07001524 return GetTwoWordSuccessValue(*return_pc,
1525 reinterpret_cast<uintptr_t>(GetQuickDeoptimizationEntryPoint()));
Ian Rogers62d6c772013-02-27 08:32:07 -08001526 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001527 if (deoptimize && !Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Alex Lightd8eb6732018-01-29 15:16:02 -08001528 VLOG(deopt) << "Got a deoptimization request on un-deoptimizable " << method->PrettyMethod()
1529 << " at PC " << reinterpret_cast<void*>(*return_pc);
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001530 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001531 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001532 LOG(INFO) << "Returning from " << method->PrettyMethod()
Brian Carlstrom2d888622013-07-18 17:02:00 -07001533 << " to PC " << reinterpret_cast<void*>(*return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001534 }
Andreas Gamped58342c2014-06-05 14:18:08 -07001535 return GetTwoWordSuccessValue(0, *return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001536 }
jeffhao725a9572012-11-13 18:20:12 -08001537}
1538
Alex Light2c8206f2018-06-08 14:51:09 -07001539uintptr_t Instrumentation::PopFramesForDeoptimization(Thread* self, size_t nframes) const {
Ian Rogers62d6c772013-02-27 08:32:07 -08001540 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
Alex Light2c8206f2018-06-08 14:51:09 -07001541 CHECK_GE(stack->size(), nframes);
1542 if (nframes == 0) {
1543 return 0u;
1544 }
1545 // Only need to send instrumentation events if it's not for deopt (do give the log messages if we
1546 // have verbose-instrumentation anyway though).
1547 if (kVerboseInstrumentation) {
1548 for (size_t i = 0; i < nframes; i++) {
1549 LOG(INFO) << "Popping for deoptimization " << stack->at(i).method_->PrettyMethod();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001550 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001551 }
Alex Light2c8206f2018-06-08 14:51:09 -07001552 // Now that we've sent all the instrumentation events we can actually modify the
1553 // instrumentation-stack. We cannot do this earlier since MethodUnwindEvent can re-enter java and
1554 // do other things that require the instrumentation stack to be in a consistent state with the
1555 // actual stack.
1556 for (size_t i = 0; i < nframes - 1; i++) {
1557 stack->pop_front();
1558 }
1559 uintptr_t return_pc = stack->front().return_pc_;
Alex Lightb7edcda2017-04-27 13:20:31 -07001560 stack->pop_front();
Alex Light2c8206f2018-06-08 14:51:09 -07001561 return return_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -08001562}
1563
1564std::string InstrumentationStackFrame::Dump() const {
1565 std::ostringstream os;
David Sehr709b0702016-10-13 09:12:37 -07001566 os << "Frame " << frame_id_ << " " << ArtMethod::PrettyMethod(method_) << ":"
Ian Rogers62d6c772013-02-27 08:32:07 -08001567 << reinterpret_cast<void*>(return_pc_) << " this=" << reinterpret_cast<void*>(this_object_);
1568 return os.str();
1569}
1570
1571} // namespace instrumentation
jeffhao725a9572012-11-13 18:20:12 -08001572} // namespace art