blob: cbcaaef26020e51a985b8e39c9d4cce725b77fc4 [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
Ian Rogerse63db272014-07-15 15:36:11 -070021#include "arch/context.h"
Alex Lightd7661582017-05-01 13:48:16 -070022#include "art_field-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include "art_method-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080024#include "base/atomic.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070025#include "base/callee_save_type.h"
jeffhao725a9572012-11-13 18:20:12 -080026#include "class_linker.h"
27#include "debugger.h"
David Sehr9e734c72018-01-04 17:56:19 -080028#include "dex/dex_file-inl.h"
29#include "dex/dex_file_types.h"
30#include "dex/dex_instruction-inl.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080031#include "entrypoints/quick/quick_alloc_entrypoints.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070032#include "entrypoints/quick/quick_entrypoints.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070033#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070034#include "gc_root-inl.h"
Sebastien Hertz138dbfc2013-12-04 18:15:25 +010035#include "interpreter/interpreter.h"
Mingyao Yang2ee17902017-08-30 11:37:08 -070036#include "interpreter/interpreter_common.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037#include "jit/jit.h"
38#include "jit/jit_code_cache.h"
Alex Lightd7661582017-05-01 13:48:16 -070039#include "jvalue-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "mirror/class-inl.h"
41#include "mirror/dex_cache.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070042#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070043#include "mirror/object_array-inl.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080044#include "nth_caller_visitor.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010045#include "oat_quick_method_header.h"
David Srbecky28f6cff2018-10-16 15:07:28 +010046#include "runtime-inl.h"
jeffhao725a9572012-11-13 18:20:12 -080047#include "thread.h"
48#include "thread_list.h"
jeffhao725a9572012-11-13 18:20:12 -080049
50namespace art {
Ian Rogers62d6c772013-02-27 08:32:07 -080051namespace instrumentation {
jeffhao725a9572012-11-13 18:20:12 -080052
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020053constexpr bool kVerboseInstrumentation = false;
Sebastien Hertz5bfd5c92013-11-15 11:36:07 +010054
Alex Lightd7661582017-05-01 13:48:16 -070055void InstrumentationListener::MethodExited(Thread* thread,
56 Handle<mirror::Object> this_object,
57 ArtMethod* method,
58 uint32_t dex_pc,
59 Handle<mirror::Object> return_value) {
60 DCHECK_EQ(method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetReturnTypePrimitive(),
61 Primitive::kPrimNot);
62 JValue v;
63 v.SetL(return_value.Get());
64 MethodExited(thread, this_object, method, dex_pc, v);
65}
66
67void InstrumentationListener::FieldWritten(Thread* thread,
68 Handle<mirror::Object> this_object,
69 ArtMethod* method,
70 uint32_t dex_pc,
71 ArtField* field,
72 Handle<mirror::Object> field_value) {
73 DCHECK(!field->IsPrimitiveType());
74 JValue v;
75 v.SetL(field_value.Get());
76 FieldWritten(thread, this_object, method, dex_pc, field, v);
77}
78
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +010079// Instrumentation works on non-inlined frames by updating returned PCs
80// of compiled frames.
81static constexpr StackVisitor::StackWalkKind kInstrumentationStackWalk =
82 StackVisitor::StackWalkKind::kSkipInlinedFrames;
83
Mathieu Chartiere0671ce2015-07-28 17:23:28 -070084class InstallStubsClassVisitor : public ClassVisitor {
85 public:
86 explicit InstallStubsClassVisitor(Instrumentation* instrumentation)
87 : instrumentation_(instrumentation) {}
88
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010089 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -070090 instrumentation_->InstallStubsForClass(klass.Ptr());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -070091 return true; // we visit all classes.
92 }
93
94 private:
95 Instrumentation* const instrumentation_;
96};
97
Alex Light2c8206f2018-06-08 14:51:09 -070098InstrumentationStackPopper::InstrumentationStackPopper(Thread* self)
99 : self_(self),
100 instrumentation_(Runtime::Current()->GetInstrumentation()),
101 frames_to_remove_(0) {}
102
103InstrumentationStackPopper::~InstrumentationStackPopper() {
104 std::deque<instrumentation::InstrumentationStackFrame>* stack = self_->GetInstrumentationStack();
105 for (size_t i = 0; i < frames_to_remove_; i++) {
106 stack->pop_front();
107 }
108}
109
110bool InstrumentationStackPopper::PopFramesTo(uint32_t desired_pops,
111 MutableHandle<mirror::Throwable>& exception) {
112 std::deque<instrumentation::InstrumentationStackFrame>* stack = self_->GetInstrumentationStack();
113 DCHECK_LE(frames_to_remove_, desired_pops);
114 DCHECK_GE(stack->size(), desired_pops);
115 DCHECK(!self_->IsExceptionPending());
116 if (!instrumentation_->HasMethodUnwindListeners()) {
117 frames_to_remove_ = desired_pops;
118 return true;
119 }
120 if (kVerboseInstrumentation) {
121 LOG(INFO) << "Popping frames for exception " << exception->Dump();
122 }
123 // The instrumentation events expect the exception to be set.
124 self_->SetException(exception.Get());
125 bool new_exception_thrown = false;
126 for (; frames_to_remove_ < desired_pops && !new_exception_thrown; frames_to_remove_++) {
127 InstrumentationStackFrame frame = stack->at(frames_to_remove_);
128 ArtMethod* method = frame.method_;
129 // Notify listeners of method unwind.
130 // TODO: improve the dex_pc information here.
131 uint32_t dex_pc = dex::kDexNoIndex;
132 if (kVerboseInstrumentation) {
133 LOG(INFO) << "Popping for unwind " << method->PrettyMethod();
134 }
135 if (!method->IsRuntimeMethod() && !frame.interpreter_entry_) {
136 instrumentation_->MethodUnwindEvent(self_, frame.this_object_, method, dex_pc);
137 new_exception_thrown = self_->GetException() != exception.Get();
138 }
139 }
140 exception.Assign(self_->GetException());
141 self_->ClearException();
142 if (kVerboseInstrumentation && new_exception_thrown) {
143 LOG(INFO) << "Failed to pop " << (desired_pops - frames_to_remove_)
144 << " frames due to new exception";
145 }
146 return !new_exception_thrown;
147}
Ian Rogers62d6c772013-02-27 08:32:07 -0800148
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700149Instrumentation::Instrumentation()
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000150 : instrumentation_stubs_installed_(false),
151 entry_exit_stubs_installed_(false),
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700152 interpreter_stubs_installed_(false),
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000153 interpret_only_(false),
154 forced_interpret_only_(false),
155 have_method_entry_listeners_(false),
156 have_method_exit_listeners_(false),
157 have_method_unwind_listeners_(false),
158 have_dex_pc_listeners_(false),
159 have_field_read_listeners_(false),
160 have_field_write_listeners_(false),
Alex Light6e1607e2017-08-23 10:06:18 -0700161 have_exception_thrown_listeners_(false),
Alex Lighte814f9d2017-07-31 16:14:39 -0700162 have_watched_frame_pop_listeners_(false),
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000163 have_branch_listeners_(false),
Alex Light9fb1ab12017-09-05 09:32:49 -0700164 have_exception_handled_listeners_(false),
Alex Light3e36a9c2018-06-19 09:45:05 -0700165 deoptimized_methods_lock_("deoptimized methods lock", kGenericBottomLock),
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700166 deoptimization_enabled_(false),
167 interpreter_handler_table_(kMainHandlerTable),
Mathieu Chartier50e93312016-03-16 11:25:29 -0700168 quick_alloc_entry_points_instrumentation_counter_(0),
169 alloc_entrypoints_instrumented_(false) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700170}
171
Sebastien Hertza10aa372015-01-21 17:30:58 +0100172void Instrumentation::InstallStubsForClass(mirror::Class* klass) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000173 if (!klass->IsResolved()) {
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100174 // We need the class to be resolved to install/uninstall stubs. Otherwise its methods
175 // could not be initialized or linked with regards to class inheritance.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000176 } else if (klass->IsErroneousResolved()) {
177 // We can't execute code in a erroneous class: do nothing.
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100178 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -0700179 for (ArtMethod& method : klass->GetMethods(kRuntimePointerSize)) {
Alex Light51a64d52015-12-17 13:55:59 -0800180 InstallStubsForMethod(&method);
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100181 }
jeffhao725a9572012-11-13 18:20:12 -0800182 }
jeffhao725a9572012-11-13 18:20:12 -0800183}
184
Mathieu Chartiere401d142015-04-22 13:56:20 -0700185static void UpdateEntrypoints(ArtMethod* method, const void* quick_code)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700186 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800187 method->SetEntryPointFromQuickCompiledCode(quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100188}
189
Alex Light0fa17862017-10-24 13:43:05 -0700190bool Instrumentation::NeedDebugVersionFor(ArtMethod* method) const
191 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightf2858632018-04-02 11:28:50 -0700192 art::Runtime* runtime = Runtime::Current();
193 // If anything says we need the debug version or we are debuggable we will need the debug version
194 // of the method.
195 return (runtime->GetRuntimeCallbacks()->MethodNeedsDebugVersion(method) ||
196 runtime->IsJavaDebuggable()) &&
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800197 !method->IsNative() &&
Alex Lightf2858632018-04-02 11:28:50 -0700198 !method->IsProxyMethod();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800199}
200
Mathieu Chartiere401d142015-04-22 13:56:20 -0700201void Instrumentation::InstallStubsForMethod(ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -0700202 if (!method->IsInvokable() || method->IsProxyMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100203 // Do not change stubs for these methods.
204 return;
205 }
Jeff Hao56802772014-08-19 10:17:36 -0700206 // Don't stub Proxy.<init>. Note that the Proxy class itself is not a proxy class.
Alex Light6cae5ea2018-06-07 17:07:02 -0700207 // TODO We should remove the need for this since it means we cannot always correctly detect calls
208 // to Proxy.<init>
209 // Annoyingly this can be called before we have actually initialized WellKnownClasses so therefore
210 // we also need to check this based on the declaring-class descriptor. The check is valid because
211 // Proxy only has a single constructor.
212 ArtMethod* well_known_proxy_init = jni::DecodeArtMethod(
213 WellKnownClasses::java_lang_reflect_Proxy_init);
214 if ((LIKELY(well_known_proxy_init != nullptr) && UNLIKELY(method == well_known_proxy_init)) ||
215 UNLIKELY(method->IsConstructor() &&
216 method->GetDeclaringClass()->DescriptorEquals("Ljava/lang/reflect/Proxy;"))) {
Jeff Haodb8a6642014-08-14 17:18:52 -0700217 return;
218 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800219 const void* new_quick_code;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100220 bool uninstall = !entry_exit_stubs_installed_ && !interpreter_stubs_installed_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800221 Runtime* const runtime = Runtime::Current();
222 ClassLinker* const class_linker = runtime->GetClassLinker();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100223 bool is_class_initialized = method->GetDeclaringClass()->IsInitialized();
224 if (uninstall) {
225 if ((forced_interpret_only_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800226 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100227 } else if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700228 new_quick_code = GetCodeForInvoke(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100229 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700230 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100231 }
232 } else { // !uninstall
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100233 if ((interpreter_stubs_installed_ || forced_interpret_only_ || IsDeoptimized(method)) &&
234 !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800235 new_quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100236 } else {
237 // Do not overwrite resolution trampoline. When the trampoline initializes the method's
238 // class, all its static methods code will be set to the instrumentation entry point.
239 // For more details, see ClassLinker::FixupStaticTrampolines.
240 if (is_class_initialized || !method->IsStatic() || method->IsConstructor()) {
Alex Light2d441b12018-06-08 15:33:21 -0700241 if (entry_exit_stubs_installed_) {
242 // This needs to be checked first since the instrumentation entrypoint will be able to
243 // find the actual JIT compiled code that corresponds to this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800244 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700245 } else if (NeedDebugVersionFor(method)) {
246 // It would be great to search the JIT for its implementation here but we cannot due to
247 // the locks we hold. Instead just set to the interpreter bridge and that code will search
248 // the JIT when it gets called and replace the entrypoint then.
249 new_quick_code = GetQuickToInterpreterBridge();
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000250 } else {
Alex Lightfc49fec2018-01-16 22:28:36 +0000251 new_quick_code = class_linker->GetQuickOatCodeFor(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100252 }
253 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700254 new_quick_code = GetQuickResolutionStub();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100255 }
256 }
257 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800258 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100259}
260
Ian Rogers62d6c772013-02-27 08:32:07 -0800261// Places the instrumentation exit pc as the return PC for every quick frame. This also allows
262// deoptimization of quick frames to interpreter frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100263// Since we may already have done this previously, we need to push new instrumentation frame before
264// existing instrumentation frames.
Ian Rogers62d6c772013-02-27 08:32:07 -0800265static void InstrumentationInstallStack(Thread* thread, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700266 REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100267 struct InstallStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800268 InstallStackVisitor(Thread* thread_in, Context* context, uintptr_t instrumentation_exit_pc)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100269 : StackVisitor(thread_in, context, kInstrumentationStackWalk),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800270 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100271 instrumentation_exit_pc_(instrumentation_exit_pc),
Alex Lighte9278662018-03-08 16:55:58 -0800272 reached_existing_instrumentation_frames_(false), instrumentation_stack_depth_(0),
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100273 last_return_pc_(0) {
274 }
jeffhao725a9572012-11-13 18:20:12 -0800275
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100276 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700277 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700278 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800279 if (kVerboseInstrumentation) {
280 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
281 }
282 last_return_pc_ = 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700283 return true; // Ignore upcalls.
Ian Rogers306057f2012-11-26 12:45:53 -0800284 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700285 if (GetCurrentQuickFrame() == nullptr) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800286 bool interpreter_frame = true;
Sebastien Hertz320deb22014-06-11 19:45:05 +0200287 InstrumentationStackFrame instrumentation_frame(GetThisObject(), m, 0, GetFrameId(),
288 interpreter_frame);
Jeff Haoa15a81b2014-05-27 18:25:47 -0700289 if (kVerboseInstrumentation) {
290 LOG(INFO) << "Pushing shadow frame " << instrumentation_frame.Dump();
291 }
292 shadow_stack_.push_back(instrumentation_frame);
293 return true; // Continue.
294 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800295 uintptr_t return_pc = GetReturnPc();
Sebastien Hertz320deb22014-06-11 19:45:05 +0200296 if (kVerboseInstrumentation) {
297 LOG(INFO) << " Installing exit stub in " << DescribeLocation();
298 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100299 if (return_pc == instrumentation_exit_pc_) {
Mingyao Yang2ee17902017-08-30 11:37:08 -0700300 CHECK_LT(instrumentation_stack_depth_, instrumentation_stack_->size());
301
302 if (m->IsRuntimeMethod()) {
303 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100304 (*instrumentation_stack_)[instrumentation_stack_depth_];
Mingyao Yang2ee17902017-08-30 11:37:08 -0700305 if (frame.interpreter_entry_) {
306 // This instrumentation frame is for an interpreter bridge and is
307 // pushed when executing the instrumented interpreter bridge. So method
308 // enter event must have been reported. However we need to push a DEX pc
309 // into the dex_pcs_ list to match size of instrumentation stack.
Andreas Gampee2abbc62017-09-15 11:59:26 -0700310 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700311 dex_pcs_.push_back(dex_pc);
312 last_return_pc_ = frame.return_pc_;
313 ++instrumentation_stack_depth_;
314 return true;
315 }
316 }
317
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100318 // We've reached a frame which has already been installed with instrumentation exit stub.
Alex Light74c91c92018-03-08 14:01:44 -0800319 // We should have already installed instrumentation or be interpreter on previous frames.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100320 reached_existing_instrumentation_frames_ = true;
321
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200322 const InstrumentationStackFrame& frame =
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100323 (*instrumentation_stack_)[instrumentation_stack_depth_];
David Sehr709b0702016-10-13 09:12:37 -0700324 CHECK_EQ(m, frame.method_) << "Expected " << ArtMethod::PrettyMethod(m)
325 << ", Found " << ArtMethod::PrettyMethod(frame.method_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100326 return_pc = frame.return_pc_;
327 if (kVerboseInstrumentation) {
328 LOG(INFO) << "Ignoring already instrumented " << frame.Dump();
329 }
330 } else {
331 CHECK_NE(return_pc, 0U);
Alex Light74c91c92018-03-08 14:01:44 -0800332 if (UNLIKELY(reached_existing_instrumentation_frames_ && !m->IsRuntimeMethod())) {
333 // We already saw an existing instrumentation frame so this should be a runtime-method
334 // inserted by the interpreter or runtime.
Alex Lighte9278662018-03-08 16:55:58 -0800335 std::string thread_name;
336 GetThread()->GetThreadName(thread_name);
337 uint32_t dex_pc = dex::kDexNoIndex;
338 if (last_return_pc_ != 0 &&
339 GetCurrentOatQuickMethodHeader() != nullptr) {
340 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
341 }
Alex Light74c91c92018-03-08 14:01:44 -0800342 LOG(FATAL) << "While walking " << thread_name << " found unexpected non-runtime method"
343 << " without instrumentation exit return or interpreter frame."
Alex Lighte9278662018-03-08 16:55:58 -0800344 << " method is " << GetMethod()->PrettyMethod()
345 << " return_pc is " << std::hex << return_pc
346 << " dex pc: " << dex_pc;
347 UNREACHABLE();
348 }
Mingyao Yang2ee17902017-08-30 11:37:08 -0700349 InstrumentationStackFrame instrumentation_frame(
350 m->IsRuntimeMethod() ? nullptr : GetThisObject(),
351 m,
352 return_pc,
353 GetFrameId(), // A runtime method still gets a frame id.
354 false);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100355 if (kVerboseInstrumentation) {
356 LOG(INFO) << "Pushing frame " << instrumentation_frame.Dump();
357 }
358
Sebastien Hertz320deb22014-06-11 19:45:05 +0200359 // Insert frame at the right position so we do not corrupt the instrumentation stack.
360 // Instrumentation stack frames are in descending frame id order.
361 auto it = instrumentation_stack_->begin();
362 for (auto end = instrumentation_stack_->end(); it != end; ++it) {
363 const InstrumentationStackFrame& current = *it;
364 if (instrumentation_frame.frame_id_ >= current.frame_id_) {
365 break;
366 }
367 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100368 instrumentation_stack_->insert(it, instrumentation_frame);
369 SetReturnPc(instrumentation_exit_pc_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800370 }
Andreas Gampee2abbc62017-09-15 11:59:26 -0700371 uint32_t dex_pc = dex::kDexNoIndex;
Mingyao Yang2ee17902017-08-30 11:37:08 -0700372 if (last_return_pc_ != 0 &&
373 GetCurrentOatQuickMethodHeader() != nullptr) {
374 dex_pc = GetCurrentOatQuickMethodHeader()->ToDexPc(m, last_return_pc_);
375 }
376 dex_pcs_.push_back(dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800377 last_return_pc_ = return_pc;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100378 ++instrumentation_stack_depth_;
Ian Rogers306057f2012-11-26 12:45:53 -0800379 return true; // Continue.
380 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800381 std::deque<InstrumentationStackFrame>* const instrumentation_stack_;
Jeff Haoa15a81b2014-05-27 18:25:47 -0700382 std::vector<InstrumentationStackFrame> shadow_stack_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800383 std::vector<uint32_t> dex_pcs_;
Ian Rogers306057f2012-11-26 12:45:53 -0800384 const uintptr_t instrumentation_exit_pc_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100385 bool reached_existing_instrumentation_frames_;
386 size_t instrumentation_stack_depth_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800387 uintptr_t last_return_pc_;
Ian Rogers306057f2012-11-26 12:45:53 -0800388 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800389 if (kVerboseInstrumentation) {
390 std::string thread_name;
391 thread->GetThreadName(thread_name);
392 LOG(INFO) << "Installing exit stubs in " << thread_name;
Ian Rogers306057f2012-11-26 12:45:53 -0800393 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100394
395 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers700a4022014-05-19 16:49:03 -0700396 std::unique_ptr<Context> context(Context::Create());
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700397 uintptr_t instrumentation_exit_pc = reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100398 InstallStackVisitor visitor(thread, context.get(), instrumentation_exit_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800399 visitor.WalkStack(true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100400 CHECK_EQ(visitor.dex_pcs_.size(), thread->GetInstrumentationStack()->size());
Ian Rogers62d6c772013-02-27 08:32:07 -0800401
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100402 if (instrumentation->ShouldNotifyMethodEnterExitEvents()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100403 // Create method enter events for all methods currently on the thread's stack. We only do this
404 // if no debugger is attached to prevent from posting events twice.
Jeff Haoa15a81b2014-05-27 18:25:47 -0700405 auto ssi = visitor.shadow_stack_.rbegin();
406 for (auto isi = thread->GetInstrumentationStack()->rbegin(),
407 end = thread->GetInstrumentationStack()->rend(); isi != end; ++isi) {
408 while (ssi != visitor.shadow_stack_.rend() && (*ssi).frame_id_ < (*isi).frame_id_) {
409 instrumentation->MethodEnterEvent(thread, (*ssi).this_object_, (*ssi).method_, 0);
410 ++ssi;
411 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100412 uint32_t dex_pc = visitor.dex_pcs_.back();
413 visitor.dex_pcs_.pop_back();
Alex Lightdc5423f2018-06-08 10:43:38 -0700414 if (!isi->interpreter_entry_ && !isi->method_->IsRuntimeMethod()) {
Sebastien Hertz320deb22014-06-11 19:45:05 +0200415 instrumentation->MethodEnterEvent(thread, (*isi).this_object_, (*isi).method_, dex_pc);
416 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100417 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800418 }
419 thread->VerifyStack();
Ian Rogers306057f2012-11-26 12:45:53 -0800420}
421
Mingyao Yang99170c62015-07-06 11:10:37 -0700422void Instrumentation::InstrumentThreadStack(Thread* thread) {
423 instrumentation_stubs_installed_ = true;
424 InstrumentationInstallStack(thread, this);
425}
426
Ian Rogers62d6c772013-02-27 08:32:07 -0800427// Removes the instrumentation exit pc as the return PC for every quick frame.
428static void InstrumentationRestoreStack(Thread* thread, void* arg)
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000429 REQUIRES(Locks::mutator_lock_) {
430 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
431
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100432 struct RestoreStackVisitor final : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800433 RestoreStackVisitor(Thread* thread_in, uintptr_t instrumentation_exit_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800434 Instrumentation* instrumentation)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100435 : StackVisitor(thread_in, nullptr, kInstrumentationStackWalk),
436 thread_(thread_in),
Ian Rogers62d6c772013-02-27 08:32:07 -0800437 instrumentation_exit_pc_(instrumentation_exit_pc),
438 instrumentation_(instrumentation),
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800439 instrumentation_stack_(thread_in->GetInstrumentationStack()),
Ian Rogers62d6c772013-02-27 08:32:07 -0800440 frames_removed_(0) {}
Ian Rogers306057f2012-11-26 12:45:53 -0800441
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100442 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800443 if (instrumentation_stack_->size() == 0) {
jeffhao725a9572012-11-13 18:20:12 -0800444 return false; // Stop.
445 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700446 ArtMethod* m = GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700447 if (GetCurrentQuickFrame() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800448 if (kVerboseInstrumentation) {
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200449 LOG(INFO) << " Ignoring a shadow frame. Frame " << GetFrameId()
David Sehr709b0702016-10-13 09:12:37 -0700450 << " Method=" << ArtMethod::PrettyMethod(m);
Ian Rogers62d6c772013-02-27 08:32:07 -0800451 }
452 return true; // Ignore shadow frames.
453 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700454 if (m == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800455 if (kVerboseInstrumentation) {
456 LOG(INFO) << " Skipping upcall. Frame " << GetFrameId();
457 }
Ian Rogers306057f2012-11-26 12:45:53 -0800458 return true; // Ignore upcalls.
459 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800460 bool removed_stub = false;
461 // TODO: make this search more efficient?
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100462 const size_t frameId = GetFrameId();
463 for (const InstrumentationStackFrame& instrumentation_frame : *instrumentation_stack_) {
464 if (instrumentation_frame.frame_id_ == frameId) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800465 if (kVerboseInstrumentation) {
466 LOG(INFO) << " Removing exit stub in " << DescribeLocation();
467 }
Jeff Hao9a916d32013-06-27 18:45:37 -0700468 if (instrumentation_frame.interpreter_entry_) {
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700469 CHECK(m == Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
Jeff Hao9a916d32013-06-27 18:45:37 -0700470 } else {
David Sehr709b0702016-10-13 09:12:37 -0700471 CHECK(m == instrumentation_frame.method_) << ArtMethod::PrettyMethod(m);
Jeff Hao9a916d32013-06-27 18:45:37 -0700472 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800473 SetReturnPc(instrumentation_frame.return_pc_);
Mingyao Yang2ee17902017-08-30 11:37:08 -0700474 if (instrumentation_->ShouldNotifyMethodEnterExitEvents() &&
475 !m->IsRuntimeMethod()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100476 // Create the method exit events. As the methods didn't really exit the result is 0.
477 // We only do this if no debugger is attached to prevent from posting events twice.
478 instrumentation_->MethodExitEvent(thread_, instrumentation_frame.this_object_, m,
479 GetDexPc(), JValue());
480 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800481 frames_removed_++;
482 removed_stub = true;
483 break;
484 }
485 }
486 if (!removed_stub) {
487 if (kVerboseInstrumentation) {
488 LOG(INFO) << " No exit stub in " << DescribeLocation();
Ian Rogers306057f2012-11-26 12:45:53 -0800489 }
jeffhao725a9572012-11-13 18:20:12 -0800490 }
491 return true; // Continue.
492 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800493 Thread* const thread_;
Ian Rogers306057f2012-11-26 12:45:53 -0800494 const uintptr_t instrumentation_exit_pc_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800495 Instrumentation* const instrumentation_;
496 std::deque<instrumentation::InstrumentationStackFrame>* const instrumentation_stack_;
497 size_t frames_removed_;
jeffhao725a9572012-11-13 18:20:12 -0800498 };
Ian Rogers62d6c772013-02-27 08:32:07 -0800499 if (kVerboseInstrumentation) {
500 std::string thread_name;
501 thread->GetThreadName(thread_name);
502 LOG(INFO) << "Removing exit stubs in " << thread_name;
503 }
504 std::deque<instrumentation::InstrumentationStackFrame>* stack = thread->GetInstrumentationStack();
505 if (stack->size() > 0) {
506 Instrumentation* instrumentation = reinterpret_cast<Instrumentation*>(arg);
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700507 uintptr_t instrumentation_exit_pc =
508 reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc());
Ian Rogers62d6c772013-02-27 08:32:07 -0800509 RestoreStackVisitor visitor(thread, instrumentation_exit_pc, instrumentation);
510 visitor.WalkStack(true);
511 CHECK_EQ(visitor.frames_removed_, stack->size());
512 while (stack->size() > 0) {
513 stack->pop_front();
514 }
jeffhao725a9572012-11-13 18:20:12 -0800515 }
516}
517
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200518static bool HasEvent(Instrumentation::InstrumentationEvent expected, uint32_t events) {
519 return (events & expected) != 0;
520}
521
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000522static void PotentiallyAddListenerTo(Instrumentation::InstrumentationEvent event,
523 uint32_t events,
524 std::list<InstrumentationListener*>& list,
525 InstrumentationListener* listener,
526 bool* has_listener)
527 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
528 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
529 if (!HasEvent(event, events)) {
530 return;
531 }
532 // If there is a free slot in the list, we insert the listener in that slot.
533 // Otherwise we add it to the end of the list.
534 auto it = std::find(list.begin(), list.end(), nullptr);
535 if (it != list.end()) {
536 *it = listener;
537 } else {
538 list.push_back(listener);
539 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100540 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000541}
542
Ian Rogers62d6c772013-02-27 08:32:07 -0800543void Instrumentation::AddListener(InstrumentationListener* listener, uint32_t events) {
544 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000545 PotentiallyAddListenerTo(kMethodEntered,
546 events,
547 method_entry_listeners_,
548 listener,
549 &have_method_entry_listeners_);
550 PotentiallyAddListenerTo(kMethodExited,
551 events,
552 method_exit_listeners_,
553 listener,
554 &have_method_exit_listeners_);
555 PotentiallyAddListenerTo(kMethodUnwind,
556 events,
557 method_unwind_listeners_,
558 listener,
559 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000560 PotentiallyAddListenerTo(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000561 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000562 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000563 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000564 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000565 PotentiallyAddListenerTo(kDexPcMoved,
566 events,
567 dex_pc_listeners_,
568 listener,
569 &have_dex_pc_listeners_);
570 PotentiallyAddListenerTo(kFieldRead,
571 events,
572 field_read_listeners_,
573 listener,
574 &have_field_read_listeners_);
575 PotentiallyAddListenerTo(kFieldWritten,
576 events,
577 field_write_listeners_,
578 listener,
579 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700580 PotentiallyAddListenerTo(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000581 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700582 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000583 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700584 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700585 PotentiallyAddListenerTo(kWatchedFramePop,
586 events,
587 watched_frame_pop_listeners_,
588 listener,
589 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700590 PotentiallyAddListenerTo(kExceptionHandled,
591 events,
592 exception_handled_listeners_,
593 listener,
594 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200595 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800596}
597
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000598static void PotentiallyRemoveListenerFrom(Instrumentation::InstrumentationEvent event,
599 uint32_t events,
600 std::list<InstrumentationListener*>& list,
601 InstrumentationListener* listener,
602 bool* has_listener)
603 REQUIRES(Locks::mutator_lock_, !Locks::thread_list_lock_, !Locks::classlinker_classes_lock_) {
604 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
605 if (!HasEvent(event, events)) {
606 return;
607 }
608 auto it = std::find(list.begin(), list.end(), listener);
609 if (it != list.end()) {
610 // Just update the entry, do not remove from the list. Removing entries in the list
611 // is unsafe when mutators are iterating over it.
612 *it = nullptr;
613 }
614
615 // Check if the list contains any non-null listener, and update 'has_listener'.
616 for (InstrumentationListener* l : list) {
617 if (l != nullptr) {
David Srbecky28f6cff2018-10-16 15:07:28 +0100618 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = true; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000619 return;
620 }
621 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100622 Runtime::DoAndMaybeSwitchInterpreter([=](){ *has_listener = false; });
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000623}
624
Ian Rogers62d6c772013-02-27 08:32:07 -0800625void Instrumentation::RemoveListener(InstrumentationListener* listener, uint32_t events) {
626 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000627 PotentiallyRemoveListenerFrom(kMethodEntered,
628 events,
629 method_entry_listeners_,
630 listener,
631 &have_method_entry_listeners_);
632 PotentiallyRemoveListenerFrom(kMethodExited,
633 events,
634 method_exit_listeners_,
635 listener,
636 &have_method_exit_listeners_);
637 PotentiallyRemoveListenerFrom(kMethodUnwind,
638 events,
639 method_unwind_listeners_,
640 listener,
641 &have_method_unwind_listeners_);
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000642 PotentiallyRemoveListenerFrom(kBranch,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000643 events,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000644 branch_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000645 listener,
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000646 &have_branch_listeners_);
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000647 PotentiallyRemoveListenerFrom(kDexPcMoved,
648 events,
649 dex_pc_listeners_,
650 listener,
651 &have_dex_pc_listeners_);
652 PotentiallyRemoveListenerFrom(kFieldRead,
653 events,
654 field_read_listeners_,
655 listener,
656 &have_field_read_listeners_);
657 PotentiallyRemoveListenerFrom(kFieldWritten,
658 events,
659 field_write_listeners_,
660 listener,
661 &have_field_write_listeners_);
Alex Light6e1607e2017-08-23 10:06:18 -0700662 PotentiallyRemoveListenerFrom(kExceptionThrown,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000663 events,
Alex Light6e1607e2017-08-23 10:06:18 -0700664 exception_thrown_listeners_,
Nicolas Geoffray514a6162015-11-03 11:44:24 +0000665 listener,
Alex Light6e1607e2017-08-23 10:06:18 -0700666 &have_exception_thrown_listeners_);
Alex Lighte814f9d2017-07-31 16:14:39 -0700667 PotentiallyRemoveListenerFrom(kWatchedFramePop,
668 events,
669 watched_frame_pop_listeners_,
670 listener,
671 &have_watched_frame_pop_listeners_);
Alex Light9fb1ab12017-09-05 09:32:49 -0700672 PotentiallyRemoveListenerFrom(kExceptionHandled,
673 events,
674 exception_handled_listeners_,
675 listener,
676 &have_exception_handled_listeners_);
Sebastien Hertzee1997a2013-09-19 14:47:09 +0200677 UpdateInterpreterHandlerTable();
jeffhao725a9572012-11-13 18:20:12 -0800678}
679
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200680Instrumentation::InstrumentationLevel Instrumentation::GetCurrentInstrumentationLevel() const {
Alex Light4ba388a2017-01-27 10:26:49 -0800681 if (interpreter_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200682 return InstrumentationLevel::kInstrumentWithInterpreter;
Ian Rogers62d6c772013-02-27 08:32:07 -0800683 } else if (entry_exit_stubs_installed_) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200684 return InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Ian Rogers62d6c772013-02-27 08:32:07 -0800685 } else {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200686 return InstrumentationLevel::kInstrumentNothing;
Ian Rogers62d6c772013-02-27 08:32:07 -0800687 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200688}
689
Alex Lightdba61482016-12-21 08:20:29 -0800690bool Instrumentation::RequiresInstrumentationInstallation(InstrumentationLevel new_level) const {
Alex Light4ba388a2017-01-27 10:26:49 -0800691 // We need to reinstall instrumentation if we go to a different level.
692 return GetCurrentInstrumentationLevel() != new_level;
Alex Lightdba61482016-12-21 08:20:29 -0800693}
694
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200695void Instrumentation::ConfigureStubs(const char* key, InstrumentationLevel desired_level) {
696 // Store the instrumentation level for this key or remove it.
697 if (desired_level == InstrumentationLevel::kInstrumentNothing) {
698 // The client no longer needs instrumentation.
699 requested_instrumentation_levels_.erase(key);
700 } else {
701 // The client needs instrumentation.
702 requested_instrumentation_levels_.Overwrite(key, desired_level);
703 }
704
705 // Look for the highest required instrumentation level.
706 InstrumentationLevel requested_level = InstrumentationLevel::kInstrumentNothing;
707 for (const auto& v : requested_instrumentation_levels_) {
708 requested_level = std::max(requested_level, v.second);
709 }
710
711 interpret_only_ = (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) ||
712 forced_interpret_only_;
713
Alex Lightdba61482016-12-21 08:20:29 -0800714 if (!RequiresInstrumentationInstallation(requested_level)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800715 // We're already set.
716 return;
717 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100718 Thread* const self = Thread::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800719 Runtime* runtime = Runtime::Current();
Sebastien Hertza8a697f2015-01-15 12:28:47 +0100720 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800721 Locks::thread_list_lock_->AssertNotHeld(self);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200722 if (requested_level > InstrumentationLevel::kInstrumentNothing) {
Alex Light4ba388a2017-01-27 10:26:49 -0800723 if (requested_level == InstrumentationLevel::kInstrumentWithInterpreter) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800724 interpreter_stubs_installed_ = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800725 entry_exit_stubs_installed_ = true;
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200726 } else {
727 CHECK_EQ(requested_level, InstrumentationLevel::kInstrumentWithInstrumentationStubs);
728 entry_exit_stubs_installed_ = true;
729 interpreter_stubs_installed_ = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800730 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700731 InstallStubsClassVisitor visitor(this);
732 runtime->GetClassLinker()->VisitClasses(&visitor);
Ian Rogers62d6c772013-02-27 08:32:07 -0800733 instrumentation_stubs_installed_ = true;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100734 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800735 runtime->GetThreadList()->ForEach(InstrumentationInstallStack, this);
736 } else {
737 interpreter_stubs_installed_ = false;
738 entry_exit_stubs_installed_ = false;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700739 InstallStubsClassVisitor visitor(this);
740 runtime->GetClassLinker()->VisitClasses(&visitor);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100741 // Restore stack only if there is no method currently deoptimized.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700742 bool empty;
743 {
744 ReaderMutexLock mu(self, deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700745 empty = IsDeoptimizedMethodsEmpty(); // Avoid lock violation.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700746 }
747 if (empty) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100748 MutexLock mu(self, *Locks::thread_list_lock_);
749 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000750 // Only do this after restoring, as walking the stack when restoring will see
751 // the instrumentation exit pc.
752 instrumentation_stubs_installed_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100753 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800754 }
jeffhao725a9572012-11-13 18:20:12 -0800755}
756
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200757static void ResetQuickAllocEntryPointsForThread(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -0800758 thread->ResetQuickAllocEntryPointsForThread(kUseReadBarrier && thread->GetIsGcMarking());
Ian Rogersfa824272013-11-05 16:12:57 -0800759}
760
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700761void Instrumentation::SetEntrypointsInstrumented(bool instrumented) {
762 Thread* self = Thread::Current();
Mathieu Chartier661974a2014-01-09 11:23:53 -0800763 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700764 Locks::mutator_lock_->AssertNotHeld(self);
765 Locks::instrument_entrypoints_lock_->AssertHeld(self);
766 if (runtime->IsStarted()) {
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700767 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700768 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier661974a2014-01-09 11:23:53 -0800769 SetQuickAllocEntryPointsInstrumented(instrumented);
770 ResetQuickAllocEntryPoints();
Mathieu Chartier50e93312016-03-16 11:25:29 -0700771 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700772 } else {
773 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
774 SetQuickAllocEntryPointsInstrumented(instrumented);
Andreas Gampe157c77e2016-10-17 17:44:41 -0700775
776 // Note: ResetQuickAllocEntryPoints only works when the runtime is started. Manually run the
777 // update for just this thread.
Andreas Gampe162ae502016-10-18 10:03:42 -0700778 // Note: self may be null. One of those paths is setting instrumentation in the Heap
779 // constructor for gcstress mode.
780 if (self != nullptr) {
781 ResetQuickAllocEntryPointsForThread(self, nullptr);
782 }
Andreas Gampe157c77e2016-10-17 17:44:41 -0700783
Mathieu Chartier50e93312016-03-16 11:25:29 -0700784 alloc_entrypoints_instrumented_ = instrumented;
Mathieu Chartier661974a2014-01-09 11:23:53 -0800785 }
786}
787
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700788void Instrumentation::InstrumentQuickAllocEntryPoints() {
789 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
790 InstrumentQuickAllocEntryPointsLocked();
Ian Rogersfa824272013-11-05 16:12:57 -0800791}
792
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700793void Instrumentation::UninstrumentQuickAllocEntryPoints() {
794 MutexLock mu(Thread::Current(), *Locks::instrument_entrypoints_lock_);
795 UninstrumentQuickAllocEntryPointsLocked();
796}
797
798void Instrumentation::InstrumentQuickAllocEntryPointsLocked() {
799 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
800 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
801 SetEntrypointsInstrumented(true);
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800802 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700803 ++quick_alloc_entry_points_instrumentation_counter_;
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700804}
805
806void Instrumentation::UninstrumentQuickAllocEntryPointsLocked() {
807 Locks::instrument_entrypoints_lock_->AssertHeld(Thread::Current());
808 CHECK_GT(quick_alloc_entry_points_instrumentation_counter_, 0U);
809 --quick_alloc_entry_points_instrumentation_counter_;
810 if (quick_alloc_entry_points_instrumentation_counter_ == 0) {
811 SetEntrypointsInstrumented(false);
812 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800813}
814
815void Instrumentation::ResetQuickAllocEntryPoints() {
816 Runtime* runtime = Runtime::Current();
817 if (runtime->IsStarted()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800818 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700819 runtime->GetThreadList()->ForEach(ResetQuickAllocEntryPointsForThread, nullptr);
Ian Rogersfa824272013-11-05 16:12:57 -0800820 }
821}
822
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700823void Instrumentation::UpdateMethodsCodeImpl(ArtMethod* method, const void* quick_code) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800824 const void* new_quick_code;
Ian Rogers62d6c772013-02-27 08:32:07 -0800825 if (LIKELY(!instrumentation_stubs_installed_)) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800826 new_quick_code = quick_code;
Jeff Hao65d15d92013-07-16 16:39:33 -0700827 } else {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100828 if ((interpreter_stubs_installed_ || IsDeoptimized(method)) && !method->IsNative()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800829 new_quick_code = GetQuickToInterpreterBridge();
Jeff Hao65d15d92013-07-16 16:39:33 -0700830 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700831 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700832 if (class_linker->IsQuickResolutionStub(quick_code) ||
833 class_linker->IsQuickToInterpreterBridge(quick_code)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700834 new_quick_code = quick_code;
Alex Light6cae5ea2018-06-07 17:07:02 -0700835 } else if (entry_exit_stubs_installed_ &&
836 // We need to make sure not to replace anything that InstallStubsForMethod
837 // wouldn't. Specifically we cannot stub out Proxy.<init> since subtypes copy the
838 // implementation directly and this will confuse the instrumentation trampolines.
839 // TODO We should remove the need for this since it makes it impossible to profile
840 // Proxy.<init> correctly in all cases.
841 method != jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700842 new_quick_code = GetQuickInstrumentationEntryPoint();
Alex Light2d441b12018-06-08 15:33:21 -0700843 if (!method->IsNative() && Runtime::Current()->GetJit() != nullptr) {
844 // Native methods use trampoline entrypoints during interpreter tracing.
845 DCHECK(!Runtime::Current()->GetJit()->GetCodeCache()->GetGarbageCollectCode());
846 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
847 // Tracing will look at the saved entry point in the profiling info to know the actual
848 // entrypoint, so we store it here.
849 if (profiling_info != nullptr) {
850 profiling_info->SetSavedEntryPoint(quick_code);
851 }
852 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700853 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700854 new_quick_code = quick_code;
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700855 }
Jeff Hao65d15d92013-07-16 16:39:33 -0700856 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800857 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800858 UpdateEntrypoints(method, new_quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100859}
860
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +0000861void Instrumentation::UpdateNativeMethodsCodeToJitCode(ArtMethod* method, const void* quick_code) {
862 // We don't do any read barrier on `method`'s declaring class in this code, as the JIT might
863 // enter here on a soon-to-be deleted ArtMethod. Updating the entrypoint is OK though, as
864 // the ArtMethod is still in memory.
865 const void* new_quick_code = quick_code;
866 if (UNLIKELY(instrumentation_stubs_installed_) && entry_exit_stubs_installed_) {
867 new_quick_code = GetQuickInstrumentationEntryPoint();
868 }
869 UpdateEntrypoints(method, new_quick_code);
870}
871
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700872void Instrumentation::UpdateMethodsCode(ArtMethod* method, const void* quick_code) {
873 DCHECK(method->GetDeclaringClass()->IsResolved());
874 UpdateMethodsCodeImpl(method, quick_code);
875}
876
Alex Light0a5ec3d2017-07-25 16:50:26 -0700877void Instrumentation::UpdateMethodsCodeToInterpreterEntryPoint(ArtMethod* method) {
878 UpdateMethodsCodeImpl(method, GetQuickToInterpreterBridge());
879}
880
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000881void Instrumentation::UpdateMethodsCodeForJavaDebuggable(ArtMethod* method,
882 const void* quick_code) {
883 // When the runtime is set to Java debuggable, we may update the entry points of
884 // all methods of a class to the interpreter bridge. A method's declaring class
885 // might not be in resolved state yet in that case, so we bypass the DCHECK in
886 // UpdateMethodsCode.
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700887 UpdateMethodsCodeImpl(method, quick_code);
888}
889
Mathieu Chartiere401d142015-04-22 13:56:20 -0700890bool Instrumentation::AddDeoptimizedMethod(ArtMethod* method) {
891 if (IsDeoptimizedMethod(method)) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700892 // Already in the map. Return.
893 return false;
894 }
895 // Not found. Add it.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700896 deoptimized_methods_.insert(method);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700897 return true;
898}
899
Mathieu Chartiere401d142015-04-22 13:56:20 -0700900bool Instrumentation::IsDeoptimizedMethod(ArtMethod* method) {
901 return deoptimized_methods_.find(method) != deoptimized_methods_.end();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700902}
903
Mathieu Chartiere401d142015-04-22 13:56:20 -0700904ArtMethod* Instrumentation::BeginDeoptimizedMethod() {
905 if (deoptimized_methods_.empty()) {
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700906 // Empty.
907 return nullptr;
908 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700909 return *deoptimized_methods_.begin();
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700910}
911
Mathieu Chartiere401d142015-04-22 13:56:20 -0700912bool Instrumentation::RemoveDeoptimizedMethod(ArtMethod* method) {
913 auto it = deoptimized_methods_.find(method);
914 if (it == deoptimized_methods_.end()) {
915 return false;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700916 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700917 deoptimized_methods_.erase(it);
918 return true;
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700919}
920
921bool Instrumentation::IsDeoptimizedMethodsEmpty() const {
922 return deoptimized_methods_.empty();
923}
924
Mathieu Chartiere401d142015-04-22 13:56:20 -0700925void Instrumentation::Deoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100926 CHECK(!method->IsNative());
927 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700928 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100929
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700930 Thread* self = Thread::Current();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700931 {
932 WriterMutexLock mu(self, deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700933 bool has_not_been_deoptimized = AddDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700934 CHECK(has_not_been_deoptimized) << "Method " << ArtMethod::PrettyMethod(method)
Daniel Mihalyica1d06c2014-08-18 18:45:31 +0200935 << " is already deoptimized";
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700936 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100937 if (!interpreter_stubs_installed_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800938 UpdateEntrypoints(method, GetQuickInstrumentationEntryPoint());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100939
940 // Install instrumentation exit stub and instrumentation frames. We may already have installed
941 // these previously so it will only cover the newly created frames.
942 instrumentation_stubs_installed_ = true;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700943 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100944 Runtime::Current()->GetThreadList()->ForEach(InstrumentationInstallStack, this);
945 }
946}
947
Mathieu Chartiere401d142015-04-22 13:56:20 -0700948void Instrumentation::Undeoptimize(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100949 CHECK(!method->IsNative());
950 CHECK(!method->IsProxyMethod());
Alex Light9139e002015-10-09 15:59:48 -0700951 CHECK(method->IsInvokable());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100952
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700953 Thread* self = Thread::Current();
954 bool empty;
955 {
956 WriterMutexLock mu(self, deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700957 bool found_and_erased = RemoveDeoptimizedMethod(method);
David Sehr709b0702016-10-13 09:12:37 -0700958 CHECK(found_and_erased) << "Method " << ArtMethod::PrettyMethod(method)
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700959 << " is not deoptimized";
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700960 empty = IsDeoptimizedMethodsEmpty();
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700961 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100962
963 // Restore code and possibly stack only if we did not deoptimize everything.
964 if (!interpreter_stubs_installed_) {
965 // Restore its code or resolution trampoline.
966 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800967 if (method->IsStatic() && !method->IsConstructor() &&
968 !method->GetDeclaringClass()->IsInitialized()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800969 UpdateEntrypoints(method, GetQuickResolutionStub());
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100970 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +0000971 const void* quick_code = NeedDebugVersionFor(method)
972 ? GetQuickToInterpreterBridge()
Alex Lightfc49fec2018-01-16 22:28:36 +0000973 : class_linker->GetQuickOatCodeFor(method);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800974 UpdateEntrypoints(method, quick_code);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100975 }
976
977 // If there is no deoptimized method left, we can restore the stack of each thread.
Alex Lightf244a572018-06-08 13:56:51 -0700978 if (empty && !entry_exit_stubs_installed_) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700979 MutexLock mu(self, *Locks::thread_list_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100980 Runtime::Current()->GetThreadList()->ForEach(InstrumentationRestoreStack, this);
981 instrumentation_stubs_installed_ = false;
982 }
983 }
984}
985
Mathieu Chartiere401d142015-04-22 13:56:20 -0700986bool Instrumentation::IsDeoptimized(ArtMethod* method) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100987 DCHECK(method != nullptr);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700988 ReaderMutexLock mu(Thread::Current(), deoptimized_methods_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700989 return IsDeoptimizedMethod(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100990}
991
992void Instrumentation::EnableDeoptimization() {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700993 ReaderMutexLock mu(Thread::Current(), deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -0700994 CHECK(IsDeoptimizedMethodsEmpty());
Sebastien Hertz11d40c22014-02-19 18:00:17 +0100995 CHECK_EQ(deoptimization_enabled_, false);
996 deoptimization_enabled_ = true;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100997}
998
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200999void Instrumentation::DisableDeoptimization(const char* key) {
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001000 CHECK_EQ(deoptimization_enabled_, true);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001001 // If we deoptimized everything, undo it.
Alex Lightdba61482016-12-21 08:20:29 -08001002 InstrumentationLevel level = GetCurrentInstrumentationLevel();
1003 if (level == InstrumentationLevel::kInstrumentWithInterpreter) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001004 UndeoptimizeEverything(key);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001005 }
1006 // Undeoptimized selected methods.
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001007 while (true) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001008 ArtMethod* method;
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001009 {
1010 ReaderMutexLock mu(Thread::Current(), deoptimized_methods_lock_);
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001011 if (IsDeoptimizedMethodsEmpty()) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001012 break;
1013 }
Hiroshi Yamauchi799eb3a2014-07-18 15:38:17 -07001014 method = BeginDeoptimizedMethod();
1015 CHECK(method != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001016 }
1017 Undeoptimize(method);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001018 }
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001019 deoptimization_enabled_ = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001020}
1021
Sebastien Hertz11d40c22014-02-19 18:00:17 +01001022// Indicates if instrumentation should notify method enter/exit events to the listeners.
1023bool Instrumentation::ShouldNotifyMethodEnterExitEvents() const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001024 if (!HasMethodEntryListeners() && !HasMethodExitListeners()) {
1025 return false;
1026 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01001027 return !deoptimization_enabled_ && !interpreter_stubs_installed_;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001028}
1029
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001030void Instrumentation::DeoptimizeEverything(const char* key) {
1031 CHECK(deoptimization_enabled_);
1032 ConfigureStubs(key, InstrumentationLevel::kInstrumentWithInterpreter);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001033}
1034
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001035void Instrumentation::UndeoptimizeEverything(const char* key) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001036 CHECK(interpreter_stubs_installed_);
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001037 CHECK(deoptimization_enabled_);
1038 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001039}
1040
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001041void Instrumentation::EnableMethodTracing(const char* key, bool needs_interpreter) {
1042 InstrumentationLevel level;
1043 if (needs_interpreter) {
1044 level = InstrumentationLevel::kInstrumentWithInterpreter;
1045 } else {
1046 level = InstrumentationLevel::kInstrumentWithInstrumentationStubs;
Alex Light2d441b12018-06-08 15:33:21 -07001047 if (Runtime::Current()->GetJit() != nullptr) {
1048 // TODO b/110263880 It would be better if we didn't need to do this.
1049 // Since we need to hold the method entrypoint across a suspend to ensure instrumentation
1050 // hooks are called correctly we have to disable jit-gc to ensure that the entrypoint doesn't
1051 // go away. Furthermore we need to leave this off permanently since one could get the same
1052 // effect by causing this to be toggled on and off.
1053 Runtime::Current()->GetJit()->GetCodeCache()->SetGarbageCollectCode(false);
1054 }
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001055 }
1056 ConfigureStubs(key, level);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001057}
1058
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001059void Instrumentation::DisableMethodTracing(const char* key) {
1060 ConfigureStubs(key, InstrumentationLevel::kInstrumentNothing);
jeffhao725a9572012-11-13 18:20:12 -08001061}
1062
Alex Light2d441b12018-06-08 15:33:21 -07001063const void* Instrumentation::GetCodeForInvoke(ArtMethod* method) const {
1064 // This is called by instrumentation entry only and that should never be getting proxy methods.
1065 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
1066 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1067 if (LIKELY(!instrumentation_stubs_installed_ && !interpreter_stubs_installed_)) {
1068 // In general we just return whatever the method thinks its entrypoint is here. The only
1069 // exception is if it still has the instrumentation entrypoint. That means we are racing another
1070 // thread getting rid of instrumentation which is unexpected but possible. In that case we want
1071 // to wait and try to get it from the oat file or jit.
1072 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(kRuntimePointerSize);
1073 DCHECK(code != nullptr);
1074 if (code != GetQuickInstrumentationEntryPoint()) {
1075 return code;
1076 } else if (method->IsNative()) {
1077 return class_linker->GetQuickOatCodeFor(method);
1078 }
1079 // We don't know what it is. Fallthough to try to find the code from the JIT or Oat file.
1080 } else if (method->IsNative()) {
1081 // TODO We could have JIT compiled native entrypoints. It might be worth it to find these.
1082 return class_linker->GetQuickOatCodeFor(method);
1083 } else if (UNLIKELY(interpreter_stubs_installed_)) {
1084 return GetQuickToInterpreterBridge();
1085 }
1086 // Since the method cannot be native due to ifs above we can always fall back to interpreter
1087 // bridge.
1088 const void* result = GetQuickToInterpreterBridge();
1089 if (!NeedDebugVersionFor(method)) {
1090 // If we don't need a debug version we should see what the oat file/class linker has to say.
1091 result = class_linker->GetQuickOatCodeFor(method);
1092 }
1093 // If both those fail try the jit.
1094 if (result == GetQuickToInterpreterBridge()) {
1095 jit::Jit* jit = Runtime::Current()->GetJit();
1096 if (jit != nullptr) {
1097 const void* res = jit->GetCodeCache()->FindCompiledCodeForInstrumentation(method);
1098 if (res != nullptr) {
1099 result = res;
1100 }
1101 }
1102 }
1103 return result;
1104}
1105
Andreas Gampe542451c2016-07-26 09:02:02 -07001106const void* Instrumentation::GetQuickCodeFor(ArtMethod* method, PointerSize pointer_size) const {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001107 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers62d6c772013-02-27 08:32:07 -08001108 if (LIKELY(!instrumentation_stubs_installed_)) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08001109 const void* code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size);
Vladimir Marko8a630572014-04-09 18:45:35 +01001110 DCHECK(code != nullptr);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001111 if (LIKELY(!class_linker->IsQuickResolutionStub(code) &&
1112 !class_linker->IsQuickToInterpreterBridge(code)) &&
1113 !class_linker->IsQuickResolutionStub(code) &&
1114 !class_linker->IsQuickToInterpreterBridge(code)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001115 return code;
1116 }
1117 }
Alex Lightfc49fec2018-01-16 22:28:36 +00001118 return class_linker->GetQuickOatCodeFor(method);
jeffhao725a9572012-11-13 18:20:12 -08001119}
1120
Alex Lightd7661582017-05-01 13:48:16 -07001121void Instrumentation::MethodEnterEventImpl(Thread* thread,
1122 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001123 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001124 uint32_t dex_pc) const {
Mingyao Yang2ee17902017-08-30 11:37:08 -07001125 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001126 if (HasMethodEntryListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001127 Thread* self = Thread::Current();
1128 StackHandleScope<1> hs(self);
1129 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001130 for (InstrumentationListener* listener : method_entry_listeners_) {
1131 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001132 listener->MethodEntered(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001133 }
1134 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001135 }
1136}
1137
Alex Lightd7661582017-05-01 13:48:16 -07001138void Instrumentation::MethodExitEventImpl(Thread* thread,
1139 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001140 ArtMethod* method,
Alex Lightd7661582017-05-01 13:48:16 -07001141 uint32_t dex_pc,
1142 const JValue& return_value) const {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001143 if (HasMethodExitListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001144 Thread* self = Thread::Current();
1145 StackHandleScope<2> hs(self);
1146 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1147 if (method->GetInterfaceMethodIfProxy(kRuntimePointerSize)
1148 ->GetReturnTypePrimitive() != Primitive::kPrimNot) {
1149 for (InstrumentationListener* listener : method_exit_listeners_) {
1150 if (listener != nullptr) {
1151 listener->MethodExited(thread, thiz, method, dex_pc, return_value);
1152 }
1153 }
1154 } else {
1155 Handle<mirror::Object> ret(hs.NewHandle(return_value.GetL()));
1156 for (InstrumentationListener* listener : method_exit_listeners_) {
1157 if (listener != nullptr) {
1158 listener->MethodExited(thread, thiz, method, dex_pc, ret);
1159 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001160 }
1161 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001162 }
1163}
1164
Alex Lightd7661582017-05-01 13:48:16 -07001165void Instrumentation::MethodUnwindEvent(Thread* thread,
1166 mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001167 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001168 uint32_t dex_pc) const {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02001169 if (HasMethodUnwindListeners()) {
Alex Lightd7661582017-05-01 13:48:16 -07001170 Thread* self = Thread::Current();
1171 StackHandleScope<1> hs(self);
1172 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Mathieu Chartier02e25112013-08-14 16:14:24 -07001173 for (InstrumentationListener* listener : method_unwind_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001174 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001175 listener->MethodUnwind(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001176 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001177 }
1178 }
1179}
1180
Alex Lightd7661582017-05-01 13:48:16 -07001181void Instrumentation::DexPcMovedEventImpl(Thread* thread,
1182 ObjPtr<mirror::Object> this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001183 ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -08001184 uint32_t dex_pc) const {
Alex Lightd7661582017-05-01 13:48:16 -07001185 Thread* self = Thread::Current();
1186 StackHandleScope<1> hs(self);
1187 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001188 for (InstrumentationListener* listener : dex_pc_listeners_) {
1189 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001190 listener->DexPcMoved(thread, thiz, method, dex_pc);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001191 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001192 }
1193}
1194
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001195void Instrumentation::BranchImpl(Thread* thread,
1196 ArtMethod* method,
1197 uint32_t dex_pc,
1198 int32_t offset) const {
1199 for (InstrumentationListener* listener : branch_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001200 if (listener != nullptr) {
Nicolas Geoffray81f0f952016-01-20 16:25:19 +00001201 listener->Branch(thread, method, dex_pc, offset);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001202 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001203 }
1204}
1205
Alex Lighte814f9d2017-07-31 16:14:39 -07001206void Instrumentation::WatchedFramePopImpl(Thread* thread, const ShadowFrame& frame) const {
1207 for (InstrumentationListener* listener : watched_frame_pop_listeners_) {
1208 if (listener != nullptr) {
1209 listener->WatchedFramePop(thread, frame);
1210 }
1211 }
1212}
1213
Alex Lightd7661582017-05-01 13:48:16 -07001214void Instrumentation::FieldReadEventImpl(Thread* thread,
1215 ObjPtr<mirror::Object> this_object,
1216 ArtMethod* method,
1217 uint32_t dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001218 ArtField* field) const {
Alex Lightd7661582017-05-01 13:48:16 -07001219 Thread* self = Thread::Current();
1220 StackHandleScope<1> hs(self);
1221 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001222 for (InstrumentationListener* listener : field_read_listeners_) {
1223 if (listener != nullptr) {
Alex Lightd7661582017-05-01 13:48:16 -07001224 listener->FieldRead(thread, thiz, method, dex_pc, field);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001225 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001226 }
1227}
1228
Alex Lightd7661582017-05-01 13:48:16 -07001229void Instrumentation::FieldWriteEventImpl(Thread* thread,
1230 ObjPtr<mirror::Object> this_object,
1231 ArtMethod* method,
1232 uint32_t dex_pc,
1233 ArtField* field,
1234 const JValue& field_value) const {
1235 Thread* self = Thread::Current();
1236 StackHandleScope<2> hs(self);
1237 Handle<mirror::Object> thiz(hs.NewHandle(this_object));
1238 if (field->IsPrimitiveType()) {
1239 for (InstrumentationListener* listener : field_write_listeners_) {
1240 if (listener != nullptr) {
1241 listener->FieldWritten(thread, thiz, method, dex_pc, field, field_value);
1242 }
1243 }
1244 } else {
1245 Handle<mirror::Object> val(hs.NewHandle(field_value.GetL()));
1246 for (InstrumentationListener* listener : field_write_listeners_) {
1247 if (listener != nullptr) {
1248 listener->FieldWritten(thread, thiz, method, dex_pc, field, val);
1249 }
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001250 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001251 }
1252}
1253
Alex Light6e1607e2017-08-23 10:06:18 -07001254void Instrumentation::ExceptionThrownEvent(Thread* thread,
Sebastien Hertz947ff082013-09-17 14:10:13 +02001255 mirror::Throwable* exception_object) const {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001256 Thread* self = Thread::Current();
1257 StackHandleScope<1> hs(self);
1258 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
Alex Light6e1607e2017-08-23 10:06:18 -07001259 if (HasExceptionThrownListeners()) {
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001260 DCHECK_EQ(thread->GetException(), h_exception.Get());
Jeff Haoc0bd4da2013-04-11 15:52:28 -07001261 thread->ClearException();
Alex Light6e1607e2017-08-23 10:06:18 -07001262 for (InstrumentationListener* listener : exception_thrown_listeners_) {
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001263 if (listener != nullptr) {
Alex Light6e1607e2017-08-23 10:06:18 -07001264 listener->ExceptionThrown(thread, h_exception);
Nicolas Geoffray514a6162015-11-03 11:44:24 +00001265 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001266 }
Alex Light9fb1ab12017-09-05 09:32:49 -07001267 // See b/65049545 for discussion about this behavior.
1268 thread->AssertNoPendingException();
Hiroshi Yamauchi3481f7a2017-02-10 12:07:36 -08001269 thread->SetException(h_exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08001270 }
1271}
1272
Alex Light9fb1ab12017-09-05 09:32:49 -07001273void Instrumentation::ExceptionHandledEvent(Thread* thread,
1274 mirror::Throwable* exception_object) const {
1275 Thread* self = Thread::Current();
1276 StackHandleScope<1> hs(self);
1277 Handle<mirror::Throwable> h_exception(hs.NewHandle(exception_object));
1278 if (HasExceptionHandledListeners()) {
1279 // We should have cleared the exception so that callers can detect a new one.
1280 DCHECK(thread->GetException() == nullptr);
1281 for (InstrumentationListener* listener : exception_handled_listeners_) {
1282 if (listener != nullptr) {
1283 listener->ExceptionHandled(thread, h_exception);
1284 }
1285 }
1286 }
1287}
1288
Sebastien Hertzb2feaaf2015-10-12 13:40:10 +00001289// Computes a frame ID by ignoring inlined frames.
1290size_t Instrumentation::ComputeFrameId(Thread* self,
1291 size_t frame_depth,
1292 size_t inlined_frames_before_frame) {
1293 CHECK_GE(frame_depth, inlined_frames_before_frame);
1294 size_t no_inline_depth = frame_depth - inlined_frames_before_frame;
1295 return StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) - no_inline_depth;
1296}
1297
Ian Rogers62d6c772013-02-27 08:32:07 -08001298static void CheckStackDepth(Thread* self, const InstrumentationStackFrame& instrumentation_frame,
1299 int delta)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001300 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001301 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk) + delta;
Ian Rogers62d6c772013-02-27 08:32:07 -08001302 if (frame_id != instrumentation_frame.frame_id_) {
1303 LOG(ERROR) << "Expected frame_id=" << frame_id << " but found "
1304 << instrumentation_frame.frame_id_;
1305 StackVisitor::DescribeStack(self);
1306 CHECK_EQ(frame_id, instrumentation_frame.frame_id_);
1307 }
1308}
1309
1310void Instrumentation::PushInstrumentationStackFrame(Thread* self, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001311 ArtMethod* method,
Jeff Hao9a916d32013-06-27 18:45:37 -07001312 uintptr_t lr, bool interpreter_entry) {
Alex Lightb7edcda2017-04-27 13:20:31 -07001313 DCHECK(!self->IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001314 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1315 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001316 LOG(INFO) << "Entering " << ArtMethod::PrettyMethod(method) << " from PC "
1317 << reinterpret_cast<void*>(lr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001318 }
Alex Lightb7edcda2017-04-27 13:20:31 -07001319
1320 // We send the enter event before pushing the instrumentation frame to make cleanup easier. If the
1321 // event causes an exception we can simply send the unwind event and return.
1322 StackHandleScope<1> hs(self);
1323 Handle<mirror::Object> h_this(hs.NewHandle(this_object));
1324 if (!interpreter_entry) {
1325 MethodEnterEvent(self, h_this.Get(), method, 0);
1326 if (self->IsExceptionPending()) {
1327 MethodUnwindEvent(self, h_this.Get(), method, 0);
1328 return;
1329 }
1330 }
1331
1332 // We have a callee-save frame meaning this value is guaranteed to never be 0.
1333 DCHECK(!self->IsExceptionPending());
1334 size_t frame_id = StackVisitor::ComputeNumFrames(self, kInstrumentationStackWalk);
1335
1336 instrumentation::InstrumentationStackFrame instrumentation_frame(h_this.Get(), method, lr,
Jeff Hao9a916d32013-06-27 18:45:37 -07001337 frame_id, interpreter_entry);
Ian Rogers62d6c772013-02-27 08:32:07 -08001338 stack->push_front(instrumentation_frame);
Ian Rogers62d6c772013-02-27 08:32:07 -08001339}
1340
Mingyao Yang2ee17902017-08-30 11:37:08 -07001341DeoptimizationMethodType Instrumentation::GetDeoptimizationMethodType(ArtMethod* method) {
1342 if (method->IsRuntimeMethod()) {
1343 // Certain methods have strict requirement on whether the dex instruction
1344 // should be re-executed upon deoptimization.
1345 if (method == Runtime::Current()->GetCalleeSaveMethod(
1346 CalleeSaveType::kSaveEverythingForClinit)) {
1347 return DeoptimizationMethodType::kKeepDexPc;
1348 }
1349 if (method == Runtime::Current()->GetCalleeSaveMethod(
1350 CalleeSaveType::kSaveEverythingForSuspendCheck)) {
1351 return DeoptimizationMethodType::kKeepDexPc;
1352 }
1353 }
1354 return DeoptimizationMethodType::kDefault;
1355}
1356
1357// Try to get the shorty of a runtime method if it's an invocation stub.
Andreas Gampe82484902018-11-16 00:47:49 +00001358struct RuntimeMethodShortyVisitor : public StackVisitor {
1359 explicit RuntimeMethodShortyVisitor(Thread* thread)
1360 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
1361 shorty('V') {}
1362
1363 static uint16_t GetMethodIndexOfInvoke(ArtMethod* caller,
1364 const Instruction& inst,
1365 uint32_t dex_pc)
1366 REQUIRES_SHARED(Locks::mutator_lock_) {
1367 switch (inst.Opcode()) {
1368 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
1369 case Instruction::INVOKE_VIRTUAL_QUICK: {
1370 uint16_t method_idx = caller->GetIndexFromQuickening(dex_pc);
1371 CHECK_NE(method_idx, DexFile::kDexNoIndex16);
1372 return method_idx;
1373 }
1374 default: {
1375 return inst.VRegB();
1376 }
1377 }
1378 }
1379
1380 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
1381 ArtMethod* m = GetMethod();
1382 if (m == nullptr || m->IsRuntimeMethod()) {
1383 return true;
1384 }
1385 // The first Java method.
1386 if (m->IsNative()) {
1387 // Use JNI method's shorty for the jni stub.
1388 shorty = m->GetShorty()[0];
1389 } else if (m->IsProxyMethod()) {
1390 // Proxy method just invokes its proxied method via
1391 // art_quick_proxy_invoke_handler.
1392 shorty = m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty()[0];
1393 } else {
1394 const Instruction& instr = m->DexInstructions().InstructionAt(GetDexPc());
1395 if (instr.IsInvoke()) {
1396 uint16_t method_index = GetMethodIndexOfInvoke(m, instr, 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];
Mingyao Yang2ee17902017-08-30 11:37:08 -07001404 }
Andreas Gampe82484902018-11-16 00:47:49 +00001405 } else {
1406 // It could be that a non-invoke opcode invokes a stub, which in turn
1407 // invokes Java code. In such cases, we should never expect a return
1408 // value from the stub.
1409 }
1410 }
1411 // Stop stack walking since we've seen a Java frame.
1412 return false;
1413 }
1414
1415 char shorty;
1416};
Mingyao Yang2ee17902017-08-30 11:37:08 -07001417
Alex Lightb7edcda2017-04-27 13:20:31 -07001418TwoWordReturn Instrumentation::PopInstrumentationStackFrame(Thread* self,
1419 uintptr_t* return_pc,
1420 uint64_t* gpr_result,
1421 uint64_t* fpr_result) {
1422 DCHECK(gpr_result != nullptr);
1423 DCHECK(fpr_result != nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -08001424 // Do the pop.
1425 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
1426 CHECK_GT(stack->size(), 0U);
1427 InstrumentationStackFrame instrumentation_frame = stack->front();
1428 stack->pop_front();
1429
1430 // Set return PC and check the sanity of the stack.
1431 *return_pc = instrumentation_frame.return_pc_;
1432 CheckStackDepth(self, instrumentation_frame, 0);
Ian Rogers1d8cdbc2014-09-22 22:51:09 -07001433 self->VerifyStack();
Ian Rogers62d6c772013-02-27 08:32:07 -08001434
Mathieu Chartiere401d142015-04-22 13:56:20 -07001435 ArtMethod* method = instrumentation_frame.method_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001436 uint32_t length;
Andreas Gampe542451c2016-07-26 09:02:02 -07001437 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001438 char return_shorty;
1439
1440 // Runtime method does not call into MethodExitEvent() so there should not be
1441 // suspension point below.
1442 ScopedAssertNoThreadSuspension ants(__FUNCTION__, method->IsRuntimeMethod());
1443 if (method->IsRuntimeMethod()) {
1444 if (method != Runtime::Current()->GetCalleeSaveMethod(
1445 CalleeSaveType::kSaveEverythingForClinit)) {
1446 // If the caller is at an invocation point and the runtime method is not
1447 // for clinit, we need to pass return results to the caller.
1448 // We need the correct shorty to decide whether we need to pass the return
1449 // result for deoptimization below.
Andreas Gampe82484902018-11-16 00:47:49 +00001450 RuntimeMethodShortyVisitor visitor(self);
1451 visitor.WalkStack();
1452 return_shorty = visitor.shorty;
Mingyao Yang2ee17902017-08-30 11:37:08 -07001453 } else {
1454 // Some runtime methods such as allocations, unresolved field getters, etc.
1455 // have return value. We don't need to set return_value since MethodExitEvent()
1456 // below isn't called for runtime methods. Deoptimization doesn't need the
1457 // value either since the dex instruction will be re-executed by the
1458 // interpreter, except these two cases:
1459 // (1) For an invoke, which is handled above to get the correct shorty.
1460 // (2) For MONITOR_ENTER/EXIT, which cannot be re-executed since it's not
1461 // idempotent. However there is no return value for it anyway.
1462 return_shorty = 'V';
1463 }
1464 } else {
1465 return_shorty = method->GetInterfaceMethodIfProxy(pointer_size)->GetShorty(&length)[0];
1466 }
1467
Alex Lightb7edcda2017-04-27 13:20:31 -07001468 bool is_ref = return_shorty == '[' || return_shorty == 'L';
1469 StackHandleScope<1> hs(self);
1470 MutableHandle<mirror::Object> res(hs.NewHandle<mirror::Object>(nullptr));
Ian Rogers62d6c772013-02-27 08:32:07 -08001471 JValue return_value;
1472 if (return_shorty == 'V') {
1473 return_value.SetJ(0);
1474 } else if (return_shorty == 'F' || return_shorty == 'D') {
Alex Lightb7edcda2017-04-27 13:20:31 -07001475 return_value.SetJ(*fpr_result);
Ian Rogers62d6c772013-02-27 08:32:07 -08001476 } else {
Alex Lightb7edcda2017-04-27 13:20:31 -07001477 return_value.SetJ(*gpr_result);
1478 }
1479 if (is_ref) {
1480 // Take a handle to the return value so we won't lose it if we suspend.
1481 res.Assign(return_value.GetL());
Ian Rogers62d6c772013-02-27 08:32:07 -08001482 }
1483 // TODO: improve the dex pc information here, requires knowledge of current PC as opposed to
1484 // return_pc.
Andreas Gampee2abbc62017-09-15 11:59:26 -07001485 uint32_t dex_pc = dex::kDexNoIndex;
Ian Rogers62d6c772013-02-27 08:32:07 -08001486 mirror::Object* this_object = instrumentation_frame.this_object_;
Mingyao Yang2ee17902017-08-30 11:37:08 -07001487 if (!method->IsRuntimeMethod() && !instrumentation_frame.interpreter_entry_) {
Sebastien Hertz320deb22014-06-11 19:45:05 +02001488 MethodExitEvent(self, this_object, instrumentation_frame.method_, dex_pc, return_value);
1489 }
jeffhao725a9572012-11-13 18:20:12 -08001490
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001491 // Deoptimize if the caller needs to continue execution in the interpreter. Do nothing if we get
1492 // back to an upcall.
1493 NthCallerVisitor visitor(self, 1, true);
1494 visitor.WalkStack(true);
Sebastien Hertz270a0e12015-01-16 19:49:09 +01001495 bool deoptimize = (visitor.caller != nullptr) &&
Daniel Mihalyieb076692014-08-22 17:33:31 +02001496 (interpreter_stubs_installed_ || IsDeoptimized(visitor.caller) ||
1497 Dbg::IsForcedInterpreterNeededForUpcall(self, visitor.caller));
Alex Lightb7edcda2017-04-27 13:20:31 -07001498 if (is_ref) {
1499 // Restore the return value if it's a reference since it might have moved.
1500 *reinterpret_cast<mirror::Object**>(gpr_result) = res.Get();
1501 }
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001502 if (deoptimize && Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001503 if (kVerboseInstrumentation) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -08001504 LOG(INFO) << "Deoptimizing "
1505 << visitor.caller->PrettyMethod()
1506 << " by returning from "
1507 << method->PrettyMethod()
1508 << " with result "
1509 << std::hex << return_value.GetJ() << std::dec
1510 << " in "
1511 << *self;
Ian Rogers62d6c772013-02-27 08:32:07 -08001512 }
Mingyao Yang2ee17902017-08-30 11:37:08 -07001513 DeoptimizationMethodType deopt_method_type = GetDeoptimizationMethodType(method);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001514 self->PushDeoptimizationContext(return_value,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001515 return_shorty == 'L' || return_shorty == '[',
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001516 /* exception= */ nullptr ,
1517 /* from_code= */ false,
Mingyao Yang2ee17902017-08-30 11:37:08 -07001518 deopt_method_type);
Andreas Gamped58342c2014-06-05 14:18:08 -07001519 return GetTwoWordSuccessValue(*return_pc,
1520 reinterpret_cast<uintptr_t>(GetQuickDeoptimizationEntryPoint()));
Ian Rogers62d6c772013-02-27 08:32:07 -08001521 } else {
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001522 if (deoptimize && !Runtime::Current()->IsAsyncDeoptimizeable(*return_pc)) {
Alex Lightd8eb6732018-01-29 15:16:02 -08001523 VLOG(deopt) << "Got a deoptimization request on un-deoptimizable " << method->PrettyMethod()
1524 << " at PC " << reinterpret_cast<void*>(*return_pc);
Nicolas Geoffraya0619e22016-12-20 13:57:43 +00001525 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001526 if (kVerboseInstrumentation) {
David Sehr709b0702016-10-13 09:12:37 -07001527 LOG(INFO) << "Returning from " << method->PrettyMethod()
Brian Carlstrom2d888622013-07-18 17:02:00 -07001528 << " to PC " << reinterpret_cast<void*>(*return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001529 }
Andreas Gamped58342c2014-06-05 14:18:08 -07001530 return GetTwoWordSuccessValue(0, *return_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -08001531 }
jeffhao725a9572012-11-13 18:20:12 -08001532}
1533
Alex Light2c8206f2018-06-08 14:51:09 -07001534uintptr_t Instrumentation::PopFramesForDeoptimization(Thread* self, size_t nframes) const {
Ian Rogers62d6c772013-02-27 08:32:07 -08001535 std::deque<instrumentation::InstrumentationStackFrame>* stack = self->GetInstrumentationStack();
Alex Light2c8206f2018-06-08 14:51:09 -07001536 CHECK_GE(stack->size(), nframes);
1537 if (nframes == 0) {
1538 return 0u;
1539 }
1540 // Only need to send instrumentation events if it's not for deopt (do give the log messages if we
1541 // have verbose-instrumentation anyway though).
1542 if (kVerboseInstrumentation) {
1543 for (size_t i = 0; i < nframes; i++) {
1544 LOG(INFO) << "Popping for deoptimization " << stack->at(i).method_->PrettyMethod();
Mingyao Yang2ee17902017-08-30 11:37:08 -07001545 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001546 }
Alex Light2c8206f2018-06-08 14:51:09 -07001547 // Now that we've sent all the instrumentation events we can actually modify the
1548 // instrumentation-stack. We cannot do this earlier since MethodUnwindEvent can re-enter java and
1549 // do other things that require the instrumentation stack to be in a consistent state with the
1550 // actual stack.
1551 for (size_t i = 0; i < nframes - 1; i++) {
1552 stack->pop_front();
1553 }
1554 uintptr_t return_pc = stack->front().return_pc_;
Alex Lightb7edcda2017-04-27 13:20:31 -07001555 stack->pop_front();
Alex Light2c8206f2018-06-08 14:51:09 -07001556 return return_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -08001557}
1558
1559std::string InstrumentationStackFrame::Dump() const {
1560 std::ostringstream os;
David Sehr709b0702016-10-13 09:12:37 -07001561 os << "Frame " << frame_id_ << " " << ArtMethod::PrettyMethod(method_) << ":"
Ian Rogers62d6c772013-02-27 08:32:07 -08001562 << reinterpret_cast<void*>(return_pc_) << " this=" << reinterpret_cast<void*>(this_object_);
1563 return os.str();
1564}
1565
1566} // namespace instrumentation
jeffhao725a9572012-11-13 18:20:12 -08001567} // namespace art