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