blob: 12f1522386e80755d156bb0b40d9fe82148f7d83 [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 Gampe3d477f32018-11-16 16:40:45 +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),
Alex Light3e36a9c2018-06-19 09:45:05 -0700167 deoptimized_methods_lock_("deoptimized methods lock", kGenericBottomLock),
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700168 deoptimization_enabled_(false),
169 interpreter_handler_table_(kMainHandlerTable),
Mathieu Chartier50e93312016-03-16 11:25:29 -0700170 quick_alloc_entry_points_instrumentation_counter_(0),
171 alloc_entrypoints_instrumented_(false) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700172}
173
Sebastien Hertza10aa372015-01-21 17:30:58 +0100174void Instrumentation::InstallStubsForClass(mirror::Class* klass) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000175 if (!klass->IsResolved()) {
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100176 // We need the class to be resolved to install/uninstall stubs. Otherwise its methods
177 // could not be initialized or linked with regards to class inheritance.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000178 } else if (klass->IsErroneousResolved()) {
179 // We can't execute code in a erroneous class: do nothing.
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100180 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -0700181 for (ArtMethod& method : klass->GetMethods(kRuntimePointerSize)) {
Alex Light51a64d52015-12-17 13:55:59 -0800182 InstallStubsForMethod(&method);
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100183 }
jeffhao725a9572012-11-13 18:20:12 -0800184 }
jeffhao725a9572012-11-13 18:20:12 -0800185}
186
Mathieu Chartiere401d142015-04-22 13:56:20 -0700187static void UpdateEntrypoints(ArtMethod* method, const void* quick_code)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700188 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800189 method->SetEntryPointFromQuickCompiledCode(quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100190}
191
Alex Light0fa17862017-10-24 13:43:05 -0700192bool Instrumentation::NeedDebugVersionFor(ArtMethod* method) const
193 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightf2858632018-04-02 11:28:50 -0700194 art::Runtime* runtime = Runtime::Current();
195 // If anything says we need the debug version or we are debuggable we will need the debug version
196 // of the method.
197 return (runtime->GetRuntimeCallbacks()->MethodNeedsDebugVersion(method) ||
198 runtime->IsJavaDebuggable()) &&
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800199 !method->IsNative() &&
Alex Lightf2858632018-04-02 11:28:50 -0700200 !method->IsProxyMethod();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800201}
202
Mathieu Chartiere401d142015-04-22 13:56:20 -0700203void Instrumentation::InstallStubsForMethod(ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -0700204 if (!method->IsInvokable() || method->IsProxyMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100205 // Do not change stubs for these methods.
206 return;
207 }
Jeff Hao56802772014-08-19 10:17:36 -0700208 // Don't stub Proxy.<init>. Note that the Proxy class itself is not a proxy class.
Alex Light6cae5ea2018-06-07 17:07:02 -0700209 // TODO We should remove the need for this since it means we cannot always correctly detect calls
210 // to Proxy.<init>
211 // Annoyingly this can be called before we have actually initialized WellKnownClasses so therefore
212 // we also need to check this based on the declaring-class descriptor. The check is valid because
213 // Proxy only has a single constructor.
214 ArtMethod* well_known_proxy_init = jni::DecodeArtMethod(
215 WellKnownClasses::java_lang_reflect_Proxy_init);
216 if ((LIKELY(well_known_proxy_init != nullptr) && UNLIKELY(method == well_known_proxy_init)) ||
217 UNLIKELY(method->IsConstructor() &&
218 method->GetDeclaringClass()->DescriptorEquals("Ljava/lang/reflect/Proxy;"))) {
Jeff Haodb8a6642014-08-14 17:18:52 -0700219 return;
220 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800221 const void* new_quick_code;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100222 bool uninstall = !entry_exit_stubs_installed_ && !interpreter_stubs_installed_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800223 Runtime* const runtime = Runtime::Current();
224 ClassLinker* const class_linker = runtime->GetClassLinker();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100225 bool is_class_initialized = method->GetDeclaringClass()->IsInitialized();
226 if (uninstall) {
227 if ((forced_interpret_only_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800228 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100229 } else if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700230 new_quick_code = GetCodeForInvoke(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100231 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700232 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100233 }
234 } else { // !uninstall
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100235 if ((interpreter_stubs_installed_ || forced_interpret_only_ || IsDeoptimized(method)) &&
236 !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800237 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100238 } else {
239 // Do not overwrite resolution trampoline. When the trampoline initializes the method's
240 // class, all its static methods code will be set to the instrumentation entry point.
241 // For more details, see ClassLinker::FixupStaticTrampolines.
242 if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light2d441b12018-06-08 15:33:21 -0700243 if (entry_exit_stubs_installed_) {
244 // This needs to be checked first since the instrumentation entrypoint will be able to
245 // find the actual JIT compiled code that corresponds to this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800246 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700247 } else if (NeedDebugVersionFor(method)) {
248 // It would be great to search the JIT for its implementation here but we cannot due to
249 // the locks we hold. Instead just set to the interpreter bridge and that code will search
250 // the JIT when it gets called and replace the entrypoint then.
251 new_quick_code = GetQuickToInterpreterBridge();
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000252 } else {
Alex Lightfc49fec2018-01-16 22:28:36 +0000253 new_quick_code = class_linker->GetQuickOatCodeFor(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100254 }
255 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700256 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100257 }
258 }
259 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800260 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100261}
262
Ian Rogers62d6c772013-02-27 08:32:07 -0800263// Places the instrumentation exit pc as the return PC for every quick frame. This also allows
264// deoptimization of quick frames to interpreter frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100265// Since we may already have done this previously, we need to push new instrumentation frame before
266// existing instrumentation frames.
Ian Rogers62d6c772013-02-27 08:32:07 -0800267static void InstrumentationInstallStack(Thread* thread, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700268 REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100269 struct InstallStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800270 InstallStackVisitor(Thread* thread_in, Context* context, uintptr_t instrumentation_exit_pc)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100271 : StackVisitor(thread_in, context, kInstrumentationStackWalk),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800272 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100273 instrumentation_exit_pc_(instrumentation_exit_pc),
Alex Lighte9278662018-03-08 16:55:58 -0800274 reached_existing_instrumentation_frames_(false), instrumentation_stack_depth_(0),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100275 last_return_pc_(0) {
276 }
jeffhao725a9572012-11-13 18:20:12 -0800277
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100278 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700279 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700280 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800281 if (kVerboseInstrumentation) {
282 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
283 }
284 last_return_pc_ = 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700285 return true; // Ignore upcalls.
Ian Rogers306057f2012-11-26 12:45:53 -0800286 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700287 if (GetCurrentQuickFrame() == nullptr) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800288 bool interpreter_frame = true;
Sebastien Hertz320deb22014-06-11 19:45:05 +0200289 InstrumentationStackFrame instrumentation_frame(GetThisObject(), m, 0, GetFrameId(),
290 interpreter_frame);
Jeff Haoa15a81b2014-05-27 18:25:47 -0700291 if (kVerboseInstrumentation) {
292 LOG(INFO) << "Pushing shadow frame " << instrumentation_frame.Dump();
293 }
294 shadow_stack_.push_back(instrumentation_frame);
295 return true; // Continue.
296 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800297 uintptr_t return_pc = GetReturnPc();
Sebastien Hertz320deb22014-06-11 19:45:05 +0200298 if (kVerboseInstrumentation) {
299 LOG(INFO) << " Installing exit stub in " << DescribeLocation();
300 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100301 if (return_pc == instrumentation_exit_pc_) {
Mingyao Yang2ee17902017-08-30 11:37:08 -0700302 CHECK_LT(instrumentation_stack_depth_, instrumentation_stack_->size());
303
304 if (m->IsRuntimeMethod()) {
305 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100306 (*instrumentation_stack_)[instrumentation_stack_depth_];
Mingyao Yang2ee17902017-08-30 11:37:08 -0700307 if (frame.interpreter_entry_) {
308 // This instrumentation frame is for an interpreter bridge and is
309 // pushed when executing the instrumented interpreter bridge. So method
310 // enter event must have been reported. However we need to push a DEX pc
311 // into the dex_pcs_ list to match size of instrumentation stack.
Andreas Gampee2abbc62017-09-15 11:59:26 -0700312 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700313 dex_pcs_.push_back(dex_pc);
314 last_return_pc_ = frame.return_pc_;
315 ++instrumentation_stack_depth_;
316 return true;
317 }
318 }
319
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100320 // We've reached a frame which has already been installed with instrumentation exit stub.
Alex Light74c91c92018-03-08 14:01:44 -0800321 // We should have already installed instrumentation or be interpreter on previous frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100322 reached_existing_instrumentation_frames_ = true;
323
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200324 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100325 (*instrumentation_stack_)[instrumentation_stack_depth_];
David Sehr709b0702016-10-13 09:12:37 -0700326 CHECK_EQ(m, frame.method_) << "Expected " << ArtMethod::PrettyMethod(m)
327 << ", Found " << ArtMethod::PrettyMethod(frame.method_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100328 return_pc = frame.return_pc_;
329 if (kVerboseInstrumentation) {
330 LOG(INFO) << "Ignoring already instrumented " << frame.Dump();
331 }
332 } else {
333 CHECK_NE(return_pc, 0U);
Alex Light74c91c92018-03-08 14:01:44 -0800334 if (UNLIKELY(reached_existing_instrumentation_frames_ && !m->IsRuntimeMethod())) {
335 // We already saw an existing instrumentation frame so this should be a runtime-method
336 // inserted by the interpreter or runtime.
Alex Lighte9278662018-03-08 16:55:58 -0800337 std::string thread_name;
338 GetThread()->GetThreadName(thread_name);
339 uint32_t dex_pc = dex::kDexNoIndex;
340 if (last_return_pc_ != 0 &&
341 GetCurrentOatQuickMethodHeader() != nullptr) {
342 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
343 }
Alex Light74c91c92018-03-08 14:01:44 -0800344 LOG(FATAL) << "While walking " << thread_name << " found unexpected non-runtime method"
345 << " without instrumentation exit return or interpreter frame."
Alex Lighte9278662018-03-08 16:55:58 -0800346 << " method is " << GetMethod()->PrettyMethod()
347 << " return_pc is " << std::hex << return_pc
348 << " dex pc: " << dex_pc;
349 UNREACHABLE();
350 }
Mingyao Yang2ee17902017-08-30 11:37:08 -0700351 InstrumentationStackFrame instrumentation_frame(
352 m->IsRuntimeMethod() ? nullptr : GetThisObject(),
353 m,
354 return_pc,
355 GetFrameId(), // A runtime method still gets a frame id.
356 false);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100357 if (kVerboseInstrumentation) {
358 LOG(INFO) << "Pushing frame " << instrumentation_frame.Dump();
359 }
360
Sebastien Hertz320deb22014-06-11 19:45:05 +0200361 // Insert frame at the right position so we do not corrupt the instrumentation stack.
362 // Instrumentation stack frames are in descending frame id order.
363 auto it = instrumentation_stack_->begin();
364 for (auto end = instrumentation_stack_->end(); it != end; ++it) {
365 const InstrumentationStackFrame& current = *it;
366 if (instrumentation_frame.frame_id_ >= current.frame_id_) {
367 break;
368 }
369 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100370 instrumentation_stack_->insert(it, instrumentation_frame);
371 SetReturnPc(instrumentation_exit_pc_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800372 }
Andreas Gampee2abbc62017-09-15 11:59:26 -0700373 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700374 if (last_return_pc_ != 0 &&
375 GetCurrentOatQuickMethodHeader() != nullptr) {
376 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
377 }
378 dex_pcs_.push_back(dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800379 last_return_pc_ = return_pc;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100380 ++instrumentation_stack_depth_;
Ian Rogers306057f2012-11-26 12:45:53 -0800381 return true; // Continue.
382 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800383 std::deque<InstrumentationStackFrame>* const instrumentation_stack_;
Jeff Haoa15a81b2014-05-27 18:25:47 -0700384 std::vector<InstrumentationStackFrame> shadow_stack_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800385 std::vector<uint32_t> dex_pcs_;
Ian Rogers306057f2012-11-26 12:45:53 -0800386 const uintptr_t instrumentation_exit_pc_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100387 bool reached_existing_instrumentation_frames_;
388 size_t instrumentation_stack_depth_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800389 uintptr_t last_return_pc_;
Ian Rogers306057f2012-11-26 12:45:53 -0800390 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800391 if (kVerboseInstrumentation) {
392 std::string thread_name;
393 thread->GetThreadName(thread_name);
394 LOG(INFO) << "Installing exit stubs in " << thread_name;
Ian Rogers306057f2012-11-26 12:45:53 -0800395 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100396
397 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers700a4022014-05-19 16:49:03 -0700398 std::unique_ptr<Context> context(Context::Create());
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700399 uintptr_t instrumentation_exit_pc = reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100400 InstallStackVisitor visitor(thread, context.get(), instrumentation_exit_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800401 visitor.WalkStack(true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100402 CHECK_EQ(visitor.dex_pcs_.size(), thread->GetInstrumentationStack()->size());
Ian Rogers62d6c772013-02-27 08:32:07 -0800403
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100404 if (instrumentation->ShouldNotifyMethodEnterExitEvents()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100405 // Create method enter events for all methods currently on the thread's stack. We only do this
406 // if no debugger is attached to prevent from posting events twice.
Jeff Haoa15a81b2014-05-27 18:25:47 -0700407 auto ssi = visitor.shadow_stack_.rbegin();
408 for (auto isi = thread->GetInstrumentationStack()->rbegin(),
409 end = thread->GetInstrumentationStack()->rend(); isi != end; ++isi) {
410 while (ssi != visitor.shadow_stack_.rend() && (*ssi).frame_id_ < (*isi).frame_id_) {
411 instrumentation->MethodEnterEvent(thread, (*ssi).this_object_, (*ssi).method_, 0);
412 ++ssi;
413 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100414 uint32_t dex_pc = visitor.dex_pcs_.back();
415 visitor.dex_pcs_.pop_back();
Alex Lightdc5423f2018-06-08 10:43:38 -0700416 if (!isi->interpreter_entry_ && !isi->method_->IsRuntimeMethod()) {
Sebastien Hertz320deb22014-06-11 19:45:05 +0200417 instrumentation->MethodEnterEvent(thread, (*isi).this_object_, (*isi).method_, dex_pc);
418 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100419 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800420 }
421 thread->VerifyStack();
Ian Rogers306057f2012-11-26 12:45:53 -0800422}
423
Mingyao Yang99170c62015-07-06 11:10:37 -0700424void Instrumentation::InstrumentThreadStack(Thread* thread) {
425 instrumentation_stubs_installed_ = true;
426 InstrumentationInstallStack(thread, this);
427}
428
Ian Rogers62d6c772013-02-27 08:32:07 -0800429// Removes the instrumentation exit pc as the return PC for every quick frame.
430static void InstrumentationRestoreStack(Thread* thread, void* arg)
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000431 REQUIRES(Locks::mutator_lock_) {
432 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
433
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100434 struct RestoreStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800435 RestoreStackVisitor(Thread* thread_in, uintptr_t instrumentation_exit_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800436 Instrumentation* instrumentation)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100437 : StackVisitor(thread_in, nullptr, kInstrumentationStackWalk),
438 thread_(thread_in),
Ian Rogers62d6c772013-02-27 08:32:07 -0800439 instrumentation_exit_pc_(instrumentation_exit_pc),
440 instrumentation_(instrumentation),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800441 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Ian Rogers62d6c772013-02-27 08:32:07 -0800442 frames_removed_(0) {}
Ian Rogers306057f2012-11-26 12:45:53 -0800443
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100444 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800445 if (instrumentation_stack_->size() == 0) {
jeffhao725a9572012-11-13 18:20:12 -0800446 return false; // Stop.
447 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700448 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700449 if (GetCurrentQuickFrame() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800450 if (kVerboseInstrumentation) {
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200451 LOG(INFO) << " Ignoring a shadow frame. Frame " << GetFrameId()
David Sehr709b0702016-10-13 09:12:37 -0700452 << " Method=" << ArtMethod::PrettyMethod(m);
Ian Rogers62d6c772013-02-27 08:32:07 -0800453 }
454 return true; // Ignore shadow frames.
455 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700456 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800457 if (kVerboseInstrumentation) {
458 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
459 }
Ian Rogers306057f2012-11-26 12:45:53 -0800460 return true; // Ignore upcalls.
461 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800462 bool removed_stub = false;
463 // TODO: make this search more efficient?
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100464 const size_t frameId = GetFrameId();
465 for (const InstrumentationStackFrame& instrumentation_frame : *instrumentation_stack_) {
466 if (instrumentation_frame.frame_id_ == frameId) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800467 if (kVerboseInstrumentation) {
468 LOG(INFO) << " Removing exit stub in " << DescribeLocation();
469 }
Jeff Hao9a916d32013-06-27 18:45:37 -0700470 if (instrumentation_frame.interpreter_entry_) {
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700471 CHECK(m == Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
Jeff Hao9a916d32013-06-27 18:45:37 -0700472 } else {
David Sehr709b0702016-10-13 09:12:37 -0700473 CHECK(m == instrumentation_frame.method_) << ArtMethod::PrettyMethod(m);
Jeff Hao9a916d32013-06-27 18:45:37 -0700474 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800475 SetReturnPc(instrumentation_frame.return_pc_);
Mingyao Yang2ee17902017-08-30 11:37:08 -0700476 if (instrumentation_->ShouldNotifyMethodEnterExitEvents() &&
477 !m->IsRuntimeMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100478 // Create the method exit events. As the methods didn't really exit the result is 0.
479 // We only do this if no debugger is attached to prevent from posting events twice.
480 instrumentation_->MethodExitEvent(thread_, instrumentation_frame.this_object_, m,
481 GetDexPc(), JValue());
482 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800483 frames_removed_++;
484 removed_stub = true;
485 break;
486 }
487 }
488 if (!removed_stub) {
489 if (kVerboseInstrumentation) {
490 LOG(INFO) << " No exit stub in " << DescribeLocation();
Ian Rogers306057f2012-11-26 12:45:53 -0800491 }
jeffhao725a9572012-11-13 18:20:12 -0800492 }
493 return true; // Continue.
494 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800495 Thread* const thread_;
Ian Rogers306057f2012-11-26 12:45:53 -0800496 const uintptr_t instrumentation_exit_pc_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800497 Instrumentation* const instrumentation_;
498 std::deque<instrumentation::InstrumentationStackFrame>* const instrumentation_stack_;
499 size_t frames_removed_;
jeffhao725a9572012-11-13 18:20:12 -0800500 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800501 if (kVerboseInstrumentation) {
502 std::string thread_name;
503 thread->GetThreadName(thread_name);
504 LOG(INFO) << "Removing exit stubs in " << thread_name;
505 }
506 std::deque<instrumentation::InstrumentationStackFrame>* stack = thread->GetInstrumentationStack();
507 if (stack->size() > 0) {
508 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700509 uintptr_t instrumentation_exit_pc =
510 reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Ian Rogers62d6c772013-02-27 08:32:07 -0800511 RestoreStackVisitor visitor(thread, instrumentation_exit_pc, instrumentation);
512 visitor.WalkStack(true);
513 CHECK_EQ(visitor.frames_removed_, stack->size());
514 while (stack->size() > 0) {
515 stack->pop_front();
516 }
jeffhao725a9572012-11-13 18:20:12 -0800517 }
518}
519
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200520static bool HasEvent(Instrumentation::InstrumentationEvent expected, uint32_t events) {
521 return (events & expected) != 0;
522}
523
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000524static void PotentiallyAddListenerTo(Instrumentation::InstrumentationEvent event,
525 uint32_t events,
526 std::list<InstrumentationListener*>& list,
527 InstrumentationListener* listener,
528 bool* has_listener)
529 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
530 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
531 if (!HasEvent(event, events)) {
532 return;
533 }
534 // If there is a free slot in the list, we insert the listener in that slot.
535 // Otherwise we add it to the end of the list.
536 auto it = std::find(list.begin(), list.end(), nullptr);
537 if (it != list.end()) {
538 *it = listener;
539 } else {
540 list.push_back(listener);
541 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100542 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000543}
544
Ian Rogers62d6c772013-02-27 08:32:07 -0800545void Instrumentation::AddListener(InstrumentationListener* listener, uint32_t events) {
546 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000547 PotentiallyAddListenerTo(kMethodEntered,
548 events,
549 method_entry_listeners_,
550 listener,
551 &have_method_entry_listeners_);
552 PotentiallyAddListenerTo(kMethodExited,
553 events,
554 method_exit_listeners_,
555 listener,
556 &have_method_exit_listeners_);
557 PotentiallyAddListenerTo(kMethodUnwind,
558 events,
559 method_unwind_listeners_,
560 listener,
561 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000562 PotentiallyAddListenerTo(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000563 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000564 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000565 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000566 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000567 PotentiallyAddListenerTo(kDexPcMoved,
568 events,
569 dex_pc_listeners_,
570 listener,
571 &have_dex_pc_listeners_);
572 PotentiallyAddListenerTo(kFieldRead,
573 events,
574 field_read_listeners_,
575 listener,
576 &have_field_read_listeners_);
577 PotentiallyAddListenerTo(kFieldWritten,
578 events,
579 field_write_listeners_,
580 listener,
581 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700582 PotentiallyAddListenerTo(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000583 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700584 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000585 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700586 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700587 PotentiallyAddListenerTo(kWatchedFramePop,
588 events,
589 watched_frame_pop_listeners_,
590 listener,
591 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700592 PotentiallyAddListenerTo(kExceptionHandled,
593 events,
594 exception_handled_listeners_,
595 listener,
596 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200597 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800598}
599
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000600static void PotentiallyRemoveListenerFrom(Instrumentation::InstrumentationEvent event,
601 uint32_t events,
602 std::list<InstrumentationListener*>& list,
603 InstrumentationListener* listener,
604 bool* has_listener)
605 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
606 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
607 if (!HasEvent(event, events)) {
608 return;
609 }
610 auto it = std::find(list.begin(), list.end(), listener);
611 if (it != list.end()) {
612 // Just update the entry, do not remove from the list. Removing entries in the list
613 // is unsafe when mutators are iterating over it.
614 *it = nullptr;
615 }
616
617 // Check if the list contains any non-null listener, and update 'has_listener'.
618 for (InstrumentationListener* l : list) {
619 if (l != nullptr) {
David Srbecky28f6cff2018-10-16 15:07:28 +0100620 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000621 return;
622 }
623 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100624 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = false; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000625}
626
Ian Rogers62d6c772013-02-27 08:32:07 -0800627void Instrumentation::RemoveListener(InstrumentationListener* listener, uint32_t events) {
628 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000629 PotentiallyRemoveListenerFrom(kMethodEntered,
630 events,
631 method_entry_listeners_,
632 listener,
633 &have_method_entry_listeners_);
634 PotentiallyRemoveListenerFrom(kMethodExited,
635 events,
636 method_exit_listeners_,
637 listener,
638 &have_method_exit_listeners_);
639 PotentiallyRemoveListenerFrom(kMethodUnwind,
640 events,
641 method_unwind_listeners_,
642 listener,
643 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000644 PotentiallyRemoveListenerFrom(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000645 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000646 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000647 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000648 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000649 PotentiallyRemoveListenerFrom(kDexPcMoved,
650 events,
651 dex_pc_listeners_,
652 listener,
653 &have_dex_pc_listeners_);
654 PotentiallyRemoveListenerFrom(kFieldRead,
655 events,
656 field_read_listeners_,
657 listener,
658 &have_field_read_listeners_);
659 PotentiallyRemoveListenerFrom(kFieldWritten,
660 events,
661 field_write_listeners_,
662 listener,
663 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700664 PotentiallyRemoveListenerFrom(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000665 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700666 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000667 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700668 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700669 PotentiallyRemoveListenerFrom(kWatchedFramePop,
670 events,
671 watched_frame_pop_listeners_,
672 listener,
673 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700674 PotentiallyRemoveListenerFrom(kExceptionHandled,
675 events,
676 exception_handled_listeners_,
677 listener,
678 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200679 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800680}
681
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200682Instrumentation::InstrumentationLevel Instrumentation::GetCurrentInstrumentationLevel() const {
Alex Light4ba388a2017-01-27 10:26:49 -0800683 if (interpreter_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200684 return InstrumentationLevel::kInstrumentWithInterpreter;
Ian Rogers62d6c772013-02-27 08:32:07 -0800685 } else if (entry_exit_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200686 return InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Ian Rogers62d6c772013-02-27 08:32:07 -0800687 } else {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200688 return InstrumentationLevel::kInstrumentNothing;
Ian Rogers62d6c772013-02-27 08:32:07 -0800689 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200690}
691
Alex Lightdba61482016-12-21 08:20:29 -0800692bool Instrumentation::RequiresInstrumentationInstallation(InstrumentationLevel new_level) const {
Alex Light4ba388a2017-01-27 10:26:49 -0800693 // We need to reinstall instrumentation if we go to a different level.
694 return GetCurrentInstrumentationLevel() != new_level;
Alex Lightdba61482016-12-21 08:20:29 -0800695}
696
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200697void Instrumentation::ConfigureStubs(const char* key, InstrumentationLevel desired_level) {
698 // Store the instrumentation level for this key or remove it.
699 if (desired_level == InstrumentationLevel::kInstrumentNothing) {
700 // The client no longer needs instrumentation.
701 requested_instrumentation_levels_.erase(key);
702 } else {
703 // The client needs instrumentation.
704 requested_instrumentation_levels_.Overwrite(key, desired_level);
705 }
706
707 // Look for the highest required instrumentation level.
708 InstrumentationLevel requested_level = InstrumentationLevel::kInstrumentNothing;
709 for (const auto& v : requested_instrumentation_levels_) {
710 requested_level = std::max(requested_level, v.second);
711 }
712
713 interpret_only_ = (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) ||
714 forced_interpret_only_;
715
Alex Lightdba61482016-12-21 08:20:29 -0800716 if (!RequiresInstrumentationInstallation(requested_level)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800717 // We're already set.
718 return;
719 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100720 Thread* const self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800721 Runtime* runtime = Runtime::Current();
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100722 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800723 Locks::thread_list_lock_->AssertNotHeld(self);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200724 if (requested_level > InstrumentationLevel::kInstrumentNothing) {
Alex Light4ba388a2017-01-27 10:26:49 -0800725 if (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800726 interpreter_stubs_installed_ = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800727 entry_exit_stubs_installed_ = true;
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200728 } else {
729 CHECK_EQ(requested_level, InstrumentationLevel::kInstrumentWithInstrumentationStubs);
730 entry_exit_stubs_installed_ = true;
731 interpreter_stubs_installed_ = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800732 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700733 InstallStubsClassVisitor visitor(this);
734 runtime->GetClassLinker()->VisitClasses(&visitor);
Ian Rogers62d6c772013-02-27 08:32:07 -0800735 instrumentation_stubs_installed_ = true;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100736 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800737 runtime->GetThreadList()->ForEach(InstrumentationInstallStack, this);
738 } else {
739 interpreter_stubs_installed_ = false;
740 entry_exit_stubs_installed_ = false;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700741 InstallStubsClassVisitor visitor(this);
742 runtime->GetClassLinker()->VisitClasses(&visitor);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100743 // Restore stack only if there is no method currently deoptimized.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700744 bool empty;
745 {
746 ReaderMutexLock mu(self, deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700747 empty = IsDeoptimizedMethodsEmpty(); // Avoid lock violation.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700748 }
749 if (empty) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100750 MutexLock mu(self, *Locks::thread_list_lock_);
751 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000752 // Only do this after restoring, as walking the stack when restoring will see
753 // the instrumentation exit pc.
754 instrumentation_stubs_installed_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100755 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800756 }
jeffhao725a9572012-11-13 18:20:12 -0800757}
758
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200759static void ResetQuickAllocEntryPointsForThread(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -0800760 thread->ResetQuickAllocEntryPointsForThread(kUseReadBarrier && thread->GetIsGcMarking());
Ian Rogersfa824272013-11-05 16:12:57 -0800761}
762
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700763void Instrumentation::SetEntrypointsInstrumented(bool instrumented) {
764 Thread* self = Thread::Current();
Mathieu Chartier661974a2014-01-09 11:23:53 -0800765 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700766 Locks::mutator_lock_->AssertNotHeld(self);
767 Locks::instrument_entrypoints_lock_->AssertHeld(self);
768 if (runtime->IsStarted()) {
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700769 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700770 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier661974a2014-01-09 11:23:53 -0800771 SetQuickAllocEntryPointsInstrumented(instrumented);
772 ResetQuickAllocEntryPoints();
Mathieu Chartier50e93312016-03-16 11:25:29 -0700773 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700774 } else {
775 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
776 SetQuickAllocEntryPointsInstrumented(instrumented);
Andreas Gampe157c77e2016-10-17 17:44:41 -0700777
778 // Note: ResetQuickAllocEntryPoints only works when the runtime is started. Manually run the
779 // update for just this thread.
Andreas Gampe162ae502016-10-18 10:03:42 -0700780 // Note: self may be null. One of those paths is setting instrumentation in the Heap
781 // constructor for gcstress mode.
782 if (self != nullptr) {
783 ResetQuickAllocEntryPointsForThread(self, nullptr);
784 }
Andreas Gampe157c77e2016-10-17 17:44:41 -0700785
Mathieu Chartier50e93312016-03-16 11:25:29 -0700786 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier661974a2014-01-09 11:23:53 -0800787 }
788}
789
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700790void Instrumentation::InstrumentQuickAllocEntryPoints() {
791 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
792 InstrumentQuickAllocEntryPointsLocked();
Ian Rogersfa824272013-11-05 16:12:57 -0800793}
794
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700795void Instrumentation::UninstrumentQuickAllocEntryPoints() {
796 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
797 UninstrumentQuickAllocEntryPointsLocked();
798}
799
800void Instrumentation::InstrumentQuickAllocEntryPointsLocked() {
801 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
802 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
803 SetEntrypointsInstrumented(true);
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800804 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700805 ++quick_alloc_entry_points_instrumentation_counter_;
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700806}
807
808void Instrumentation::UninstrumentQuickAllocEntryPointsLocked() {
809 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
810 CHECK_GT(quick_alloc_entry_points_instrumentation_counter_, 0U);
811 --quick_alloc_entry_points_instrumentation_counter_;
812 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
813 SetEntrypointsInstrumented(false);
814 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800815}
816
817void Instrumentation::ResetQuickAllocEntryPoints() {
818 Runtime* runtime = Runtime::Current();
819 if (runtime->IsStarted()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800820 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700821 runtime->GetThreadList()->ForEach(ResetQuickAllocEntryPointsForThread, nullptr);
Ian Rogersfa824272013-11-05 16:12:57 -0800822 }
823}
824
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700825void Instrumentation::UpdateMethodsCodeImpl(ArtMethod* method, const void* quick_code) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800826 const void* new_quick_code;
Ian Rogers62d6c772013-02-27 08:32:07 -0800827 if (LIKELY(!instrumentation_stubs_installed_)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800828 new_quick_code = quick_code;
Jeff Hao65d15d92013-07-16 16:39:33 -0700829 } else {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100830 if ((interpreter_stubs_installed_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800831 new_quick_code = GetQuickToInterpreterBridge();
Jeff Hao65d15d92013-07-16 16:39:33 -0700832 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700833 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700834 if (class_linker->IsQuickResolutionStub(quick_code) ||
835 class_linker->IsQuickToInterpreterBridge(quick_code)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700836 new_quick_code = quick_code;
Alex Light6cae5ea2018-06-07 17:07:02 -0700837 } else if (entry_exit_stubs_installed_ &&
838 // We need to make sure not to replace anything that InstallStubsForMethod
839 // wouldn't. Specifically we cannot stub out Proxy.<init> since subtypes copy the
840 // implementation directly and this will confuse the instrumentation trampolines.
841 // TODO We should remove the need for this since it makes it impossible to profile
842 // Proxy.<init> correctly in all cases.
843 method != jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700844 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700845 if (!method->IsNative() && Runtime::Current()->GetJit() != nullptr) {
846 // Native methods use trampoline entrypoints during interpreter tracing.
847 DCHECK(!Runtime::Current()->GetJit()->GetCodeCache()->GetGarbageCollectCode());
848 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
849 // Tracing will look at the saved entry point in the profiling info to know the actual
850 // entrypoint, so we store it here.
851 if (profiling_info != nullptr) {
852 profiling_info->SetSavedEntryPoint(quick_code);
853 }
854 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700855 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700856 new_quick_code = quick_code;
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700857 }
Jeff Hao65d15d92013-07-16 16:39:33 -0700858 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800859 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800860 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100861}
862
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +0000863void Instrumentation::UpdateNativeMethodsCodeToJitCode(ArtMethod* method, const void* quick_code) {
864 // We don't do any read barrier on `method`'s declaring class in this code, as the JIT might
865 // enter here on a soon-to-be deleted ArtMethod. Updating the entrypoint is OK though, as
866 // the ArtMethod is still in memory.
867 const void* new_quick_code = quick_code;
868 if (UNLIKELY(instrumentation_stubs_installed_) && entry_exit_stubs_installed_) {
869 new_quick_code = GetQuickInstrumentationEntryPoint();
870 }
871 UpdateEntrypoints(method, new_quick_code);
872}
873
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700874void Instrumentation::UpdateMethodsCode(ArtMethod* method, const void* quick_code) {
875 DCHECK(method->GetDeclaringClass()->IsResolved());
876 UpdateMethodsCodeImpl(method, quick_code);
877}
878
Alex Light0a5ec3d2017-07-25 16:50:26 -0700879void Instrumentation::UpdateMethodsCodeToInterpreterEntryPoint(ArtMethod* method) {
880 UpdateMethodsCodeImpl(method, GetQuickToInterpreterBridge());
881}
882
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000883void Instrumentation::UpdateMethodsCodeForJavaDebuggable(ArtMethod* method,
884 const void* quick_code) {
885 // When the runtime is set to Java debuggable, we may update the entry points of
886 // all methods of a class to the interpreter bridge. A method's declaring class
887 // might not be in resolved state yet in that case, so we bypass the DCHECK in
888 // UpdateMethodsCode.
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700889 UpdateMethodsCodeImpl(method, quick_code);
890}
891
Mathieu Chartiere401d142015-04-22 13:56:20 -0700892bool Instrumentation::AddDeoptimizedMethod(ArtMethod* method) {
893 if (IsDeoptimizedMethod(method)) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700894 // Already in the map. Return.
895 return false;
896 }
897 // Not found. Add it.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700898 deoptimized_methods_.insert(method);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700899 return true;
900}
901
Mathieu Chartiere401d142015-04-22 13:56:20 -0700902bool Instrumentation::IsDeoptimizedMethod(ArtMethod* method) {
903 return deoptimized_methods_.find(method) != deoptimized_methods_.end();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700904}
905
Mathieu Chartiere401d142015-04-22 13:56:20 -0700906ArtMethod* Instrumentation::BeginDeoptimizedMethod() {
907 if (deoptimized_methods_.empty()) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700908 // Empty.
909 return nullptr;
910 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700911 return *deoptimized_methods_.begin();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700912}
913
Mathieu Chartiere401d142015-04-22 13:56:20 -0700914bool Instrumentation::RemoveDeoptimizedMethod(ArtMethod* method) {
915 auto it = deoptimized_methods_.find(method);
916 if (it == deoptimized_methods_.end()) {
917 return false;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700918 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700919 deoptimized_methods_.erase(it);
920 return true;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700921}
922
923bool Instrumentation::IsDeoptimizedMethodsEmpty() const {
924 return deoptimized_methods_.empty();
925}
926
Mathieu Chartiere401d142015-04-22 13:56:20 -0700927void Instrumentation::Deoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100928 CHECK(!method->IsNative());
929 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700930 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100931
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700932 Thread* self = Thread::Current();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700933 {
934 WriterMutexLock mu(self, deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700935 bool has_not_been_deoptimized = AddDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700936 CHECK(has_not_been_deoptimized) << "Method " << ArtMethod::PrettyMethod(method)
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200937 << " is already deoptimized";
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700938 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100939 if (!interpreter_stubs_installed_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800940 UpdateEntrypoints(method, GetQuickInstrumentationEntryPoint());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100941
942 // Install instrumentation exit stub and instrumentation frames. We may already have installed
943 // these previously so it will only cover the newly created frames.
944 instrumentation_stubs_installed_ = true;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700945 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100946 Runtime::Current()->GetThreadList()->ForEach(InstrumentationInstallStack, this);
947 }
948}
949
Mathieu Chartiere401d142015-04-22 13:56:20 -0700950void Instrumentation::Undeoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100951 CHECK(!method->IsNative());
952 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700953 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100954
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700955 Thread* self = Thread::Current();
956 bool empty;
957 {
958 WriterMutexLock mu(self, deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700959 bool found_and_erased = RemoveDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700960 CHECK(found_and_erased) << "Method " << ArtMethod::PrettyMethod(method)
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700961 << " is not deoptimized";
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700962 empty = IsDeoptimizedMethodsEmpty();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700963 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100964
965 // Restore code and possibly stack only if we did not deoptimize everything.
966 if (!interpreter_stubs_installed_) {
967 // Restore its code or resolution trampoline.
968 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800969 if (method->IsStatic() && !method->IsConstructor() &&
970 !method->GetDeclaringClass()->IsInitialized()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800971 UpdateEntrypoints(method, GetQuickResolutionStub());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100972 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000973 const void* quick_code = NeedDebugVersionFor(method)
974 ? GetQuickToInterpreterBridge()
Alex Lightfc49fec2018-01-16 22:28:36 +0000975 : class_linker->GetQuickOatCodeFor(method);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800976 UpdateEntrypoints(method, quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100977 }
978
979 // If there is no deoptimized method left, we can restore the stack of each thread.
Alex Lightf244a572018-06-08 13:56:51 -0700980 if (empty && !entry_exit_stubs_installed_) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700981 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100982 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
983 instrumentation_stubs_installed_ = false;
984 }
985 }
986}
987
Mathieu Chartiere401d142015-04-22 13:56:20 -0700988bool Instrumentation::IsDeoptimized(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100989 DCHECK(method != nullptr);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700990 ReaderMutexLock mu(Thread::Current(), deoptimized_methods_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700991 return IsDeoptimizedMethod(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100992}
993
994void Instrumentation::EnableDeoptimization() {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700995 ReaderMutexLock mu(Thread::Current(), deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700996 CHECK(IsDeoptimizedMethodsEmpty());
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100997 CHECK_EQ(deoptimization_enabled_, false);
998 deoptimization_enabled_ = true;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100999}
1000
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001001void Instrumentation::DisableDeoptimization(const char* key) {
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001002 CHECK_EQ(deoptimization_enabled_, true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001003 // If we deoptimized everything, undo it.
Alex Lightdba61482016-12-21 08:20:29 -08001004 InstrumentationLevel level = GetCurrentInstrumentationLevel();
1005 if (level == InstrumentationLevel::kInstrumentWithInterpreter) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001006 UndeoptimizeEverything(key);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001007 }
1008 // Undeoptimized selected methods.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001009 while (true) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001010 ArtMethod* method;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001011 {
1012 ReaderMutexLock mu(Thread::Current(), deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001013 if (IsDeoptimizedMethodsEmpty()) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001014 break;
1015 }
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001016 method = BeginDeoptimizedMethod();
1017 CHECK(method != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001018 }
1019 Undeoptimize(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001020 }
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001021 deoptimization_enabled_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001022}
1023
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001024// Indicates if instrumentation should notify method enter/exit events to the listeners.
1025bool Instrumentation::ShouldNotifyMethodEnterExitEvents() const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001026 if (!HasMethodEntryListeners() && !HasMethodExitListeners()) {
1027 return false;
1028 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01001029 return !deoptimization_enabled_ && !interpreter_stubs_installed_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001030}
1031
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001032void Instrumentation::DeoptimizeEverything(const char* key) {
1033 CHECK(deoptimization_enabled_);
1034 ConfigureStubs(key, InstrumentationLevel::kInstrumentWithInterpreter);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001035}
1036
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001037void Instrumentation::UndeoptimizeEverything(const char* key) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001038 CHECK(interpreter_stubs_installed_);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001039 CHECK(deoptimization_enabled_);
1040 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001041}
1042
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001043void Instrumentation::EnableMethodTracing(const char* key, bool needs_interpreter) {
1044 InstrumentationLevel level;
1045 if (needs_interpreter) {
1046 level = InstrumentationLevel::kInstrumentWithInterpreter;
1047 } else {
1048 level = InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Alex Light2d441b12018-06-08 15:33:21 -07001049 if (Runtime::Current()->GetJit() != nullptr) {
1050 // TODO b/110263880 It would be better if we didn't need to do this.
1051 // Since we need to hold the method entrypoint across a suspend to ensure instrumentation
1052 // hooks are called correctly we have to disable jit-gc to ensure that the entrypoint doesn't
1053 // go away. Furthermore we need to leave this off permanently since one could get the same
1054 // effect by causing this to be toggled on and off.
1055 Runtime::Current()->GetJit()->GetCodeCache()->SetGarbageCollectCode(false);
1056 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001057 }
1058 ConfigureStubs(key, level);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001059}
1060
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001061void Instrumentation::DisableMethodTracing(const char* key) {
1062 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
jeffhao725a9572012-11-13 18:20:12 -08001063}
1064
Alex Light2d441b12018-06-08 15:33:21 -07001065const void* Instrumentation::GetCodeForInvoke(ArtMethod* method) const {
1066 // This is called by instrumentation entry only and that should never be getting proxy methods.
1067 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
1068 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1069 if (LIKELY(!instrumentation_stubs_installed_ && !interpreter_stubs_installed_)) {
1070 // In general we just return whatever the method thinks its entrypoint is here. The only
1071 // exception is if it still has the instrumentation entrypoint. That means we are racing another
1072 // thread getting rid of instrumentation which is unexpected but possible. In that case we want
1073 // to wait and try to get it from the oat file or jit.
1074 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(kRuntimePointerSize);
1075 DCHECK(code != nullptr);
1076 if (code != GetQuickInstrumentationEntryPoint()) {
1077 return code;
1078 } else if (method->IsNative()) {
1079 return class_linker->GetQuickOatCodeFor(method);
1080 }
1081 // We don't know what it is. Fallthough to try to find the code from the JIT or Oat file.
1082 } else if (method->IsNative()) {
1083 // TODO We could have JIT compiled native entrypoints. It might be worth it to find these.
1084 return class_linker->GetQuickOatCodeFor(method);
1085 } else if (UNLIKELY(interpreter_stubs_installed_)) {
1086 return GetQuickToInterpreterBridge();
1087 }
1088 // Since the method cannot be native due to ifs above we can always fall back to interpreter
1089 // bridge.
1090 const void* result = GetQuickToInterpreterBridge();
1091 if (!NeedDebugVersionFor(method)) {
1092 // If we don't need a debug version we should see what the oat file/class linker has to say.
1093 result = class_linker->GetQuickOatCodeFor(method);
1094 }
1095 // If both those fail try the jit.
1096 if (result == GetQuickToInterpreterBridge()) {
1097 jit::Jit* jit = Runtime::Current()->GetJit();
1098 if (jit != nullptr) {
1099 const void* res = jit->GetCodeCache()->FindCompiledCodeForInstrumentation(method);
1100 if (res != nullptr) {
1101 result = res;
1102 }
1103 }
1104 }
1105 return result;
1106}
1107
Andreas Gampe542451c2016-07-26 09:02:02 -07001108const void* Instrumentation::GetQuickCodeFor(ArtMethod* method, PointerSize pointer_size) const {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001109 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers62d6c772013-02-27 08:32:07 -08001110 if (LIKELY(!instrumentation_stubs_installed_)) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08001111 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size);
Vladimir Marko8a630572014-04-09 18:45:35 +01001112 DCHECK(code != nullptr);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001113 if (LIKELY(!class_linker->IsQuickResolutionStub(code) &&
1114 !class_linker->IsQuickToInterpreterBridge(code)) &&
1115 !class_linker->IsQuickResolutionStub(code) &&
1116 !class_linker->IsQuickToInterpreterBridge(code)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001117 return code;
1118 }
1119 }
Alex Lightfc49fec2018-01-16 22:28:36 +00001120 return class_linker->GetQuickOatCodeFor(method);
jeffhao725a9572012-11-13 18:20:12 -08001121}
1122
Alex Lightd7661582017-05-01 13:48:16 -07001123void Instrumentation::MethodEnterEventImpl(Thread* thread,
1124 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001125 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001126 uint32_t dex_pc) const {
Mingyao Yang2ee17902017-08-30 11:37:08 -07001127 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001128 if (HasMethodEntryListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001129 Thread* self = Thread::Current();
1130 StackHandleScope<1> hs(self);
1131 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001132 for (InstrumentationListener* listener : method_entry_listeners_) {
1133 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001134 listener->MethodEntered(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001135 }
1136 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001137 }
1138}
1139
Alex Lightd7661582017-05-01 13:48:16 -07001140void Instrumentation::MethodExitEventImpl(Thread* thread,
1141 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001142 ArtMethod* method,
Alex Lightd7661582017-05-01 13:48:16 -07001143 uint32_t dex_pc,
1144 const JValue& return_value) const {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001145 if (HasMethodExitListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001146 Thread* self = Thread::Current();
1147 StackHandleScope<2> hs(self);
1148 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1149 if (method->GetInterfaceMethodIfProxy(kRuntimePointerSize)
1150 ->GetReturnTypePrimitive() != Primitive::kPrimNot) {
1151 for (InstrumentationListener* listener : method_exit_listeners_) {
1152 if (listener != nullptr) {
1153 listener->MethodExited(thread, thiz, method, dex_pc, return_value);
1154 }
1155 }
1156 } else {
1157 Handle<mirror::Object> ret(hs.NewHandle(return_value.GetL()));
1158 for (InstrumentationListener* listener : method_exit_listeners_) {
1159 if (listener != nullptr) {
1160 listener->MethodExited(thread, thiz, method, dex_pc, ret);
1161 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001162 }
1163 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001164 }
1165}
1166
Alex Lightd7661582017-05-01 13:48:16 -07001167void Instrumentation::MethodUnwindEvent(Thread* thread,
1168 mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001169 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001170 uint32_t dex_pc) const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001171 if (HasMethodUnwindListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001172 Thread* self = Thread::Current();
1173 StackHandleScope<1> hs(self);
1174 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Mathieu Chartier02e25112013-08-14 16:14:24 -07001175 for (InstrumentationListener* listener : method_unwind_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001176 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001177 listener->MethodUnwind(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001178 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001179 }
1180 }
1181}
1182
Alex Lightd7661582017-05-01 13:48:16 -07001183void Instrumentation::DexPcMovedEventImpl(Thread* thread,
1184 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001185 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001186 uint32_t dex_pc) const {
Alex Lightd7661582017-05-01 13:48:16 -07001187 Thread* self = Thread::Current();
1188 StackHandleScope<1> hs(self);
1189 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001190 for (InstrumentationListener* listener : dex_pc_listeners_) {
1191 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001192 listener->DexPcMoved(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001193 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001194 }
1195}
1196
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001197void Instrumentation::BranchImpl(Thread* thread,
1198 ArtMethod* method,
1199 uint32_t dex_pc,
1200 int32_t offset) const {
1201 for (InstrumentationListener* listener : branch_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001202 if (listener != nullptr) {
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001203 listener->Branch(thread, method, dex_pc, offset);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001204 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001205 }
1206}
1207
Alex Lighte814f9d2017-07-31 16:14:39 -07001208void Instrumentation::WatchedFramePopImpl(Thread* thread, const ShadowFrame& frame) const {
1209 for (InstrumentationListener* listener : watched_frame_pop_listeners_) {
1210 if (listener != nullptr) {
1211 listener->WatchedFramePop(thread, frame);
1212 }
1213 }
1214}
1215
Alex Lightd7661582017-05-01 13:48:16 -07001216void Instrumentation::FieldReadEventImpl(Thread* thread,
1217 ObjPtr<mirror::Object> this_object,
1218 ArtMethod* method,
1219 uint32_t dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001220 ArtField* field) const {
Alex Lightd7661582017-05-01 13:48:16 -07001221 Thread* self = Thread::Current();
1222 StackHandleScope<1> hs(self);
1223 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001224 for (InstrumentationListener* listener : field_read_listeners_) {
1225 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001226 listener->FieldRead(thread, thiz, method, dex_pc, field);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001227 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001228 }
1229}
1230
Alex Lightd7661582017-05-01 13:48:16 -07001231void Instrumentation::FieldWriteEventImpl(Thread* thread,
1232 ObjPtr<mirror::Object> this_object,
1233 ArtMethod* method,
1234 uint32_t dex_pc,
1235 ArtField* field,
1236 const JValue& field_value) const {
1237 Thread* self = Thread::Current();
1238 StackHandleScope<2> hs(self);
1239 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1240 if (field->IsPrimitiveType()) {
1241 for (InstrumentationListener* listener : field_write_listeners_) {
1242 if (listener != nullptr) {
1243 listener->FieldWritten(thread, thiz, method, dex_pc, field, field_value);
1244 }
1245 }
1246 } else {
1247 Handle<mirror::Object> val(hs.NewHandle(field_value.GetL()));
1248 for (InstrumentationListener* listener : field_write_listeners_) {
1249 if (listener != nullptr) {
1250 listener->FieldWritten(thread, thiz, method, dex_pc, field, val);
1251 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001252 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001253 }
1254}
1255
Alex Light6e1607e2017-08-23 10:06:18 -07001256void Instrumentation::ExceptionThrownEvent(Thread* thread,
Sebastien Hertz947ff082013-09-17 14:10:13 +02001257 mirror::Throwable* exception_object) const {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001258 Thread* self = Thread::Current();
1259 StackHandleScope<1> hs(self);
1260 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
Alex Light6e1607e2017-08-23 10:06:18 -07001261 if (HasExceptionThrownListeners()) {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001262 DCHECK_EQ(thread->GetException(), h_exception.Get());
Jeff Haoc0bd4da2013-04-11 15:52:28 -07001263 thread->ClearException();
Alex Light6e1607e2017-08-23 10:06:18 -07001264 for (InstrumentationListener* listener : exception_thrown_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001265 if (listener != nullptr) {
Alex Light6e1607e2017-08-23 10:06:18 -07001266 listener->ExceptionThrown(thread, h_exception);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001267 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001268 }
Alex Light9fb1ab12017-09-05 09:32:49 -07001269 // See b/65049545 for discussion about this behavior.
1270 thread->AssertNoPendingException();
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001271 thread->SetException(h_exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08001272 }
1273}
1274
Alex Light9fb1ab12017-09-05 09:32:49 -07001275void Instrumentation::ExceptionHandledEvent(Thread* thread,
1276 mirror::Throwable* exception_object) const {
1277 Thread* self = Thread::Current();
1278 StackHandleScope<1> hs(self);
1279 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
1280 if (HasExceptionHandledListeners()) {
1281 // We should have cleared the exception so that callers can detect a new one.
1282 DCHECK(thread->GetException() == nullptr);
1283 for (InstrumentationListener* listener : exception_handled_listeners_) {
1284 if (listener != nullptr) {
1285 listener->ExceptionHandled(thread, h_exception);
1286 }
1287 }
1288 }
1289}
1290
Sebastien Hertzb2feaaf2015-10-12 13:40:10 +00001291// Computes a frame ID by ignoring inlined frames.
1292size_t Instrumentation::ComputeFrameId(Thread* self,
1293 size_t frame_depth,
1294 size_t inlined_frames_before_frame) {
1295 CHECK_GE(frame_depth, inlined_frames_before_frame);
1296 size_t no_inline_depth = frame_depth - inlined_frames_before_frame;
1297 return StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) - no_inline_depth;
1298}
1299
Ian Rogers62d6c772013-02-27 08:32:07 -08001300static void CheckStackDepth(Thread* self, const InstrumentationStackFrame& instrumentation_frame,
1301 int delta)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001302 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001303 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) + delta;
Ian Rogers62d6c772013-02-27 08:32:07 -08001304 if (frame_id != instrumentation_frame.frame_id_) {
1305 LOG(ERROR) << "Expected frame_id=" << frame_id << " but found "
1306 << instrumentation_frame.frame_id_;
1307 StackVisitor::DescribeStack(self);
1308 CHECK_EQ(frame_id, instrumentation_frame.frame_id_);
1309 }
1310}
1311
1312void Instrumentation::PushInstrumentationStackFrame(Thread* self, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001313 ArtMethod* method,
Jeff Hao9a916d32013-06-27 18:45:37 -07001314 uintptr_t lr, bool interpreter_entry) {
Alex Lightb7edcda2017-04-27 13:20:31 -07001315 DCHECK(!self->IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001316 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1317 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001318 LOG(INFO) << "Entering " << ArtMethod::PrettyMethod(method) << " from PC "
1319 << reinterpret_cast<void*>(lr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001320 }
Alex Lightb7edcda2017-04-27 13:20:31 -07001321
1322 // We send the enter event before pushing the instrumentation frame to make cleanup easier. If the
1323 // event causes an exception we can simply send the unwind event and return.
1324 StackHandleScope<1> hs(self);
1325 Handle<mirror::Object> h_this(hs.NewHandle(this_object));
1326 if (!interpreter_entry) {
1327 MethodEnterEvent(self, h_this.Get(), method, 0);
1328 if (self->IsExceptionPending()) {
1329 MethodUnwindEvent(self, h_this.Get(), method, 0);
1330 return;
1331 }
1332 }
1333
1334 // We have a callee-save frame meaning this value is guaranteed to never be 0.
1335 DCHECK(!self->IsExceptionPending());
1336 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk);
1337
1338 instrumentation::InstrumentationStackFrame instrumentation_frame(h_this.Get(), method, lr,
Jeff Hao9a916d32013-06-27 18:45:37 -07001339 frame_id, interpreter_entry);
Ian Rogers62d6c772013-02-27 08:32:07 -08001340 stack->push_front(instrumentation_frame);
Ian Rogers62d6c772013-02-27 08:32:07 -08001341}
1342
Mingyao Yang2ee17902017-08-30 11:37:08 -07001343DeoptimizationMethodType Instrumentation::GetDeoptimizationMethodType(ArtMethod* method) {
1344 if (method->IsRuntimeMethod()) {
1345 // Certain methods have strict requirement on whether the dex instruction
1346 // should be re-executed upon deoptimization.
1347 if (method == Runtime::Current()->GetCalleeSaveMethod(
1348 CalleeSaveType::kSaveEverythingForClinit)) {
1349 return DeoptimizationMethodType::kKeepDexPc;
1350 }
1351 if (method == Runtime::Current()->GetCalleeSaveMethod(
1352 CalleeSaveType::kSaveEverythingForSuspendCheck)) {
1353 return DeoptimizationMethodType::kKeepDexPc;
1354 }
1355 }
1356 return DeoptimizationMethodType::kDefault;
1357}
1358
1359// Try to get the shorty of a runtime method if it's an invocation stub.
Andreas Gampe3d477f32018-11-16 16:40:45 +00001360static char GetRuntimeMethodShorty(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
1361 char shorty = 'V';
1362 StackVisitor::WalkStack(
1363 [&shorty](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1364 ArtMethod* m = stack_visitor->GetMethod();
1365 if (m == nullptr || m->IsRuntimeMethod()) {
1366 return true;
Mingyao Yang2ee17902017-08-30 11:37:08 -07001367 }
Andreas Gampe3d477f32018-11-16 16:40:45 +00001368 // The first Java method.
1369 if (m->IsNative()) {
1370 // Use JNI method's shorty for the jni stub.
1371 shorty = m->GetShorty()[0];
1372 } else if (m->IsProxyMethod()) {
1373 // Proxy method just invokes its proxied method via
1374 // art_quick_proxy_invoke_handler.
1375 shorty = m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty()[0];
1376 } else {
1377 const Instruction& instr = m->DexInstructions().InstructionAt(stack_visitor->GetDexPc());
1378 if (instr.IsInvoke()) {
1379 auto get_method_index_fn = [](ArtMethod* caller,
1380 const Instruction& inst,
1381 uint32_t dex_pc)
1382 REQUIRES_SHARED(Locks::mutator_lock_) {
1383 switch (inst.Opcode()) {
1384 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
1385 case Instruction::INVOKE_VIRTUAL_QUICK: {
1386 uint16_t method_idx = caller->GetIndexFromQuickening(dex_pc);
1387 CHECK_NE(method_idx, DexFile::kDexNoIndex16);
1388 return method_idx;
1389 }
1390 default: {
1391 return static_cast<uint16_t>(inst.VRegB());
1392 }
1393 }
1394 };
Andreas Gampe82484902018-11-16 00:47:49 +00001395
Andreas Gampe3d477f32018-11-16 16:40:45 +00001396 uint16_t method_index = get_method_index_fn(m, instr, stack_visitor->GetDexPc());
1397 const DexFile* dex_file = m->GetDexFile();
1398 if (interpreter::IsStringInit(dex_file, method_index)) {
1399 // Invoking string init constructor is turned into invoking
1400 // StringFactory.newStringFromChars() which returns a string.
1401 shorty = 'L';
1402 } else {
1403 shorty = dex_file->GetMethodShorty(method_index)[0];
1404 }
1405
1406 } else {
1407 // It could be that a non-invoke opcode invokes a stub, which in turn
1408 // invokes Java code. In such cases, we should never expect a return
1409 // value from the stub.
1410 }
1411 }
1412 // Stop stack walking since we've seen a Java frame.
1413 return false;
1414 },
1415 thread,
1416 /* context= */ nullptr,
1417 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
1418 return shorty;
1419}
Mingyao Yang2ee17902017-08-30 11:37:08 -07001420
Alex Lightb7edcda2017-04-27 13:20:31 -07001421TwoWordReturn Instrumentation::PopInstrumentationStackFrame(Thread* self,
1422 uintptr_t* return_pc,
1423 uint64_t* gpr_result,
1424 uint64_t* fpr_result) {
1425 DCHECK(gpr_result != nullptr);
1426 DCHECK(fpr_result != nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001427 // Do the pop.
1428 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1429 CHECK_GT(stack->size(), 0U);
1430 InstrumentationStackFrame instrumentation_frame = stack->front();
1431 stack->pop_front();
1432
1433 // Set return PC and check the sanity of the stack.
1434 *return_pc = instrumentation_frame.return_pc_;
1435 CheckStackDepth(self, instrumentation_frame, 0);
Ian Rogers1d8cdbc2014-09-22 22:51:09 -07001436 self->VerifyStack();
Ian Rogers62d6c772013-02-27 08:32:07 -08001437
Mathieu Chartiere401d142015-04-22 13:56:20 -07001438 ArtMethod* method = instrumentation_frame.method_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001439 uint32_t length;
Andreas Gampe542451c2016-07-26 09:02:02 -07001440 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001441 char return_shorty;
1442
1443 // Runtime method does not call into MethodExitEvent() so there should not be
1444 // suspension point below.
1445 ScopedAssertNoThreadSuspension ants(__FUNCTION__, method->IsRuntimeMethod());
1446 if (method->IsRuntimeMethod()) {
1447 if (method != Runtime::Current()->GetCalleeSaveMethod(
1448 CalleeSaveType::kSaveEverythingForClinit)) {
1449 // If the caller is at an invocation point and the runtime method is not
1450 // for clinit, we need to pass return results to the caller.
1451 // We need the correct shorty to decide whether we need to pass the return
1452 // result for deoptimization below.
Andreas Gampe3d477f32018-11-16 16:40:45 +00001453 return_shorty = GetRuntimeMethodShorty(self);
Mingyao Yang2ee17902017-08-30 11:37:08 -07001454 } else {
1455 // Some runtime methods such as allocations, unresolved field getters, etc.
1456 // have return value. We don't need to set return_value since MethodExitEvent()
1457 // below isn't called for runtime methods. Deoptimization doesn't need the
1458 // value either since the dex instruction will be re-executed by the
1459 // interpreter, except these two cases:
1460 // (1) For an invoke, which is handled above to get the correct shorty.
1461 // (2) For MONITOR_ENTER/EXIT, which cannot be re-executed since it's not
1462 // idempotent. However there is no return value for it anyway.
1463 return_shorty = 'V';
1464 }
1465 } else {
1466 return_shorty = method->GetInterfaceMethodIfProxy(pointer_size)->GetShorty(&length)[0];
1467 }
1468
Alex Lightb7edcda2017-04-27 13:20:31 -07001469 bool is_ref = return_shorty == '[' || return_shorty == 'L';
1470 StackHandleScope<1> hs(self);
1471 MutableHandle<mirror::Object> res(hs.NewHandle<mirror::Object>(nullptr));
Ian Rogers62d6c772013-02-27 08:32:07 -08001472 JValue return_value;
1473 if (return_shorty == 'V') {
1474 return_value.SetJ(0);
1475 } else if (return_shorty == 'F' || return_shorty == 'D') {
Alex Lightb7edcda2017-04-27 13:20:31 -07001476 return_value.SetJ(*fpr_result);
Ian Rogers62d6c772013-02-27 08:32:07 -08001477 } else {
Alex Lightb7edcda2017-04-27 13:20:31 -07001478 return_value.SetJ(*gpr_result);
1479 }
1480 if (is_ref) {
1481 // Take a handle to the return value so we won't lose it if we suspend.
1482 res.Assign(return_value.GetL());
Ian Rogers62d6c772013-02-27 08:32:07 -08001483 }
1484 // TODO: improve the dex pc information here, requires knowledge of current PC as opposed to
1485 // return_pc.
Andreas Gampee2abbc62017-09-15 11:59:26 -07001486 uint32_t dex_pc = dex::kDexNoIndex;
Ian Rogers62d6c772013-02-27 08:32:07 -08001487 mirror::Object* this_object = instrumentation_frame.this_object_;
Mingyao Yang2ee17902017-08-30 11:37:08 -07001488 if (!method->IsRuntimeMethod() && !instrumentation_frame.interpreter_entry_) {
Sebastien Hertz320deb22014-06-11 19:45:05 +02001489 MethodExitEvent(self, this_object, instrumentation_frame.method_, dex_pc, return_value);
1490 }
jeffhao725a9572012-11-13 18:20:12 -08001491
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001492 // Deoptimize if the caller needs to continue execution in the interpreter. Do nothing if we get
1493 // back to an upcall.
1494 NthCallerVisitor visitor(self, 1, true);
1495 visitor.WalkStack(true);
Sebastien Hertz270a0e12015-01-16 19:49:09 +01001496 bool deoptimize = (visitor.caller != nullptr) &&
Daniel Mihalyieb076692014-08-22 17:33:31 +02001497 (interpreter_stubs_installed_ || IsDeoptimized(visitor.caller) ||
1498 Dbg::IsForcedInterpreterNeededForUpcall(self, visitor.caller));
Alex Lightb7edcda2017-04-27 13:20:31 -07001499 if (is_ref) {
1500 // Restore the return value if it's a reference since it might have moved.
1501 *reinterpret_cast<mirror::Object**>(gpr_result) = res.Get();
1502 }
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001503 if (deoptimize && Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001504 if (kVerboseInstrumentation) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -08001505 LOG(INFO) << "Deoptimizing "
1506 << visitor.caller->PrettyMethod()
1507 << " by returning from "
1508 << method->PrettyMethod()
1509 << " with result "
1510 << std::hex << return_value.GetJ() << std::dec
1511 << " in "
1512 << *self;
Ian Rogers62d6c772013-02-27 08:32:07 -08001513 }
Mingyao Yang2ee17902017-08-30 11:37:08 -07001514 DeoptimizationMethodType deopt_method_type = GetDeoptimizationMethodType(method);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001515 self->PushDeoptimizationContext(return_value,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001516 return_shorty == 'L' || return_shorty == '[',
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001517 /* exception= */ nullptr ,
1518 /* from_code= */ false,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001519 deopt_method_type);
Andreas Gamped58342c2014-06-05 14:18:08 -07001520 return GetTwoWordSuccessValue(*return_pc,
1521 reinterpret_cast<uintptr_t>(GetQuickDeoptimizationEntryPoint()));
Ian Rogers62d6c772013-02-27 08:32:07 -08001522 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001523 if (deoptimize && !Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Alex Lightd8eb6732018-01-29 15:16:02 -08001524 VLOG(deopt) << "Got a deoptimization request on un-deoptimizable " << method->PrettyMethod()
1525 << " at PC " << reinterpret_cast<void*>(*return_pc);
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001526 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001527 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001528 LOG(INFO) << "Returning from " << method->PrettyMethod()
Brian Carlstrom2d888622013-07-18 17:02:00 -07001529 << " to PC " << reinterpret_cast<void*>(*return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001530 }
Andreas Gamped58342c2014-06-05 14:18:08 -07001531 return GetTwoWordSuccessValue(0, *return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001532 }
jeffhao725a9572012-11-13 18:20:12 -08001533}
1534
Alex Light2c8206f2018-06-08 14:51:09 -07001535uintptr_t Instrumentation::PopFramesForDeoptimization(Thread* self, size_t nframes) const {
Ian Rogers62d6c772013-02-27 08:32:07 -08001536 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
Alex Light2c8206f2018-06-08 14:51:09 -07001537 CHECK_GE(stack->size(), nframes);
1538 if (nframes == 0) {
1539 return 0u;
1540 }
1541 // Only need to send instrumentation events if it's not for deopt (do give the log messages if we
1542 // have verbose-instrumentation anyway though).
1543 if (kVerboseInstrumentation) {
1544 for (size_t i = 0; i < nframes; i++) {
1545 LOG(INFO) << "Popping for deoptimization " << stack->at(i).method_->PrettyMethod();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001546 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001547 }
Alex Light2c8206f2018-06-08 14:51:09 -07001548 // Now that we've sent all the instrumentation events we can actually modify the
1549 // instrumentation-stack. We cannot do this earlier since MethodUnwindEvent can re-enter java and
1550 // do other things that require the instrumentation stack to be in a consistent state with the
1551 // actual stack.
1552 for (size_t i = 0; i < nframes - 1; i++) {
1553 stack->pop_front();
1554 }
1555 uintptr_t return_pc = stack->front().return_pc_;
Alex Lightb7edcda2017-04-27 13:20:31 -07001556 stack->pop_front();
Alex Light2c8206f2018-06-08 14:51:09 -07001557 return return_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -08001558}
1559
1560std::string InstrumentationStackFrame::Dump() const {
1561 std::ostringstream os;
David Sehr709b0702016-10-13 09:12:37 -07001562 os << "Frame " << frame_id_ << " " << ArtMethod::PrettyMethod(method_) << ":"
Ian Rogers62d6c772013-02-27 08:32:07 -08001563 << reinterpret_cast<void*>(return_pc_) << " this=" << reinterpret_cast<void*>(this_object_);
1564 return os.str();
1565}
1566
1567} // namespace instrumentation
jeffhao725a9572012-11-13 18:20:12 -08001568} // namespace art