• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 "debugger.h"
18 
19 #include <sys/uio.h>
20 
21 #include <functional>
22 #include <memory>
23 #include <set>
24 #include <vector>
25 
26 #include "android-base/stringprintf.h"
27 
28 #include "arch/context.h"
29 #include "art_field-inl.h"
30 #include "art_method-inl.h"
31 #include "base/enums.h"
32 #include "base/safe_map.h"
33 #include "base/strlcpy.h"
34 #include "base/time_utils.h"
35 #include "class_linker-inl.h"
36 #include "class_linker.h"
37 #include "dex/descriptors_names.h"
38 #include "dex/dex_file-inl.h"
39 #include "dex/dex_file_annotations.h"
40 #include "dex/dex_file_types.h"
41 #include "dex/dex_instruction.h"
42 #include "dex/utf.h"
43 #include "entrypoints/runtime_asm_entrypoints.h"
44 #include "gc/accounting/card_table-inl.h"
45 #include "gc/allocation_record.h"
46 #include "gc/gc_cause.h"
47 #include "gc/scoped_gc_critical_section.h"
48 #include "gc/space/bump_pointer_space-walk-inl.h"
49 #include "gc/space/large_object_space.h"
50 #include "gc/space/space-inl.h"
51 #include "handle_scope-inl.h"
52 #include "jdwp/jdwp_priv.h"
53 #include "jdwp/object_registry.h"
54 #include "jni/jni_internal.h"
55 #include "jvalue-inl.h"
56 #include "mirror/array-alloc-inl.h"
57 #include "mirror/class-alloc-inl.h"
58 #include "mirror/class-inl.h"
59 #include "mirror/class.h"
60 #include "mirror/class_loader.h"
61 #include "mirror/object-inl.h"
62 #include "mirror/object_array-inl.h"
63 #include "mirror/string-alloc-inl.h"
64 #include "mirror/string-inl.h"
65 #include "mirror/throwable.h"
66 #include "nativehelper/scoped_local_ref.h"
67 #include "nativehelper/scoped_primitive_array.h"
68 #include "oat_file.h"
69 #include "obj_ptr-inl.h"
70 #include "reflection.h"
71 #include "runtime-inl.h"
72 #include "scoped_thread_state_change-inl.h"
73 #include "stack.h"
74 #include "thread_list.h"
75 #include "well_known_classes.h"
76 
77 namespace art {
78 
79 using android::base::StringPrintf;
80 
81 // The key identifying the debugger to update instrumentation.
82 static constexpr const char* kDbgInstrumentationKey = "Debugger";
83 
84 // Limit alloc_record_count to the 2BE value (64k-1) that is the limit of the current protocol.
CappedAllocRecordCount(size_t alloc_record_count)85 static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
86   const size_t cap = 0xffff;
87   if (alloc_record_count > cap) {
88     return cap;
89   }
90   return alloc_record_count;
91 }
92 
93 class Breakpoint : public ValueObject {
94  public:
Breakpoint(ArtMethod * method,uint32_t dex_pc,DeoptimizationRequest::Kind deoptimization_kind)95   Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
96     : method_(method->GetCanonicalMethod(kRuntimePointerSize)),
97       dex_pc_(dex_pc),
98       deoptimization_kind_(deoptimization_kind) {
99     CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
100           deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
101           deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
102   }
103 
REQUIRES_SHARED(Locks::mutator_lock_)104   Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
105     : method_(other.method_),
106       dex_pc_(other.dex_pc_),
107       deoptimization_kind_(other.deoptimization_kind_) {}
108 
109   // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
110   // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
Method() const111   ArtMethod* Method() const {
112     return method_;
113   }
114 
DexPc() const115   uint32_t DexPc() const {
116     return dex_pc_;
117   }
118 
GetDeoptimizationKind() const119   DeoptimizationRequest::Kind GetDeoptimizationKind() const {
120     return deoptimization_kind_;
121   }
122 
123   // Returns true if the method of this breakpoint and the passed in method should be considered the
124   // same. That is, they are either the same method or they are copied from the same method.
IsInMethod(ArtMethod * m) const125   bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
126     return method_ == m->GetCanonicalMethod(kRuntimePointerSize);
127   }
128 
129  private:
130   // The location of this breakpoint.
131   ArtMethod* method_;
132   uint32_t dex_pc_;
133 
134   // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
135   DeoptimizationRequest::Kind deoptimization_kind_;
136 };
137 
operator <<(std::ostream & os,const Breakpoint & rhs)138 static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
139     REQUIRES_SHARED(Locks::mutator_lock_) {
140   os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
141                      rhs.DexPc());
142   return os;
143 }
144 
145 class DebugInstrumentationListener final : public instrumentation::InstrumentationListener {
146  public:
DebugInstrumentationListener()147   DebugInstrumentationListener() {}
~DebugInstrumentationListener()148   virtual ~DebugInstrumentationListener() {}
149 
MethodEntered(Thread * thread,Handle<mirror::Object> this_object,ArtMethod * method,uint32_t dex_pc)150   void MethodEntered(Thread* thread,
151                      Handle<mirror::Object> this_object,
152                      ArtMethod* method,
153                      uint32_t dex_pc)
154       override REQUIRES_SHARED(Locks::mutator_lock_) {
155     if (method->IsNative()) {
156       // TODO: post location events is a suspension point and native method entry stubs aren't.
157       return;
158     }
159     if (IsListeningToDexPcMoved()) {
160       // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
161       // going to be called right after us. To avoid sending JDWP events twice for this location,
162       // we report the event in DexPcMoved. However, we must remind this is method entry so we
163       // send the METHOD_ENTRY event. And we can also group it with other events for this location
164       // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
165       thread->SetDebugMethodEntry();
166     } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
167       // We also listen to kMethodExited instrumentation event and the current instruction is a
168       // RETURN so we know the MethodExited method is going to be called right after us. To avoid
169       // sending JDWP events twice for this location, we report the event(s) in MethodExited.
170       // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
171       // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
172       thread->SetDebugMethodEntry();
173     } else {
174       Dbg::UpdateDebugger(thread, this_object.Get(), method, 0, Dbg::kMethodEntry, nullptr);
175     }
176   }
177 
MethodExited(Thread * thread,Handle<mirror::Object> this_object,ArtMethod * method,uint32_t dex_pc,const JValue & return_value)178   void MethodExited(Thread* thread,
179                     Handle<mirror::Object> this_object,
180                     ArtMethod* method,
181                     uint32_t dex_pc,
182                     const JValue& return_value)
183       override REQUIRES_SHARED(Locks::mutator_lock_) {
184     if (method->IsNative()) {
185       // TODO: post location events is a suspension point and native method entry stubs aren't.
186       return;
187     }
188     uint32_t events = Dbg::kMethodExit;
189     if (thread->IsDebugMethodEntry()) {
190       // It is also the method entry.
191       DCHECK(IsReturn(method, dex_pc));
192       events |= Dbg::kMethodEntry;
193       thread->ClearDebugMethodEntry();
194     }
195     Dbg::UpdateDebugger(thread, this_object.Get(), method, dex_pc, events, &return_value);
196   }
197 
MethodUnwind(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,ArtMethod * method,uint32_t dex_pc)198   void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED,
199                     Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
200                     ArtMethod* method,
201                     uint32_t dex_pc)
202       override REQUIRES_SHARED(Locks::mutator_lock_) {
203     // We're not recorded to listen to this kind of event, so complain.
204     LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
205                << " " << dex_pc;
206   }
207 
DexPcMoved(Thread * thread,Handle<mirror::Object> this_object,ArtMethod * method,uint32_t new_dex_pc)208   void DexPcMoved(Thread* thread,
209                   Handle<mirror::Object> this_object,
210                   ArtMethod* method,
211                   uint32_t new_dex_pc)
212       override REQUIRES_SHARED(Locks::mutator_lock_) {
213     if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
214       // We also listen to kMethodExited instrumentation event and the current instruction is a
215       // RETURN so we know the MethodExited method is going to be called right after us. Like in
216       // MethodEntered, we delegate event reporting to MethodExited.
217       // Besides, if this RETURN instruction is the only one in the method, we can send multiple
218       // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
219       // Therefore, we must not clear the debug method entry flag here.
220     } else {
221       uint32_t events = 0;
222       if (thread->IsDebugMethodEntry()) {
223         // It is also the method entry.
224         events = Dbg::kMethodEntry;
225         thread->ClearDebugMethodEntry();
226       }
227       Dbg::UpdateDebugger(thread, this_object.Get(), method, new_dex_pc, events, nullptr);
228     }
229   }
230 
FieldRead(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Object> this_object,ArtMethod * method,uint32_t dex_pc,ArtField * field)231   void FieldRead(Thread* thread ATTRIBUTE_UNUSED,
232                  Handle<mirror::Object> this_object,
233                  ArtMethod* method,
234                  uint32_t dex_pc,
235                  ArtField* field)
236       override REQUIRES_SHARED(Locks::mutator_lock_) {
237     Dbg::PostFieldAccessEvent(method, dex_pc, this_object.Get(), field);
238   }
239 
FieldWritten(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Object> this_object,ArtMethod * method,uint32_t dex_pc,ArtField * field,const JValue & field_value)240   void FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
241                     Handle<mirror::Object> this_object,
242                     ArtMethod* method,
243                     uint32_t dex_pc,
244                     ArtField* field,
245                     const JValue& field_value)
246       override REQUIRES_SHARED(Locks::mutator_lock_) {
247     Dbg::PostFieldModificationEvent(method, dex_pc, this_object.Get(), field, &field_value);
248   }
249 
ExceptionThrown(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Throwable> exception_object)250   void ExceptionThrown(Thread* thread ATTRIBUTE_UNUSED,
251                        Handle<mirror::Throwable> exception_object)
252       override REQUIRES_SHARED(Locks::mutator_lock_) {
253     Dbg::PostException(exception_object.Get());
254   }
255 
256   // We only care about branches in the Jit.
Branch(Thread *,ArtMethod * method,uint32_t dex_pc,int32_t dex_pc_offset)257   void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
258       override REQUIRES_SHARED(Locks::mutator_lock_) {
259     LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
260                << " " << dex_pc << ", " << dex_pc_offset;
261   }
262 
263   // TODO Might be worth it to post ExceptionCatch event.
ExceptionHandled(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Throwable> throwable ATTRIBUTE_UNUSED)264   void ExceptionHandled(Thread* thread ATTRIBUTE_UNUSED,
265                         Handle<mirror::Throwable> throwable ATTRIBUTE_UNUSED) override {
266     LOG(ERROR) << "Unexpected exception handled event in debugger";
267   }
268 
269   // TODO Might be worth it to implement this.
WatchedFramePop(Thread * thread ATTRIBUTE_UNUSED,const ShadowFrame & frame ATTRIBUTE_UNUSED)270   void WatchedFramePop(Thread* thread ATTRIBUTE_UNUSED,
271                        const ShadowFrame& frame ATTRIBUTE_UNUSED) override {
272     LOG(ERROR) << "Unexpected WatchedFramePop event in debugger";
273   }
274 
275  private:
IsReturn(ArtMethod * method,uint32_t dex_pc)276   static bool IsReturn(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
277     return method->DexInstructions().InstructionAt(dex_pc).IsReturn();
278   }
279 
IsListeningToDexPcMoved()280   static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
281     return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
282   }
283 
IsListeningToMethodExit()284   static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
285     return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
286   }
287 
IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)288   static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
289       REQUIRES_SHARED(Locks::mutator_lock_) {
290     return (Dbg::GetInstrumentationEvents() & event) != 0;
291   }
292 
293   DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
294 } gDebugInstrumentationListener;
295 
296 // JDWP is allowed unless the Zygote forbids it.
297 static bool gJdwpAllowed = true;
298 
299 // Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
300 static bool gJdwpConfigured = false;
301 
302 // JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
303 static JDWP::JdwpOptions gJdwpOptions;
304 
305 // Runtime JDWP state.
306 static JDWP::JdwpState* gJdwpState = nullptr;
307 static bool gDebuggerConnected;  // debugger or DDMS is connected.
308 
309 static bool gDdmThreadNotification = false;
310 
311 // DDMS GC-related settings.
312 static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
313 static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
314 static Dbg::HpsgWhat gDdmHpsgWhat;
315 static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
316 static Dbg::HpsgWhat gDdmNhsgWhat;
317 
318 bool Dbg::gDebuggerActive = false;
319 bool Dbg::gDisposed = false;
320 ObjectRegistry* Dbg::gRegistry = nullptr;
321 DebuggerActiveMethodInspectionCallback Dbg::gDebugActiveCallback;
322 DebuggerDdmCallback Dbg::gDebugDdmCallback;
323 InternalDebuggerControlCallback Dbg::gDebuggerControlCallback;
324 
325 // Deoptimization support.
326 std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
327 size_t Dbg::full_deoptimization_event_count_ = 0;
328 
329 // Instrumentation event reference counters.
330 size_t Dbg::dex_pc_change_event_ref_count_ = 0;
331 size_t Dbg::method_enter_event_ref_count_ = 0;
332 size_t Dbg::method_exit_event_ref_count_ = 0;
333 size_t Dbg::field_read_event_ref_count_ = 0;
334 size_t Dbg::field_write_event_ref_count_ = 0;
335 size_t Dbg::exception_catch_event_ref_count_ = 0;
336 uint32_t Dbg::instrumentation_events_ = 0;
337 
338 Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_;
339 Dbg::DbgClassLoadCallback Dbg::class_load_callback_;
340 
DdmPublishChunk(uint32_t type,const ArrayRef<const uint8_t> & data)341 void DebuggerDdmCallback::DdmPublishChunk(uint32_t type, const ArrayRef<const uint8_t>& data) {
342   if (gJdwpState == nullptr) {
343     VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
344   } else {
345     iovec vec[1];
346     vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(data.data()));
347     vec[0].iov_len = data.size();
348     gJdwpState->DdmSendChunkV(type, vec, 1);
349   }
350 }
351 
IsMethodBeingInspected(ArtMethod * m ATTRIBUTE_UNUSED)352 bool DebuggerActiveMethodInspectionCallback::IsMethodBeingInspected(ArtMethod* m ATTRIBUTE_UNUSED) {
353   return Dbg::IsDebuggerActive();
354 }
355 
IsMethodSafeToJit(ArtMethod * m)356 bool DebuggerActiveMethodInspectionCallback::IsMethodSafeToJit(ArtMethod* m) {
357   return !Dbg::MethodHasAnyBreakpoints(m);
358 }
359 
MethodNeedsDebugVersion(ArtMethod * m ATTRIBUTE_UNUSED)360 bool DebuggerActiveMethodInspectionCallback::MethodNeedsDebugVersion(
361     ArtMethod* m ATTRIBUTE_UNUSED) {
362   return Dbg::IsDebuggerActive();
363 }
364 
StartDebugger()365 void InternalDebuggerControlCallback::StartDebugger() {
366   // Release the mutator lock.
367   ScopedThreadStateChange stsc(art::Thread::Current(), kNative);
368   Dbg::StartJdwp();
369 }
370 
StopDebugger()371 void InternalDebuggerControlCallback::StopDebugger() {
372   Dbg::StopJdwp();
373 }
374 
IsDebuggerConfigured()375 bool InternalDebuggerControlCallback::IsDebuggerConfigured() {
376   return Dbg::IsJdwpConfigured();
377 }
378 
379 // Breakpoints.
380 static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
381 
VisitRoots(RootVisitor * visitor,const RootInfo & root_info)382 void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
383   receiver.VisitRootIfNonNull(visitor, root_info);  // null for static method call.
384   klass.VisitRoot(visitor, root_info);
385 }
386 
AddDexPc(uint32_t dex_pc)387 void SingleStepControl::AddDexPc(uint32_t dex_pc) {
388   dex_pcs_.insert(dex_pc);
389 }
390 
ContainsDexPc(uint32_t dex_pc) const391 bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
392   return dex_pcs_.find(dex_pc) == dex_pcs_.end();
393 }
394 
IsBreakpoint(ArtMethod * m,uint32_t dex_pc)395 static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
396     REQUIRES(!Locks::breakpoint_lock_)
397     REQUIRES_SHARED(Locks::mutator_lock_) {
398   ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
399   for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
400     if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
401       VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
402       return true;
403     }
404   }
405   return false;
406 }
407 
IsSuspendedForDebugger(ScopedObjectAccessUnchecked & soa,Thread * thread)408 static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
409     REQUIRES(!Locks::thread_suspend_count_lock_) {
410   MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
411   // A thread may be suspended for GC; in this code, we really want to know whether
412   // there's a debugger suspension active.
413   return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
414 }
415 
DecodeNonNullArray(JDWP::RefTypeId id,JDWP::JdwpError * error)416 static ObjPtr<mirror::Array> DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
417     REQUIRES_SHARED(Locks::mutator_lock_) {
418   ObjPtr<mirror::Object> o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
419   if (o == nullptr) {
420     *error = JDWP::ERR_INVALID_OBJECT;
421     return nullptr;
422   }
423   if (!o->IsArrayInstance()) {
424     *error = JDWP::ERR_INVALID_ARRAY;
425     return nullptr;
426   }
427   *error = JDWP::ERR_NONE;
428   return o->AsArray();
429 }
430 
DecodeClass(JDWP::RefTypeId id,JDWP::JdwpError * error)431 static ObjPtr<mirror::Class> DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
432     REQUIRES_SHARED(Locks::mutator_lock_) {
433   ObjPtr<mirror::Object> o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
434   if (o == nullptr) {
435     *error = JDWP::ERR_INVALID_OBJECT;
436     return nullptr;
437   }
438   if (!o->IsClass()) {
439     *error = JDWP::ERR_INVALID_CLASS;
440     return nullptr;
441   }
442   *error = JDWP::ERR_NONE;
443   return o->AsClass();
444 }
445 
DecodeThread(ScopedObjectAccessUnchecked & soa,JDWP::ObjectId thread_id,JDWP::JdwpError * error)446 static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
447                             JDWP::JdwpError* error)
448     REQUIRES_SHARED(Locks::mutator_lock_)
449     REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
450   ObjPtr<mirror::Object> thread_peer =
451       Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
452   if (thread_peer == nullptr) {
453     // This isn't even an object.
454     *error = JDWP::ERR_INVALID_OBJECT;
455     return nullptr;
456   }
457 
458   ObjPtr<mirror::Class> java_lang_Thread =
459       soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
460   if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
461     // This isn't a thread.
462     *error = JDWP::ERR_INVALID_THREAD;
463     return nullptr;
464   }
465 
466   MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
467   Thread* thread = Thread::FromManagedThread(soa, thread_peer);
468   // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
469   // zombie.
470   *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
471   return thread;
472 }
473 
BasicTagFromDescriptor(const char * descriptor)474 static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
475   // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
476   // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
477   return static_cast<JDWP::JdwpTag>(descriptor[0]);
478 }
479 
BasicTagFromClass(ObjPtr<mirror::Class> klass)480 static JDWP::JdwpTag BasicTagFromClass(ObjPtr<mirror::Class> klass)
481     REQUIRES_SHARED(Locks::mutator_lock_) {
482   std::string temp;
483   const char* descriptor = klass->GetDescriptor(&temp);
484   return BasicTagFromDescriptor(descriptor);
485 }
486 
TagFromClass(const ScopedObjectAccessUnchecked & soa,mirror::Class * c)487 static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
488     REQUIRES_SHARED(Locks::mutator_lock_) {
489   CHECK(c != nullptr);
490   if (c->IsArrayClass()) {
491     return JDWP::JT_ARRAY;
492   }
493   if (c->IsStringClass()) {
494     return JDWP::JT_STRING;
495   }
496   if (c->IsClassClass()) {
497     return JDWP::JT_CLASS_OBJECT;
498   }
499   {
500     ObjPtr<mirror::Class> thread_class =
501         soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
502     if (thread_class->IsAssignableFrom(c)) {
503       return JDWP::JT_THREAD;
504     }
505   }
506   {
507     ObjPtr<mirror::Class> thread_group_class =
508         soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
509     if (thread_group_class->IsAssignableFrom(c)) {
510       return JDWP::JT_THREAD_GROUP;
511     }
512   }
513   {
514     ObjPtr<mirror::Class> class_loader_class =
515         soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
516     if (class_loader_class->IsAssignableFrom(c)) {
517       return JDWP::JT_CLASS_LOADER;
518     }
519   }
520   return JDWP::JT_OBJECT;
521 }
522 
523 /*
524  * Objects declared to hold Object might actually hold a more specific
525  * type.  The debugger may take a special interest in these (e.g. it
526  * wants to display the contents of Strings), so we want to return an
527  * appropriate tag.
528  *
529  * Null objects are tagged JT_OBJECT.
530  */
TagFromObject(const ScopedObjectAccessUnchecked & soa,ObjPtr<mirror::Object> o)531 JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, ObjPtr<mirror::Object> o) {
532   return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
533 }
534 
IsPrimitiveTag(JDWP::JdwpTag tag)535 static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
536   switch (tag) {
537   case JDWP::JT_BOOLEAN:
538   case JDWP::JT_BYTE:
539   case JDWP::JT_CHAR:
540   case JDWP::JT_FLOAT:
541   case JDWP::JT_DOUBLE:
542   case JDWP::JT_INT:
543   case JDWP::JT_LONG:
544   case JDWP::JT_SHORT:
545   case JDWP::JT_VOID:
546     return true;
547   default:
548     return false;
549   }
550 }
551 
StartJdwp()552 void Dbg::StartJdwp() {
553   if (!gJdwpAllowed || !IsJdwpConfigured()) {
554     // No JDWP for you!
555     return;
556   }
557 
558   CHECK(gRegistry == nullptr);
559   gRegistry = new ObjectRegistry;
560 
561   {
562     // Setup the Ddm listener
563     ScopedObjectAccess soa(Thread::Current());
564     Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&gDebugDdmCallback);
565   }
566 
567   // Init JDWP if the debugger is enabled. This may connect out to a
568   // debugger, passively listen for a debugger, or block waiting for a
569   // debugger.
570   gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
571   if (gJdwpState == nullptr) {
572     // We probably failed because some other process has the port already, which means that
573     // if we don't abort the user is likely to think they're talking to us when they're actually
574     // talking to that other process.
575     LOG(FATAL) << "Debugger thread failed to initialize";
576   }
577 
578   // If a debugger has already attached, send the "welcome" message.
579   // This may cause us to suspend all threads.
580   if (gJdwpState->IsActive()) {
581     ScopedObjectAccess soa(Thread::Current());
582     gJdwpState->PostVMStart();
583   }
584 }
585 
StopJdwp()586 void Dbg::StopJdwp() {
587   // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
588   // destruction of gJdwpState).
589   if (gJdwpState != nullptr && gJdwpState->IsActive()) {
590     gJdwpState->PostVMDeath();
591   }
592   // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
593   Dispose();
594   delete gJdwpState;
595   gJdwpState = nullptr;
596   delete gRegistry;
597   gRegistry = nullptr;
598 }
599 
GcDidFinish()600 void Dbg::GcDidFinish() {
601   if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
602     ScopedObjectAccess soa(Thread::Current());
603     VLOG(jdwp) << "Sending heap info to DDM";
604     DdmSendHeapInfo(gDdmHpifWhen);
605   }
606   if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
607     ScopedObjectAccess soa(Thread::Current());
608     VLOG(jdwp) << "Dumping heap to DDM";
609     DdmSendHeapSegments(false);
610   }
611   if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
612     ScopedObjectAccess soa(Thread::Current());
613     VLOG(jdwp) << "Dumping native heap to DDM";
614     DdmSendHeapSegments(true);
615   }
616 }
617 
SetJdwpAllowed(bool allowed)618 void Dbg::SetJdwpAllowed(bool allowed) {
619   gJdwpAllowed = allowed;
620 }
621 
IsJdwpAllowed()622 bool Dbg::IsJdwpAllowed() {
623   return gJdwpAllowed;
624 }
625 
GetInvokeReq()626 DebugInvokeReq* Dbg::GetInvokeReq() {
627   return Thread::Current()->GetInvokeReq();
628 }
629 
GetDebugThread()630 Thread* Dbg::GetDebugThread() {
631   return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
632 }
633 
ClearWaitForEventThread()634 void Dbg::ClearWaitForEventThread() {
635   gJdwpState->ReleaseJdwpTokenForEvent();
636 }
637 
Connected()638 void Dbg::Connected() {
639   CHECK(!gDebuggerConnected);
640   VLOG(jdwp) << "JDWP has attached";
641   gDebuggerConnected = true;
642   gDisposed = false;
643 }
644 
RequiresDeoptimization()645 bool Dbg::RequiresDeoptimization() {
646   // We don't need deoptimization if everything runs with interpreter after
647   // enabling -Xint mode.
648   return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
649 }
650 
GoActive()651 void Dbg::GoActive() {
652   // Enable all debugging features, including scans for breakpoints.
653   // This is a no-op if we're already active.
654   // Only called from the JDWP handler thread.
655   if (IsDebuggerActive()) {
656     return;
657   }
658 
659   Thread* const self = Thread::Current();
660   {
661     // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
662     ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
663     CHECK_EQ(gBreakpoints.size(), 0U);
664   }
665 
666   {
667     MutexLock mu(self, *Locks::deoptimization_lock_);
668     CHECK_EQ(deoptimization_requests_.size(), 0U);
669     CHECK_EQ(full_deoptimization_event_count_, 0U);
670     CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
671     CHECK_EQ(method_enter_event_ref_count_, 0U);
672     CHECK_EQ(method_exit_event_ref_count_, 0U);
673     CHECK_EQ(field_read_event_ref_count_, 0U);
674     CHECK_EQ(field_write_event_ref_count_, 0U);
675     CHECK_EQ(exception_catch_event_ref_count_, 0U);
676   }
677 
678   Runtime* runtime = Runtime::Current();
679   // Best effort deoptimization if the runtime is non-Java debuggable. This happens when
680   // ro.debuggable is set, but the application is not debuggable, or when a standalone
681   // dalvikvm invocation is not passed the debuggable option (-Xcompiler-option --debuggable).
682   //
683   // The performance cost of this is non-negligible during native-debugging due to the
684   // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
685   ScopedSuspendAll ssa(__FUNCTION__);
686   if (!runtime->IsJavaDebuggable() &&
687       !runtime->GetInstrumentation()->IsForcedInterpretOnly() &&
688       !runtime->IsNativeDebuggable()) {
689     runtime->DeoptimizeBootImage();
690   }
691 
692   if (RequiresDeoptimization()) {
693     runtime->GetInstrumentation()->EnableDeoptimization();
694   }
695   instrumentation_events_ = 0;
696   Runtime::DoAndMaybeSwitchInterpreter([=](){ gDebuggerActive = true; });
697   Runtime::Current()->GetRuntimeCallbacks()->AddMethodInspectionCallback(&gDebugActiveCallback);
698   LOG(INFO) << "Debugger is active";
699 }
700 
Disconnected()701 void Dbg::Disconnected() {
702   CHECK(gDebuggerConnected);
703 
704   LOG(INFO) << "Debugger is no longer active";
705 
706   // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
707   // and clear the object registry.
708   Runtime* runtime = Runtime::Current();
709   Thread* self = Thread::Current();
710   {
711     // Required for DisableDeoptimization.
712     gc::ScopedGCCriticalSection gcs(self,
713                                     gc::kGcCauseInstrumentation,
714                                     gc::kCollectorTypeInstrumentation);
715     ScopedSuspendAll ssa(__FUNCTION__);
716     // Debugger may not be active at this point.
717     if (IsDebuggerActive()) {
718       {
719         // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
720         // This prevents us from having any pending deoptimization request when the debugger attaches
721         // to us again while no event has been requested yet.
722         MutexLock mu(self, *Locks::deoptimization_lock_);
723         deoptimization_requests_.clear();
724         full_deoptimization_event_count_ = 0U;
725       }
726       if (instrumentation_events_ != 0) {
727         runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
728                                                       instrumentation_events_);
729         instrumentation_events_ = 0;
730       }
731       if (RequiresDeoptimization()) {
732         runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
733       }
734       Runtime::DoAndMaybeSwitchInterpreter([=](){ gDebuggerActive = false; });
735       Runtime::Current()->GetRuntimeCallbacks()->RemoveMethodInspectionCallback(
736           &gDebugActiveCallback);
737     }
738   }
739 
740   {
741     ScopedObjectAccess soa(self);
742     gRegistry->Clear();
743   }
744 
745   gDebuggerConnected = false;
746 }
747 
ConfigureJdwp(const JDWP::JdwpOptions & jdwp_options)748 void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
749   CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
750   gJdwpOptions = jdwp_options;
751   gJdwpConfigured = true;
752   Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&gDebuggerControlCallback);
753 }
754 
IsJdwpConfigured()755 bool Dbg::IsJdwpConfigured() {
756   return gJdwpConfigured;
757 }
758 
LastDebuggerActivity()759 int64_t Dbg::LastDebuggerActivity() {
760   return gJdwpState->LastDebuggerActivity();
761 }
762 
UndoDebuggerSuspensions()763 void Dbg::UndoDebuggerSuspensions() {
764   Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
765 }
766 
GetClassName(JDWP::RefTypeId class_id)767 std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
768   JDWP::JdwpError error;
769   ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(class_id, &error);
770   if (o == nullptr) {
771     if (error == JDWP::ERR_NONE) {
772       return "null";
773     } else {
774       return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
775     }
776   }
777   if (!o->IsClass()) {
778     return StringPrintf("non-class %p", o.Ptr());  // This is only used for debugging output anyway.
779   }
780   return GetClassName(o->AsClass());
781 }
782 
GetClassName(ObjPtr<mirror::Class> klass)783 std::string Dbg::GetClassName(ObjPtr<mirror::Class> klass) {
784   if (klass == nullptr) {
785     return "null";
786   }
787   std::string temp;
788   return DescriptorToName(klass->GetDescriptor(&temp));
789 }
790 
GetClassObject(JDWP::RefTypeId id,JDWP::ObjectId * class_object_id)791 JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
792   JDWP::JdwpError status;
793   ObjPtr<mirror::Class> c = DecodeClass(id, &status);
794   if (c == nullptr) {
795     *class_object_id = 0;
796     return status;
797   }
798   *class_object_id = gRegistry->Add(c);
799   return JDWP::ERR_NONE;
800 }
801 
GetSuperclass(JDWP::RefTypeId id,JDWP::RefTypeId * superclass_id)802 JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
803   JDWP::JdwpError status;
804   ObjPtr<mirror::Class> c = DecodeClass(id, &status);
805   if (c == nullptr) {
806     *superclass_id = 0;
807     return status;
808   }
809   if (c->IsInterface()) {
810     // http://code.google.com/p/android/issues/detail?id=20856
811     *superclass_id = 0;
812   } else {
813     *superclass_id = gRegistry->Add(c->GetSuperClass());
814   }
815   return JDWP::ERR_NONE;
816 }
817 
GetClassLoader(JDWP::RefTypeId id,JDWP::ExpandBuf * pReply)818 JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
819   JDWP::JdwpError error;
820   ObjPtr<mirror::Class> c = DecodeClass(id, &error);
821   if (c == nullptr) {
822     return error;
823   }
824   expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
825   return JDWP::ERR_NONE;
826 }
827 
GetModifiers(JDWP::RefTypeId id,JDWP::ExpandBuf * pReply)828 JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
829   JDWP::JdwpError error;
830   ObjPtr<mirror::Class> c = DecodeClass(id, &error);
831   if (c == nullptr) {
832     return error;
833   }
834 
835   uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
836 
837   // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
838   // not interfaces.
839   // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
840   if ((access_flags & kAccInterface) == 0) {
841     access_flags |= kAccSuper;
842   }
843 
844   expandBufAdd4BE(pReply, access_flags);
845 
846   return JDWP::ERR_NONE;
847 }
848 
GetMonitorInfo(JDWP::ObjectId object_id,JDWP::ExpandBuf * reply)849 JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
850   JDWP::JdwpError error;
851   Thread* self = Thread::Current();
852   StackHandleScope<1u> hs(self);
853   Handle<mirror::Object> o = hs.NewHandle(gRegistry->Get<mirror::Object*>(object_id, &error));
854   if (o == nullptr) {
855     return JDWP::ERR_INVALID_OBJECT;
856   }
857 
858   // Ensure all threads are suspended while we read objects' lock words.
859   CHECK_EQ(self->GetState(), kRunnable);
860 
861   MonitorInfo monitor_info;
862   {
863     ScopedThreadSuspension sts(self, kSuspended);
864     ScopedSuspendAll ssa(__FUNCTION__);
865     monitor_info = MonitorInfo(o.Get());
866   }
867   if (monitor_info.owner_ != nullptr) {
868     expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
869   } else {
870     expandBufAddObjectId(reply, gRegistry->Add(nullptr));
871   }
872   expandBufAdd4BE(reply, monitor_info.entry_count_);
873   expandBufAdd4BE(reply, monitor_info.waiters_.size());
874   for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
875     expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
876   }
877   return JDWP::ERR_NONE;
878 }
879 
GetOwnedMonitors(JDWP::ObjectId thread_id,std::vector<JDWP::ObjectId> * monitors,std::vector<uint32_t> * stack_depths)880 JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
881                                       std::vector<JDWP::ObjectId>* monitors,
882                                       std::vector<uint32_t>* stack_depths) {
883   struct OwnedMonitorVisitor : public StackVisitor {
884     OwnedMonitorVisitor(Thread* thread, Context* context,
885                         std::vector<JDWP::ObjectId>* monitor_vector,
886                         std::vector<uint32_t>* stack_depth_vector)
887         REQUIRES_SHARED(Locks::mutator_lock_)
888       : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
889         current_stack_depth(0),
890         monitors(monitor_vector),
891         stack_depths(stack_depth_vector) {}
892 
893     // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
894     // annotalysis.
895     bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
896       if (!GetMethod()->IsRuntimeMethod()) {
897         Monitor::VisitLocks(this, AppendOwnedMonitors, this);
898         ++current_stack_depth;
899       }
900       return true;
901     }
902 
903     static void AppendOwnedMonitors(ObjPtr<mirror::Object> owned_monitor, void* arg)
904         REQUIRES_SHARED(Locks::mutator_lock_) {
905       OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
906       visitor->monitors->push_back(gRegistry->Add(owned_monitor));
907       visitor->stack_depths->push_back(visitor->current_stack_depth);
908     }
909 
910     size_t current_stack_depth;
911     std::vector<JDWP::ObjectId>* const monitors;
912     std::vector<uint32_t>* const stack_depths;
913   };
914 
915   ScopedObjectAccessUnchecked soa(Thread::Current());
916   JDWP::JdwpError error;
917   Thread* thread = DecodeThread(soa, thread_id, &error);
918   if (thread == nullptr) {
919     return error;
920   }
921   if (!IsSuspendedForDebugger(soa, thread)) {
922     return JDWP::ERR_THREAD_NOT_SUSPENDED;
923   }
924   std::unique_ptr<Context> context(Context::Create());
925   OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
926   visitor.WalkStack();
927   return JDWP::ERR_NONE;
928 }
929 
GetContendedMonitor(JDWP::ObjectId thread_id,JDWP::ObjectId * contended_monitor)930 JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
931                                          JDWP::ObjectId* contended_monitor) {
932   ScopedObjectAccessUnchecked soa(Thread::Current());
933   *contended_monitor = 0;
934   JDWP::JdwpError error;
935   Thread* thread = DecodeThread(soa, thread_id, &error);
936   if (thread == nullptr) {
937     return error;
938   }
939   if (!IsSuspendedForDebugger(soa, thread)) {
940     return JDWP::ERR_THREAD_NOT_SUSPENDED;
941   }
942   ObjPtr<mirror::Object> contended_monitor_obj = Monitor::GetContendedMonitor(thread);
943   // Add() requires the thread_list_lock_ not held to avoid the lock
944   // level violation.
945   *contended_monitor = gRegistry->Add(contended_monitor_obj);
946   return JDWP::ERR_NONE;
947 }
948 
GetInstanceCounts(const std::vector<JDWP::RefTypeId> & class_ids,std::vector<uint64_t> * counts)949 JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
950                                        std::vector<uint64_t>* counts) {
951   gc::Heap* heap = Runtime::Current()->GetHeap();
952   heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
953   VariableSizedHandleScope hs(Thread::Current());
954   std::vector<Handle<mirror::Class>> classes;
955   counts->clear();
956   for (size_t i = 0; i < class_ids.size(); ++i) {
957     JDWP::JdwpError error;
958     ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
959     if (c == nullptr) {
960       return error;
961     }
962     classes.push_back(hs.NewHandle(c));
963     counts->push_back(0);
964   }
965   heap->CountInstances(classes, false, &(*counts)[0]);
966   return JDWP::ERR_NONE;
967 }
968 
GetInstances(JDWP::RefTypeId class_id,int32_t max_count,std::vector<JDWP::ObjectId> * instances)969 JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
970                                   std::vector<JDWP::ObjectId>* instances) {
971   gc::Heap* heap = Runtime::Current()->GetHeap();
972   // We only want reachable instances, so do a GC.
973   heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
974   JDWP::JdwpError error;
975   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
976   if (c == nullptr) {
977     return error;
978   }
979   VariableSizedHandleScope hs(Thread::Current());
980   std::vector<Handle<mirror::Object>> raw_instances;
981   Runtime::Current()->GetHeap()->GetInstances(hs,
982                                               hs.NewHandle(c),
983                                               /* use_is_assignable_from= */ false,
984                                               max_count,
985                                               raw_instances);
986   for (size_t i = 0; i < raw_instances.size(); ++i) {
987     instances->push_back(gRegistry->Add(raw_instances[i].Get()));
988   }
989   return JDWP::ERR_NONE;
990 }
991 
GetReferringObjects(JDWP::ObjectId object_id,int32_t max_count,std::vector<JDWP::ObjectId> * referring_objects)992 JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
993                                          std::vector<JDWP::ObjectId>* referring_objects) {
994   gc::Heap* heap = Runtime::Current()->GetHeap();
995   heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
996   JDWP::JdwpError error;
997   ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
998   if (o == nullptr) {
999     return JDWP::ERR_INVALID_OBJECT;
1000   }
1001   VariableSizedHandleScope hs(Thread::Current());
1002   std::vector<Handle<mirror::Object>> raw_instances;
1003   heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
1004   for (size_t i = 0; i < raw_instances.size(); ++i) {
1005     referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
1006   }
1007   return JDWP::ERR_NONE;
1008 }
1009 
DisableCollection(JDWP::ObjectId object_id)1010 JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1011   JDWP::JdwpError error;
1012   mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1013   if (o == nullptr) {
1014     return JDWP::ERR_INVALID_OBJECT;
1015   }
1016   gRegistry->DisableCollection(object_id);
1017   return JDWP::ERR_NONE;
1018 }
1019 
EnableCollection(JDWP::ObjectId object_id)1020 JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1021   JDWP::JdwpError error;
1022   mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1023   // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1024   // also ignores these cases and never return an error. However it's not obvious why this command
1025   // should behave differently from DisableCollection and IsCollected commands. So let's be more
1026   // strict and return an error if this happens.
1027   if (o == nullptr) {
1028     return JDWP::ERR_INVALID_OBJECT;
1029   }
1030   gRegistry->EnableCollection(object_id);
1031   return JDWP::ERR_NONE;
1032 }
1033 
IsCollected(JDWP::ObjectId object_id,bool * is_collected)1034 JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1035   *is_collected = true;
1036   if (object_id == 0) {
1037     // Null object id is invalid.
1038     return JDWP::ERR_INVALID_OBJECT;
1039   }
1040   // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1041   // the RI seems to ignore this and assume object has been collected.
1042   JDWP::JdwpError error;
1043   mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1044   if (o != nullptr) {
1045     *is_collected = gRegistry->IsCollected(object_id);
1046   }
1047   return JDWP::ERR_NONE;
1048 }
1049 
DisposeObject(JDWP::ObjectId object_id,uint32_t reference_count)1050 void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
1051   gRegistry->DisposeObject(object_id, reference_count);
1052 }
1053 
GetTypeTag(ObjPtr<mirror::Class> klass)1054 JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
1055   DCHECK(klass != nullptr);
1056   if (klass->IsArrayClass()) {
1057     return JDWP::TT_ARRAY;
1058   } else if (klass->IsInterface()) {
1059     return JDWP::TT_INTERFACE;
1060   } else {
1061     return JDWP::TT_CLASS;
1062   }
1063 }
1064 
GetReflectedType(JDWP::RefTypeId class_id,JDWP::ExpandBuf * pReply)1065 JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
1066   JDWP::JdwpError error;
1067   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1068   if (c == nullptr) {
1069     return error;
1070   }
1071 
1072   JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1073   expandBufAdd1(pReply, type_tag);
1074   expandBufAddRefTypeId(pReply, class_id);
1075   return JDWP::ERR_NONE;
1076 }
1077 
1078 // Get the complete list of reference classes (i.e. all classes except
1079 // the primitive types).
1080 // Returns a newly-allocated buffer full of RefTypeId values.
1081 class ClassListCreator : public ClassVisitor {
1082  public:
ClassListCreator(std::vector<JDWP::RefTypeId> * classes)1083   explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1084 
operator ()(ObjPtr<mirror::Class> c)1085   bool operator()(ObjPtr<mirror::Class> c) override REQUIRES_SHARED(Locks::mutator_lock_) {
1086     if (!c->IsPrimitive()) {
1087       classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1088     }
1089     return true;
1090   }
1091 
1092  private:
1093   std::vector<JDWP::RefTypeId>* const classes_;
1094 };
1095 
GetClassList(std::vector<JDWP::RefTypeId> * classes)1096 void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
1097   ClassListCreator clc(classes);
1098   Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
1099 }
1100 
GetClassInfo(JDWP::RefTypeId class_id,JDWP::JdwpTypeTag * pTypeTag,uint32_t * pStatus,std::string * pDescriptor)1101 JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1102                                   uint32_t* pStatus, std::string* pDescriptor) {
1103   JDWP::JdwpError error;
1104   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1105   if (c == nullptr) {
1106     return error;
1107   }
1108 
1109   if (c->IsArrayClass()) {
1110     *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1111     *pTypeTag = JDWP::TT_ARRAY;
1112   } else {
1113     if (c->IsErroneous()) {
1114       *pStatus = JDWP::CS_ERROR;
1115     } else {
1116       *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1117     }
1118     *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1119   }
1120 
1121   if (pDescriptor != nullptr) {
1122     std::string temp;
1123     *pDescriptor = c->GetDescriptor(&temp);
1124   }
1125   return JDWP::ERR_NONE;
1126 }
1127 
FindLoadedClassBySignature(const char * descriptor,std::vector<JDWP::RefTypeId> * ids)1128 void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
1129   std::vector<ObjPtr<mirror::Class>> classes;
1130   Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1131   ids->clear();
1132   for (ObjPtr<mirror::Class> c : classes) {
1133     ids->push_back(gRegistry->Add(c));
1134   }
1135 }
1136 
GetReferenceType(JDWP::ObjectId object_id,JDWP::ExpandBuf * pReply)1137 JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1138   JDWP::JdwpError error;
1139   mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1140   if (o == nullptr) {
1141     return JDWP::ERR_INVALID_OBJECT;
1142   }
1143 
1144   JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
1145   JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
1146 
1147   expandBufAdd1(pReply, type_tag);
1148   expandBufAddRefTypeId(pReply, type_id);
1149 
1150   return JDWP::ERR_NONE;
1151 }
1152 
GetSignature(JDWP::RefTypeId class_id,std::string * signature)1153 JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
1154   JDWP::JdwpError error;
1155   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1156   if (c == nullptr) {
1157     return error;
1158   }
1159   std::string temp;
1160   *signature = c->GetDescriptor(&temp);
1161   return JDWP::ERR_NONE;
1162 }
1163 
GetSourceDebugExtension(JDWP::RefTypeId class_id,std::string * extension_data)1164 JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1165                                              std::string* extension_data) {
1166   JDWP::JdwpError error;
1167   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1168   if (c == nullptr) {
1169     return error;
1170   }
1171   StackHandleScope<1> hs(Thread::Current());
1172   Handle<mirror::Class> klass(hs.NewHandle(c));
1173   const char* data = annotations::GetSourceDebugExtension(klass);
1174   if (data == nullptr) {
1175     return JDWP::ERR_ABSENT_INFORMATION;
1176   }
1177   *extension_data = data;
1178   return JDWP::ERR_NONE;
1179 }
1180 
GetSourceFile(JDWP::RefTypeId class_id,std::string * result)1181 JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1182   JDWP::JdwpError error;
1183   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1184   if (c == nullptr) {
1185     return error;
1186   }
1187   const char* source_file = c->GetSourceFile();
1188   if (source_file == nullptr) {
1189     return JDWP::ERR_ABSENT_INFORMATION;
1190   }
1191   *result = source_file;
1192   return JDWP::ERR_NONE;
1193 }
1194 
GetObjectTag(JDWP::ObjectId object_id,uint8_t * tag)1195 JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
1196   ScopedObjectAccessUnchecked soa(Thread::Current());
1197   JDWP::JdwpError error;
1198   mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1199   if (error != JDWP::ERR_NONE) {
1200     *tag = JDWP::JT_VOID;
1201     return error;
1202   }
1203   *tag = TagFromObject(soa, o);
1204   return JDWP::ERR_NONE;
1205 }
1206 
GetTagWidth(JDWP::JdwpTag tag)1207 size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
1208   switch (tag) {
1209   case JDWP::JT_VOID:
1210     return 0;
1211   case JDWP::JT_BYTE:
1212   case JDWP::JT_BOOLEAN:
1213     return 1;
1214   case JDWP::JT_CHAR:
1215   case JDWP::JT_SHORT:
1216     return 2;
1217   case JDWP::JT_FLOAT:
1218   case JDWP::JT_INT:
1219     return 4;
1220   case JDWP::JT_ARRAY:
1221   case JDWP::JT_OBJECT:
1222   case JDWP::JT_STRING:
1223   case JDWP::JT_THREAD:
1224   case JDWP::JT_THREAD_GROUP:
1225   case JDWP::JT_CLASS_LOADER:
1226   case JDWP::JT_CLASS_OBJECT:
1227     return sizeof(JDWP::ObjectId);
1228   case JDWP::JT_DOUBLE:
1229   case JDWP::JT_LONG:
1230     return 8;
1231   default:
1232     LOG(FATAL) << "Unknown tag " << tag;
1233     UNREACHABLE();
1234   }
1235 }
1236 
GetArrayLength(JDWP::ObjectId array_id,int32_t * length)1237 JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1238   JDWP::JdwpError error;
1239   ObjPtr<mirror::Array> a = DecodeNonNullArray(array_id, &error);
1240   if (a == nullptr) {
1241     return error;
1242   }
1243   *length = a->GetLength();
1244   return JDWP::ERR_NONE;
1245 }
1246 
OutputArray(JDWP::ObjectId array_id,int offset,int count,JDWP::ExpandBuf * pReply)1247 JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id,
1248                                  int offset,
1249                                  int count,
1250                                  JDWP::ExpandBuf* pReply) {
1251   JDWP::JdwpError error;
1252   ObjPtr<mirror::Array> a = DecodeNonNullArray(array_id, &error);
1253   if (a == nullptr) {
1254     return error;
1255   }
1256 
1257   if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1258     LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
1259     return JDWP::ERR_INVALID_LENGTH;
1260   }
1261   JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1262   expandBufAdd1(pReply, element_tag);
1263   expandBufAdd4BE(pReply, count);
1264 
1265   if (IsPrimitiveTag(element_tag)) {
1266     size_t width = GetTagWidth(element_tag);
1267     uint8_t* dst = expandBufAddSpace(pReply, count * width);
1268     if (width == 8) {
1269       const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
1270       for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1271     } else if (width == 4) {
1272       const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
1273       for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1274     } else if (width == 2) {
1275       const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
1276       for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1277     } else {
1278       const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
1279       memcpy(dst, &src[offset * width], count * width);
1280     }
1281   } else {
1282     ScopedObjectAccessUnchecked soa(Thread::Current());
1283     ObjPtr<mirror::ObjectArray<mirror::Object>> oa = a->AsObjectArray<mirror::Object>();
1284     for (int i = 0; i < count; ++i) {
1285       ObjPtr<mirror::Object> element = oa->Get(offset + i);
1286       JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1287                                                         : element_tag;
1288       expandBufAdd1(pReply, specific_tag);
1289       expandBufAddObjectId(pReply, gRegistry->Add(element));
1290     }
1291   }
1292 
1293   return JDWP::ERR_NONE;
1294 }
1295 
1296 template <typename T>
CopyArrayData(ObjPtr<mirror::Array> a,JDWP::Request * src,int offset,int count)1297 static void CopyArrayData(ObjPtr<mirror::Array> a, JDWP::Request* src, int offset, int count)
1298     NO_THREAD_SAFETY_ANALYSIS {
1299   // TODO: fix when annotalysis correctly handles non-member functions.
1300   DCHECK(a->GetClass()->IsPrimitiveArray());
1301 
1302   T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
1303   for (int i = 0; i < count; ++i) {
1304     *dst++ = src->ReadValue(sizeof(T));
1305   }
1306 }
1307 
SetArrayElements(JDWP::ObjectId array_id,int offset,int count,JDWP::Request * request)1308 JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
1309                                       JDWP::Request* request) {
1310   JDWP::JdwpError error;
1311   ObjPtr<mirror::Array> dst = DecodeNonNullArray(array_id, &error);
1312   if (dst == nullptr) {
1313     return error;
1314   }
1315 
1316   if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
1317     LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
1318     return JDWP::ERR_INVALID_LENGTH;
1319   }
1320   JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
1321 
1322   if (IsPrimitiveTag(element_tag)) {
1323     size_t width = GetTagWidth(element_tag);
1324     if (width == 8) {
1325       CopyArrayData<uint64_t>(dst, request, offset, count);
1326     } else if (width == 4) {
1327       CopyArrayData<uint32_t>(dst, request, offset, count);
1328     } else if (width == 2) {
1329       CopyArrayData<uint16_t>(dst, request, offset, count);
1330     } else {
1331       CopyArrayData<uint8_t>(dst, request, offset, count);
1332     }
1333   } else {
1334     ObjPtr<mirror::ObjectArray<mirror::Object>> oa = dst->AsObjectArray<mirror::Object>();
1335     for (int i = 0; i < count; ++i) {
1336       JDWP::ObjectId id = request->ReadObjectId();
1337       ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(id, &error);
1338       if (error != JDWP::ERR_NONE) {
1339         return error;
1340       }
1341       // Check if the object's type is compatible with the array's type.
1342       if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1343         return JDWP::ERR_TYPE_MISMATCH;
1344       }
1345       oa->Set<false>(offset + i, o);
1346     }
1347   }
1348 
1349   return JDWP::ERR_NONE;
1350 }
1351 
CreateString(const std::string & str,JDWP::ObjectId * new_string_id)1352 JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1353   Thread* self = Thread::Current();
1354   ObjPtr<mirror::String> new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1355   if (new_string == nullptr) {
1356     DCHECK(self->IsExceptionPending());
1357     self->ClearException();
1358     LOG(ERROR) << "Could not allocate string";
1359     *new_string_id = 0;
1360     return JDWP::ERR_OUT_OF_MEMORY;
1361   }
1362   *new_string_id = gRegistry->Add(new_string);
1363   return JDWP::ERR_NONE;
1364 }
1365 
CreateObject(JDWP::RefTypeId class_id,JDWP::ObjectId * new_object_id)1366 JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
1367   JDWP::JdwpError error;
1368   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1369   if (c == nullptr) {
1370     *new_object_id = 0;
1371     return error;
1372   }
1373   Thread* self = Thread::Current();
1374   ObjPtr<mirror::Object> new_object;
1375   if (c->IsStringClass()) {
1376     // Special case for java.lang.String.
1377     gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
1378     new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
1379   } else {
1380     new_object = c->AllocObject(self);
1381   }
1382   if (new_object == nullptr) {
1383     DCHECK(self->IsExceptionPending());
1384     self->ClearException();
1385     LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
1386     *new_object_id = 0;
1387     return JDWP::ERR_OUT_OF_MEMORY;
1388   }
1389   *new_object_id = gRegistry->Add(new_object);
1390   return JDWP::ERR_NONE;
1391 }
1392 
1393 /*
1394  * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1395  */
CreateArrayObject(JDWP::RefTypeId array_class_id,uint32_t length,JDWP::ObjectId * new_array_id)1396 JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
1397                                        JDWP::ObjectId* new_array_id) {
1398   JDWP::JdwpError error;
1399   ObjPtr<mirror::Class> c = DecodeClass(array_class_id, &error);
1400   if (c == nullptr) {
1401     *new_array_id = 0;
1402     return error;
1403   }
1404   Thread* self = Thread::Current();
1405   gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
1406   ObjPtr<mirror::Array> new_array =
1407       mirror::Array::Alloc<true>(self, c, length, c->GetComponentSizeShift(), allocator_type);
1408   if (new_array == nullptr) {
1409     DCHECK(self->IsExceptionPending());
1410     self->ClearException();
1411     LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
1412     *new_array_id = 0;
1413     return JDWP::ERR_OUT_OF_MEMORY;
1414   }
1415   *new_array_id = gRegistry->Add(new_array);
1416   return JDWP::ERR_NONE;
1417 }
1418 
ToFieldId(const ArtField * f)1419 JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
1420   return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1421 }
1422 
ToMethodId(ArtMethod * m)1423 static JDWP::MethodId ToMethodId(ArtMethod* m)
1424     REQUIRES_SHARED(Locks::mutator_lock_) {
1425   return static_cast<JDWP::MethodId>(
1426       reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
1427 }
1428 
FromFieldId(JDWP::FieldId fid)1429 static ArtField* FromFieldId(JDWP::FieldId fid)
1430     REQUIRES_SHARED(Locks::mutator_lock_) {
1431   return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
1432 }
1433 
FromMethodId(JDWP::MethodId mid)1434 static ArtMethod* FromMethodId(JDWP::MethodId mid)
1435     REQUIRES_SHARED(Locks::mutator_lock_) {
1436   return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
1437 }
1438 
MatchThread(JDWP::ObjectId expected_thread_id,Thread * event_thread)1439 bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1440   CHECK(event_thread != nullptr);
1441   JDWP::JdwpError error;
1442   mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1443       expected_thread_id, &error);
1444   return expected_thread_peer == event_thread->GetPeerFromOtherThread();
1445 }
1446 
MatchLocation(const JDWP::JdwpLocation & expected_location,const JDWP::EventLocation & event_location)1447 bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1448                         const JDWP::EventLocation& event_location) {
1449   if (expected_location.dex_pc != event_location.dex_pc) {
1450     return false;
1451   }
1452   ArtMethod* m = FromMethodId(expected_location.method_id);
1453   return m == event_location.method;
1454 }
1455 
MatchType(ObjPtr<mirror::Class> event_class,JDWP::RefTypeId class_id)1456 bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
1457   if (event_class == nullptr) {
1458     return false;
1459   }
1460   JDWP::JdwpError error;
1461   ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
1462   CHECK(expected_class != nullptr);
1463   return expected_class->IsAssignableFrom(event_class);
1464 }
1465 
MatchField(JDWP::RefTypeId expected_type_id,JDWP::FieldId expected_field_id,ArtField * event_field)1466 bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
1467                      ArtField* event_field) {
1468   ArtField* expected_field = FromFieldId(expected_field_id);
1469   if (expected_field != event_field) {
1470     return false;
1471   }
1472   return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1473 }
1474 
MatchInstance(JDWP::ObjectId expected_instance_id,mirror::Object * event_instance)1475 bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1476   JDWP::JdwpError error;
1477   mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1478   return modifier_instance == event_instance;
1479 }
1480 
SetJdwpLocation(JDWP::JdwpLocation * location,ArtMethod * m,uint32_t dex_pc)1481 void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
1482   if (m == nullptr) {
1483     memset(location, 0, sizeof(*location));
1484   } else {
1485     ObjPtr<mirror::Class> c = m->GetDeclaringClass();
1486     location->type_tag = GetTypeTag(c);
1487     location->class_id = gRegistry->AddRefType(c);
1488     // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1489     location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
1490     location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
1491   }
1492 }
1493 
GetMethodName(JDWP::MethodId method_id)1494 std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
1495   ArtMethod* m = FromMethodId(method_id);
1496   if (m == nullptr) {
1497     return "null";
1498   }
1499   return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
1500 }
1501 
IsMethodObsolete(JDWP::MethodId method_id)1502 bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1503   ArtMethod* m = FromMethodId(method_id);
1504   if (m == nullptr) {
1505     // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1506     return true;
1507   }
1508   return m->IsObsolete();
1509 }
1510 
GetFieldName(JDWP::FieldId field_id)1511 std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
1512   ArtField* f = FromFieldId(field_id);
1513   if (f == nullptr) {
1514     return "null";
1515   }
1516   return f->GetName();
1517 }
1518 
1519 /*
1520  * Augment the access flags for synthetic methods and fields by setting
1521  * the (as described by the spec) "0xf0000000 bit".  Also, strip out any
1522  * flags not specified by the Java programming language.
1523  */
MangleAccessFlags(uint32_t accessFlags)1524 static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1525   accessFlags &= kAccJavaFlagsMask;
1526   if ((accessFlags & kAccSynthetic) != 0) {
1527     accessFlags |= 0xf0000000;
1528   }
1529   return accessFlags;
1530 }
1531 
1532 /*
1533  * Circularly shifts registers so that arguments come first. Debuggers
1534  * expect slots to begin with arguments, but dex code places them at
1535  * the end.
1536  */
MangleSlot(uint16_t slot,ArtMethod * m)1537 static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
1538     REQUIRES_SHARED(Locks::mutator_lock_) {
1539   CodeItemDataAccessor accessor(m->DexInstructionData());
1540   if (!accessor.HasCodeItem()) {
1541     // We should not get here for a method without code (native, proxy or abstract). Log it and
1542     // return the slot as is since all registers are arguments.
1543     LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
1544     return slot;
1545   }
1546   uint16_t ins_size = accessor.InsSize();
1547   uint16_t locals_size = accessor.RegistersSize() - ins_size;
1548   if (slot >= locals_size) {
1549     return slot - locals_size;
1550   } else {
1551     return slot + ins_size;
1552   }
1553 }
1554 
GetMethodNumArgRegistersIncludingThis(ArtMethod * method)1555 static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
1556     REQUIRES_SHARED(Locks::mutator_lock_) {
1557   uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1558   if (!method->IsStatic()) {
1559     ++num_registers;
1560   }
1561   return num_registers;
1562 }
1563 
1564 /*
1565  * Circularly shifts registers so that arguments come last. Reverts
1566  * slots to dex style argument placement.
1567  */
DemangleSlot(uint16_t slot,ArtMethod * m,JDWP::JdwpError * error)1568 static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
1569     REQUIRES_SHARED(Locks::mutator_lock_) {
1570   CodeItemDataAccessor accessor(m->DexInstructionData());
1571   if (!accessor.HasCodeItem()) {
1572     // We should not get here for a method without code (native, proxy or abstract). Log it and
1573     // return the slot as is since all registers are arguments.
1574     LOG(WARNING) << "Trying to demangle slot for method without code "
1575                  << m->PrettyMethod();
1576     uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
1577     if (slot < vreg_count) {
1578       *error = JDWP::ERR_NONE;
1579       return slot;
1580     }
1581   } else {
1582     if (slot < accessor.RegistersSize()) {
1583       uint16_t ins_size = accessor.InsSize();
1584       uint16_t locals_size = accessor.RegistersSize() - ins_size;
1585       *error = JDWP::ERR_NONE;
1586       return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1587     }
1588   }
1589 
1590   // Slot is invalid in the method.
1591   LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
1592   *error = JDWP::ERR_INVALID_SLOT;
1593   return DexFile::kDexNoIndex16;
1594 }
1595 
OutputDeclaredFields(JDWP::RefTypeId class_id,bool with_generic,JDWP::ExpandBuf * pReply)1596 JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1597                                           JDWP::ExpandBuf* pReply) {
1598   JDWP::JdwpError error;
1599   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1600   if (c == nullptr) {
1601     return error;
1602   }
1603 
1604   size_t instance_field_count = c->NumInstanceFields();
1605   size_t static_field_count = c->NumStaticFields();
1606 
1607   expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1608 
1609   for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1610     ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1611         c->GetStaticField(i - instance_field_count);
1612     expandBufAddFieldId(pReply, ToFieldId(f));
1613     expandBufAddUtf8String(pReply, f->GetName());
1614     expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
1615     if (with_generic) {
1616       static const char genericSignature[1] = "";
1617       expandBufAddUtf8String(pReply, genericSignature);
1618     }
1619     expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1620   }
1621   return JDWP::ERR_NONE;
1622 }
1623 
OutputDeclaredMethods(JDWP::RefTypeId class_id,bool with_generic,JDWP::ExpandBuf * pReply)1624 JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
1625                                            JDWP::ExpandBuf* pReply) {
1626   JDWP::JdwpError error;
1627   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1628   if (c == nullptr) {
1629     return error;
1630   }
1631 
1632   expandBufAdd4BE(pReply, c->NumMethods());
1633 
1634   auto* cl = Runtime::Current()->GetClassLinker();
1635   auto ptr_size = cl->GetImagePointerSize();
1636   for (ArtMethod& m : c->GetMethods(ptr_size)) {
1637     expandBufAddMethodId(pReply, ToMethodId(&m));
1638     expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1639     expandBufAddUtf8String(
1640         pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
1641     if (with_generic) {
1642       const char* generic_signature = "";
1643       expandBufAddUtf8String(pReply, generic_signature);
1644     }
1645     expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
1646   }
1647   return JDWP::ERR_NONE;
1648 }
1649 
OutputDeclaredInterfaces(JDWP::RefTypeId class_id,JDWP::ExpandBuf * pReply)1650 JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
1651   JDWP::JdwpError error;
1652   Thread* self = Thread::Current();
1653   ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1654   if (c == nullptr) {
1655     return error;
1656   }
1657   size_t interface_count = c->NumDirectInterfaces();
1658   expandBufAdd4BE(pReply, interface_count);
1659   for (size_t i = 0; i < interface_count; ++i) {
1660     ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1661     DCHECK(interface != nullptr);
1662     expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
1663   }
1664   return JDWP::ERR_NONE;
1665 }
1666 
OutputLineTable(JDWP::RefTypeId,JDWP::MethodId method_id,JDWP::ExpandBuf * pReply)1667 void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
1668   ArtMethod* m = FromMethodId(method_id);
1669   CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
1670   uint64_t start, end;
1671   if (!accessor.HasCodeItem()) {
1672     DCHECK(m->IsNative() || m->IsProxyMethod());
1673     start = -1;
1674     end = -1;
1675   } else {
1676     start = 0;
1677     // Return the index of the last instruction
1678     end = accessor.InsnsSizeInCodeUnits() - 1;
1679   }
1680 
1681   expandBufAdd8BE(pReply, start);
1682   expandBufAdd8BE(pReply, end);
1683 
1684   // Add numLines later
1685   size_t numLinesOffset = expandBufGetLength(pReply);
1686   expandBufAdd4BE(pReply, 0);
1687 
1688   int numItems = 0;
1689   accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
1690     expandBufAdd8BE(pReply, entry.address_);
1691     expandBufAdd4BE(pReply, entry.line_);
1692     numItems++;
1693     return false;
1694   });
1695 
1696   JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, numItems);
1697 }
1698 
OutputVariableTable(JDWP::RefTypeId,JDWP::MethodId method_id,bool with_generic,JDWP::ExpandBuf * pReply)1699 void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1700                               JDWP::ExpandBuf* pReply) {
1701   ArtMethod* m = FromMethodId(method_id);
1702   CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
1703 
1704   // arg_count considers doubles and longs to take 2 units.
1705   // variable_count considers everything to take 1 unit.
1706   expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
1707 
1708   // We don't know the total number of variables yet, so leave a blank and update it later.
1709   size_t variable_count_offset = expandBufGetLength(pReply);
1710   expandBufAdd4BE(pReply, 0);
1711 
1712   size_t variable_count = 0;
1713 
1714   if (accessor.HasCodeItem()) {
1715     accessor.DecodeDebugLocalInfo(m->IsStatic(),
1716                                   m->GetDexMethodIndex(),
1717                                   [&](const DexFile::LocalInfo& entry)
1718         REQUIRES_SHARED(Locks::mutator_lock_) {
1719       uint16_t slot = entry.reg_;
1720       VLOG(jdwp) << StringPrintf("    %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1721                                  variable_count,
1722                                  entry.start_address_,
1723                                  entry.end_address_ - entry.start_address_,
1724                                  entry.name_,
1725                                  entry.descriptor_, entry.signature_,
1726                                  slot,
1727                                  MangleSlot(slot, m));
1728 
1729       slot = MangleSlot(slot, m);
1730 
1731       expandBufAdd8BE(pReply, entry.start_address_);
1732       expandBufAddUtf8String(pReply, entry.name_);
1733       expandBufAddUtf8String(pReply, entry.descriptor_);
1734       if (with_generic) {
1735         expandBufAddUtf8String(pReply, entry.signature_);
1736       }
1737       expandBufAdd4BE(pReply, entry.end_address_- entry.start_address_);
1738       expandBufAdd4BE(pReply, slot);
1739 
1740       ++variable_count;
1741     });
1742   }
1743 
1744   JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, variable_count);
1745 }
1746 
OutputMethodReturnValue(JDWP::MethodId method_id,const JValue * return_value,JDWP::ExpandBuf * pReply)1747 void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1748                                   JDWP::ExpandBuf* pReply) {
1749   ArtMethod* m = FromMethodId(method_id);
1750   JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
1751   OutputJValue(tag, return_value, pReply);
1752 }
1753 
OutputFieldValue(JDWP::FieldId field_id,const JValue * field_value,JDWP::ExpandBuf * pReply)1754 void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1755                            JDWP::ExpandBuf* pReply) {
1756   ArtField* f = FromFieldId(field_id);
1757   JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
1758   OutputJValue(tag, field_value, pReply);
1759 }
1760 
GetBytecodes(JDWP::RefTypeId,JDWP::MethodId method_id,std::vector<uint8_t> * bytecodes)1761 JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1762                                   std::vector<uint8_t>* bytecodes) {
1763   ArtMethod* m = FromMethodId(method_id);
1764   if (m == nullptr) {
1765     return JDWP::ERR_INVALID_METHODID;
1766   }
1767   CodeItemDataAccessor accessor(m->DexInstructionData());
1768   size_t byte_count = accessor.InsnsSizeInCodeUnits() * 2;
1769   const uint8_t* begin = reinterpret_cast<const uint8_t*>(accessor.Insns());
1770   const uint8_t* end = begin + byte_count;
1771   for (const uint8_t* p = begin; p != end; ++p) {
1772     bytecodes->push_back(*p);
1773   }
1774   return JDWP::ERR_NONE;
1775 }
1776 
GetFieldBasicTag(JDWP::FieldId field_id)1777 JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1778   return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
1779 }
1780 
GetStaticFieldBasicTag(JDWP::FieldId field_id)1781 JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1782   return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
1783 }
1784 
GetArtFieldValue(ArtField * f,mirror::Object * o)1785 static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
1786     REQUIRES_SHARED(Locks::mutator_lock_) {
1787   Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1788   JValue field_value;
1789   switch (fieldType) {
1790     case Primitive::kPrimBoolean:
1791       field_value.SetZ(f->GetBoolean(o));
1792       return field_value;
1793 
1794     case Primitive::kPrimByte:
1795       field_value.SetB(f->GetByte(o));
1796       return field_value;
1797 
1798     case Primitive::kPrimChar:
1799       field_value.SetC(f->GetChar(o));
1800       return field_value;
1801 
1802     case Primitive::kPrimShort:
1803       field_value.SetS(f->GetShort(o));
1804       return field_value;
1805 
1806     case Primitive::kPrimInt:
1807     case Primitive::kPrimFloat:
1808       // Int and Float must be treated as 32-bit values in JDWP.
1809       field_value.SetI(f->GetInt(o));
1810       return field_value;
1811 
1812     case Primitive::kPrimLong:
1813     case Primitive::kPrimDouble:
1814       // Long and Double must be treated as 64-bit values in JDWP.
1815       field_value.SetJ(f->GetLong(o));
1816       return field_value;
1817 
1818     case Primitive::kPrimNot:
1819       field_value.SetL(f->GetObject(o));
1820       return field_value;
1821 
1822     case Primitive::kPrimVoid:
1823       LOG(FATAL) << "Attempt to read from field of type 'void'";
1824       UNREACHABLE();
1825   }
1826   LOG(FATAL) << "Attempt to read from field of unknown type";
1827   UNREACHABLE();
1828 }
1829 
GetFieldValueImpl(JDWP::RefTypeId ref_type_id,JDWP::ObjectId object_id,JDWP::FieldId field_id,JDWP::ExpandBuf * pReply,bool is_static)1830 static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1831                                          JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
1832                                          bool is_static)
1833     REQUIRES_SHARED(Locks::mutator_lock_) {
1834   JDWP::JdwpError error;
1835   ObjPtr<mirror::Class> c = DecodeClass(ref_type_id, &error);
1836   if (ref_type_id != 0 && c == nullptr) {
1837     return error;
1838   }
1839 
1840   Thread* self = Thread::Current();
1841   StackHandleScope<2> hs(self);
1842   MutableHandle<mirror::Object>
1843       o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
1844   if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
1845     return JDWP::ERR_INVALID_OBJECT;
1846   }
1847   ArtField* f = FromFieldId(field_id);
1848 
1849   ObjPtr<mirror::Class> receiver_class = c;
1850   if (receiver_class == nullptr && o != nullptr) {
1851     receiver_class = o->GetClass();
1852   }
1853 
1854   // TODO: should we give up now if receiver_class is null?
1855   if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1856     LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1857               << receiver_class->PrettyClass();
1858     return JDWP::ERR_INVALID_FIELDID;
1859   }
1860 
1861   // Ensure the field's class is initialized.
1862   Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1863   if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
1864     LOG(WARNING) << "Not able to initialize class for SetValues: "
1865                  << mirror::Class::PrettyClass(klass.Get());
1866   }
1867 
1868   // The RI only enforces the static/non-static mismatch in one direction.
1869   // TODO: should we change the tests and check both?
1870   if (is_static) {
1871     if (!f->IsStatic()) {
1872       return JDWP::ERR_INVALID_FIELDID;
1873     }
1874   } else {
1875     if (f->IsStatic()) {
1876       LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
1877                    << " on static field " << f->PrettyField();
1878     }
1879   }
1880   if (f->IsStatic()) {
1881     o.Assign(f->GetDeclaringClass());
1882   }
1883 
1884   JValue field_value(GetArtFieldValue(f, o.Get()));
1885   JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
1886   Dbg::OutputJValue(tag, &field_value, pReply);
1887   return JDWP::ERR_NONE;
1888 }
1889 
GetFieldValue(JDWP::ObjectId object_id,JDWP::FieldId field_id,JDWP::ExpandBuf * pReply)1890 JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
1891                                    JDWP::ExpandBuf* pReply) {
1892   return GetFieldValueImpl(0, object_id, field_id, pReply, false);
1893 }
1894 
GetStaticFieldValue(JDWP::RefTypeId ref_type_id,JDWP::FieldId field_id,JDWP::ExpandBuf * pReply)1895 JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1896                                          JDWP::ExpandBuf* pReply) {
1897   return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
1898 }
1899 
SetArtFieldValue(ArtField * f,mirror::Object * o,uint64_t value,int width)1900 static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
1901     REQUIRES_SHARED(Locks::mutator_lock_) {
1902   Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1903   // Debugging only happens at runtime so we know we are not running in a transaction.
1904   static constexpr bool kNoTransactionMode = false;
1905   switch (fieldType) {
1906     case Primitive::kPrimBoolean:
1907       CHECK_EQ(width, 1);
1908       f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1909       return JDWP::ERR_NONE;
1910 
1911     case Primitive::kPrimByte:
1912       CHECK_EQ(width, 1);
1913       f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1914       return JDWP::ERR_NONE;
1915 
1916     case Primitive::kPrimChar:
1917       CHECK_EQ(width, 2);
1918       f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1919       return JDWP::ERR_NONE;
1920 
1921     case Primitive::kPrimShort:
1922       CHECK_EQ(width, 2);
1923       f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1924       return JDWP::ERR_NONE;
1925 
1926     case Primitive::kPrimInt:
1927     case Primitive::kPrimFloat:
1928       CHECK_EQ(width, 4);
1929       // Int and Float must be treated as 32-bit values in JDWP.
1930       f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1931       return JDWP::ERR_NONE;
1932 
1933     case Primitive::kPrimLong:
1934     case Primitive::kPrimDouble:
1935       CHECK_EQ(width, 8);
1936       // Long and Double must be treated as 64-bit values in JDWP.
1937       f->SetLong<kNoTransactionMode>(o, value);
1938       return JDWP::ERR_NONE;
1939 
1940     case Primitive::kPrimNot: {
1941       JDWP::JdwpError error;
1942       mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1943       if (error != JDWP::ERR_NONE) {
1944         return JDWP::ERR_INVALID_OBJECT;
1945       }
1946       if (v != nullptr) {
1947         ObjPtr<mirror::Class> field_type;
1948         {
1949           StackHandleScope<2> hs(Thread::Current());
1950           HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1951           HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1952           field_type = f->ResolveType();
1953         }
1954         if (!field_type->IsAssignableFrom(v->GetClass())) {
1955           return JDWP::ERR_INVALID_OBJECT;
1956         }
1957       }
1958       f->SetObject<kNoTransactionMode>(o, v);
1959       return JDWP::ERR_NONE;
1960     }
1961 
1962     case Primitive::kPrimVoid:
1963       LOG(FATAL) << "Attempt to write to field of type 'void'";
1964       UNREACHABLE();
1965   }
1966   LOG(FATAL) << "Attempt to write to field of unknown type";
1967   UNREACHABLE();
1968 }
1969 
SetFieldValueImpl(JDWP::ObjectId object_id,JDWP::FieldId field_id,uint64_t value,int width,bool is_static)1970 static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
1971                                          uint64_t value, int width, bool is_static)
1972     REQUIRES_SHARED(Locks::mutator_lock_) {
1973   JDWP::JdwpError error;
1974   Thread* self = Thread::Current();
1975   StackHandleScope<2> hs(self);
1976   MutableHandle<mirror::Object>
1977       o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
1978   if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
1979     return JDWP::ERR_INVALID_OBJECT;
1980   }
1981   ArtField* f = FromFieldId(field_id);
1982 
1983   // Ensure the field's class is initialized.
1984   Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1985   if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
1986     LOG(WARNING) << "Not able to initialize class for SetValues: "
1987                  << mirror::Class::PrettyClass(klass.Get());
1988   }
1989 
1990   // The RI only enforces the static/non-static mismatch in one direction.
1991   // TODO: should we change the tests and check both?
1992   if (is_static) {
1993     if (!f->IsStatic()) {
1994       return JDWP::ERR_INVALID_FIELDID;
1995     }
1996   } else {
1997     if (f->IsStatic()) {
1998       LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
1999                    << " on static field " << f->PrettyField();
2000     }
2001   }
2002   if (f->IsStatic()) {
2003     o.Assign(f->GetDeclaringClass());
2004   }
2005   return SetArtFieldValue(f, o.Get(), value, width);
2006 }
2007 
SetFieldValue(JDWP::ObjectId object_id,JDWP::FieldId field_id,uint64_t value,int width)2008 JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
2009                                    int width) {
2010   return SetFieldValueImpl(object_id, field_id, value, width, false);
2011 }
2012 
SetStaticFieldValue(JDWP::FieldId field_id,uint64_t value,int width)2013 JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2014   return SetFieldValueImpl(0, field_id, value, width, true);
2015 }
2016 
StringToUtf8(JDWP::ObjectId string_id,std::string * str)2017 JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
2018   JDWP::JdwpError error;
2019   mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
2020   if (error != JDWP::ERR_NONE) {
2021     return error;
2022   }
2023   if (obj == nullptr) {
2024     return JDWP::ERR_INVALID_OBJECT;
2025   }
2026   {
2027     ScopedObjectAccessUnchecked soa(Thread::Current());
2028     ObjPtr<mirror::Class> java_lang_String =
2029         soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
2030     if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2031       // This isn't a string.
2032       return JDWP::ERR_INVALID_STRING;
2033     }
2034   }
2035   *str = obj->AsString()->ToModifiedUtf8();
2036   return JDWP::ERR_NONE;
2037 }
2038 
OutputJValue(JDWP::JdwpTag tag,const JValue * return_value,JDWP::ExpandBuf * pReply)2039 void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2040   if (IsPrimitiveTag(tag)) {
2041     expandBufAdd1(pReply, tag);
2042     if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2043       expandBufAdd1(pReply, return_value->GetI());
2044     } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2045       expandBufAdd2BE(pReply, return_value->GetI());
2046     } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2047       expandBufAdd4BE(pReply, return_value->GetI());
2048     } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2049       expandBufAdd8BE(pReply, return_value->GetJ());
2050     } else {
2051       CHECK_EQ(tag, JDWP::JT_VOID);
2052     }
2053   } else {
2054     ScopedObjectAccessUnchecked soa(Thread::Current());
2055     mirror::Object* value = return_value->GetL();
2056     expandBufAdd1(pReply, TagFromObject(soa, value));
2057     expandBufAddObjectId(pReply, gRegistry->Add(value));
2058   }
2059 }
2060 
GetThreadName(JDWP::ObjectId thread_id,std::string * name)2061 JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
2062   ScopedObjectAccessUnchecked soa(Thread::Current());
2063   JDWP::JdwpError error;
2064   DecodeThread(soa, thread_id, &error);
2065   if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2066     return error;
2067   }
2068 
2069   // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
2070   mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2071   CHECK(thread_object != nullptr) << error;
2072   ArtField* java_lang_Thread_name_field =
2073       jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
2074   ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
2075   if (s != nullptr) {
2076     *name = s->ToModifiedUtf8();
2077   }
2078   return JDWP::ERR_NONE;
2079 }
2080 
GetThreadGroup(JDWP::ObjectId thread_id,JDWP::ExpandBuf * pReply)2081 JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
2082   ScopedObjectAccessUnchecked soa(Thread::Current());
2083   JDWP::JdwpError error;
2084   mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2085   if (error != JDWP::ERR_NONE) {
2086     return JDWP::ERR_INVALID_OBJECT;
2087   }
2088   ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
2089   // Okay, so it's an object, but is it actually a thread?
2090   DecodeThread(soa, thread_id, &error);
2091   if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2092     // Zombie threads are in the null group.
2093     expandBufAddObjectId(pReply, JDWP::ObjectId(0));
2094     error = JDWP::ERR_NONE;
2095   } else if (error == JDWP::ERR_NONE) {
2096     ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
2097     CHECK(c != nullptr);
2098     ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
2099     CHECK(f != nullptr);
2100     ObjPtr<mirror::Object> group = f->GetObject(thread_object);
2101     CHECK(group != nullptr);
2102     JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2103     expandBufAddObjectId(pReply, thread_group_id);
2104   }
2105   return error;
2106 }
2107 
DecodeThreadGroup(ScopedObjectAccessUnchecked & soa,JDWP::ObjectId thread_group_id,JDWP::JdwpError * error)2108 static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2109                                          JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
2110     REQUIRES_SHARED(Locks::mutator_lock_) {
2111   mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2112                                                                                 error);
2113   if (*error != JDWP::ERR_NONE) {
2114     return nullptr;
2115   }
2116   if (thread_group == nullptr) {
2117     *error = JDWP::ERR_INVALID_OBJECT;
2118     return nullptr;
2119   }
2120   ObjPtr<mirror::Class> c =
2121       soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
2122   CHECK(c != nullptr);
2123   if (!c->IsAssignableFrom(thread_group->GetClass())) {
2124     // This is not a java.lang.ThreadGroup.
2125     *error = JDWP::ERR_INVALID_THREAD_GROUP;
2126     return nullptr;
2127   }
2128   *error = JDWP::ERR_NONE;
2129   return thread_group;
2130 }
2131 
GetThreadGroupName(JDWP::ObjectId thread_group_id,JDWP::ExpandBuf * pReply)2132 JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2133   ScopedObjectAccessUnchecked soa(Thread::Current());
2134   JDWP::JdwpError error;
2135   mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2136   if (error != JDWP::ERR_NONE) {
2137     return error;
2138   }
2139   ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
2140   ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
2141   CHECK(f != nullptr);
2142   ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
2143 
2144   std::string thread_group_name(s->ToModifiedUtf8());
2145   expandBufAddUtf8String(pReply, thread_group_name);
2146   return JDWP::ERR_NONE;
2147 }
2148 
GetThreadGroupParent(JDWP::ObjectId thread_group_id,JDWP::ExpandBuf * pReply)2149 JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2150   ScopedObjectAccessUnchecked soa(Thread::Current());
2151   JDWP::JdwpError error;
2152   mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2153   if (error != JDWP::ERR_NONE) {
2154     return error;
2155   }
2156   ObjPtr<mirror::Object> parent;
2157   {
2158     ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
2159     ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
2160     CHECK(f != nullptr);
2161     parent = f->GetObject(thread_group);
2162   }
2163   JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2164   expandBufAddObjectId(pReply, parent_group_id);
2165   return JDWP::ERR_NONE;
2166 }
2167 
GetChildThreadGroups(mirror::Object * thread_group,std::vector<JDWP::ObjectId> * child_thread_group_ids)2168 static void GetChildThreadGroups(mirror::Object* thread_group,
2169                                  std::vector<JDWP::ObjectId>* child_thread_group_ids)
2170     REQUIRES_SHARED(Locks::mutator_lock_) {
2171   CHECK(thread_group != nullptr);
2172 
2173   // Get the int "ngroups" count of this thread group...
2174   ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
2175   CHECK(ngroups_field != nullptr);
2176   const int32_t size = ngroups_field->GetInt(thread_group);
2177   if (size == 0) {
2178     return;
2179   }
2180 
2181   // Get the ThreadGroup[] "groups" out of this thread group...
2182   ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
2183   ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
2184 
2185   CHECK(groups_array != nullptr);
2186   CHECK(groups_array->IsObjectArray());
2187 
2188   ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
2189       groups_array->AsObjectArray<mirror::Object>();
2190 
2191   // Copy the first 'size' elements out of the array into the result.
2192   ObjectRegistry* registry = Dbg::GetObjectRegistry();
2193   for (int32_t i = 0; i < size; ++i) {
2194     child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
2195   }
2196 }
2197 
GetThreadGroupChildren(JDWP::ObjectId thread_group_id,JDWP::ExpandBuf * pReply)2198 JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2199                                             JDWP::ExpandBuf* pReply) {
2200   ScopedObjectAccessUnchecked soa(Thread::Current());
2201   JDWP::JdwpError error;
2202   mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2203   if (error != JDWP::ERR_NONE) {
2204     return error;
2205   }
2206 
2207   // Add child threads.
2208   {
2209     std::vector<JDWP::ObjectId> child_thread_ids;
2210     GetThreads(thread_group, &child_thread_ids);
2211     expandBufAdd4BE(pReply, child_thread_ids.size());
2212     for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2213       expandBufAddObjectId(pReply, child_thread_id);
2214     }
2215   }
2216 
2217   // Add child thread groups.
2218   {
2219     std::vector<JDWP::ObjectId> child_thread_groups_ids;
2220     GetChildThreadGroups(thread_group, &child_thread_groups_ids);
2221     expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2222     for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2223       expandBufAddObjectId(pReply, child_thread_group_id);
2224     }
2225   }
2226 
2227   return JDWP::ERR_NONE;
2228 }
2229 
GetSystemThreadGroupId()2230 JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
2231   ScopedObjectAccessUnchecked soa(Thread::Current());
2232   ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
2233   ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
2234   return gRegistry->Add(group);
2235 }
2236 
ToJdwpThreadStatus(ThreadState state)2237 JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2238   switch (state) {
2239     case kBlocked:
2240       return JDWP::TS_MONITOR;
2241     case kNative:
2242     case kRunnable:
2243     case kSuspended:
2244       return JDWP::TS_RUNNING;
2245     case kSleeping:
2246       return JDWP::TS_SLEEPING;
2247     case kStarting:
2248     case kTerminated:
2249       return JDWP::TS_ZOMBIE;
2250     case kTimedWaiting:
2251     case kWaitingForTaskProcessor:
2252     case kWaitingForLockInflation:
2253     case kWaitingForCheckPointsToRun:
2254     case kWaitingForDebuggerSend:
2255     case kWaitingForDebuggerSuspension:
2256     case kWaitingForDebuggerToAttach:
2257     case kWaitingForDeoptimization:
2258     case kWaitingForGcToComplete:
2259     case kWaitingForGetObjectsAllocated:
2260     case kWaitingForJniOnLoad:
2261     case kWaitingForMethodTracingStart:
2262     case kWaitingForSignalCatcherOutput:
2263     case kWaitingForVisitObjects:
2264     case kWaitingInMainDebuggerLoop:
2265     case kWaitingInMainSignalCatcherLoop:
2266     case kWaitingPerformingGc:
2267     case kWaitingWeakGcRootRead:
2268     case kWaitingForGcThreadFlip:
2269     case kNativeForAbort:
2270     case kWaiting:
2271       return JDWP::TS_WAIT;
2272       // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2273   }
2274   LOG(FATAL) << "Unknown thread state: " << state;
2275   UNREACHABLE();
2276 }
2277 
GetThreadStatus(JDWP::ObjectId thread_id,JDWP::JdwpThreadStatus * pThreadStatus,JDWP::JdwpSuspendStatus * pSuspendStatus)2278 JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2279                                      JDWP::JdwpSuspendStatus* pSuspendStatus) {
2280   ScopedObjectAccess soa(Thread::Current());
2281 
2282   *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2283 
2284   JDWP::JdwpError error;
2285   Thread* thread = DecodeThread(soa, thread_id, &error);
2286   if (error != JDWP::ERR_NONE) {
2287     if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2288       *pThreadStatus = JDWP::TS_ZOMBIE;
2289       return JDWP::ERR_NONE;
2290     }
2291     return error;
2292   }
2293 
2294   if (IsSuspendedForDebugger(soa, thread)) {
2295     *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
2296   }
2297 
2298   *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
2299   return JDWP::ERR_NONE;
2300 }
2301 
GetThreadDebugSuspendCount(JDWP::ObjectId thread_id,JDWP::ExpandBuf * pReply)2302 JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
2303   ScopedObjectAccess soa(Thread::Current());
2304   JDWP::JdwpError error;
2305   Thread* thread = DecodeThread(soa, thread_id, &error);
2306   if (error != JDWP::ERR_NONE) {
2307     return error;
2308   }
2309   MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
2310   expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
2311   return JDWP::ERR_NONE;
2312 }
2313 
Interrupt(JDWP::ObjectId thread_id)2314 JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2315   ScopedObjectAccess soa(Thread::Current());
2316   JDWP::JdwpError error;
2317   Thread* thread = DecodeThread(soa, thread_id, &error);
2318   if (error != JDWP::ERR_NONE) {
2319     return error;
2320   }
2321   thread->Interrupt(soa.Self());
2322   return JDWP::ERR_NONE;
2323 }
2324 
IsInDesiredThreadGroup(mirror::Object * desired_thread_group,mirror::Object * peer)2325 static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
2326     REQUIRES_SHARED(Locks::mutator_lock_) {
2327   // Do we want threads from all thread groups?
2328   if (desired_thread_group == nullptr) {
2329     return true;
2330   }
2331   ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
2332   DCHECK(thread_group_field != nullptr);
2333   ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
2334   return (group == desired_thread_group);
2335 }
2336 
GetThreads(mirror::Object * thread_group,std::vector<JDWP::ObjectId> * thread_ids)2337 void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
2338   ScopedObjectAccessUnchecked soa(Thread::Current());
2339   std::list<Thread*> all_threads_list;
2340   {
2341     MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2342     all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2343   }
2344   for (Thread* t : all_threads_list) {
2345     if (t == Dbg::GetDebugThread()) {
2346       // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2347       // query all threads, so it's easier if we just don't tell them about this thread.
2348       continue;
2349     }
2350     if (t->IsStillStarting()) {
2351       // This thread is being started (and has been registered in the thread list). However, it is
2352       // not completely started yet so we must ignore it.
2353       continue;
2354     }
2355     mirror::Object* peer = t->GetPeerFromOtherThread();
2356     if (peer == nullptr) {
2357       // peer might be null if the thread is still starting up. We can't tell the debugger about
2358       // this thread yet.
2359       // TODO: if we identified threads to the debugger by their Thread*
2360       // rather than their peer's mirror::Object*, we could fix this.
2361       // Doing so might help us report ZOMBIE threads too.
2362       continue;
2363     }
2364     if (IsInDesiredThreadGroup(thread_group, peer)) {
2365       thread_ids->push_back(gRegistry->Add(peer));
2366     }
2367   }
2368 }
2369 
GetStackDepth(Thread * thread)2370 static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
2371   size_t depth = 0u;
2372   StackVisitor::WalkStack(
2373       [&depth](const StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2374         if (!visitor->GetMethod()->IsRuntimeMethod()) {
2375           ++depth;
2376         }
2377         return true;
2378       },
2379       thread,
2380       /* context= */ nullptr,
2381       StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2382   return depth;
2383 }
2384 
GetThreadFrameCount(JDWP::ObjectId thread_id,size_t * result)2385 JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
2386   ScopedObjectAccess soa(Thread::Current());
2387   JDWP::JdwpError error;
2388   *result = 0;
2389   Thread* thread = DecodeThread(soa, thread_id, &error);
2390   if (error != JDWP::ERR_NONE) {
2391     return error;
2392   }
2393   if (!IsSuspendedForDebugger(soa, thread)) {
2394     return JDWP::ERR_THREAD_NOT_SUSPENDED;
2395   }
2396   *result = GetStackDepth(thread);
2397   return JDWP::ERR_NONE;
2398 }
2399 
GetThreadFrames(JDWP::ObjectId thread_id,const size_t start_frame,const size_t frame_count,JDWP::ExpandBuf * buf)2400 JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id,
2401                                      const size_t start_frame,
2402                                      const size_t frame_count,
2403                                      JDWP::ExpandBuf* buf) {
2404   ScopedObjectAccessUnchecked soa(Thread::Current());
2405   JDWP::JdwpError error;
2406   Thread* thread = DecodeThread(soa, thread_id, &error);
2407   if (error != JDWP::ERR_NONE) {
2408     return error;
2409   }
2410   if (!IsSuspendedForDebugger(soa, thread)) {
2411     return JDWP::ERR_THREAD_NOT_SUSPENDED;
2412   }
2413 
2414   expandBufAdd4BE(buf, frame_count);
2415 
2416   size_t depth = 0u;
2417   StackVisitor::WalkStack(
2418       [&](StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2419         if (visitor->GetMethod()->IsRuntimeMethod()) {
2420           return true;  // The debugger can't do anything useful with a frame that has no Method*.
2421         }
2422         if (depth >= start_frame + frame_count) {
2423           return false;
2424         }
2425         if (depth >= start_frame) {
2426           JDWP::FrameId frame_id(visitor->GetFrameId());
2427           JDWP::JdwpLocation location;
2428           SetJdwpLocation(&location, visitor->GetMethod(), visitor->GetDexPc());
2429           VLOG(jdwp)
2430               << StringPrintf("    Frame %3zd: id=%3" PRIu64 " ", depth, frame_id) << location;
2431           expandBufAdd8BE(buf, frame_id);
2432           expandBufAddLocation(buf, location);
2433         }
2434         ++depth;
2435         return true;
2436       },
2437       thread,
2438       /* context= */ nullptr,
2439       StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2440 
2441   return JDWP::ERR_NONE;
2442 }
2443 
GetThreadSelfId()2444 JDWP::ObjectId Dbg::GetThreadSelfId() {
2445   return GetThreadId(Thread::Current());
2446 }
2447 
GetThreadId(Thread * thread)2448 JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
2449   ScopedObjectAccessUnchecked soa(Thread::Current());
2450   return gRegistry->Add(thread->GetPeerFromOtherThread());
2451 }
2452 
SuspendVM()2453 void Dbg::SuspendVM() {
2454   // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2455   gc::ScopedGCCriticalSection gcs(Thread::Current(),
2456                                   gc::kGcCauseDebugger,
2457                                   gc::kCollectorTypeDebugger);
2458   Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
2459 }
2460 
ResumeVM()2461 void Dbg::ResumeVM() {
2462   Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
2463 }
2464 
SuspendThread(JDWP::ObjectId thread_id,bool request_suspension)2465 JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
2466   Thread* self = Thread::Current();
2467   ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
2468   {
2469     ScopedObjectAccess soa(self);
2470     JDWP::JdwpError error;
2471     peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
2472   }
2473   if (peer.get() == nullptr) {
2474     return JDWP::ERR_THREAD_NOT_ALIVE;
2475   }
2476   // Suspend thread to build stack trace.
2477   bool timed_out;
2478   ThreadList* thread_list = Runtime::Current()->GetThreadList();
2479   Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2480                                                     request_suspension,
2481                                                     SuspendReason::kForDebugger,
2482                                                     &timed_out);
2483   if (thread != nullptr) {
2484     return JDWP::ERR_NONE;
2485   } else if (timed_out) {
2486     return JDWP::ERR_INTERNAL;
2487   } else {
2488     return JDWP::ERR_THREAD_NOT_ALIVE;
2489   }
2490 }
2491 
ResumeThread(JDWP::ObjectId thread_id)2492 void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
2493   ScopedObjectAccessUnchecked soa(Thread::Current());
2494   JDWP::JdwpError error;
2495   mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2496   CHECK(peer != nullptr) << error;
2497   Thread* thread;
2498   {
2499     MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2500     thread = Thread::FromManagedThread(soa, peer);
2501   }
2502   if (thread == nullptr) {
2503     LOG(WARNING) << "No such thread for resume: " << peer;
2504     return;
2505   }
2506   bool needs_resume;
2507   {
2508     MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
2509     needs_resume = thread->GetDebugSuspendCount() > 0;
2510   }
2511   if (needs_resume) {
2512     bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2513     DCHECK(resumed);
2514   }
2515 }
2516 
SuspendSelf()2517 void Dbg::SuspendSelf() {
2518   Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
2519 }
2520 
GetThisObject(JDWP::ObjectId thread_id,JDWP::FrameId frame_id,JDWP::ObjectId * result)2521 JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2522                                    JDWP::ObjectId* result) {
2523   ScopedObjectAccessUnchecked soa(Thread::Current());
2524   JDWP::JdwpError error;
2525   Thread* thread = DecodeThread(soa, thread_id, &error);
2526   if (error != JDWP::ERR_NONE) {
2527     return error;
2528   }
2529   if (!IsSuspendedForDebugger(soa, thread)) {
2530     return JDWP::ERR_THREAD_NOT_SUSPENDED;
2531   }
2532   std::unique_ptr<Context> context(Context::Create());
2533   mirror::Object* this_object = nullptr;
2534   StackVisitor::WalkStack(
2535       [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2536         if (frame_id != stack_visitor->GetFrameId()) {
2537           return true;  // continue
2538         } else {
2539           this_object = stack_visitor->GetThisObject();
2540           return false;
2541         }
2542       },
2543       thread,
2544       context.get(),
2545       art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2546   *result = gRegistry->Add(this_object);
2547   return JDWP::ERR_NONE;
2548 }
2549 
2550 template <typename FrameHandler>
FindAndHandleNonNativeFrame(Thread * thread,JDWP::FrameId frame_id,const FrameHandler & handler)2551 static JDWP::JdwpError FindAndHandleNonNativeFrame(Thread* thread,
2552                                                    JDWP::FrameId frame_id,
2553                                                    const FrameHandler& handler)
2554     REQUIRES_SHARED(Locks::mutator_lock_) {
2555   JDWP::JdwpError result = JDWP::ERR_INVALID_FRAMEID;
2556   std::unique_ptr<Context> context(Context::Create());
2557   StackVisitor::WalkStack(
2558       [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2559         if (stack_visitor->GetFrameId() != frame_id) {
2560           return true;  // Not our frame, carry on.
2561         }
2562         ArtMethod* m = stack_visitor->GetMethod();
2563         if (m->IsNative()) {
2564           // We can't read/write local value from/into native method.
2565           result = JDWP::ERR_OPAQUE_FRAME;
2566         } else {
2567           // We found our frame.
2568           result = handler(stack_visitor);
2569         }
2570         return false;
2571       },
2572       thread,
2573       context.get(),
2574       art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2575   return result;
2576 }
2577 
GetLocalValues(JDWP::Request * request,JDWP::ExpandBuf * pReply)2578 JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2579   JDWP::ObjectId thread_id = request->ReadThreadId();
2580   JDWP::FrameId frame_id = request->ReadFrameId();
2581 
2582   ScopedObjectAccessUnchecked soa(Thread::Current());
2583   JDWP::JdwpError error;
2584   Thread* thread = DecodeThread(soa, thread_id, &error);
2585   if (error != JDWP::ERR_NONE) {
2586     return error;
2587   }
2588   if (!IsSuspendedForDebugger(soa, thread)) {
2589     return JDWP::ERR_THREAD_NOT_SUSPENDED;
2590   }
2591 
2592   return FindAndHandleNonNativeFrame(
2593       thread,
2594       frame_id,
2595       [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2596         // Read the values from visitor's context.
2597         int32_t slot_count = request->ReadSigned32("slot count");
2598         expandBufAdd4BE(pReply, slot_count);     /* "int values" */
2599         for (int32_t i = 0; i < slot_count; ++i) {
2600           uint32_t slot = request->ReadUnsigned32("slot");
2601           JDWP::JdwpTag reqSigByte = request->ReadTag();
2602 
2603           VLOG(jdwp) << "    --> slot " << slot << " " << reqSigByte;
2604 
2605           size_t width = Dbg::GetTagWidth(reqSigByte);
2606           uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
2607           error = Dbg::GetLocalValue(*stack_visitor, soa, slot, reqSigByte, ptr, width);
2608           if (error != JDWP::ERR_NONE) {
2609             return error;
2610           }
2611         }
2612         return JDWP::ERR_NONE;
2613       });
2614 }
2615 
2616 constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2617 
GetStackContextAsString(const StackVisitor & visitor)2618 static std::string GetStackContextAsString(const StackVisitor& visitor)
2619     REQUIRES_SHARED(Locks::mutator_lock_) {
2620   return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2621                       ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
2622 }
2623 
FailGetLocalValue(const StackVisitor & visitor,uint16_t vreg,JDWP::JdwpTag tag)2624 static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2625                                          JDWP::JdwpTag tag)
2626     REQUIRES_SHARED(Locks::mutator_lock_) {
2627   LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2628              << GetStackContextAsString(visitor);
2629   return kStackFrameLocalAccessError;
2630 }
2631 
GetLocalValue(const StackVisitor & visitor,ScopedObjectAccessUnchecked & soa,int slot,JDWP::JdwpTag tag,uint8_t * buf,size_t width)2632 JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2633                                    int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
2634   ArtMethod* m = visitor.GetMethod();
2635   JDWP::JdwpError error = JDWP::ERR_NONE;
2636   uint16_t vreg = DemangleSlot(slot, m, &error);
2637   if (error != JDWP::ERR_NONE) {
2638     return error;
2639   }
2640   // TODO: check that the tag is compatible with the actual type of the slot!
2641   switch (tag) {
2642     case JDWP::JT_BOOLEAN: {
2643       CHECK_EQ(width, 1U);
2644       uint32_t intVal;
2645       if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2646         return FailGetLocalValue(visitor, vreg, tag);
2647       }
2648       VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2649       JDWP::Set1(buf + 1, intVal != 0);
2650       break;
2651     }
2652     case JDWP::JT_BYTE: {
2653       CHECK_EQ(width, 1U);
2654       uint32_t intVal;
2655       if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2656         return FailGetLocalValue(visitor, vreg, tag);
2657       }
2658       VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2659       JDWP::Set1(buf + 1, intVal);
2660       break;
2661     }
2662     case JDWP::JT_SHORT:
2663     case JDWP::JT_CHAR: {
2664       CHECK_EQ(width, 2U);
2665       uint32_t intVal;
2666       if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2667         return FailGetLocalValue(visitor, vreg, tag);
2668       }
2669       VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2670       JDWP::Set2BE(buf + 1, intVal);
2671       break;
2672     }
2673     case JDWP::JT_INT: {
2674       CHECK_EQ(width, 4U);
2675       uint32_t intVal;
2676       if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2677         return FailGetLocalValue(visitor, vreg, tag);
2678       }
2679       VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2680       JDWP::Set4BE(buf + 1, intVal);
2681       break;
2682     }
2683     case JDWP::JT_FLOAT: {
2684       CHECK_EQ(width, 4U);
2685       uint32_t intVal;
2686       if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2687         return FailGetLocalValue(visitor, vreg, tag);
2688       }
2689       VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2690       JDWP::Set4BE(buf + 1, intVal);
2691       break;
2692     }
2693     case JDWP::JT_ARRAY:
2694     case JDWP::JT_CLASS_LOADER:
2695     case JDWP::JT_CLASS_OBJECT:
2696     case JDWP::JT_OBJECT:
2697     case JDWP::JT_STRING:
2698     case JDWP::JT_THREAD:
2699     case JDWP::JT_THREAD_GROUP: {
2700       CHECK_EQ(width, sizeof(JDWP::ObjectId));
2701       uint32_t intVal;
2702       if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2703         return FailGetLocalValue(visitor, vreg, tag);
2704       }
2705       mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2706       VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2707       if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2708         LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2709                                    reinterpret_cast<uintptr_t>(o), vreg)
2710                                    << GetStackContextAsString(visitor);
2711         UNREACHABLE();
2712       }
2713       tag = TagFromObject(soa, o);
2714       JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
2715       break;
2716     }
2717     case JDWP::JT_DOUBLE: {
2718       CHECK_EQ(width, 8U);
2719       uint64_t longVal;
2720       if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2721         return FailGetLocalValue(visitor, vreg, tag);
2722       }
2723       VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2724       JDWP::Set8BE(buf + 1, longVal);
2725       break;
2726     }
2727     case JDWP::JT_LONG: {
2728       CHECK_EQ(width, 8U);
2729       uint64_t longVal;
2730       if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2731         return FailGetLocalValue(visitor, vreg, tag);
2732       }
2733       VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2734       JDWP::Set8BE(buf + 1, longVal);
2735       break;
2736     }
2737     default:
2738       LOG(FATAL) << "Unknown tag " << tag;
2739       UNREACHABLE();
2740   }
2741 
2742   // Prepend tag, which may have been updated.
2743   JDWP::Set1(buf, tag);
2744   return JDWP::ERR_NONE;
2745 }
2746 
SetLocalValues(JDWP::Request * request)2747 JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2748   JDWP::ObjectId thread_id = request->ReadThreadId();
2749   JDWP::FrameId frame_id = request->ReadFrameId();
2750 
2751   ScopedObjectAccessUnchecked soa(Thread::Current());
2752   JDWP::JdwpError error;
2753   Thread* thread = DecodeThread(soa, thread_id, &error);
2754   if (error != JDWP::ERR_NONE) {
2755     return error;
2756   }
2757   if (!IsSuspendedForDebugger(soa, thread)) {
2758     return JDWP::ERR_THREAD_NOT_SUSPENDED;
2759   }
2760 
2761   return FindAndHandleNonNativeFrame(
2762       thread,
2763       frame_id,
2764       [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2765         // Writes the values into visitor's context.
2766         int32_t slot_count = request->ReadSigned32("slot count");
2767         for (int32_t i = 0; i < slot_count; ++i) {
2768           uint32_t slot = request->ReadUnsigned32("slot");
2769           JDWP::JdwpTag sigByte = request->ReadTag();
2770           size_t width = Dbg::GetTagWidth(sigByte);
2771           uint64_t value = request->ReadValue(width);
2772 
2773           VLOG(jdwp) << "    --> slot " << slot << " " << sigByte << " " << value;
2774           error = Dbg::SetLocalValue(thread, *stack_visitor, slot, sigByte, value, width);
2775           if (error != JDWP::ERR_NONE) {
2776             return error;
2777           }
2778         }
2779         return JDWP::ERR_NONE;
2780       });
2781 }
2782 
2783 template<typename T>
FailSetLocalValue(const StackVisitor & visitor,uint16_t vreg,JDWP::JdwpTag tag,T value)2784 static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2785                                          JDWP::JdwpTag tag, T value)
2786     REQUIRES_SHARED(Locks::mutator_lock_) {
2787   LOG(ERROR) << "Failed to write " << tag << " local " << value
2788              << " (0x" << std::hex << value << ") into register v" << vreg
2789              << GetStackContextAsString(visitor);
2790   return kStackFrameLocalAccessError;
2791 }
2792 
SetLocalValue(Thread * thread,StackVisitor & visitor,int slot,JDWP::JdwpTag tag,uint64_t value,size_t width)2793 JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2794                                    JDWP::JdwpTag tag, uint64_t value, size_t width) {
2795   ArtMethod* m = visitor.GetMethod();
2796   JDWP::JdwpError error = JDWP::ERR_NONE;
2797   uint16_t vreg = DemangleSlot(slot, m, &error);
2798   if (error != JDWP::ERR_NONE) {
2799     return error;
2800   }
2801   // TODO: check that the tag is compatible with the actual type of the slot!
2802   switch (tag) {
2803     case JDWP::JT_BOOLEAN:
2804     case JDWP::JT_BYTE:
2805       CHECK_EQ(width, 1U);
2806       if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2807         return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
2808       }
2809       break;
2810     case JDWP::JT_SHORT:
2811     case JDWP::JT_CHAR:
2812       CHECK_EQ(width, 2U);
2813       if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2814         return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
2815       }
2816       break;
2817     case JDWP::JT_INT:
2818       CHECK_EQ(width, 4U);
2819       if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2820         return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
2821       }
2822       break;
2823     case JDWP::JT_FLOAT:
2824       CHECK_EQ(width, 4U);
2825       if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
2826         return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
2827       }
2828       break;
2829     case JDWP::JT_ARRAY:
2830     case JDWP::JT_CLASS_LOADER:
2831     case JDWP::JT_CLASS_OBJECT:
2832     case JDWP::JT_OBJECT:
2833     case JDWP::JT_STRING:
2834     case JDWP::JT_THREAD:
2835     case JDWP::JT_THREAD_GROUP: {
2836       CHECK_EQ(width, sizeof(JDWP::ObjectId));
2837       mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2838                                                           &error);
2839       if (error != JDWP::ERR_NONE) {
2840         VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2841         return JDWP::ERR_INVALID_OBJECT;
2842       }
2843       if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2844                                  kReferenceVReg)) {
2845         return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
2846       }
2847       break;
2848     }
2849     case JDWP::JT_DOUBLE: {
2850       CHECK_EQ(width, 8U);
2851       if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2852         return FailSetLocalValue(visitor, vreg, tag, value);
2853       }
2854       break;
2855     }
2856     case JDWP::JT_LONG: {
2857       CHECK_EQ(width, 8U);
2858       if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
2859         return FailSetLocalValue(visitor, vreg, tag, value);
2860       }
2861       break;
2862     }
2863     default:
2864       LOG(FATAL) << "Unknown tag " << tag;
2865       UNREACHABLE();
2866   }
2867 
2868   // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2869   // the stack so we continue execution with the interpreter using the new value(s) of the updated
2870   // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2871   // thread's stack. The stub will cause the deoptimization to happen.
2872   if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2873     Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2874   }
2875 
2876   return JDWP::ERR_NONE;
2877 }
2878 
SetEventLocation(JDWP::EventLocation * location,ArtMethod * m,uint32_t dex_pc)2879 static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
2880     REQUIRES_SHARED(Locks::mutator_lock_) {
2881   DCHECK(location != nullptr);
2882   if (m == nullptr) {
2883     memset(location, 0, sizeof(*location));
2884   } else {
2885     location->method = m->GetCanonicalMethod(kRuntimePointerSize);
2886     location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
2887   }
2888 }
2889 
PostLocationEvent(ArtMethod * m,int dex_pc,mirror::Object * this_object,int event_flags,const JValue * return_value)2890 void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
2891                             int event_flags, const JValue* return_value) {
2892   if (!IsDebuggerActive()) {
2893     return;
2894   }
2895   DCHECK(m != nullptr);
2896   DCHECK_EQ(m->IsStatic(), this_object == nullptr);
2897   JDWP::EventLocation location;
2898   SetEventLocation(&location, m, dex_pc);
2899 
2900   // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2901   // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2902   // we temporarily clear the current thread's exception (if any) and will restore it after
2903   // the call.
2904   // Note: the only way to get a pending exception here is to suspend on a move-exception
2905   // instruction.
2906   Thread* const self = Thread::Current();
2907   StackHandleScope<1> hs(self);
2908   Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2909   self->ClearException();
2910   if (kIsDebugBuild && pending_exception != nullptr) {
2911     const Instruction& instr = location.method->DexInstructions().InstructionAt(location.dex_pc);
2912     CHECK_EQ(Instruction::MOVE_EXCEPTION, instr.Opcode());
2913   }
2914 
2915   gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
2916 
2917   if (pending_exception != nullptr) {
2918     self->SetException(pending_exception.Get());
2919   }
2920 }
2921 
PostFieldAccessEvent(ArtMethod * m,int dex_pc,mirror::Object * this_object,ArtField * f)2922 void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
2923                                mirror::Object* this_object, ArtField* f) {
2924   // TODO We should send events for native methods.
2925   if (!IsDebuggerActive() || m->IsNative()) {
2926     return;
2927   }
2928   DCHECK(m != nullptr);
2929   DCHECK(f != nullptr);
2930   JDWP::EventLocation location;
2931   SetEventLocation(&location, m, dex_pc);
2932 
2933   gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
2934 }
2935 
PostFieldModificationEvent(ArtMethod * m,int dex_pc,mirror::Object * this_object,ArtField * f,const JValue * field_value)2936 void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
2937                                      mirror::Object* this_object, ArtField* f,
2938                                      const JValue* field_value) {
2939   // TODO We should send events for native methods.
2940   if (!IsDebuggerActive() || m->IsNative()) {
2941     return;
2942   }
2943   DCHECK(m != nullptr);
2944   DCHECK(f != nullptr);
2945   DCHECK(field_value != nullptr);
2946   JDWP::EventLocation location;
2947   SetEventLocation(&location, m, dex_pc);
2948 
2949   gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
2950 }
2951 
PostException(mirror::Throwable * exception_object)2952 void Dbg::PostException(mirror::Throwable* exception_object) {
2953   if (!IsDebuggerActive()) {
2954     return;
2955   }
2956   Thread* const self = Thread::Current();
2957   StackHandleScope<2> handle_scope(self);
2958   Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2959   MutableHandle<mirror::Object> this_at_throw = handle_scope.NewHandle<mirror::Object>(nullptr);
2960   std::unique_ptr<Context> context(Context::Create());
2961 
2962   ArtMethod* catch_method = nullptr;
2963   ArtMethod* throw_method = nullptr;
2964   uint32_t catch_dex_pc = dex::kDexNoIndex;
2965   uint32_t throw_dex_pc = dex::kDexNoIndex;
2966   StackVisitor::WalkStack(
2967       /**
2968        * Finds the location where this exception will be caught. We search until we reach the top
2969        * frame, in which case this exception is considered uncaught.
2970        */
2971       [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2972         ArtMethod* method = stack_visitor->GetMethod();
2973         DCHECK(method != nullptr);
2974         if (method->IsRuntimeMethod()) {
2975           // Ignore callee save method.
2976           DCHECK(method->IsCalleeSaveMethod());
2977           return true;
2978         }
2979 
2980         uint32_t dex_pc = stack_visitor->GetDexPc();
2981         if (throw_method == nullptr) {
2982           // First Java method found. It is either the method that threw the exception,
2983           // or the Java native method that is reporting an exception thrown by
2984           // native code.
2985           this_at_throw.Assign(stack_visitor->GetThisObject());
2986           throw_method = method;
2987           throw_dex_pc = dex_pc;
2988         }
2989 
2990         if (dex_pc != dex::kDexNoIndex) {
2991           StackHandleScope<1> hs(stack_visitor->GetThread());
2992           uint32_t found_dex_pc;
2993           Handle<mirror::Class> exception_class(hs.NewHandle(h_exception->GetClass()));
2994           bool unused_clear_exception;
2995           found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
2996           if (found_dex_pc != dex::kDexNoIndex) {
2997             catch_method = method;
2998             catch_dex_pc = found_dex_pc;
2999             return false;  // End stack walk.
3000           }
3001         }
3002         return true;  // Continue stack walk.
3003       },
3004       self,
3005       context.get(),
3006       art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
3007 
3008   JDWP::EventLocation exception_throw_location;
3009   SetEventLocation(&exception_throw_location, throw_method, throw_dex_pc);
3010   JDWP::EventLocation exception_catch_location;
3011   SetEventLocation(&exception_catch_location, catch_method, catch_dex_pc);
3012 
3013   gJdwpState->PostException(&exception_throw_location,
3014                             h_exception.Get(),
3015                             &exception_catch_location,
3016                             this_at_throw.Get());
3017 }
3018 
PostClassPrepare(mirror::Class * c)3019 void Dbg::PostClassPrepare(mirror::Class* c) {
3020   if (!IsDebuggerActive()) {
3021     return;
3022   }
3023   gJdwpState->PostClassPrepare(c);
3024 }
3025 
UpdateDebugger(Thread * thread,mirror::Object * this_object,ArtMethod * m,uint32_t dex_pc,int event_flags,const JValue * return_value)3026 void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
3027                          ArtMethod* m, uint32_t dex_pc,
3028                          int event_flags, const JValue* return_value) {
3029   if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
3030     return;
3031   }
3032 
3033   if (IsBreakpoint(m, dex_pc)) {
3034     event_flags |= kBreakpoint;
3035   }
3036 
3037   // If the debugger is single-stepping one of our threads, check to
3038   // see if we're that thread and we've reached a step point.
3039   const SingleStepControl* single_step_control = thread->GetSingleStepControl();
3040   if (single_step_control != nullptr) {
3041     CHECK(!m->IsNative());
3042     if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
3043       // Step into method calls.  We break when the line number
3044       // or method pointer changes.  If we're in SS_MIN mode, we
3045       // always stop.
3046       if (single_step_control->GetMethod() != m) {
3047         event_flags |= kSingleStep;
3048         VLOG(jdwp) << "SS new method";
3049       } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
3050         event_flags |= kSingleStep;
3051         VLOG(jdwp) << "SS new instruction";
3052       } else if (single_step_control->ContainsDexPc(dex_pc)) {
3053         event_flags |= kSingleStep;
3054         VLOG(jdwp) << "SS new line";
3055       }
3056     } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
3057       // Step over method calls.  We break when the line number is
3058       // different and the frame depth is <= the original frame
3059       // depth.  (We can't just compare on the method, because we
3060       // might get unrolled past it by an exception, and it's tricky
3061       // to identify recursion.)
3062 
3063       int stack_depth = GetStackDepth(thread);
3064 
3065       if (stack_depth < single_step_control->GetStackDepth()) {
3066         // Popped up one or more frames, always trigger.
3067         event_flags |= kSingleStep;
3068         VLOG(jdwp) << "SS method pop";
3069       } else if (stack_depth == single_step_control->GetStackDepth()) {
3070         // Same depth, see if we moved.
3071         if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
3072           event_flags |= kSingleStep;
3073           VLOG(jdwp) << "SS new instruction";
3074         } else if (single_step_control->ContainsDexPc(dex_pc)) {
3075           event_flags |= kSingleStep;
3076           VLOG(jdwp) << "SS new line";
3077         }
3078       }
3079     } else {
3080       CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
3081       // Return from the current method.  We break when the frame
3082       // depth pops up.
3083 
3084       // This differs from the "method exit" break in that it stops
3085       // with the PC at the next instruction in the returned-to
3086       // function, rather than the end of the returning function.
3087 
3088       int stack_depth = GetStackDepth(thread);
3089       if (stack_depth < single_step_control->GetStackDepth()) {
3090         event_flags |= kSingleStep;
3091         VLOG(jdwp) << "SS method pop";
3092       }
3093     }
3094   }
3095 
3096   // If there's something interesting going on, see if it matches one
3097   // of the debugger filters.
3098   if (event_flags != 0) {
3099     Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
3100   }
3101 }
3102 
GetReferenceCounterForEvent(uint32_t instrumentation_event)3103 size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3104   switch (instrumentation_event) {
3105     case instrumentation::Instrumentation::kMethodEntered:
3106       return &method_enter_event_ref_count_;
3107     case instrumentation::Instrumentation::kMethodExited:
3108       return &method_exit_event_ref_count_;
3109     case instrumentation::Instrumentation::kDexPcMoved:
3110       return &dex_pc_change_event_ref_count_;
3111     case instrumentation::Instrumentation::kFieldRead:
3112       return &field_read_event_ref_count_;
3113     case instrumentation::Instrumentation::kFieldWritten:
3114       return &field_write_event_ref_count_;
3115     case instrumentation::Instrumentation::kExceptionThrown:
3116       return &exception_catch_event_ref_count_;
3117     default:
3118       return nullptr;
3119   }
3120 }
3121 
3122 // Process request while all mutator threads are suspended.
ProcessDeoptimizationRequest(const DeoptimizationRequest & request)3123 void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
3124   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3125   switch (request.GetKind()) {
3126     case DeoptimizationRequest::kNothing:
3127       LOG(WARNING) << "Ignoring empty deoptimization request.";
3128       break;
3129     case DeoptimizationRequest::kRegisterForEvent:
3130       VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
3131                                  request.InstrumentationEvent());
3132       instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3133       instrumentation_events_ |= request.InstrumentationEvent();
3134       break;
3135     case DeoptimizationRequest::kUnregisterForEvent:
3136       VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
3137                                  request.InstrumentationEvent());
3138       instrumentation->RemoveListener(&gDebugInstrumentationListener,
3139                                       request.InstrumentationEvent());
3140       instrumentation_events_ &= ~request.InstrumentationEvent();
3141       break;
3142     case DeoptimizationRequest::kFullDeoptimization:
3143       VLOG(jdwp) << "Deoptimize the world ...";
3144       instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
3145       VLOG(jdwp) << "Deoptimize the world DONE";
3146       break;
3147     case DeoptimizationRequest::kFullUndeoptimization:
3148       VLOG(jdwp) << "Undeoptimize the world ...";
3149       instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
3150       VLOG(jdwp) << "Undeoptimize the world DONE";
3151       break;
3152     case DeoptimizationRequest::kSelectiveDeoptimization:
3153       VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
3154       instrumentation->Deoptimize(request.Method());
3155       VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
3156       break;
3157     case DeoptimizationRequest::kSelectiveUndeoptimization:
3158       VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
3159       instrumentation->Undeoptimize(request.Method());
3160       VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
3161       break;
3162     default:
3163       LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
3164       UNREACHABLE();
3165   }
3166 }
3167 
RequestDeoptimization(const DeoptimizationRequest & req)3168 void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
3169   if (req.GetKind() == DeoptimizationRequest::kNothing) {
3170     // Nothing to do.
3171     return;
3172   }
3173   MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
3174   RequestDeoptimizationLocked(req);
3175 }
3176 
RequestDeoptimizationLocked(const DeoptimizationRequest & req)3177 void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
3178   switch (req.GetKind()) {
3179     case DeoptimizationRequest::kRegisterForEvent: {
3180       DCHECK_NE(req.InstrumentationEvent(), 0u);
3181       size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
3182       CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
3183                                                 req.InstrumentationEvent());
3184       if (*counter == 0) {
3185         VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
3186                                    deoptimization_requests_.size(), req.InstrumentationEvent());
3187         deoptimization_requests_.push_back(req);
3188       }
3189       *counter = *counter + 1;
3190       break;
3191     }
3192     case DeoptimizationRequest::kUnregisterForEvent: {
3193       DCHECK_NE(req.InstrumentationEvent(), 0u);
3194       size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
3195       CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
3196                                                 req.InstrumentationEvent());
3197       *counter = *counter - 1;
3198       if (*counter == 0) {
3199         VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
3200                                    deoptimization_requests_.size(), req.InstrumentationEvent());
3201         deoptimization_requests_.push_back(req);
3202       }
3203       break;
3204     }
3205     case DeoptimizationRequest::kFullDeoptimization: {
3206       DCHECK(req.Method() == nullptr);
3207       if (full_deoptimization_event_count_ == 0) {
3208         VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3209                    << " for full deoptimization";
3210         deoptimization_requests_.push_back(req);
3211       }
3212       ++full_deoptimization_event_count_;
3213       break;
3214     }
3215     case DeoptimizationRequest::kFullUndeoptimization: {
3216       DCHECK(req.Method() == nullptr);
3217       DCHECK_GT(full_deoptimization_event_count_, 0U);
3218       --full_deoptimization_event_count_;
3219       if (full_deoptimization_event_count_ == 0) {
3220         VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3221                    << " for full undeoptimization";
3222         deoptimization_requests_.push_back(req);
3223       }
3224       break;
3225     }
3226     case DeoptimizationRequest::kSelectiveDeoptimization: {
3227       DCHECK(req.Method() != nullptr);
3228       VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3229                  << " for deoptimization of " << req.Method()->PrettyMethod();
3230       deoptimization_requests_.push_back(req);
3231       break;
3232     }
3233     case DeoptimizationRequest::kSelectiveUndeoptimization: {
3234       DCHECK(req.Method() != nullptr);
3235       VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3236                  << " for undeoptimization of " << req.Method()->PrettyMethod();
3237       deoptimization_requests_.push_back(req);
3238       break;
3239     }
3240     default: {
3241       LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
3242       UNREACHABLE();
3243     }
3244   }
3245 }
3246 
ManageDeoptimization()3247 void Dbg::ManageDeoptimization() {
3248   Thread* const self = Thread::Current();
3249   {
3250     // Avoid suspend/resume if there is no pending request.
3251     MutexLock mu(self, *Locks::deoptimization_lock_);
3252     if (deoptimization_requests_.empty()) {
3253       return;
3254     }
3255   }
3256   CHECK_EQ(self->GetState(), kRunnable);
3257   ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
3258   // Required for ProcessDeoptimizationRequest.
3259   gc::ScopedGCCriticalSection gcs(self,
3260                                   gc::kGcCauseInstrumentation,
3261                                   gc::kCollectorTypeInstrumentation);
3262   // We need to suspend mutator threads first.
3263   ScopedSuspendAll ssa(__FUNCTION__);
3264   const ThreadState old_state = self->SetStateUnsafe(kRunnable);
3265   {
3266     MutexLock mu(self, *Locks::deoptimization_lock_);
3267     size_t req_index = 0;
3268     for (DeoptimizationRequest& request : deoptimization_requests_) {
3269       VLOG(jdwp) << "Process deoptimization request #" << req_index++;
3270       ProcessDeoptimizationRequest(request);
3271     }
3272     deoptimization_requests_.clear();
3273   }
3274   CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3275 }
3276 
FindFirstBreakpointForMethod(ArtMethod * m)3277 static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
3278     REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
3279   for (Breakpoint& breakpoint : gBreakpoints) {
3280     if (breakpoint.IsInMethod(m)) {
3281       return &breakpoint;
3282     }
3283   }
3284   return nullptr;
3285 }
3286 
MethodHasAnyBreakpoints(ArtMethod * method)3287 bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
3288   ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3289   return FindFirstBreakpointForMethod(method) != nullptr;
3290 }
3291 
3292 // Sanity checks all existing breakpoints on the same method.
SanityCheckExistingBreakpoints(ArtMethod * m,DeoptimizationRequest::Kind deoptimization_kind)3293 static void SanityCheckExistingBreakpoints(ArtMethod* m,
3294                                            DeoptimizationRequest::Kind deoptimization_kind)
3295     REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
3296   for (const Breakpoint& breakpoint : gBreakpoints) {
3297     if (breakpoint.IsInMethod(m)) {
3298       CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3299     }
3300   }
3301   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3302   if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
3303     // We should have deoptimized everything but not "selectively" deoptimized this method.
3304     CHECK(instrumentation->AreAllMethodsDeoptimized());
3305     CHECK(!instrumentation->IsDeoptimized(m));
3306   } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3307     // We should have "selectively" deoptimized this method.
3308     // Note: while we have not deoptimized everything for this method, we may have done it for
3309     // another event.
3310     CHECK(instrumentation->IsDeoptimized(m));
3311   } else {
3312     // This method does not require deoptimization.
3313     CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3314     CHECK(!instrumentation->IsDeoptimized(m));
3315   }
3316 }
3317 
3318 // Returns the deoptimization kind required to set a breakpoint in a method.
3319 // If a breakpoint has already been set, we also return the first breakpoint
3320 // through the given 'existing_brkpt' pointer.
GetRequiredDeoptimizationKind(Thread * self,ArtMethod * m,const Breakpoint ** existing_brkpt)3321 static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
3322                                                                  ArtMethod* m,
3323                                                                  const Breakpoint** existing_brkpt)
3324     REQUIRES_SHARED(Locks::mutator_lock_) {
3325   if (!Dbg::RequiresDeoptimization()) {
3326     // We already run in interpreter-only mode so we don't need to deoptimize anything.
3327     VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3328                << ArtMethod::PrettyMethod(m);
3329     return DeoptimizationRequest::kNothing;
3330   }
3331   const Breakpoint* first_breakpoint;
3332   {
3333     ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3334     first_breakpoint = FindFirstBreakpointForMethod(m);
3335     *existing_brkpt = first_breakpoint;
3336   }
3337 
3338   if (first_breakpoint == nullptr) {
3339     // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3340     // we deoptimize everything; otherwise we deoptimize only this method. We
3341     // deoptimize with defaults because we do not know everywhere they are used. It is possible some
3342     // of the copies could be missed.
3343     // TODO Deoptimizing on default methods might not be necessary in all cases.
3344     bool need_full_deoptimization = m->IsDefault();
3345     if (need_full_deoptimization) {
3346       VLOG(jdwp) << "Need full deoptimization because of copying of method "
3347                  << ArtMethod::PrettyMethod(m);
3348       return DeoptimizationRequest::kFullDeoptimization;
3349     } else {
3350       // We don't need to deoptimize if the method has not been compiled.
3351       const bool is_compiled = m->HasAnyCompiledCode();
3352       if (is_compiled) {
3353         VLOG(jdwp) << "Need selective deoptimization for compiled method "
3354                    << ArtMethod::PrettyMethod(m);
3355         return DeoptimizationRequest::kSelectiveDeoptimization;
3356       } else {
3357         // Method is not compiled: we don't need to deoptimize.
3358         VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3359                    << ArtMethod::PrettyMethod(m);
3360         return DeoptimizationRequest::kNothing;
3361       }
3362     }
3363   } else {
3364     // There is at least one breakpoint for this method: we don't need to deoptimize.
3365     // Let's check that all breakpoints are configured the same way for deoptimization.
3366     VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
3367     DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
3368     if (kIsDebugBuild) {
3369       ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3370       SanityCheckExistingBreakpoints(m, deoptimization_kind);
3371     }
3372     return DeoptimizationRequest::kNothing;
3373   }
3374 }
3375 
3376 // Installs a breakpoint at the specified location. Also indicates through the deoptimization
3377 // request if we need to deoptimize.
WatchLocation(const JDWP::JdwpLocation * location,DeoptimizationRequest * req)3378 void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3379   Thread* const self = Thread::Current();
3380   ArtMethod* m = FromMethodId(location->method_id);
3381   DCHECK(m != nullptr) << "No method for method id " << location->method_id;
3382 
3383   const Breakpoint* existing_breakpoint = nullptr;
3384   const DeoptimizationRequest::Kind deoptimization_kind =
3385       GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
3386   req->SetKind(deoptimization_kind);
3387   if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3388     req->SetMethod(m);
3389   } else {
3390     CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3391           deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
3392     req->SetMethod(nullptr);
3393   }
3394 
3395   {
3396     WriterMutexLock mu(self, *Locks::breakpoint_lock_);
3397     // If there is at least one existing breakpoint on the same method, the new breakpoint
3398     // must have the same deoptimization kind than the existing breakpoint(s).
3399     DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3400     if (existing_breakpoint != nullptr) {
3401       breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3402     } else {
3403       breakpoint_deoptimization_kind = deoptimization_kind;
3404     }
3405     gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
3406     VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3407                << gBreakpoints[gBreakpoints.size() - 1];
3408   }
3409 }
3410 
3411 // Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3412 // request if we need to undeoptimize.
UnwatchLocation(const JDWP::JdwpLocation * location,DeoptimizationRequest * req)3413 void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3414   WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3415   ArtMethod* m = FromMethodId(location->method_id);
3416   DCHECK(m != nullptr) << "No method for method id " << location->method_id;
3417   DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
3418   for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
3419     if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
3420       VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
3421       deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3422       DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3423                 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
3424       gBreakpoints.erase(gBreakpoints.begin() + i);
3425       break;
3426     }
3427   }
3428   const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3429   if (existing_breakpoint == nullptr) {
3430     // There is no more breakpoint on this method: we need to undeoptimize.
3431     if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
3432       // This method required full deoptimization: we need to undeoptimize everything.
3433       req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3434       req->SetMethod(nullptr);
3435     } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3436       // This method required selective deoptimization: we need to undeoptimize only that method.
3437       req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3438       req->SetMethod(m);
3439     } else {
3440       // This method had no need for deoptimization: do nothing.
3441       CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3442       req->SetKind(DeoptimizationRequest::kNothing);
3443       req->SetMethod(nullptr);
3444     }
3445   } else {
3446     // There is at least one breakpoint for this method: we don't need to undeoptimize.
3447     req->SetKind(DeoptimizationRequest::kNothing);
3448     req->SetMethod(nullptr);
3449     if (kIsDebugBuild) {
3450       SanityCheckExistingBreakpoints(m, deoptimization_kind);
3451     }
3452   }
3453 }
3454 
IsForcedInterpreterNeededForCallingImpl(Thread * thread,ArtMethod * m)3455 bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
3456   const SingleStepControl* const ssc = thread->GetSingleStepControl();
3457   if (ssc == nullptr) {
3458     // If we are not single-stepping, then we don't have to force interpreter.
3459     return false;
3460   }
3461   if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3462     // If we are in interpreter only mode, then we don't have to force interpreter.
3463     return false;
3464   }
3465 
3466   if (!m->IsNative() && !m->IsProxyMethod()) {
3467     // If we want to step into a method, then we have to force interpreter on that call.
3468     if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3469       return true;
3470     }
3471   }
3472   return false;
3473 }
3474 
IsForcedInterpreterNeededForResolutionImpl(Thread * thread,ArtMethod * m)3475 bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
3476   instrumentation::Instrumentation* const instrumentation =
3477       Runtime::Current()->GetInstrumentation();
3478   // If we are in interpreter only mode, then we don't have to force interpreter.
3479   if (instrumentation->InterpretOnly()) {
3480     return false;
3481   }
3482   // We can only interpret pure Java method.
3483   if (m->IsNative() || m->IsProxyMethod()) {
3484     return false;
3485   }
3486   const SingleStepControl* const ssc = thread->GetSingleStepControl();
3487   if (ssc != nullptr) {
3488     // If we want to step into a method, then we have to force interpreter on that call.
3489     if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3490       return true;
3491     }
3492     // If we are stepping out from a static initializer, by issuing a step
3493     // in or step over, that was implicitly invoked by calling a static method,
3494     // then we need to step into that method. Having a lower stack depth than
3495     // the one the single step control has indicates that the step originates
3496     // from the static initializer.
3497     if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3498         ssc->GetStackDepth() > GetStackDepth(thread)) {
3499       return true;
3500     }
3501   }
3502   // There are cases where we have to force interpreter on deoptimized methods,
3503   // because in some cases the call will not be performed by invoking an entry
3504   // point that has been replaced by the deoptimization, but instead by directly
3505   // invoking the compiled code of the method, for example.
3506   return instrumentation->IsDeoptimized(m);
3507 }
3508 
IsForcedInstrumentationNeededForResolutionImpl(Thread * thread,ArtMethod * m)3509 bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
3510   // The upcall can be null and in that case we don't need to do anything.
3511   if (m == nullptr) {
3512     return false;
3513   }
3514   instrumentation::Instrumentation* const instrumentation =
3515       Runtime::Current()->GetInstrumentation();
3516   // If we are in interpreter only mode, then we don't have to force interpreter.
3517   if (instrumentation->InterpretOnly()) {
3518     return false;
3519   }
3520   // We can only interpret pure Java method.
3521   if (m->IsNative() || m->IsProxyMethod()) {
3522     return false;
3523   }
3524   const SingleStepControl* const ssc = thread->GetSingleStepControl();
3525   if (ssc != nullptr) {
3526     // If we are stepping out from a static initializer, by issuing a step
3527     // out, that was implicitly invoked by calling a static method, then we
3528     // need to step into the caller of that method. Having a lower stack
3529     // depth than the one the single step control has indicates that the
3530     // step originates from the static initializer.
3531     if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3532         ssc->GetStackDepth() > GetStackDepth(thread)) {
3533       return true;
3534     }
3535   }
3536   // If we are returning from a static intializer, that was implicitly
3537   // invoked by calling a static method and the caller is deoptimized,
3538   // then we have to deoptimize the stack without forcing interpreter
3539   // on the static method that was called originally. This problem can
3540   // be solved easily by forcing instrumentation on the called method,
3541   // because the instrumentation exit hook will recognise the need of
3542   // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3543   return instrumentation->IsDeoptimized(m);
3544 }
3545 
IsForcedInterpreterNeededForUpcallImpl(Thread * thread,ArtMethod * m)3546 bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
3547   // The upcall can be null and in that case we don't need to do anything.
3548   if (m == nullptr) {
3549     return false;
3550   }
3551   instrumentation::Instrumentation* const instrumentation =
3552       Runtime::Current()->GetInstrumentation();
3553   // If we are in interpreter only mode, then we don't have to force interpreter.
3554   if (instrumentation->InterpretOnly()) {
3555     return false;
3556   }
3557   // We can only interpret pure Java method.
3558   if (m->IsNative() || m->IsProxyMethod()) {
3559     return false;
3560   }
3561   const SingleStepControl* const ssc = thread->GetSingleStepControl();
3562   if (ssc != nullptr) {
3563     // The debugger is not interested in what is happening under the level
3564     // of the step, thus we only force interpreter when we are not below of
3565     // the step.
3566     if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3567       return true;
3568     }
3569   }
3570   if (thread->HasDebuggerShadowFrames()) {
3571     // We need to deoptimize the stack for the exception handling flow so that
3572     // we don't miss any deoptimization that should be done when there are
3573     // debugger shadow frames.
3574     return true;
3575   }
3576   // We have to require stack deoptimization if the upcall is deoptimized.
3577   return instrumentation->IsDeoptimized(m);
3578 }
3579 
3580 // Do we need to deoptimize the stack to handle an exception?
IsForcedInterpreterNeededForExceptionImpl(Thread * thread)3581 bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3582   const SingleStepControl* const ssc = thread->GetSingleStepControl();
3583   if (ssc != nullptr) {
3584     // We deopt to step into the catch handler.
3585     return true;
3586   }
3587   // Deoptimization is required if at least one method in the stack needs it. However we
3588   // skip frames that will be unwound (thus not executed).
3589   bool needs_deoptimization = false;
3590   StackVisitor::WalkStack(
3591       [&](art::StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
3592         // The visitor is meant to be used when handling exception from compiled code only.
3593         CHECK(!visitor->IsShadowFrame()) << "We only expect to visit compiled frame: "
3594                                          << ArtMethod::PrettyMethod(visitor->GetMethod());
3595         ArtMethod* method = visitor->GetMethod();
3596         if (method == nullptr) {
3597           // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3598           // so we can stop the visit.
3599           DCHECK(!needs_deoptimization);
3600           return false;
3601         }
3602         if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3603           // We found a compiled frame in the stack but instrumentation is set to interpret
3604           // everything: we need to deoptimize.
3605           needs_deoptimization = true;
3606           return false;
3607         }
3608         if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3609           // We found a deoptimized method in the stack.
3610           needs_deoptimization = true;
3611           return false;
3612         }
3613         ShadowFrame* frame = visitor->GetThread()->FindDebuggerShadowFrame(visitor->GetFrameId());
3614         if (frame != nullptr) {
3615           // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3616           // deoptimize the stack to execute (and deallocate) this frame.
3617           needs_deoptimization = true;
3618           return false;
3619         }
3620         return true;
3621       },
3622       thread,
3623       /* context= */ nullptr,
3624       art::StackVisitor::StackWalkKind::kIncludeInlinedFrames,
3625       /* check_suspended */ true,
3626       /* include_transitions */ true);
3627   return needs_deoptimization;
3628 }
3629 
3630 // Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3631 // cause suspension if the thread is the current thread.
3632 class ScopedDebuggerThreadSuspension {
3633  public:
ScopedDebuggerThreadSuspension(Thread * self,JDWP::ObjectId thread_id)3634   ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
3635       REQUIRES(!Locks::thread_list_lock_)
3636       REQUIRES_SHARED(Locks::mutator_lock_) :
3637       thread_(nullptr),
3638       error_(JDWP::ERR_NONE),
3639       self_suspend_(false),
3640       other_suspend_(false) {
3641     ScopedObjectAccessUnchecked soa(self);
3642     thread_ = DecodeThread(soa, thread_id, &error_);
3643     if (error_ == JDWP::ERR_NONE) {
3644       if (thread_ == soa.Self()) {
3645         self_suspend_ = true;
3646       } else {
3647         Thread* suspended_thread;
3648         {
3649           ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3650           jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3651           bool timed_out;
3652           ThreadList* const thread_list = Runtime::Current()->GetThreadList();
3653           suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
3654                                                               /* request_suspension= */ true,
3655                                                               SuspendReason::kForDebugger,
3656                                                               &timed_out);
3657         }
3658         if (suspended_thread == nullptr) {
3659           // Thread terminated from under us while suspending.
3660           error_ = JDWP::ERR_INVALID_THREAD;
3661         } else {
3662           CHECK_EQ(suspended_thread, thread_);
3663           other_suspend_ = true;
3664         }
3665       }
3666     }
3667   }
3668 
GetThread() const3669   Thread* GetThread() const {
3670     return thread_;
3671   }
3672 
GetError() const3673   JDWP::JdwpError GetError() const {
3674     return error_;
3675   }
3676 
~ScopedDebuggerThreadSuspension()3677   ~ScopedDebuggerThreadSuspension() {
3678     if (other_suspend_) {
3679       bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3680                                                                  SuspendReason::kForDebugger);
3681       DCHECK(resumed);
3682     }
3683   }
3684 
3685  private:
3686   Thread* thread_;
3687   JDWP::JdwpError error_;
3688   bool self_suspend_;
3689   bool other_suspend_;
3690 };
3691 
ConfigureStep(JDWP::ObjectId thread_id,JDWP::JdwpStepSize step_size,JDWP::JdwpStepDepth step_depth)3692 JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3693                                    JDWP::JdwpStepDepth step_depth) {
3694   Thread* self = Thread::Current();
3695   ScopedDebuggerThreadSuspension sts(self, thread_id);
3696   if (sts.GetError() != JDWP::ERR_NONE) {
3697     return sts.GetError();
3698   }
3699 
3700   // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
3701   // is for step-out.
3702   struct SingleStepStackVisitor : public StackVisitor {
3703     explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
3704         : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3705           stack_depth(0),
3706           method(nullptr),
3707           line_number(-1) {}
3708 
3709     // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3710     // annotalysis.
3711     bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
3712       ArtMethod* m = GetMethod();
3713       if (!m->IsRuntimeMethod()) {
3714         ++stack_depth;
3715         if (method == nullptr) {
3716           const DexFile* dex_file = m->GetDexFile();
3717           method = m;
3718           if (dex_file != nullptr) {
3719             line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
3720           }
3721         }
3722       }
3723       return true;
3724     }
3725 
3726     int stack_depth;
3727     ArtMethod* method;
3728     int32_t line_number;
3729   };
3730 
3731   Thread* const thread = sts.GetThread();
3732   SingleStepStackVisitor visitor(thread);
3733   visitor.WalkStack();
3734 
3735   // Allocate single step.
3736   SingleStepControl* single_step_control =
3737       new (std::nothrow) SingleStepControl(step_size, step_depth,
3738                                            visitor.stack_depth, visitor.method);
3739   if (single_step_control == nullptr) {
3740     LOG(ERROR) << "Failed to allocate SingleStepControl";
3741     return JDWP::ERR_OUT_OF_MEMORY;
3742   }
3743 
3744   ArtMethod* m = single_step_control->GetMethod();
3745   const int32_t line_number = visitor.line_number;
3746   // Note: if the thread is not running Java code (pure native thread), there is no "current"
3747   // method on the stack (and no line number either).
3748   if (m != nullptr && !m->IsNative()) {
3749     CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
3750     bool last_pc_valid = false;
3751     uint32_t last_pc = 0u;
3752     // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3753     accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
3754       if (static_cast<int32_t>(entry.line_) == line_number) {
3755         if (!last_pc_valid) {
3756           // Everything from this address until the next line change is ours.
3757           last_pc = entry.address_;
3758           last_pc_valid = true;
3759         }
3760         // Otherwise, if we're already in a valid range for this line,
3761         // just keep going (shouldn't really happen)...
3762       } else if (last_pc_valid) {  // and the line number is new
3763         // Add everything from the last entry up until here to the set
3764         for (uint32_t dex_pc = last_pc; dex_pc < entry.address_; ++dex_pc) {
3765           single_step_control->AddDexPc(dex_pc);
3766         }
3767         last_pc_valid = false;
3768       }
3769       return false;  // There may be multiple entries for any given line.
3770     });
3771     // If the line number was the last in the position table...
3772     if (last_pc_valid) {
3773       for (uint32_t dex_pc = last_pc; dex_pc < accessor.InsnsSizeInCodeUnits(); ++dex_pc) {
3774         single_step_control->AddDexPc(dex_pc);
3775       }
3776     }
3777   }
3778 
3779   // Activate single-step in the thread.
3780   thread->ActivateSingleStepControl(single_step_control);
3781 
3782   if (VLOG_IS_ON(jdwp)) {
3783     VLOG(jdwp) << "Single-step thread: " << *thread;
3784     VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3785     VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3786     VLOG(jdwp) << "Single-step current method: "
3787                << ArtMethod::PrettyMethod(single_step_control->GetMethod());
3788     VLOG(jdwp) << "Single-step current line: " << line_number;
3789     VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
3790     VLOG(jdwp) << "Single-step dex_pc values:";
3791     for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
3792       VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
3793     }
3794   }
3795 
3796   return JDWP::ERR_NONE;
3797 }
3798 
UnconfigureStep(JDWP::ObjectId thread_id)3799 void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3800   ScopedObjectAccessUnchecked soa(Thread::Current());
3801   JDWP::JdwpError error;
3802   Thread* thread = DecodeThread(soa, thread_id, &error);
3803   if (error == JDWP::ERR_NONE) {
3804     thread->DeactivateSingleStepControl();
3805   }
3806 }
3807 
JdwpTagToShortyChar(JDWP::JdwpTag tag)3808 static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3809   switch (tag) {
3810     default:
3811       LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3812       UNREACHABLE();
3813 
3814     // Primitives.
3815     case JDWP::JT_BYTE:    return 'B';
3816     case JDWP::JT_CHAR:    return 'C';
3817     case JDWP::JT_FLOAT:   return 'F';
3818     case JDWP::JT_DOUBLE:  return 'D';
3819     case JDWP::JT_INT:     return 'I';
3820     case JDWP::JT_LONG:    return 'J';
3821     case JDWP::JT_SHORT:   return 'S';
3822     case JDWP::JT_VOID:    return 'V';
3823     case JDWP::JT_BOOLEAN: return 'Z';
3824 
3825     // Reference types.
3826     case JDWP::JT_ARRAY:
3827     case JDWP::JT_OBJECT:
3828     case JDWP::JT_STRING:
3829     case JDWP::JT_THREAD:
3830     case JDWP::JT_THREAD_GROUP:
3831     case JDWP::JT_CLASS_LOADER:
3832     case JDWP::JT_CLASS_OBJECT:
3833       return 'L';
3834   }
3835 }
3836 
PrepareInvokeMethod(uint32_t request_id,JDWP::ObjectId thread_id,JDWP::ObjectId object_id,JDWP::RefTypeId class_id,JDWP::MethodId method_id,uint32_t arg_count,uint64_t arg_values[],JDWP::JdwpTag * arg_types,uint32_t options)3837 JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3838                                          JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3839                                          JDWP::MethodId method_id, uint32_t arg_count,
3840                                          uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3841                                          uint32_t options) {
3842   Thread* const self = Thread::Current();
3843   CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
3844   const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
3845 
3846   ThreadList* thread_list = Runtime::Current()->GetThreadList();
3847   Thread* targetThread = nullptr;
3848   {
3849     ScopedObjectAccessUnchecked soa(self);
3850     JDWP::JdwpError error;
3851     targetThread = DecodeThread(soa, thread_id, &error);
3852     if (error != JDWP::ERR_NONE) {
3853       LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3854       return error;
3855     }
3856     if (targetThread->GetInvokeReq() != nullptr) {
3857       // Thread is already invoking a method on behalf of the debugger.
3858       LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3859       return JDWP::ERR_ALREADY_INVOKING;
3860     }
3861     if (!targetThread->IsReadyForDebugInvoke()) {
3862       // Thread is not suspended by an event so it cannot invoke a method.
3863       LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3864       return JDWP::ERR_INVALID_THREAD;
3865     }
3866 
3867     /*
3868      * According to the JDWP specs, we are expected to resume all threads (or only the
3869      * target thread) once. So if a thread has been suspended more than once (either by
3870      * the debugger for an event or by the runtime for GC), it will remain suspended before
3871      * the invoke is executed. This means the debugger is responsible to properly resume all
3872      * the threads it has suspended so the target thread can execute the method.
3873      *
3874      * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3875      * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3876      * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3877      *
3878      * On the other hand, if we are asked to only resume the target thread, then we follow the
3879      * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3880      * if it has been suspended more than once before the invoke (and again, this is the
3881      * responsibility of the debugger to properly resume that thread before invoking a method).
3882      */
3883     int suspend_count;
3884     {
3885       MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
3886       suspend_count = targetThread->GetSuspendCount();
3887     }
3888     if (suspend_count > 1 && resume_all_threads) {
3889       // The target thread will remain suspended even after we resume it. Let's emit a warning
3890       // to indicate the invoke won't be executed until the thread is resumed.
3891       LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3892                    << suspend_count << "). This thread will invoke the method only once "
3893                    << "it is fully resumed.";
3894     }
3895 
3896     ObjPtr<mirror::Object> receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3897     if (error != JDWP::ERR_NONE) {
3898       return JDWP::ERR_INVALID_OBJECT;
3899     }
3900 
3901     gRegistry->Get<mirror::Object*>(thread_id, &error);
3902     if (error != JDWP::ERR_NONE) {
3903       return JDWP::ERR_INVALID_OBJECT;
3904     }
3905 
3906     ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
3907     if (c == nullptr) {
3908       return error;
3909     }
3910 
3911     ArtMethod* m = FromMethodId(method_id);
3912     if (m->IsStatic() != (receiver == nullptr)) {
3913       return JDWP::ERR_INVALID_METHODID;
3914     }
3915     if (m->IsStatic()) {
3916       if (m->GetDeclaringClass() != c) {
3917         return JDWP::ERR_INVALID_METHODID;
3918       }
3919     } else {
3920       if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3921         return JDWP::ERR_INVALID_METHODID;
3922       }
3923     }
3924 
3925     // Check the argument list matches the method.
3926     uint32_t shorty_len = 0;
3927     const char* shorty = m->GetShorty(&shorty_len);
3928     if (shorty_len - 1 != arg_count) {
3929       return JDWP::ERR_ILLEGAL_ARGUMENT;
3930     }
3931 
3932     {
3933       StackHandleScope<2> hs(soa.Self());
3934       HandleWrapperObjPtr<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3935       HandleWrapperObjPtr<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3936       const dex::TypeList* types = m->GetParameterTypeList();
3937       for (size_t i = 0; i < arg_count; ++i) {
3938         if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
3939           return JDWP::ERR_ILLEGAL_ARGUMENT;
3940         }
3941 
3942         if (shorty[i + 1] == 'L') {
3943           // Did we really get an argument of an appropriate reference type?
3944           ObjPtr<mirror::Class> parameter_type =
3945               m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
3946           mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3947           if (error != JDWP::ERR_NONE) {
3948             return JDWP::ERR_INVALID_OBJECT;
3949           }
3950           if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
3951             return JDWP::ERR_ILLEGAL_ARGUMENT;
3952           }
3953 
3954           // Turn the on-the-wire ObjectId into a jobject.
3955           jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3956           v.l = gRegistry->GetJObject(arg_values[i]);
3957         }
3958       }
3959     }
3960 
3961     // Allocates a DebugInvokeReq.
3962     DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(
3963         request_id, thread_id, receiver, c, m, options, arg_values, arg_count);
3964     if (req == nullptr) {
3965       LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3966       return JDWP::ERR_OUT_OF_MEMORY;
3967     }
3968 
3969     // Attaches the DebugInvokeReq to the target thread so it executes the method when
3970     // it is resumed. Once the invocation completes, the target thread will delete it before
3971     // suspending itself (see ThreadList::SuspendSelfForDebugger).
3972     targetThread->SetDebugInvokeReq(req);
3973   }
3974 
3975   // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3976   // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3977   // call.
3978   if (resume_all_threads) {
3979     VLOG(jdwp) << "      Resuming all threads";
3980     thread_list->UndoDebuggerSuspensions();
3981   } else {
3982     VLOG(jdwp) << "      Resuming event thread only";
3983     bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
3984     DCHECK(resumed);
3985   }
3986 
3987   return JDWP::ERR_NONE;
3988 }
3989 
ExecuteMethod(DebugInvokeReq * pReq)3990 void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
3991   Thread* const self = Thread::Current();
3992   CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
3993 
3994   ScopedObjectAccess soa(self);
3995 
3996   // We can be called while an exception is pending. We need
3997   // to preserve that across the method invocation.
3998   StackHandleScope<1> hs(soa.Self());
3999   Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
4000   soa.Self()->ClearException();
4001 
4002   // Execute the method then sends reply to the debugger.
4003   ExecuteMethodWithoutPendingException(soa, pReq);
4004 
4005   // If an exception was pending before the invoke, restore it now.
4006   if (old_exception != nullptr) {
4007     soa.Self()->SetException(old_exception.Get());
4008   }
4009 }
4010 
4011 // Helper function: write a variable-width value into the output input buffer.
WriteValue(JDWP::ExpandBuf * pReply,int width,uint64_t value)4012 static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4013   switch (width) {
4014     case 1:
4015       expandBufAdd1(pReply, value);
4016       break;
4017     case 2:
4018       expandBufAdd2BE(pReply, value);
4019       break;
4020     case 4:
4021       expandBufAdd4BE(pReply, value);
4022       break;
4023     case 8:
4024       expandBufAdd8BE(pReply, value);
4025       break;
4026     default:
4027       LOG(FATAL) << width;
4028       UNREACHABLE();
4029   }
4030 }
4031 
ExecuteMethodWithoutPendingException(ScopedObjectAccess & soa,DebugInvokeReq * pReq)4032 void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4033   soa.Self()->AssertNoPendingException();
4034 
4035   // Translate the method through the vtable, unless the debugger wants to suppress it.
4036   ArtMethod* m = pReq->method;
4037   PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
4038   if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
4039     ArtMethod* actual_method =
4040         pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4041     if (actual_method != m) {
4042       VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4043                  << " to " << ArtMethod::PrettyMethod(actual_method);
4044       m = actual_method;
4045     }
4046   }
4047   VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
4048              << " receiver=" << pReq->receiver.Read()
4049              << " arg_count=" << pReq->arg_count;
4050   CHECK(m != nullptr);
4051 
4052   static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
4053 
4054   // Invoke the method.
4055   ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
4056   JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
4057                                     reinterpret_cast<jvalue*>(pReq->arg_values.get()));
4058 
4059   // Prepare JDWP ids for the reply.
4060   JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4061   const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
4062   StackHandleScope<3> hs(soa.Self());
4063   Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4064   Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4065   soa.Self()->ClearException();
4066 
4067   if (!IsDebuggerActive()) {
4068     // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4069     // because it won't be sent either.
4070     return;
4071   }
4072 
4073   JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4074   uint64_t result_value = 0;
4075   if (exceptionObjectId != 0) {
4076     VLOG(jdwp) << "  JDWP invocation returning with exception=" << exception.Get()
4077                << " " << exception->Dump();
4078     result_value = 0;
4079   } else if (is_object_result) {
4080     /* if no exception was thrown, examine object result more closely */
4081     JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
4082     if (new_tag != result_tag) {
4083       VLOG(jdwp) << "  JDWP promoted result from " << result_tag << " to " << new_tag;
4084       result_tag = new_tag;
4085     }
4086 
4087     // Register the object in the registry and reference its ObjectId. This ensures
4088     // GC safety and prevents from accessing stale reference if the object is moved.
4089     result_value = gRegistry->Add(object_result.Get());
4090   } else {
4091     // Primitive result.
4092     DCHECK(IsPrimitiveTag(result_tag));
4093     result_value = result.GetJ();
4094   }
4095   const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4096   if (is_constructor) {
4097     // If we invoked a constructor (which actually returns void), return the receiver,
4098     // unless we threw, in which case we return null.
4099     DCHECK_EQ(JDWP::JT_VOID, result_tag);
4100     if (exceptionObjectId == 0) {
4101       if (m->GetDeclaringClass()->IsStringClass()) {
4102         // For string constructors, the new string is remapped to the receiver (stored in ref).
4103         Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4104         result_value = gRegistry->Add(decoded_ref);
4105         result_tag = TagFromObject(soa, decoded_ref.Get());
4106       } else {
4107         // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4108         // object registry.
4109         result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4110         result_tag = TagFromObject(soa, pReq->receiver.Read());
4111       }
4112     } else {
4113       result_value = 0;
4114       result_tag = JDWP::JT_OBJECT;
4115     }
4116   }
4117 
4118   // Suspend other threads if the invoke is not single-threaded.
4119   if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
4120     ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
4121     // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4122     gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
4123     VLOG(jdwp) << "      Suspending all threads";
4124     Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
4125   }
4126 
4127   VLOG(jdwp) << "  --> returned " << result_tag
4128              << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4129                              exceptionObjectId);
4130 
4131   // Show detailed debug output.
4132   if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4133     if (result_value != 0) {
4134       if (VLOG_IS_ON(jdwp)) {
4135         std::string result_string;
4136         JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4137         CHECK_EQ(error, JDWP::ERR_NONE);
4138         VLOG(jdwp) << "      string '" << result_string << "'";
4139       }
4140     } else {
4141       VLOG(jdwp) << "      string (null)";
4142     }
4143   }
4144 
4145   // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4146   // is ready to suspend.
4147   BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4148 }
4149 
BuildInvokeReply(JDWP::ExpandBuf * pReply,uint32_t request_id,JDWP::JdwpTag result_tag,uint64_t result_value,JDWP::ObjectId exception)4150 void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4151                            uint64_t result_value, JDWP::ObjectId exception) {
4152   // Make room for the JDWP header since we do not know the size of the reply yet.
4153   JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4154 
4155   size_t width = GetTagWidth(result_tag);
4156   JDWP::expandBufAdd1(pReply, result_tag);
4157   if (width != 0) {
4158     WriteValue(pReply, width, result_value);
4159   }
4160   JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4161   JDWP::expandBufAddObjectId(pReply, exception);
4162 
4163   // Now we know the size, we can complete the JDWP header.
4164   uint8_t* buf = expandBufGetBuffer(pReply);
4165   JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4166   JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4167   JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply);  // flags
4168   JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4169 }
4170 
FinishInvokeMethod(DebugInvokeReq * pReq)4171 void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4172   CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4173 
4174   JDWP::ExpandBuf* const pReply = pReq->reply;
4175   CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4176 
4177   // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4178   // while we send the reply but are not yet suspended. The JDWP token will be released just before
4179   // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4180   gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4181 
4182   // Send the reply unless the debugger detached before the completion of the method.
4183   if (IsDebuggerActive()) {
4184     const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4185     VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4186                                pReq->request_id, replyDataLength);
4187 
4188     gJdwpState->SendRequest(pReply);
4189   } else {
4190     VLOG(jdwp) << "Not sending invoke reply because debugger detached";
4191   }
4192 }
4193 
DdmHandleChunk(JNIEnv * env,uint32_t type,const ArrayRef<const jbyte> & data,uint32_t * out_type,std::vector<uint8_t> * out_data)4194 bool Dbg::DdmHandleChunk(JNIEnv* env,
4195                          uint32_t type,
4196                          const ArrayRef<const jbyte>& data,
4197                          /*out*/uint32_t* out_type,
4198                          /*out*/std::vector<uint8_t>* out_data) {
4199   ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
4200   if (dataArray.get() == nullptr) {
4201     LOG(WARNING) << "byte[] allocation failed: " << data.size();
4202     env->ExceptionClear();
4203     return false;
4204   }
4205   env->SetByteArrayRegion(dataArray.get(),
4206                           0,
4207                           data.size(),
4208                           reinterpret_cast<const jbyte*>(data.data()));
4209   // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
4210   ScopedLocalRef<jobject> chunk(
4211       env,
4212       env->CallStaticObjectMethod(
4213           WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4214           WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4215           type, dataArray.get(), 0, data.size()));
4216   if (env->ExceptionCheck()) {
4217     Thread* self = Thread::Current();
4218     ScopedObjectAccess soa(self);
4219     LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type) << std::endl
4220               << self->GetException()->Dump();
4221     self->ClearException();
4222     return false;
4223   }
4224 
4225   if (chunk.get() == nullptr) {
4226     return false;
4227   }
4228 
4229   /*
4230    * Pull the pieces out of the chunk.  We copy the results into a
4231    * newly-allocated buffer that the caller can free.  We don't want to
4232    * continue using the Chunk object because nothing has a reference to it.
4233    *
4234    * We could avoid this by returning type/data/offset/length and having
4235    * the caller be aware of the object lifetime issues, but that
4236    * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
4237    * if we have responses for multiple chunks.
4238    *
4239    * So we're pretty much stuck with copying data around multiple times.
4240    */
4241   ScopedLocalRef<jbyteArray> replyData(
4242       env,
4243       reinterpret_cast<jbyteArray>(
4244           env->GetObjectField(
4245               chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4246   jint offset = env->GetIntField(chunk.get(),
4247                                  WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4248   jint length = env->GetIntField(chunk.get(),
4249                                  WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4250   *out_type = env->GetIntField(chunk.get(),
4251                                WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
4252 
4253   VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4254                              type,
4255                              replyData.get(),
4256                              offset,
4257                              length);
4258   out_data->resize(length);
4259   env->GetByteArrayRegion(replyData.get(),
4260                           offset,
4261                           length,
4262                           reinterpret_cast<jbyte*>(out_data->data()));
4263 
4264   if (env->ExceptionCheck()) {
4265     Thread* self = Thread::Current();
4266     ScopedObjectAccess soa(self);
4267     LOG(INFO) << StringPrintf("Exception thrown when reading response data from dispatcher 0x%08x",
4268                               type) << std::endl << self->GetException()->Dump();
4269     self->ClearException();
4270     return false;
4271   }
4272 
4273   return true;
4274 }
4275 
4276 /*
4277  * "request" contains a full JDWP packet, possibly with multiple chunks.  We
4278  * need to process each, accumulate the replies, and ship the whole thing
4279  * back.
4280  *
4281  * Returns "true" if we have a reply.  The reply buffer is newly allocated,
4282  * and includes the chunk type/length, followed by the data.
4283  *
4284  * OLD-TODO: we currently assume that the request and reply include a single
4285  * chunk.  If this becomes inconvenient we will need to adapt.
4286  */
DdmHandlePacket(JDWP::Request * request,uint8_t ** pReplyBuf,int * pReplyLen)4287 bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4288   Thread* self = Thread::Current();
4289   JNIEnv* env = self->GetJniEnv();
4290 
4291   uint32_t type = request->ReadUnsigned32("type");
4292   uint32_t length = request->ReadUnsigned32("length");
4293 
4294   // Create a byte[] corresponding to 'request'.
4295   size_t request_length = request->size();
4296   // Run through and find all chunks.  [Currently just find the first.]
4297   if (length != request_length) {
4298     LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
4299     return false;
4300   }
4301 
4302   ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4303   std::vector<uint8_t> out_data;
4304   uint32_t out_type = 0;
4305   request->Skip(request_length);
4306   if (!DdmHandleChunk(env, type, data, &out_type, &out_data) || out_data.empty()) {
4307     return false;
4308   }
4309   const uint32_t kDdmHeaderSize = 8;
4310   *pReplyLen = out_data.size() + kDdmHeaderSize;
4311   *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4312   memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4313   JDWP::Set4BE(*pReplyBuf, out_type);
4314   JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4315   VLOG(jdwp)
4316       << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4317       << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4318       << " len= " << out_data.size();
4319   return true;
4320 }
4321 
DdmBroadcast(bool connect)4322 void Dbg::DdmBroadcast(bool connect) {
4323   VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
4324 
4325   Thread* self = Thread::Current();
4326   if (self->GetState() != kRunnable) {
4327     LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4328     /* try anyway? */
4329   }
4330 
4331   JNIEnv* env = self->GetJniEnv();
4332   jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
4333   env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4334                             WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4335                             event);
4336   if (env->ExceptionCheck()) {
4337     LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4338     env->ExceptionDescribe();
4339     env->ExceptionClear();
4340   }
4341 }
4342 
DdmConnected()4343 void Dbg::DdmConnected() {
4344   Dbg::DdmBroadcast(true);
4345 }
4346 
DdmDisconnected()4347 void Dbg::DdmDisconnected() {
4348   Dbg::DdmBroadcast(false);
4349   gDdmThreadNotification = false;
4350 }
4351 
4352 /*
4353  * Send a notification when a thread starts, stops, or changes its name.
4354  *
4355  * Because we broadcast the full set of threads when the notifications are
4356  * first enabled, it's possible for "thread" to be actively executing.
4357  */
DdmSendThreadNotification(Thread * t,uint32_t type)4358 void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
4359   if (!gDdmThreadNotification) {
4360     return;
4361   }
4362 
4363   RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
4364   if (type == CHUNK_TYPE("THDE")) {
4365     uint8_t buf[4];
4366     JDWP::Set4BE(&buf[0], t->GetThreadId());
4367     cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
4368   } else {
4369     CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
4370     ScopedObjectAccessUnchecked soa(Thread::Current());
4371     StackHandleScope<1> hs(soa.Self());
4372     Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
4373     size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4374     const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4375     bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
4376 
4377     std::vector<uint8_t> bytes;
4378     JDWP::Append4BE(bytes, t->GetThreadId());
4379     if (is_compressed) {
4380       const uint8_t* chars_compressed = name->GetValueCompressed();
4381       JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4382     } else {
4383       JDWP::AppendUtf16BE(bytes, chars, char_count);
4384     }
4385     CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4386     cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
4387   }
4388 }
4389 
DdmSetThreadNotification(bool enable)4390 void Dbg::DdmSetThreadNotification(bool enable) {
4391   // Enable/disable thread notifications.
4392   gDdmThreadNotification = enable;
4393   if (enable) {
4394     // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4395     // see a suspension in progress and block until that ends. They then post their own start
4396     // notification.
4397     SuspendVM();
4398     std::list<Thread*> threads;
4399     Thread* self = Thread::Current();
4400     {
4401       MutexLock mu(self, *Locks::thread_list_lock_);
4402       threads = Runtime::Current()->GetThreadList()->GetList();
4403     }
4404     {
4405       ScopedObjectAccess soa(self);
4406       for (Thread* thread : threads) {
4407         Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
4408       }
4409     }
4410     ResumeVM();
4411   }
4412 }
4413 
PostThreadStartOrStop(Thread * t,uint32_t type)4414 void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
4415   if (IsDebuggerActive()) {
4416     gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
4417   }
4418   Dbg::DdmSendThreadNotification(t, type);
4419 }
4420 
PostThreadStart(Thread * t)4421 void Dbg::PostThreadStart(Thread* t) {
4422   Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
4423 }
4424 
PostThreadDeath(Thread * t)4425 void Dbg::PostThreadDeath(Thread* t) {
4426   Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
4427 }
4428 
GetJdwpState()4429 JDWP::JdwpState* Dbg::GetJdwpState() {
4430   return gJdwpState;
4431 }
4432 
DdmHandleHpifChunk(HpifWhen when)4433 int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4434   if (when == HPIF_WHEN_NOW) {
4435     DdmSendHeapInfo(when);
4436     return true;
4437   }
4438 
4439   if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4440     LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4441     return false;
4442   }
4443 
4444   gDdmHpifWhen = when;
4445   return true;
4446 }
4447 
DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when,Dbg::HpsgWhat what,bool native)4448 bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4449   if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4450     LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4451     return false;
4452   }
4453 
4454   if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4455     LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4456     return false;
4457   }
4458 
4459   if (native) {
4460     gDdmNhsgWhen = when;
4461     gDdmNhsgWhat = what;
4462   } else {
4463     gDdmHpsgWhen = when;
4464     gDdmHpsgWhat = what;
4465   }
4466   return true;
4467 }
4468 
DdmSendHeapInfo(HpifWhen reason)4469 void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4470   // If there's a one-shot 'when', reset it.
4471   if (reason == gDdmHpifWhen) {
4472     if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4473       gDdmHpifWhen = HPIF_WHEN_NEVER;
4474     }
4475   }
4476 
4477   /*
4478    * Chunk HPIF (client --> server)
4479    *
4480    * Heap Info. General information about the heap,
4481    * suitable for a summary display.
4482    *
4483    *   [u4]: number of heaps
4484    *
4485    *   For each heap:
4486    *     [u4]: heap ID
4487    *     [u8]: timestamp in ms since Unix epoch
4488    *     [u1]: capture reason (same as 'when' value from server)
4489    *     [u4]: max heap size in bytes (-Xmx)
4490    *     [u4]: current heap size in bytes
4491    *     [u4]: current number of bytes allocated
4492    *     [u4]: current number of objects allocated
4493    */
4494   uint8_t heap_count = 1;
4495   gc::Heap* heap = Runtime::Current()->GetHeap();
4496   std::vector<uint8_t> bytes;
4497   JDWP::Append4BE(bytes, heap_count);
4498   JDWP::Append4BE(bytes, 1);  // Heap id (bogus; we only have one heap).
4499   JDWP::Append8BE(bytes, MilliTime());
4500   JDWP::Append1BE(bytes, reason);
4501   JDWP::Append4BE(bytes, heap->GetMaxMemory());  // Max allowed heap size in bytes.
4502   JDWP::Append4BE(bytes, heap->GetTotalMemory());  // Current heap size in bytes.
4503   JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4504   JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
4505   CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4506   Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4507                                                              ArrayRef<const uint8_t>(bytes));
4508 }
4509 
4510 enum HpsgSolidity {
4511   SOLIDITY_FREE = 0,
4512   SOLIDITY_HARD = 1,
4513   SOLIDITY_SOFT = 2,
4514   SOLIDITY_WEAK = 3,
4515   SOLIDITY_PHANTOM = 4,
4516   SOLIDITY_FINALIZABLE = 5,
4517   SOLIDITY_SWEEP = 6,
4518 };
4519 
4520 enum HpsgKind {
4521   KIND_OBJECT = 0,
4522   KIND_CLASS_OBJECT = 1,
4523   KIND_ARRAY_1 = 2,
4524   KIND_ARRAY_2 = 3,
4525   KIND_ARRAY_4 = 4,
4526   KIND_ARRAY_8 = 5,
4527   KIND_UNKNOWN = 6,
4528   KIND_NATIVE = 7,
4529 };
4530 
4531 #define HPSG_PARTIAL (1<<7)
4532 #define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4533 
4534 class HeapChunkContext {
4535  public:
4536   // Maximum chunk size.  Obtain this from the formula:
4537   // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
HeapChunkContext(bool merge,bool native)4538   HeapChunkContext(bool merge, bool native)
4539       : buf_(16384 - 16),
4540         type_(0),
4541         chunk_overhead_(0) {
4542     Reset();
4543     if (native) {
4544       type_ = CHUNK_TYPE("NHSG");
4545     } else {
4546       type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
4547     }
4548   }
4549 
~HeapChunkContext()4550   ~HeapChunkContext() {
4551     if (p_ > &buf_[0]) {
4552       Flush();
4553     }
4554   }
4555 
SetChunkOverhead(size_t chunk_overhead)4556   void SetChunkOverhead(size_t chunk_overhead) {
4557     chunk_overhead_ = chunk_overhead;
4558   }
4559 
ResetStartOfNextChunk()4560   void ResetStartOfNextChunk() {
4561     startOfNextMemoryChunk_ = nullptr;
4562   }
4563 
EnsureHeader(const void * chunk_ptr)4564   void EnsureHeader(const void* chunk_ptr) {
4565     if (!needHeader_) {
4566       return;
4567     }
4568 
4569     // Start a new HPSx chunk.
4570     JDWP::Write4BE(&p_, 1);  // Heap id (bogus; we only have one heap).
4571     JDWP::Write1BE(&p_, 8);  // Size of allocation unit, in bytes.
4572 
4573     JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr));  // virtual address of segment start.
4574     JDWP::Write4BE(&p_, 0);  // offset of this piece (relative to the virtual address).
4575     // [u4]: length of piece, in allocation units
4576     // We won't know this until we're done, so save the offset and stuff in a dummy value.
4577     pieceLenField_ = p_;
4578     JDWP::Write4BE(&p_, 0x55555555);
4579     needHeader_ = false;
4580   }
4581 
Flush()4582   void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
4583     if (pieceLenField_ == nullptr) {
4584       // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4585       CHECK(needHeader_);
4586       return;
4587     }
4588     // Patch the "length of piece" field.
4589     CHECK_LE(&buf_[0], pieceLenField_);
4590     CHECK_LE(pieceLenField_, p_);
4591     JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
4592 
4593     ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4594     Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
4595     Reset();
4596   }
4597 
HeapChunkJavaCallback(void * start,void * end,size_t used_bytes,void * arg)4598   static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
4599       REQUIRES_SHARED(Locks::heap_bitmap_lock_,
4600                             Locks::mutator_lock_) {
4601     reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4602   }
4603 
HeapChunkNativeCallback(void * start,void * end,size_t used_bytes,void * arg)4604   static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4605       REQUIRES_SHARED(Locks::mutator_lock_) {
4606     reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
4607   }
4608 
4609  private:
4610   enum { ALLOCATION_UNIT_SIZE = 8 };
4611 
Reset()4612   void Reset() {
4613     p_ = &buf_[0];
4614     ResetStartOfNextChunk();
4615     totalAllocationUnits_ = 0;
4616     needHeader_ = true;
4617     pieceLenField_ = nullptr;
4618   }
4619 
IsNative() const4620   bool IsNative() const {
4621     return type_ == CHUNK_TYPE("NHSG");
4622   }
4623 
4624   // Returns true if the object is not an empty chunk.
ProcessRecord(void * start,size_t used_bytes)4625   bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
4626     // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4627     // in the following code not to allocate memory, by ensuring buf_ is of the correct size
4628     if (used_bytes == 0) {
4629       if (start == nullptr) {
4630         // Reset for start of new heap.
4631         startOfNextMemoryChunk_ = nullptr;
4632         Flush();
4633       }
4634       // Only process in use memory so that free region information
4635       // also includes dlmalloc book keeping.
4636       return false;
4637     }
4638     if (startOfNextMemoryChunk_ != nullptr) {
4639       // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4640       // of the use of mmaps, so don't report. If not free memory then start a new segment.
4641       bool flush = true;
4642       if (start > startOfNextMemoryChunk_) {
4643         const size_t kMaxFreeLen = 2 * kPageSize;
4644         void* free_start = startOfNextMemoryChunk_;
4645         void* free_end = start;
4646         const size_t free_len =
4647             reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4648         if (!IsNative() || free_len < kMaxFreeLen) {
4649           AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4650           flush = false;
4651         }
4652       }
4653       if (flush) {
4654         startOfNextMemoryChunk_ = nullptr;
4655         Flush();
4656       }
4657     }
4658     return true;
4659   }
4660 
HeapChunkNativeCallback(void * start,void *,size_t used_bytes)4661   void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4662       REQUIRES_SHARED(Locks::mutator_lock_) {
4663     if (ProcessRecord(start, used_bytes)) {
4664       uint8_t state = ExamineNativeObject(start);
4665       AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ true);
4666       startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4667     }
4668   }
4669 
HeapChunkJavaCallback(void * start,void *,size_t used_bytes)4670   void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4671       REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4672     if (ProcessRecord(start, used_bytes)) {
4673       // Determine the type of this chunk.
4674       // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4675       // If it's the same, we should combine them.
4676       uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4677       AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ false);
4678       startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4679     }
4680   }
4681 
AppendChunk(uint8_t state,void * ptr,size_t length,bool is_native)4682   void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
4683       REQUIRES_SHARED(Locks::mutator_lock_) {
4684     // Make sure there's enough room left in the buffer.
4685     // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4686     // 17 bytes for any header.
4687     const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4688     size_t byte_left = &buf_.back() - p_;
4689     if (byte_left < needed) {
4690       if (is_native) {
4691       // Cannot trigger memory allocation while walking native heap.
4692         return;
4693       }
4694       Flush();
4695     }
4696 
4697     byte_left = &buf_.back() - p_;
4698     if (byte_left < needed) {
4699       LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4700           << needed << " bytes)";
4701       return;
4702     }
4703     EnsureHeader(ptr);
4704     // Write out the chunk description.
4705     length /= ALLOCATION_UNIT_SIZE;   // Convert to allocation units.
4706     totalAllocationUnits_ += length;
4707     while (length > 256) {
4708       *p_++ = state | HPSG_PARTIAL;
4709       *p_++ = 255;     // length - 1
4710       length -= 256;
4711     }
4712     *p_++ = state;
4713     *p_++ = length - 1;
4714   }
4715 
ExamineNativeObject(const void * p)4716   uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
4717     return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4718   }
4719 
ExamineJavaObject(mirror::Object * o)4720   uint8_t ExamineJavaObject(mirror::Object* o)
4721       REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
4722     if (o == nullptr) {
4723       return HPSG_STATE(SOLIDITY_FREE, 0);
4724     }
4725     // It's an allocated chunk. Figure out what it is.
4726     gc::Heap* heap = Runtime::Current()->GetHeap();
4727     if (!heap->IsLiveObjectLocked(o)) {
4728       LOG(ERROR) << "Invalid object in managed heap: " << o;
4729       return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4730     }
4731     ObjPtr<mirror::Class> c = o->GetClass();
4732     if (c == nullptr) {
4733       // The object was probably just created but hasn't been initialized yet.
4734       return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4735     }
4736     if (!heap->IsValidObjectAddress(c.Ptr())) {
4737       LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
4738       return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4739     }
4740     if (c->GetClass() == nullptr) {
4741       LOG(ERROR) << "Null class of class " << c << " for object " << o;
4742       return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4743     }
4744     if (c->IsClassClass()) {
4745       return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4746     }
4747     if (c->IsArrayClass()) {
4748       switch (c->GetComponentSize()) {
4749       case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4750       case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4751       case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4752       case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4753       }
4754     }
4755     return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4756   }
4757 
4758   std::vector<uint8_t> buf_;
4759   uint8_t* p_;
4760   uint8_t* pieceLenField_;
4761   void* startOfNextMemoryChunk_;
4762   size_t totalAllocationUnits_;
4763   uint32_t type_;
4764   bool needHeader_;
4765   size_t chunk_overhead_;
4766 
4767   DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4768 };
4769 
DdmSendHeapSegments(bool native)4770 void Dbg::DdmSendHeapSegments(bool native) {
4771   Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4772   Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
4773   if (when == HPSG_WHEN_NEVER) {
4774     return;
4775   }
4776   RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
4777   // Figure out what kind of chunks we'll be sending.
4778   CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4779       << static_cast<int>(what);
4780 
4781   // First, send a heap start chunk.
4782   uint8_t heap_id[4];
4783   JDWP::Set4BE(&heap_id[0], 1);  // Heap id (bogus; we only have one heap).
4784   cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4785                       ArrayRef<const uint8_t>(heap_id));
4786   Thread* self = Thread::Current();
4787   Locks::mutator_lock_->AssertSharedHeld(self);
4788 
4789   // Send a series of heap segment chunks.
4790   HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
4791   auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4792       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4793     const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4794     HeapChunkContext::HeapChunkJavaCallback(
4795         obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4796   };
4797   if (native) {
4798     UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
4799   } else {
4800     gc::Heap* heap = Runtime::Current()->GetHeap();
4801     for (const auto& space : heap->GetContinuousSpaces()) {
4802       if (space->IsDlMallocSpace()) {
4803         ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4804         // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4805         // allocation then the first sizeof(size_t) may belong to it.
4806         context.SetChunkOverhead(sizeof(size_t));
4807         space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
4808       } else if (space->IsRosAllocSpace()) {
4809         context.SetChunkOverhead(0);
4810         // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4811         // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4812         ScopedThreadSuspension sts(self, kSuspended);
4813         ScopedSuspendAll ssa(__FUNCTION__);
4814         ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4815         space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
4816       } else if (space->IsBumpPointerSpace()) {
4817         ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4818         context.SetChunkOverhead(0);
4819         space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
4820         HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4821       } else if (space->IsRegionSpace()) {
4822         heap->IncrementDisableMovingGC(self);
4823         {
4824           ScopedThreadSuspension sts(self, kSuspended);
4825           ScopedSuspendAll ssa(__FUNCTION__);
4826           ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4827           context.SetChunkOverhead(0);
4828           space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
4829           HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4830         }
4831         heap->DecrementDisableMovingGC(self);
4832       } else {
4833         UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
4834       }
4835       context.ResetStartOfNextChunk();
4836     }
4837     ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4838     // Walk the large objects, these are not in the AllocSpace.
4839     context.SetChunkOverhead(0);
4840     heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
4841   }
4842 
4843   // Finally, send a heap end chunk.
4844   cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4845                       ArrayRef<const uint8_t>(heap_id));
4846 }
4847 
SetAllocTrackingEnabled(bool enable)4848 void Dbg::SetAllocTrackingEnabled(bool enable) {
4849   gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
4850 }
4851 
DumpRecentAllocations()4852 void Dbg::DumpRecentAllocations() {
4853   ScopedObjectAccess soa(Thread::Current());
4854   MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
4855   if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
4856     LOG(INFO) << "Not recording tracked allocations";
4857     return;
4858   }
4859   gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4860   CHECK(records != nullptr);
4861 
4862   const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
4863   uint16_t count = capped_count;
4864 
4865   LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4866   for (auto it = records->RBegin(), end = records->REnd();
4867       count > 0 && it != end; count--, it++) {
4868     const gc::AllocRecord* record = &it->second;
4869 
4870     LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
4871               << mirror::Class::PrettyClass(record->GetClass());
4872 
4873     for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4874       const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4875       ArtMethod* m = stack_element.GetMethod();
4876       LOG(INFO) << "    " << ArtMethod::PrettyMethod(m) << " line "
4877                 << stack_element.ComputeLineNumber();
4878     }
4879 
4880     // pause periodically to help logcat catch up
4881     if ((count % 5) == 0) {
4882       usleep(40000);
4883     }
4884   }
4885 }
4886 
4887 class StringTable {
4888  private:
4889   struct Entry {
Entryart::StringTable::Entry4890     explicit Entry(const char* data_in)
4891         : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
4892     }
4893     Entry(const Entry& entry) = default;
4894     Entry(Entry&& entry) = default;
4895 
4896     // Pointer to the actual string data.
4897     const char* data;
4898 
4899     // The hash of the data.
4900     const uint32_t hash;
4901 
4902     // The index. This will be filled in on Finish and is not part of the ordering, so mark it
4903     // mutable.
4904     mutable uint32_t index;
4905 
operator ==art::StringTable::Entry4906     bool operator==(const Entry& other) const {
4907       return strcmp(data, other.data) == 0;
4908     }
4909   };
4910   struct EntryHash {
operator ()art::StringTable::EntryHash4911     size_t operator()(const Entry& entry) const {
4912       return entry.hash;
4913     }
4914   };
4915 
4916  public:
StringTable()4917   StringTable() : finished_(false) {
4918   }
4919 
Add(const char * str,bool copy_string)4920   void Add(const char* str, bool copy_string) {
4921     DCHECK(!finished_);
4922     if (UNLIKELY(copy_string)) {
4923       // Check whether it's already there.
4924       Entry entry(str);
4925       if (table_.find(entry) != table_.end()) {
4926         return;
4927       }
4928 
4929       // Make a copy.
4930       size_t str_len = strlen(str);
4931       char* copy = new char[str_len + 1];
4932       strlcpy(copy, str, str_len + 1);
4933       string_backup_.emplace_back(copy);
4934       str = copy;
4935     }
4936     Entry entry(str);
4937     table_.insert(entry);
4938   }
4939 
4940   // Update all entries and give them an index. Note that this is likely not the insertion order,
4941   // as the set will with high likelihood reorder elements. Thus, Add must not be called after
4942   // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
4943   // the same order as Finish, and indices will agree. The order invariant, as well as indices,
4944   // are enforced through debug checks.
Finish()4945   void Finish() {
4946     DCHECK(!finished_);
4947     finished_ = true;
4948     uint32_t index = 0;
4949     for (auto& entry : table_) {
4950       entry.index = index;
4951       ++index;
4952     }
4953   }
4954 
IndexOf(const char * s) const4955   size_t IndexOf(const char* s) const {
4956     DCHECK(finished_);
4957     Entry entry(s);
4958     auto it = table_.find(entry);
4959     if (it == table_.end()) {
4960       LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4961     }
4962     return it->index;
4963   }
4964 
Size() const4965   size_t Size() const {
4966     return table_.size();
4967   }
4968 
WriteTo(std::vector<uint8_t> & bytes) const4969   void WriteTo(std::vector<uint8_t>& bytes) const {
4970     DCHECK(finished_);
4971     uint32_t cur_index = 0;
4972     for (const auto& entry : table_) {
4973       DCHECK_EQ(cur_index++, entry.index);
4974 
4975       size_t s_len = CountModifiedUtf8Chars(entry.data);
4976       std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
4977       ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
4978       JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
4979     }
4980   }
4981 
4982  private:
4983   std::unordered_set<Entry, EntryHash> table_;
4984   std::vector<std::unique_ptr<char[]>> string_backup_;
4985 
4986   bool finished_;
4987 
4988   DISALLOW_COPY_AND_ASSIGN(StringTable);
4989 };
4990 
GetMethodSourceFile(ArtMethod * method)4991 static const char* GetMethodSourceFile(ArtMethod* method)
4992     REQUIRES_SHARED(Locks::mutator_lock_) {
4993   DCHECK(method != nullptr);
4994   const char* source_file = method->GetDeclaringClassSourceFile();
4995   return (source_file != nullptr) ? source_file : "";
4996 }
4997 
4998 /*
4999  * The data we send to DDMS contains everything we have recorded.
5000  *
5001  * Message header (all values big-endian):
5002  * (1b) message header len (to allow future expansion); includes itself
5003  * (1b) entry header len
5004  * (1b) stack frame len
5005  * (2b) number of entries
5006  * (4b) offset to string table from start of message
5007  * (2b) number of class name strings
5008  * (2b) number of method name strings
5009  * (2b) number of source file name strings
5010  * For each entry:
5011  *   (4b) total allocation size
5012  *   (2b) thread id
5013  *   (2b) allocated object's class name index
5014  *   (1b) stack depth
5015  *   For each stack frame:
5016  *     (2b) method's class name
5017  *     (2b) method name
5018  *     (2b) method source file
5019  *     (2b) line number, clipped to 32767; -2 if native; -1 if no source
5020  * (xb) class name strings
5021  * (xb) method name strings
5022  * (xb) source file strings
5023  *
5024  * As with other DDM traffic, strings are sent as a 4-byte length
5025  * followed by UTF-16 data.
5026  *
5027  * We send up 16-bit unsigned indexes into string tables.  In theory there
5028  * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
5029  * each table, but in practice there should be far fewer.
5030  *
5031  * The chief reason for using a string table here is to keep the size of
5032  * the DDMS message to a minimum.  This is partly to make the protocol
5033  * efficient, but also because we have to form the whole thing up all at
5034  * once in a memory buffer.
5035  *
5036  * We use separate string tables for class names, method names, and source
5037  * files to keep the indexes small.  There will generally be no overlap
5038  * between the contents of these tables.
5039  */
GetRecentAllocations()5040 jbyteArray Dbg::GetRecentAllocations() {
5041   if ((false)) {
5042     DumpRecentAllocations();
5043   }
5044 
5045   Thread* self = Thread::Current();
5046   std::vector<uint8_t> bytes;
5047   {
5048     MutexLock mu(self, *Locks::alloc_tracker_lock_);
5049     gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5050     // In case this method is called when allocation tracker is disabled,
5051     // we should still send some data back.
5052     gc::AllocRecordObjectMap dummy;
5053     if (records == nullptr) {
5054       CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5055       records = &dummy;
5056     }
5057     // We don't need to wait on the condition variable records->new_record_condition_, because this
5058     // function only reads the class objects, which are already marked so it doesn't change their
5059     // reachability.
5060 
5061     //
5062     // Part 1: generate string tables.
5063     //
5064     StringTable class_names;
5065     StringTable method_names;
5066     StringTable filenames;
5067 
5068     VLOG(jdwp) << "Collecting StringTables.";
5069 
5070     const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
5071     uint16_t count = capped_count;
5072     size_t alloc_byte_count = 0;
5073     for (auto it = records->RBegin(), end = records->REnd();
5074          count > 0 && it != end; count--, it++) {
5075       const gc::AllocRecord* record = &it->second;
5076       std::string temp;
5077       const char* class_descr = record->GetClassDescriptor(&temp);
5078       class_names.Add(class_descr, !temp.empty());
5079 
5080       // Size + tid + class name index + stack depth.
5081       alloc_byte_count += 4u + 2u + 2u + 1u;
5082 
5083       for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5084         ArtMethod* m = record->StackElement(i).GetMethod();
5085         class_names.Add(m->GetDeclaringClassDescriptor(), false);
5086         method_names.Add(m->GetName(), false);
5087         filenames.Add(GetMethodSourceFile(m), false);
5088       }
5089 
5090       // Depth * (class index + method name index + file name index + line number).
5091       alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
5092     }
5093 
5094     class_names.Finish();
5095     method_names.Finish();
5096     filenames.Finish();
5097     VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5098                << "  ClassNames: " << class_names.Size() << std::endl
5099                << "  MethodNames: " << method_names.Size() << std::endl
5100                << "  Filenames: " << filenames.Size();
5101 
5102     LOG(INFO) << "recent allocation records: " << capped_count;
5103     LOG(INFO) << "allocation records all objects: " << records->Size();
5104 
5105     //
5106     // Part 2: Generate the output and store it in the buffer.
5107     //
5108 
5109     // (1b) message header len (to allow future expansion); includes itself
5110     // (1b) entry header len
5111     // (1b) stack frame len
5112     const int kMessageHeaderLen = 15;
5113     const int kEntryHeaderLen = 9;
5114     const int kStackFrameLen = 8;
5115     JDWP::Append1BE(bytes, kMessageHeaderLen);
5116     JDWP::Append1BE(bytes, kEntryHeaderLen);
5117     JDWP::Append1BE(bytes, kStackFrameLen);
5118 
5119     // (2b) number of entries
5120     // (4b) offset to string table from start of message
5121     // (2b) number of class name strings
5122     // (2b) number of method name strings
5123     // (2b) number of source file name strings
5124     JDWP::Append2BE(bytes, capped_count);
5125     size_t string_table_offset = bytes.size();
5126     JDWP::Append4BE(bytes, 0);  // We'll patch this later...
5127     JDWP::Append2BE(bytes, class_names.Size());
5128     JDWP::Append2BE(bytes, method_names.Size());
5129     JDWP::Append2BE(bytes, filenames.Size());
5130 
5131     VLOG(jdwp) << "Dumping allocations with stacks";
5132 
5133     // Enlarge the vector for the allocation data.
5134     size_t reserve_size = bytes.size() + alloc_byte_count;
5135     bytes.reserve(reserve_size);
5136 
5137     std::string temp;
5138     count = capped_count;
5139     // The last "count" number of allocation records in "records" are the most recent "count" number
5140     // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5141     for (auto it = records->RBegin(), end = records->REnd();
5142          count > 0 && it != end; count--, it++) {
5143       // For each entry:
5144       // (4b) total allocation size
5145       // (2b) thread id
5146       // (2b) allocated object's class name index
5147       // (1b) stack depth
5148       const gc::AllocRecord* record = &it->second;
5149       size_t stack_depth = record->GetDepth();
5150       size_t allocated_object_class_name_index =
5151           class_names.IndexOf(record->GetClassDescriptor(&temp));
5152       JDWP::Append4BE(bytes, record->ByteCount());
5153       JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
5154       JDWP::Append2BE(bytes, allocated_object_class_name_index);
5155       JDWP::Append1BE(bytes, stack_depth);
5156 
5157       for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5158         // For each stack frame:
5159         // (2b) method's class name
5160         // (2b) method name
5161         // (2b) method source file
5162         // (2b) line number, clipped to 32767; -2 if native; -1 if no source
5163         ArtMethod* m = record->StackElement(stack_frame).GetMethod();
5164         size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5165         size_t method_name_index = method_names.IndexOf(m->GetName());
5166         size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
5167         JDWP::Append2BE(bytes, class_name_index);
5168         JDWP::Append2BE(bytes, method_name_index);
5169         JDWP::Append2BE(bytes, file_name_index);
5170         JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
5171       }
5172     }
5173 
5174     CHECK_EQ(bytes.size(), reserve_size);
5175     VLOG(jdwp) << "Dumping tables.";
5176 
5177     // (xb) class name strings
5178     // (xb) method name strings
5179     // (xb) source file strings
5180     JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5181     class_names.WriteTo(bytes);
5182     method_names.WriteTo(bytes);
5183     filenames.WriteTo(bytes);
5184 
5185     VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
5186   }
5187   JNIEnv* env = self->GetJniEnv();
5188   jbyteArray result = env->NewByteArray(bytes.size());
5189   if (result != nullptr) {
5190     env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5191   }
5192   return result;
5193 }
5194 
Method() const5195 ArtMethod* DeoptimizationRequest::Method() const {
5196   return jni::DecodeArtMethod(method_);
5197 }
5198 
SetMethod(ArtMethod * m)5199 void DeoptimizationRequest::SetMethod(ArtMethod* m) {
5200   method_ = jni::EncodeArtMethod(m);
5201 }
5202 
VisitRoots(RootVisitor * visitor)5203 void Dbg::VisitRoots(RootVisitor* visitor) {
5204   // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5205   ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5206   BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5207   for (Breakpoint& breakpoint : gBreakpoints) {
5208     breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
5209   }
5210 }
5211 
ThreadStart(Thread * self)5212 void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5213   Dbg::PostThreadStart(self);
5214 }
5215 
ThreadDeath(Thread * self)5216 void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5217   Dbg::PostThreadDeath(self);
5218 }
5219 
ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED)5220 void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5221   // Ignore ClassLoad;
5222 }
ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,Handle<mirror::Class> klass)5223 void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5224                                              Handle<mirror::Class> klass) {
5225   Dbg::PostClassPrepare(klass.Get());
5226 }
5227 
5228 }  // namespace art
5229