blob: 21c4272934f0d601b30723697d65f6a7e5986a14 [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),
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_];
Alex Lightfc81d802018-12-07 13:39:05 -0800326 CHECK_EQ(m->GetNonObsoleteMethod(), frame.method_->GetNonObsoleteMethod())
327 << "Expected " << ArtMethod::PrettyMethod(m)
328 << ", Found " << ArtMethod::PrettyMethod(frame.method_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100329 return_pc = frame.return_pc_;
330 if (kVerboseInstrumentation) {
331 LOG(INFO) << "Ignoring already instrumented " << frame.Dump();
332 }
333 } else {
334 CHECK_NE(return_pc, 0U);
Alex Light74c91c92018-03-08 14:01:44 -0800335 if (UNLIKELY(reached_existing_instrumentation_frames_ && !m->IsRuntimeMethod())) {
336 // We already saw an existing instrumentation frame so this should be a runtime-method
337 // inserted by the interpreter or runtime.
Alex Lighte9278662018-03-08 16:55:58 -0800338 std::string thread_name;
339 GetThread()->GetThreadName(thread_name);
340 uint32_t dex_pc = dex::kDexNoIndex;
341 if (last_return_pc_ != 0 &&
342 GetCurrentOatQuickMethodHeader() != nullptr) {
343 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
344 }
Alex Light74c91c92018-03-08 14:01:44 -0800345 LOG(FATAL) << "While walking " << thread_name << " found unexpected non-runtime method"
346 << " without instrumentation exit return or interpreter frame."
Alex Lighte9278662018-03-08 16:55:58 -0800347 << " method is " << GetMethod()->PrettyMethod()
348 << " return_pc is " << std::hex << return_pc
349 << " dex pc: " << dex_pc;
350 UNREACHABLE();
351 }
Mingyao Yang2ee17902017-08-30 11:37:08 -0700352 InstrumentationStackFrame instrumentation_frame(
353 m->IsRuntimeMethod() ? nullptr : GetThisObject(),
354 m,
355 return_pc,
356 GetFrameId(), // A runtime method still gets a frame id.
357 false);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100358 if (kVerboseInstrumentation) {
359 LOG(INFO) << "Pushing frame " << instrumentation_frame.Dump();
360 }
361
Sebastien Hertz320deb22014-06-11 19:45:05 +0200362 // Insert frame at the right position so we do not corrupt the instrumentation stack.
363 // Instrumentation stack frames are in descending frame id order.
364 auto it = instrumentation_stack_->begin();
365 for (auto end = instrumentation_stack_->end(); it != end; ++it) {
366 const InstrumentationStackFrame& current = *it;
367 if (instrumentation_frame.frame_id_ >= current.frame_id_) {
368 break;
369 }
370 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100371 instrumentation_stack_->insert(it, instrumentation_frame);
372 SetReturnPc(instrumentation_exit_pc_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800373 }
Andreas Gampee2abbc62017-09-15 11:59:26 -0700374 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700375 if (last_return_pc_ != 0 &&
376 GetCurrentOatQuickMethodHeader() != nullptr) {
377 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
378 }
379 dex_pcs_.push_back(dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800380 last_return_pc_ = return_pc;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100381 ++instrumentation_stack_depth_;
Ian Rogers306057f2012-11-26 12:45:53 -0800382 return true; // Continue.
383 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800384 std::deque<InstrumentationStackFrame>* const instrumentation_stack_;
Jeff Haoa15a81b2014-05-27 18:25:47 -0700385 std::vector<InstrumentationStackFrame> shadow_stack_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800386 std::vector<uint32_t> dex_pcs_;
Ian Rogers306057f2012-11-26 12:45:53 -0800387 const uintptr_t instrumentation_exit_pc_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100388 bool reached_existing_instrumentation_frames_;
389 size_t instrumentation_stack_depth_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800390 uintptr_t last_return_pc_;
Ian Rogers306057f2012-11-26 12:45:53 -0800391 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800392 if (kVerboseInstrumentation) {
393 std::string thread_name;
394 thread->GetThreadName(thread_name);
395 LOG(INFO) << "Installing exit stubs in " << thread_name;
Ian Rogers306057f2012-11-26 12:45:53 -0800396 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100397
398 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers700a4022014-05-19 16:49:03 -0700399 std::unique_ptr<Context> context(Context::Create());
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700400 uintptr_t instrumentation_exit_pc = reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100401 InstallStackVisitor visitor(thread, context.get(), instrumentation_exit_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800402 visitor.WalkStack(true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100403 CHECK_EQ(visitor.dex_pcs_.size(), thread->GetInstrumentationStack()->size());
Ian Rogers62d6c772013-02-27 08:32:07 -0800404
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100405 if (instrumentation->ShouldNotifyMethodEnterExitEvents()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100406 // Create method enter events for all methods currently on the thread's stack. We only do this
407 // if no debugger is attached to prevent from posting events twice.
Jeff Haoa15a81b2014-05-27 18:25:47 -0700408 auto ssi = visitor.shadow_stack_.rbegin();
409 for (auto isi = thread->GetInstrumentationStack()->rbegin(),
410 end = thread->GetInstrumentationStack()->rend(); isi != end; ++isi) {
411 while (ssi != visitor.shadow_stack_.rend() && (*ssi).frame_id_ < (*isi).frame_id_) {
412 instrumentation->MethodEnterEvent(thread, (*ssi).this_object_, (*ssi).method_, 0);
413 ++ssi;
414 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100415 uint32_t dex_pc = visitor.dex_pcs_.back();
416 visitor.dex_pcs_.pop_back();
Alex Lightdc5423f2018-06-08 10:43:38 -0700417 if (!isi->interpreter_entry_ && !isi->method_->IsRuntimeMethod()) {
Sebastien Hertz320deb22014-06-11 19:45:05 +0200418 instrumentation->MethodEnterEvent(thread, (*isi).this_object_, (*isi).method_, dex_pc);
419 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100420 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800421 }
422 thread->VerifyStack();
Ian Rogers306057f2012-11-26 12:45:53 -0800423}
424
Mingyao Yang99170c62015-07-06 11:10:37 -0700425void Instrumentation::InstrumentThreadStack(Thread* thread) {
426 instrumentation_stubs_installed_ = true;
427 InstrumentationInstallStack(thread, this);
428}
429
Ian Rogers62d6c772013-02-27 08:32:07 -0800430// Removes the instrumentation exit pc as the return PC for every quick frame.
431static void InstrumentationRestoreStack(Thread* thread, void* arg)
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000432 REQUIRES(Locks::mutator_lock_) {
433 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
434
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100435 struct RestoreStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800436 RestoreStackVisitor(Thread* thread_in, uintptr_t instrumentation_exit_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800437 Instrumentation* instrumentation)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100438 : StackVisitor(thread_in, nullptr, kInstrumentationStackWalk),
439 thread_(thread_in),
Ian Rogers62d6c772013-02-27 08:32:07 -0800440 instrumentation_exit_pc_(instrumentation_exit_pc),
441 instrumentation_(instrumentation),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800442 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Ian Rogers62d6c772013-02-27 08:32:07 -0800443 frames_removed_(0) {}
Ian Rogers306057f2012-11-26 12:45:53 -0800444
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100445 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800446 if (instrumentation_stack_->size() == 0) {
jeffhao725a9572012-11-13 18:20:12 -0800447 return false; // Stop.
448 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700449 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700450 if (GetCurrentQuickFrame() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800451 if (kVerboseInstrumentation) {
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200452 LOG(INFO) << " Ignoring a shadow frame. Frame " << GetFrameId()
David Sehr709b0702016-10-13 09:12:37 -0700453 << " Method=" << ArtMethod::PrettyMethod(m);
Ian Rogers62d6c772013-02-27 08:32:07 -0800454 }
455 return true; // Ignore shadow frames.
456 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700457 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800458 if (kVerboseInstrumentation) {
459 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
460 }
Ian Rogers306057f2012-11-26 12:45:53 -0800461 return true; // Ignore upcalls.
462 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800463 bool removed_stub = false;
464 // TODO: make this search more efficient?
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100465 const size_t frameId = GetFrameId();
466 for (const InstrumentationStackFrame& instrumentation_frame : *instrumentation_stack_) {
467 if (instrumentation_frame.frame_id_ == frameId) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800468 if (kVerboseInstrumentation) {
469 LOG(INFO) << " Removing exit stub in " << DescribeLocation();
470 }
Jeff Hao9a916d32013-06-27 18:45:37 -0700471 if (instrumentation_frame.interpreter_entry_) {
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700472 CHECK(m == Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
Jeff Hao9a916d32013-06-27 18:45:37 -0700473 } else {
Alex Lightfc81d802018-12-07 13:39:05 -0800474 CHECK_EQ(m->GetNonObsoleteMethod(),
475 instrumentation_frame.method_->GetNonObsoleteMethod())
476 << ArtMethod::PrettyMethod(m);
Jeff Hao9a916d32013-06-27 18:45:37 -0700477 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800478 SetReturnPc(instrumentation_frame.return_pc_);
Mingyao Yang2ee17902017-08-30 11:37:08 -0700479 if (instrumentation_->ShouldNotifyMethodEnterExitEvents() &&
480 !m->IsRuntimeMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100481 // Create the method exit events. As the methods didn't really exit the result is 0.
482 // We only do this if no debugger is attached to prevent from posting events twice.
483 instrumentation_->MethodExitEvent(thread_, instrumentation_frame.this_object_, m,
484 GetDexPc(), JValue());
485 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800486 frames_removed_++;
487 removed_stub = true;
488 break;
489 }
490 }
491 if (!removed_stub) {
492 if (kVerboseInstrumentation) {
493 LOG(INFO) << " No exit stub in " << DescribeLocation();
Ian Rogers306057f2012-11-26 12:45:53 -0800494 }
jeffhao725a9572012-11-13 18:20:12 -0800495 }
496 return true; // Continue.
497 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800498 Thread* const thread_;
Ian Rogers306057f2012-11-26 12:45:53 -0800499 const uintptr_t instrumentation_exit_pc_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800500 Instrumentation* const instrumentation_;
501 std::deque<instrumentation::InstrumentationStackFrame>* const instrumentation_stack_;
502 size_t frames_removed_;
jeffhao725a9572012-11-13 18:20:12 -0800503 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800504 if (kVerboseInstrumentation) {
505 std::string thread_name;
506 thread->GetThreadName(thread_name);
507 LOG(INFO) << "Removing exit stubs in " << thread_name;
508 }
509 std::deque<instrumentation::InstrumentationStackFrame>* stack = thread->GetInstrumentationStack();
510 if (stack->size() > 0) {
511 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700512 uintptr_t instrumentation_exit_pc =
513 reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Ian Rogers62d6c772013-02-27 08:32:07 -0800514 RestoreStackVisitor visitor(thread, instrumentation_exit_pc, instrumentation);
515 visitor.WalkStack(true);
516 CHECK_EQ(visitor.frames_removed_, stack->size());
517 while (stack->size() > 0) {
518 stack->pop_front();
519 }
jeffhao725a9572012-11-13 18:20:12 -0800520 }
521}
522
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200523static bool HasEvent(Instrumentation::InstrumentationEvent expected, uint32_t events) {
524 return (events & expected) != 0;
525}
526
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000527static void PotentiallyAddListenerTo(Instrumentation::InstrumentationEvent event,
528 uint32_t events,
529 std::list<InstrumentationListener*>& list,
530 InstrumentationListener* listener,
531 bool* has_listener)
532 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
533 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
534 if (!HasEvent(event, events)) {
535 return;
536 }
537 // If there is a free slot in the list, we insert the listener in that slot.
538 // Otherwise we add it to the end of the list.
539 auto it = std::find(list.begin(), list.end(), nullptr);
540 if (it != list.end()) {
541 *it = listener;
542 } else {
543 list.push_back(listener);
544 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100545 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000546}
547
Ian Rogers62d6c772013-02-27 08:32:07 -0800548void Instrumentation::AddListener(InstrumentationListener* listener, uint32_t events) {
549 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000550 PotentiallyAddListenerTo(kMethodEntered,
551 events,
552 method_entry_listeners_,
553 listener,
554 &have_method_entry_listeners_);
555 PotentiallyAddListenerTo(kMethodExited,
556 events,
557 method_exit_listeners_,
558 listener,
559 &have_method_exit_listeners_);
560 PotentiallyAddListenerTo(kMethodUnwind,
561 events,
562 method_unwind_listeners_,
563 listener,
564 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000565 PotentiallyAddListenerTo(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000566 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000567 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000568 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000569 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000570 PotentiallyAddListenerTo(kDexPcMoved,
571 events,
572 dex_pc_listeners_,
573 listener,
574 &have_dex_pc_listeners_);
575 PotentiallyAddListenerTo(kFieldRead,
576 events,
577 field_read_listeners_,
578 listener,
579 &have_field_read_listeners_);
580 PotentiallyAddListenerTo(kFieldWritten,
581 events,
582 field_write_listeners_,
583 listener,
584 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700585 PotentiallyAddListenerTo(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000586 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700587 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000588 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700589 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700590 PotentiallyAddListenerTo(kWatchedFramePop,
591 events,
592 watched_frame_pop_listeners_,
593 listener,
594 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700595 PotentiallyAddListenerTo(kExceptionHandled,
596 events,
597 exception_handled_listeners_,
598 listener,
599 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200600 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800601}
602
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000603static void PotentiallyRemoveListenerFrom(Instrumentation::InstrumentationEvent event,
604 uint32_t events,
605 std::list<InstrumentationListener*>& list,
606 InstrumentationListener* listener,
607 bool* has_listener)
608 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
609 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
610 if (!HasEvent(event, events)) {
611 return;
612 }
613 auto it = std::find(list.begin(), list.end(), listener);
614 if (it != list.end()) {
615 // Just update the entry, do not remove from the list. Removing entries in the list
616 // is unsafe when mutators are iterating over it.
617 *it = nullptr;
618 }
619
620 // Check if the list contains any non-null listener, and update 'has_listener'.
621 for (InstrumentationListener* l : list) {
622 if (l != nullptr) {
David Srbecky28f6cff2018-10-16 15:07:28 +0100623 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000624 return;
625 }
626 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100627 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = false; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000628}
629
Ian Rogers62d6c772013-02-27 08:32:07 -0800630void Instrumentation::RemoveListener(InstrumentationListener* listener, uint32_t events) {
631 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000632 PotentiallyRemoveListenerFrom(kMethodEntered,
633 events,
634 method_entry_listeners_,
635 listener,
636 &have_method_entry_listeners_);
637 PotentiallyRemoveListenerFrom(kMethodExited,
638 events,
639 method_exit_listeners_,
640 listener,
641 &have_method_exit_listeners_);
642 PotentiallyRemoveListenerFrom(kMethodUnwind,
643 events,
644 method_unwind_listeners_,
645 listener,
646 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000647 PotentiallyRemoveListenerFrom(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000648 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000649 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000650 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000651 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000652 PotentiallyRemoveListenerFrom(kDexPcMoved,
653 events,
654 dex_pc_listeners_,
655 listener,
656 &have_dex_pc_listeners_);
657 PotentiallyRemoveListenerFrom(kFieldRead,
658 events,
659 field_read_listeners_,
660 listener,
661 &have_field_read_listeners_);
662 PotentiallyRemoveListenerFrom(kFieldWritten,
663 events,
664 field_write_listeners_,
665 listener,
666 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700667 PotentiallyRemoveListenerFrom(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000668 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700669 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000670 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700671 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700672 PotentiallyRemoveListenerFrom(kWatchedFramePop,
673 events,
674 watched_frame_pop_listeners_,
675 listener,
676 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700677 PotentiallyRemoveListenerFrom(kExceptionHandled,
678 events,
679 exception_handled_listeners_,
680 listener,
681 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200682 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800683}
684
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200685Instrumentation::InstrumentationLevel Instrumentation::GetCurrentInstrumentationLevel() const {
Alex Light4ba388a2017-01-27 10:26:49 -0800686 if (interpreter_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200687 return InstrumentationLevel::kInstrumentWithInterpreter;
Ian Rogers62d6c772013-02-27 08:32:07 -0800688 } else if (entry_exit_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200689 return InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Ian Rogers62d6c772013-02-27 08:32:07 -0800690 } else {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200691 return InstrumentationLevel::kInstrumentNothing;
Ian Rogers62d6c772013-02-27 08:32:07 -0800692 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200693}
694
Alex Lightdba61482016-12-21 08:20:29 -0800695bool Instrumentation::RequiresInstrumentationInstallation(InstrumentationLevel new_level) const {
Alex Light4ba388a2017-01-27 10:26:49 -0800696 // We need to reinstall instrumentation if we go to a different level.
697 return GetCurrentInstrumentationLevel() != new_level;
Alex Lightdba61482016-12-21 08:20:29 -0800698}
699
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200700void Instrumentation::ConfigureStubs(const char* key, InstrumentationLevel desired_level) {
701 // Store the instrumentation level for this key or remove it.
702 if (desired_level == InstrumentationLevel::kInstrumentNothing) {
703 // The client no longer needs instrumentation.
704 requested_instrumentation_levels_.erase(key);
705 } else {
706 // The client needs instrumentation.
707 requested_instrumentation_levels_.Overwrite(key, desired_level);
708 }
709
710 // Look for the highest required instrumentation level.
711 InstrumentationLevel requested_level = InstrumentationLevel::kInstrumentNothing;
712 for (const auto& v : requested_instrumentation_levels_) {
713 requested_level = std::max(requested_level, v.second);
714 }
715
716 interpret_only_ = (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) ||
717 forced_interpret_only_;
718
Alex Lightdba61482016-12-21 08:20:29 -0800719 if (!RequiresInstrumentationInstallation(requested_level)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800720 // We're already set.
721 return;
722 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100723 Thread* const self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800724 Runtime* runtime = Runtime::Current();
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100725 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800726 Locks::thread_list_lock_->AssertNotHeld(self);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200727 if (requested_level > InstrumentationLevel::kInstrumentNothing) {
Alex Light4ba388a2017-01-27 10:26:49 -0800728 if (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800729 interpreter_stubs_installed_ = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800730 entry_exit_stubs_installed_ = true;
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200731 } else {
732 CHECK_EQ(requested_level, InstrumentationLevel::kInstrumentWithInstrumentationStubs);
733 entry_exit_stubs_installed_ = true;
734 interpreter_stubs_installed_ = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800735 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700736 InstallStubsClassVisitor visitor(this);
737 runtime->GetClassLinker()->VisitClasses(&visitor);
Ian Rogers62d6c772013-02-27 08:32:07 -0800738 instrumentation_stubs_installed_ = true;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100739 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800740 runtime->GetThreadList()->ForEach(InstrumentationInstallStack, this);
741 } else {
742 interpreter_stubs_installed_ = false;
743 entry_exit_stubs_installed_ = false;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700744 InstallStubsClassVisitor visitor(this);
745 runtime->GetClassLinker()->VisitClasses(&visitor);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100746 // Restore stack only if there is no method currently deoptimized.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700747 bool empty;
748 {
749 ReaderMutexLock mu(self, deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700750 empty = IsDeoptimizedMethodsEmpty(); // Avoid lock violation.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700751 }
752 if (empty) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100753 MutexLock mu(self, *Locks::thread_list_lock_);
754 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000755 // Only do this after restoring, as walking the stack when restoring will see
756 // the instrumentation exit pc.
757 instrumentation_stubs_installed_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100758 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800759 }
jeffhao725a9572012-11-13 18:20:12 -0800760}
761
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200762static void ResetQuickAllocEntryPointsForThread(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -0800763 thread->ResetQuickAllocEntryPointsForThread(kUseReadBarrier && thread->GetIsGcMarking());
Ian Rogersfa824272013-11-05 16:12:57 -0800764}
765
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700766void Instrumentation::SetEntrypointsInstrumented(bool instrumented) {
767 Thread* self = Thread::Current();
Mathieu Chartier661974a2014-01-09 11:23:53 -0800768 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700769 Locks::mutator_lock_->AssertNotHeld(self);
770 Locks::instrument_entrypoints_lock_->AssertHeld(self);
771 if (runtime->IsStarted()) {
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700772 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700773 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier661974a2014-01-09 11:23:53 -0800774 SetQuickAllocEntryPointsInstrumented(instrumented);
775 ResetQuickAllocEntryPoints();
Mathieu Chartier50e93312016-03-16 11:25:29 -0700776 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700777 } else {
778 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
779 SetQuickAllocEntryPointsInstrumented(instrumented);
Andreas Gampe157c77e2016-10-17 17:44:41 -0700780
781 // Note: ResetQuickAllocEntryPoints only works when the runtime is started. Manually run the
782 // update for just this thread.
Andreas Gampe162ae502016-10-18 10:03:42 -0700783 // Note: self may be null. One of those paths is setting instrumentation in the Heap
784 // constructor for gcstress mode.
785 if (self != nullptr) {
786 ResetQuickAllocEntryPointsForThread(self, nullptr);
787 }
Andreas Gampe157c77e2016-10-17 17:44:41 -0700788
Mathieu Chartier50e93312016-03-16 11:25:29 -0700789 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier661974a2014-01-09 11:23:53 -0800790 }
791}
792
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700793void Instrumentation::InstrumentQuickAllocEntryPoints() {
794 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
795 InstrumentQuickAllocEntryPointsLocked();
Ian Rogersfa824272013-11-05 16:12:57 -0800796}
797
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700798void Instrumentation::UninstrumentQuickAllocEntryPoints() {
799 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
800 UninstrumentQuickAllocEntryPointsLocked();
801}
802
803void Instrumentation::InstrumentQuickAllocEntryPointsLocked() {
804 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
805 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
806 SetEntrypointsInstrumented(true);
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800807 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700808 ++quick_alloc_entry_points_instrumentation_counter_;
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700809}
810
811void Instrumentation::UninstrumentQuickAllocEntryPointsLocked() {
812 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
813 CHECK_GT(quick_alloc_entry_points_instrumentation_counter_, 0U);
814 --quick_alloc_entry_points_instrumentation_counter_;
815 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
816 SetEntrypointsInstrumented(false);
817 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800818}
819
820void Instrumentation::ResetQuickAllocEntryPoints() {
821 Runtime* runtime = Runtime::Current();
822 if (runtime->IsStarted()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800823 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700824 runtime->GetThreadList()->ForEach(ResetQuickAllocEntryPointsForThread, nullptr);
Ian Rogersfa824272013-11-05 16:12:57 -0800825 }
826}
827
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700828void Instrumentation::UpdateMethodsCodeImpl(ArtMethod* method, const void* quick_code) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800829 const void* new_quick_code;
Ian Rogers62d6c772013-02-27 08:32:07 -0800830 if (LIKELY(!instrumentation_stubs_installed_)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800831 new_quick_code = quick_code;
Jeff Hao65d15d92013-07-16 16:39:33 -0700832 } else {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100833 if ((interpreter_stubs_installed_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800834 new_quick_code = GetQuickToInterpreterBridge();
Jeff Hao65d15d92013-07-16 16:39:33 -0700835 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700836 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700837 if (class_linker->IsQuickResolutionStub(quick_code) ||
838 class_linker->IsQuickToInterpreterBridge(quick_code)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700839 new_quick_code = quick_code;
Alex Light6cae5ea2018-06-07 17:07:02 -0700840 } else if (entry_exit_stubs_installed_ &&
841 // We need to make sure not to replace anything that InstallStubsForMethod
842 // wouldn't. Specifically we cannot stub out Proxy.<init> since subtypes copy the
843 // implementation directly and this will confuse the instrumentation trampolines.
844 // TODO We should remove the need for this since it makes it impossible to profile
845 // Proxy.<init> correctly in all cases.
846 method != jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700847 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700848 if (!method->IsNative() && Runtime::Current()->GetJit() != nullptr) {
849 // Native methods use trampoline entrypoints during interpreter tracing.
850 DCHECK(!Runtime::Current()->GetJit()->GetCodeCache()->GetGarbageCollectCode());
851 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
852 // Tracing will look at the saved entry point in the profiling info to know the actual
853 // entrypoint, so we store it here.
854 if (profiling_info != nullptr) {
855 profiling_info->SetSavedEntryPoint(quick_code);
856 }
857 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700858 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700859 new_quick_code = quick_code;
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700860 }
Jeff Hao65d15d92013-07-16 16:39:33 -0700861 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800862 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800863 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100864}
865
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +0000866void Instrumentation::UpdateNativeMethodsCodeToJitCode(ArtMethod* method, const void* quick_code) {
867 // We don't do any read barrier on `method`'s declaring class in this code, as the JIT might
868 // enter here on a soon-to-be deleted ArtMethod. Updating the entrypoint is OK though, as
869 // the ArtMethod is still in memory.
870 const void* new_quick_code = quick_code;
871 if (UNLIKELY(instrumentation_stubs_installed_) && entry_exit_stubs_installed_) {
872 new_quick_code = GetQuickInstrumentationEntryPoint();
873 }
874 UpdateEntrypoints(method, new_quick_code);
875}
876
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700877void Instrumentation::UpdateMethodsCode(ArtMethod* method, const void* quick_code) {
878 DCHECK(method->GetDeclaringClass()->IsResolved());
879 UpdateMethodsCodeImpl(method, quick_code);
880}
881
Alex Light0a5ec3d2017-07-25 16:50:26 -0700882void Instrumentation::UpdateMethodsCodeToInterpreterEntryPoint(ArtMethod* method) {
883 UpdateMethodsCodeImpl(method, GetQuickToInterpreterBridge());
884}
885
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000886void Instrumentation::UpdateMethodsCodeForJavaDebuggable(ArtMethod* method,
887 const void* quick_code) {
888 // When the runtime is set to Java debuggable, we may update the entry points of
889 // all methods of a class to the interpreter bridge. A method's declaring class
890 // might not be in resolved state yet in that case, so we bypass the DCHECK in
891 // UpdateMethodsCode.
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700892 UpdateMethodsCodeImpl(method, quick_code);
893}
894
Mathieu Chartiere401d142015-04-22 13:56:20 -0700895bool Instrumentation::AddDeoptimizedMethod(ArtMethod* method) {
896 if (IsDeoptimizedMethod(method)) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700897 // Already in the map. Return.
898 return false;
899 }
900 // Not found. Add it.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700901 deoptimized_methods_.insert(method);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700902 return true;
903}
904
Mathieu Chartiere401d142015-04-22 13:56:20 -0700905bool Instrumentation::IsDeoptimizedMethod(ArtMethod* method) {
906 return deoptimized_methods_.find(method) != deoptimized_methods_.end();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700907}
908
Mathieu Chartiere401d142015-04-22 13:56:20 -0700909ArtMethod* Instrumentation::BeginDeoptimizedMethod() {
910 if (deoptimized_methods_.empty()) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700911 // Empty.
912 return nullptr;
913 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700914 return *deoptimized_methods_.begin();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700915}
916
Mathieu Chartiere401d142015-04-22 13:56:20 -0700917bool Instrumentation::RemoveDeoptimizedMethod(ArtMethod* method) {
918 auto it = deoptimized_methods_.find(method);
919 if (it == deoptimized_methods_.end()) {
920 return false;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700921 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700922 deoptimized_methods_.erase(it);
923 return true;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700924}
925
926bool Instrumentation::IsDeoptimizedMethodsEmpty() const {
927 return deoptimized_methods_.empty();
928}
929
Mathieu Chartiere401d142015-04-22 13:56:20 -0700930void Instrumentation::Deoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100931 CHECK(!method->IsNative());
932 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700933 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100934
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700935 Thread* self = Thread::Current();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700936 {
937 WriterMutexLock mu(self, deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700938 bool has_not_been_deoptimized = AddDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700939 CHECK(has_not_been_deoptimized) << "Method " << ArtMethod::PrettyMethod(method)
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200940 << " is already deoptimized";
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700941 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100942 if (!interpreter_stubs_installed_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800943 UpdateEntrypoints(method, GetQuickInstrumentationEntryPoint());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100944
945 // Install instrumentation exit stub and instrumentation frames. We may already have installed
946 // these previously so it will only cover the newly created frames.
947 instrumentation_stubs_installed_ = true;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700948 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100949 Runtime::Current()->GetThreadList()->ForEach(InstrumentationInstallStack, this);
950 }
951}
952
Mathieu Chartiere401d142015-04-22 13:56:20 -0700953void Instrumentation::Undeoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100954 CHECK(!method->IsNative());
955 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700956 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100957
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700958 Thread* self = Thread::Current();
959 bool empty;
960 {
961 WriterMutexLock mu(self, deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700962 bool found_and_erased = RemoveDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700963 CHECK(found_and_erased) << "Method " << ArtMethod::PrettyMethod(method)
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700964 << " is not deoptimized";
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700965 empty = IsDeoptimizedMethodsEmpty();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700966 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100967
968 // Restore code and possibly stack only if we did not deoptimize everything.
969 if (!interpreter_stubs_installed_) {
970 // Restore its code or resolution trampoline.
971 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800972 if (method->IsStatic() && !method->IsConstructor() &&
973 !method->GetDeclaringClass()->IsInitialized()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800974 UpdateEntrypoints(method, GetQuickResolutionStub());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100975 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000976 const void* quick_code = NeedDebugVersionFor(method)
977 ? GetQuickToInterpreterBridge()
Alex Lightfc49fec2018-01-16 22:28:36 +0000978 : class_linker->GetQuickOatCodeFor(method);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800979 UpdateEntrypoints(method, quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100980 }
981
982 // If there is no deoptimized method left, we can restore the stack of each thread.
Alex Lightf244a572018-06-08 13:56:51 -0700983 if (empty && !entry_exit_stubs_installed_) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700984 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100985 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
986 instrumentation_stubs_installed_ = false;
987 }
988 }
989}
990
Mathieu Chartiere401d142015-04-22 13:56:20 -0700991bool Instrumentation::IsDeoptimized(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100992 DCHECK(method != nullptr);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700993 ReaderMutexLock mu(Thread::Current(), deoptimized_methods_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700994 return IsDeoptimizedMethod(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100995}
996
997void Instrumentation::EnableDeoptimization() {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700998 ReaderMutexLock mu(Thread::Current(), deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700999 CHECK(IsDeoptimizedMethodsEmpty());
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001000 CHECK_EQ(deoptimization_enabled_, false);
1001 deoptimization_enabled_ = true;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001002}
1003
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001004void Instrumentation::DisableDeoptimization(const char* key) {
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001005 CHECK_EQ(deoptimization_enabled_, true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001006 // If we deoptimized everything, undo it.
Alex Lightdba61482016-12-21 08:20:29 -08001007 InstrumentationLevel level = GetCurrentInstrumentationLevel();
1008 if (level == InstrumentationLevel::kInstrumentWithInterpreter) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001009 UndeoptimizeEverything(key);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001010 }
1011 // Undeoptimized selected methods.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001012 while (true) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001013 ArtMethod* method;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001014 {
1015 ReaderMutexLock mu(Thread::Current(), deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001016 if (IsDeoptimizedMethodsEmpty()) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001017 break;
1018 }
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001019 method = BeginDeoptimizedMethod();
1020 CHECK(method != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001021 }
1022 Undeoptimize(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001023 }
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001024 deoptimization_enabled_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001025}
1026
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001027// Indicates if instrumentation should notify method enter/exit events to the listeners.
1028bool Instrumentation::ShouldNotifyMethodEnterExitEvents() const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001029 if (!HasMethodEntryListeners() && !HasMethodExitListeners()) {
1030 return false;
1031 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01001032 return !deoptimization_enabled_ && !interpreter_stubs_installed_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001033}
1034
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001035void Instrumentation::DeoptimizeEverything(const char* key) {
1036 CHECK(deoptimization_enabled_);
1037 ConfigureStubs(key, InstrumentationLevel::kInstrumentWithInterpreter);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001038}
1039
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001040void Instrumentation::UndeoptimizeEverything(const char* key) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001041 CHECK(interpreter_stubs_installed_);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001042 CHECK(deoptimization_enabled_);
1043 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001044}
1045
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001046void Instrumentation::EnableMethodTracing(const char* key, bool needs_interpreter) {
1047 InstrumentationLevel level;
1048 if (needs_interpreter) {
1049 level = InstrumentationLevel::kInstrumentWithInterpreter;
1050 } else {
1051 level = InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Alex Light2d441b12018-06-08 15:33:21 -07001052 if (Runtime::Current()->GetJit() != nullptr) {
1053 // TODO b/110263880 It would be better if we didn't need to do this.
1054 // Since we need to hold the method entrypoint across a suspend to ensure instrumentation
1055 // hooks are called correctly we have to disable jit-gc to ensure that the entrypoint doesn't
1056 // go away. Furthermore we need to leave this off permanently since one could get the same
1057 // effect by causing this to be toggled on and off.
1058 Runtime::Current()->GetJit()->GetCodeCache()->SetGarbageCollectCode(false);
1059 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001060 }
1061 ConfigureStubs(key, level);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001062}
1063
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001064void Instrumentation::DisableMethodTracing(const char* key) {
1065 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
jeffhao725a9572012-11-13 18:20:12 -08001066}
1067
Alex Light2d441b12018-06-08 15:33:21 -07001068const void* Instrumentation::GetCodeForInvoke(ArtMethod* method) const {
1069 // This is called by instrumentation entry only and that should never be getting proxy methods.
1070 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
1071 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1072 if (LIKELY(!instrumentation_stubs_installed_ && !interpreter_stubs_installed_)) {
1073 // In general we just return whatever the method thinks its entrypoint is here. The only
1074 // exception is if it still has the instrumentation entrypoint. That means we are racing another
1075 // thread getting rid of instrumentation which is unexpected but possible. In that case we want
1076 // to wait and try to get it from the oat file or jit.
1077 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(kRuntimePointerSize);
1078 DCHECK(code != nullptr);
1079 if (code != GetQuickInstrumentationEntryPoint()) {
1080 return code;
1081 } else if (method->IsNative()) {
1082 return class_linker->GetQuickOatCodeFor(method);
1083 }
1084 // We don't know what it is. Fallthough to try to find the code from the JIT or Oat file.
1085 } else if (method->IsNative()) {
1086 // TODO We could have JIT compiled native entrypoints. It might be worth it to find these.
1087 return class_linker->GetQuickOatCodeFor(method);
1088 } else if (UNLIKELY(interpreter_stubs_installed_)) {
1089 return GetQuickToInterpreterBridge();
1090 }
1091 // Since the method cannot be native due to ifs above we can always fall back to interpreter
1092 // bridge.
1093 const void* result = GetQuickToInterpreterBridge();
1094 if (!NeedDebugVersionFor(method)) {
1095 // If we don't need a debug version we should see what the oat file/class linker has to say.
1096 result = class_linker->GetQuickOatCodeFor(method);
1097 }
1098 // If both those fail try the jit.
1099 if (result == GetQuickToInterpreterBridge()) {
1100 jit::Jit* jit = Runtime::Current()->GetJit();
1101 if (jit != nullptr) {
1102 const void* res = jit->GetCodeCache()->FindCompiledCodeForInstrumentation(method);
1103 if (res != nullptr) {
1104 result = res;
1105 }
1106 }
1107 }
1108 return result;
1109}
1110
Andreas Gampe542451c2016-07-26 09:02:02 -07001111const void* Instrumentation::GetQuickCodeFor(ArtMethod* method, PointerSize pointer_size) const {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001112 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers62d6c772013-02-27 08:32:07 -08001113 if (LIKELY(!instrumentation_stubs_installed_)) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08001114 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size);
Vladimir Marko8a630572014-04-09 18:45:35 +01001115 DCHECK(code != nullptr);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001116 if (LIKELY(!class_linker->IsQuickResolutionStub(code) &&
1117 !class_linker->IsQuickToInterpreterBridge(code)) &&
1118 !class_linker->IsQuickResolutionStub(code) &&
1119 !class_linker->IsQuickToInterpreterBridge(code)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001120 return code;
1121 }
1122 }
Alex Lightfc49fec2018-01-16 22:28:36 +00001123 return class_linker->GetQuickOatCodeFor(method);
jeffhao725a9572012-11-13 18:20:12 -08001124}
1125
Alex Lightd7661582017-05-01 13:48:16 -07001126void Instrumentation::MethodEnterEventImpl(Thread* thread,
1127 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001128 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001129 uint32_t dex_pc) const {
Mingyao Yang2ee17902017-08-30 11:37:08 -07001130 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001131 if (HasMethodEntryListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001132 Thread* self = Thread::Current();
1133 StackHandleScope<1> hs(self);
1134 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001135 for (InstrumentationListener* listener : method_entry_listeners_) {
1136 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001137 listener->MethodEntered(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001138 }
1139 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001140 }
1141}
1142
Alex Lightd7661582017-05-01 13:48:16 -07001143void Instrumentation::MethodExitEventImpl(Thread* thread,
1144 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001145 ArtMethod* method,
Alex Lightd7661582017-05-01 13:48:16 -07001146 uint32_t dex_pc,
1147 const JValue& return_value) const {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001148 if (HasMethodExitListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001149 Thread* self = Thread::Current();
1150 StackHandleScope<2> hs(self);
1151 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1152 if (method->GetInterfaceMethodIfProxy(kRuntimePointerSize)
1153 ->GetReturnTypePrimitive() != Primitive::kPrimNot) {
1154 for (InstrumentationListener* listener : method_exit_listeners_) {
1155 if (listener != nullptr) {
1156 listener->MethodExited(thread, thiz, method, dex_pc, return_value);
1157 }
1158 }
1159 } else {
1160 Handle<mirror::Object> ret(hs.NewHandle(return_value.GetL()));
1161 for (InstrumentationListener* listener : method_exit_listeners_) {
1162 if (listener != nullptr) {
1163 listener->MethodExited(thread, thiz, method, dex_pc, ret);
1164 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001165 }
1166 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001167 }
1168}
1169
Alex Lightd7661582017-05-01 13:48:16 -07001170void Instrumentation::MethodUnwindEvent(Thread* thread,
1171 mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001172 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001173 uint32_t dex_pc) const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001174 if (HasMethodUnwindListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001175 Thread* self = Thread::Current();
1176 StackHandleScope<1> hs(self);
1177 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Mathieu Chartier02e25112013-08-14 16:14:24 -07001178 for (InstrumentationListener* listener : method_unwind_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001179 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001180 listener->MethodUnwind(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001181 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001182 }
1183 }
1184}
1185
Alex Lightd7661582017-05-01 13:48:16 -07001186void Instrumentation::DexPcMovedEventImpl(Thread* thread,
1187 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001188 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001189 uint32_t dex_pc) const {
Alex Lightd7661582017-05-01 13:48:16 -07001190 Thread* self = Thread::Current();
1191 StackHandleScope<1> hs(self);
1192 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001193 for (InstrumentationListener* listener : dex_pc_listeners_) {
1194 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001195 listener->DexPcMoved(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001196 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001197 }
1198}
1199
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001200void Instrumentation::BranchImpl(Thread* thread,
1201 ArtMethod* method,
1202 uint32_t dex_pc,
1203 int32_t offset) const {
1204 for (InstrumentationListener* listener : branch_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001205 if (listener != nullptr) {
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001206 listener->Branch(thread, method, dex_pc, offset);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001207 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001208 }
1209}
1210
Alex Lighte814f9d2017-07-31 16:14:39 -07001211void Instrumentation::WatchedFramePopImpl(Thread* thread, const ShadowFrame& frame) const {
1212 for (InstrumentationListener* listener : watched_frame_pop_listeners_) {
1213 if (listener != nullptr) {
1214 listener->WatchedFramePop(thread, frame);
1215 }
1216 }
1217}
1218
Alex Lightd7661582017-05-01 13:48:16 -07001219void Instrumentation::FieldReadEventImpl(Thread* thread,
1220 ObjPtr<mirror::Object> this_object,
1221 ArtMethod* method,
1222 uint32_t dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001223 ArtField* field) const {
Alex Lightd7661582017-05-01 13:48:16 -07001224 Thread* self = Thread::Current();
1225 StackHandleScope<1> hs(self);
1226 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001227 for (InstrumentationListener* listener : field_read_listeners_) {
1228 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001229 listener->FieldRead(thread, thiz, method, dex_pc, field);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001230 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001231 }
1232}
1233
Alex Lightd7661582017-05-01 13:48:16 -07001234void Instrumentation::FieldWriteEventImpl(Thread* thread,
1235 ObjPtr<mirror::Object> this_object,
1236 ArtMethod* method,
1237 uint32_t dex_pc,
1238 ArtField* field,
1239 const JValue& field_value) const {
1240 Thread* self = Thread::Current();
1241 StackHandleScope<2> hs(self);
1242 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1243 if (field->IsPrimitiveType()) {
1244 for (InstrumentationListener* listener : field_write_listeners_) {
1245 if (listener != nullptr) {
1246 listener->FieldWritten(thread, thiz, method, dex_pc, field, field_value);
1247 }
1248 }
1249 } else {
1250 Handle<mirror::Object> val(hs.NewHandle(field_value.GetL()));
1251 for (InstrumentationListener* listener : field_write_listeners_) {
1252 if (listener != nullptr) {
1253 listener->FieldWritten(thread, thiz, method, dex_pc, field, val);
1254 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001255 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001256 }
1257}
1258
Alex Light6e1607e2017-08-23 10:06:18 -07001259void Instrumentation::ExceptionThrownEvent(Thread* thread,
Sebastien Hertz947ff082013-09-17 14:10:13 +02001260 mirror::Throwable* exception_object) const {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001261 Thread* self = Thread::Current();
1262 StackHandleScope<1> hs(self);
1263 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
Alex Light6e1607e2017-08-23 10:06:18 -07001264 if (HasExceptionThrownListeners()) {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001265 DCHECK_EQ(thread->GetException(), h_exception.Get());
Jeff Haoc0bd4da2013-04-11 15:52:28 -07001266 thread->ClearException();
Alex Light6e1607e2017-08-23 10:06:18 -07001267 for (InstrumentationListener* listener : exception_thrown_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001268 if (listener != nullptr) {
Alex Light6e1607e2017-08-23 10:06:18 -07001269 listener->ExceptionThrown(thread, h_exception);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001270 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001271 }
Alex Light9fb1ab12017-09-05 09:32:49 -07001272 // See b/65049545 for discussion about this behavior.
1273 thread->AssertNoPendingException();
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001274 thread->SetException(h_exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08001275 }
1276}
1277
Alex Light9fb1ab12017-09-05 09:32:49 -07001278void Instrumentation::ExceptionHandledEvent(Thread* thread,
1279 mirror::Throwable* exception_object) const {
1280 Thread* self = Thread::Current();
1281 StackHandleScope<1> hs(self);
1282 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
1283 if (HasExceptionHandledListeners()) {
1284 // We should have cleared the exception so that callers can detect a new one.
1285 DCHECK(thread->GetException() == nullptr);
1286 for (InstrumentationListener* listener : exception_handled_listeners_) {
1287 if (listener != nullptr) {
1288 listener->ExceptionHandled(thread, h_exception);
1289 }
1290 }
1291 }
1292}
1293
Sebastien Hertzb2feaaf2015-10-12 13:40:10 +00001294// Computes a frame ID by ignoring inlined frames.
1295size_t Instrumentation::ComputeFrameId(Thread* self,
1296 size_t frame_depth,
1297 size_t inlined_frames_before_frame) {
1298 CHECK_GE(frame_depth, inlined_frames_before_frame);
1299 size_t no_inline_depth = frame_depth - inlined_frames_before_frame;
1300 return StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) - no_inline_depth;
1301}
1302
Ian Rogers62d6c772013-02-27 08:32:07 -08001303static void CheckStackDepth(Thread* self, const InstrumentationStackFrame& instrumentation_frame,
1304 int delta)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001305 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001306 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) + delta;
Ian Rogers62d6c772013-02-27 08:32:07 -08001307 if (frame_id != instrumentation_frame.frame_id_) {
1308 LOG(ERROR) << "Expected frame_id=" << frame_id << " but found "
1309 << instrumentation_frame.frame_id_;
1310 StackVisitor::DescribeStack(self);
1311 CHECK_EQ(frame_id, instrumentation_frame.frame_id_);
1312 }
1313}
1314
1315void Instrumentation::PushInstrumentationStackFrame(Thread* self, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001316 ArtMethod* method,
Jeff Hao9a916d32013-06-27 18:45:37 -07001317 uintptr_t lr, bool interpreter_entry) {
Alex Lightb7edcda2017-04-27 13:20:31 -07001318 DCHECK(!self->IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001319 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1320 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001321 LOG(INFO) << "Entering " << ArtMethod::PrettyMethod(method) << " from PC "
1322 << reinterpret_cast<void*>(lr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001323 }
Alex Lightb7edcda2017-04-27 13:20:31 -07001324
1325 // We send the enter event before pushing the instrumentation frame to make cleanup easier. If the
1326 // event causes an exception we can simply send the unwind event and return.
1327 StackHandleScope<1> hs(self);
1328 Handle<mirror::Object> h_this(hs.NewHandle(this_object));
1329 if (!interpreter_entry) {
1330 MethodEnterEvent(self, h_this.Get(), method, 0);
1331 if (self->IsExceptionPending()) {
1332 MethodUnwindEvent(self, h_this.Get(), method, 0);
1333 return;
1334 }
1335 }
1336
1337 // We have a callee-save frame meaning this value is guaranteed to never be 0.
1338 DCHECK(!self->IsExceptionPending());
1339 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk);
1340
1341 instrumentation::InstrumentationStackFrame instrumentation_frame(h_this.Get(), method, lr,
Jeff Hao9a916d32013-06-27 18:45:37 -07001342 frame_id, interpreter_entry);
Ian Rogers62d6c772013-02-27 08:32:07 -08001343 stack->push_front(instrumentation_frame);
Ian Rogers62d6c772013-02-27 08:32:07 -08001344}
1345
Mingyao Yang2ee17902017-08-30 11:37:08 -07001346DeoptimizationMethodType Instrumentation::GetDeoptimizationMethodType(ArtMethod* method) {
1347 if (method->IsRuntimeMethod()) {
1348 // Certain methods have strict requirement on whether the dex instruction
1349 // should be re-executed upon deoptimization.
1350 if (method == Runtime::Current()->GetCalleeSaveMethod(
1351 CalleeSaveType::kSaveEverythingForClinit)) {
1352 return DeoptimizationMethodType::kKeepDexPc;
1353 }
1354 if (method == Runtime::Current()->GetCalleeSaveMethod(
1355 CalleeSaveType::kSaveEverythingForSuspendCheck)) {
1356 return DeoptimizationMethodType::kKeepDexPc;
1357 }
1358 }
1359 return DeoptimizationMethodType::kDefault;
1360}
1361
1362// Try to get the shorty of a runtime method if it's an invocation stub.
Andreas Gampec7d878d2018-11-19 18:42:06 +00001363static char GetRuntimeMethodShorty(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
1364 char shorty = 'V';
1365 StackVisitor::WalkStack(
1366 [&shorty](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1367 ArtMethod* m = stack_visitor->GetMethod();
1368 if (m == nullptr || m->IsRuntimeMethod()) {
1369 return true;
Andreas Gampe3d477f32018-11-16 16:40:45 +00001370 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00001371 // The first Java method.
1372 if (m->IsNative()) {
1373 // Use JNI method's shorty for the jni stub.
1374 shorty = m->GetShorty()[0];
1375 } else if (m->IsProxyMethod()) {
1376 // Proxy method just invokes its proxied method via
1377 // art_quick_proxy_invoke_handler.
1378 shorty = m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty()[0];
1379 } else {
1380 const Instruction& instr = m->DexInstructions().InstructionAt(stack_visitor->GetDexPc());
1381 if (instr.IsInvoke()) {
1382 auto get_method_index_fn = [](ArtMethod* caller,
1383 const Instruction& inst,
1384 uint32_t dex_pc)
1385 REQUIRES_SHARED(Locks::mutator_lock_) {
1386 switch (inst.Opcode()) {
1387 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
1388 case Instruction::INVOKE_VIRTUAL_QUICK: {
1389 uint16_t method_idx = caller->GetIndexFromQuickening(dex_pc);
1390 CHECK_NE(method_idx, DexFile::kDexNoIndex16);
1391 return method_idx;
1392 }
1393 default: {
1394 return static_cast<uint16_t>(inst.VRegB());
1395 }
1396 }
1397 };
Nicolas Geoffrayec43a012018-11-17 13:10:40 +00001398
Andreas Gampec7d878d2018-11-19 18:42:06 +00001399 uint16_t method_index = get_method_index_fn(m, instr, stack_visitor->GetDexPc());
1400 const DexFile* dex_file = m->GetDexFile();
1401 if (interpreter::IsStringInit(dex_file, method_index)) {
1402 // Invoking string init constructor is turned into invoking
1403 // StringFactory.newStringFromChars() which returns a string.
1404 shorty = 'L';
1405 } else {
1406 shorty = dex_file->GetMethodShorty(method_index)[0];
1407 }
1408
1409 } else {
1410 // It could be that a non-invoke opcode invokes a stub, which in turn
1411 // invokes Java code. In such cases, we should never expect a return
1412 // value from the stub.
1413 }
1414 }
1415 // Stop stack walking since we've seen a Java frame.
1416 return false;
1417 },
1418 thread,
1419 /* context= */ nullptr,
1420 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
1421 return shorty;
1422}
Mingyao Yang2ee17902017-08-30 11:37:08 -07001423
Alex Lightb7edcda2017-04-27 13:20:31 -07001424TwoWordReturn Instrumentation::PopInstrumentationStackFrame(Thread* self,
1425 uintptr_t* return_pc,
1426 uint64_t* gpr_result,
1427 uint64_t* fpr_result) {
1428 DCHECK(gpr_result != nullptr);
1429 DCHECK(fpr_result != nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001430 // Do the pop.
1431 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1432 CHECK_GT(stack->size(), 0U);
1433 InstrumentationStackFrame instrumentation_frame = stack->front();
1434 stack->pop_front();
1435
1436 // Set return PC and check the sanity of the stack.
1437 *return_pc = instrumentation_frame.return_pc_;
1438 CheckStackDepth(self, instrumentation_frame, 0);
Ian Rogers1d8cdbc2014-09-22 22:51:09 -07001439 self->VerifyStack();
Ian Rogers62d6c772013-02-27 08:32:07 -08001440
Mathieu Chartiere401d142015-04-22 13:56:20 -07001441 ArtMethod* method = instrumentation_frame.method_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001442 uint32_t length;
Andreas Gampe542451c2016-07-26 09:02:02 -07001443 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001444 char return_shorty;
1445
1446 // Runtime method does not call into MethodExitEvent() so there should not be
1447 // suspension point below.
1448 ScopedAssertNoThreadSuspension ants(__FUNCTION__, method->IsRuntimeMethod());
1449 if (method->IsRuntimeMethod()) {
1450 if (method != Runtime::Current()->GetCalleeSaveMethod(
1451 CalleeSaveType::kSaveEverythingForClinit)) {
1452 // If the caller is at an invocation point and the runtime method is not
1453 // for clinit, we need to pass return results to the caller.
1454 // We need the correct shorty to decide whether we need to pass the return
1455 // result for deoptimization below.
Andreas Gampec7d878d2018-11-19 18:42:06 +00001456 return_shorty = GetRuntimeMethodShorty(self);
Mingyao Yang2ee17902017-08-30 11:37:08 -07001457 } else {
1458 // Some runtime methods such as allocations, unresolved field getters, etc.
1459 // have return value. We don't need to set return_value since MethodExitEvent()
1460 // below isn't called for runtime methods. Deoptimization doesn't need the
1461 // value either since the dex instruction will be re-executed by the
1462 // interpreter, except these two cases:
1463 // (1) For an invoke, which is handled above to get the correct shorty.
1464 // (2) For MONITOR_ENTER/EXIT, which cannot be re-executed since it's not
1465 // idempotent. However there is no return value for it anyway.
1466 return_shorty = 'V';
1467 }
1468 } else {
1469 return_shorty = method->GetInterfaceMethodIfProxy(pointer_size)->GetShorty(&length)[0];
1470 }
1471
Alex Lightb7edcda2017-04-27 13:20:31 -07001472 bool is_ref = return_shorty == '[' || return_shorty == 'L';
1473 StackHandleScope<1> hs(self);
1474 MutableHandle<mirror::Object> res(hs.NewHandle<mirror::Object>(nullptr));
Ian Rogers62d6c772013-02-27 08:32:07 -08001475 JValue return_value;
1476 if (return_shorty == 'V') {
1477 return_value.SetJ(0);
1478 } else if (return_shorty == 'F' || return_shorty == 'D') {
Alex Lightb7edcda2017-04-27 13:20:31 -07001479 return_value.SetJ(*fpr_result);
Ian Rogers62d6c772013-02-27 08:32:07 -08001480 } else {
Alex Lightb7edcda2017-04-27 13:20:31 -07001481 return_value.SetJ(*gpr_result);
1482 }
1483 if (is_ref) {
1484 // Take a handle to the return value so we won't lose it if we suspend.
1485 res.Assign(return_value.GetL());
Ian Rogers62d6c772013-02-27 08:32:07 -08001486 }
1487 // TODO: improve the dex pc information here, requires knowledge of current PC as opposed to
1488 // return_pc.
Andreas Gampee2abbc62017-09-15 11:59:26 -07001489 uint32_t dex_pc = dex::kDexNoIndex;
Ian Rogers62d6c772013-02-27 08:32:07 -08001490 mirror::Object* this_object = instrumentation_frame.this_object_;
Mingyao Yang2ee17902017-08-30 11:37:08 -07001491 if (!method->IsRuntimeMethod() && !instrumentation_frame.interpreter_entry_) {
Sebastien Hertz320deb22014-06-11 19:45:05 +02001492 MethodExitEvent(self, this_object, instrumentation_frame.method_, dex_pc, return_value);
1493 }
jeffhao725a9572012-11-13 18:20:12 -08001494
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001495 // Deoptimize if the caller needs to continue execution in the interpreter. Do nothing if we get
1496 // back to an upcall.
1497 NthCallerVisitor visitor(self, 1, true);
1498 visitor.WalkStack(true);
Sebastien Hertz270a0e12015-01-16 19:49:09 +01001499 bool deoptimize = (visitor.caller != nullptr) &&
Daniel Mihalyieb076692014-08-22 17:33:31 +02001500 (interpreter_stubs_installed_ || IsDeoptimized(visitor.caller) ||
1501 Dbg::IsForcedInterpreterNeededForUpcall(self, visitor.caller));
Alex Lightb7edcda2017-04-27 13:20:31 -07001502 if (is_ref) {
1503 // Restore the return value if it's a reference since it might have moved.
1504 *reinterpret_cast<mirror::Object**>(gpr_result) = res.Get();
1505 }
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001506 if (deoptimize && Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001507 if (kVerboseInstrumentation) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -08001508 LOG(INFO) << "Deoptimizing "
1509 << visitor.caller->PrettyMethod()
1510 << " by returning from "
1511 << method->PrettyMethod()
1512 << " with result "
1513 << std::hex << return_value.GetJ() << std::dec
1514 << " in "
1515 << *self;
Ian Rogers62d6c772013-02-27 08:32:07 -08001516 }
Mingyao Yang2ee17902017-08-30 11:37:08 -07001517 DeoptimizationMethodType deopt_method_type = GetDeoptimizationMethodType(method);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001518 self->PushDeoptimizationContext(return_value,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001519 return_shorty == 'L' || return_shorty == '[',
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001520 /* exception= */ nullptr ,
1521 /* from_code= */ false,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001522 deopt_method_type);
Andreas Gamped58342c2014-06-05 14:18:08 -07001523 return GetTwoWordSuccessValue(*return_pc,
1524 reinterpret_cast<uintptr_t>(GetQuickDeoptimizationEntryPoint()));
Ian Rogers62d6c772013-02-27 08:32:07 -08001525 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001526 if (deoptimize && !Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Alex Lightd8eb6732018-01-29 15:16:02 -08001527 VLOG(deopt) << "Got a deoptimization request on un-deoptimizable " << method->PrettyMethod()
1528 << " at PC " << reinterpret_cast<void*>(*return_pc);
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001529 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001530 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001531 LOG(INFO) << "Returning from " << method->PrettyMethod()
Brian Carlstrom2d888622013-07-18 17:02:00 -07001532 << " to PC " << reinterpret_cast<void*>(*return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001533 }
Andreas Gamped58342c2014-06-05 14:18:08 -07001534 return GetTwoWordSuccessValue(0, *return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001535 }
jeffhao725a9572012-11-13 18:20:12 -08001536}
1537
Alex Light2c8206f2018-06-08 14:51:09 -07001538uintptr_t Instrumentation::PopFramesForDeoptimization(Thread* self, size_t nframes) const {
Ian Rogers62d6c772013-02-27 08:32:07 -08001539 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
Alex Light2c8206f2018-06-08 14:51:09 -07001540 CHECK_GE(stack->size(), nframes);
1541 if (nframes == 0) {
1542 return 0u;
1543 }
1544 // Only need to send instrumentation events if it's not for deopt (do give the log messages if we
1545 // have verbose-instrumentation anyway though).
1546 if (kVerboseInstrumentation) {
1547 for (size_t i = 0; i < nframes; i++) {
1548 LOG(INFO) << "Popping for deoptimization " << stack->at(i).method_->PrettyMethod();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001549 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001550 }
Alex Light2c8206f2018-06-08 14:51:09 -07001551 // Now that we've sent all the instrumentation events we can actually modify the
1552 // instrumentation-stack. We cannot do this earlier since MethodUnwindEvent can re-enter java and
1553 // do other things that require the instrumentation stack to be in a consistent state with the
1554 // actual stack.
1555 for (size_t i = 0; i < nframes - 1; i++) {
1556 stack->pop_front();
1557 }
1558 uintptr_t return_pc = stack->front().return_pc_;
Alex Lightb7edcda2017-04-27 13:20:31 -07001559 stack->pop_front();
Alex Light2c8206f2018-06-08 14:51:09 -07001560 return return_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -08001561}
1562
1563std::string InstrumentationStackFrame::Dump() const {
1564 std::ostringstream os;
David Sehr709b0702016-10-13 09:12:37 -07001565 os << "Frame " << frame_id_ << " " << ArtMethod::PrettyMethod(method_) << ":"
Ian Rogers62d6c772013-02-27 08:32:07 -08001566 << reinterpret_cast<void*>(return_pc_) << " this=" << reinterpret_cast<void*>(this_object_);
1567 return os.str();
1568}
1569
1570} // namespace instrumentation
jeffhao725a9572012-11-13 18:20:12 -08001571} // namespace art