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 /*
18  * Dalvik-specific side of debugger support.  (The JDWP code is intended to
19  * be relatively generic.)
20  */
21 #ifndef ART_RUNTIME_DEBUGGER_H_
22 #define ART_RUNTIME_DEBUGGER_H_
23 
24 #include <pthread.h>
25 
26 #include <map>
27 #include <set>
28 #include <string>
29 #include <vector>
30 
31 #include "gc_root.h"
32 #include "jdwp/jdwp.h"
33 #include "jni.h"
34 #include "jvalue.h"
35 #include "object_callbacks.h"
36 #include "thread_state.h"
37 
38 namespace art {
39 namespace mirror {
40 class Class;
41 class Object;
42 class Throwable;
43 }  // namespace mirror
44 class AllocRecord;
45 class ArtField;
46 class ArtMethod;
47 class ObjectRegistry;
48 class ScopedObjectAccess;
49 class ScopedObjectAccessUnchecked;
50 class StackVisitor;
51 class Thread;
52 
53 /*
54  * Invoke-during-breakpoint support.
55  */
56 struct DebugInvokeReq {
DebugInvokeReqDebugInvokeReq57   DebugInvokeReq(uint32_t invoke_request_id, JDWP::ObjectId invoke_thread_id,
58                  mirror::Object* invoke_receiver, mirror::Class* invoke_class,
59                  ArtMethod* invoke_method, uint32_t invoke_options,
60                  uint64_t args[], uint32_t args_count)
61       : request_id(invoke_request_id), thread_id(invoke_thread_id), receiver(invoke_receiver),
62         klass(invoke_class), method(invoke_method), arg_count(args_count), arg_values(args),
63         options(invoke_options), reply(JDWP::expandBufAlloc()) {
64   }
65 
~DebugInvokeReqDebugInvokeReq66   ~DebugInvokeReq() {
67     JDWP::expandBufFree(reply);
68   }
69 
70   // Request
71   const uint32_t request_id;
72   const JDWP::ObjectId thread_id;
73   GcRoot<mirror::Object> receiver;      // not used for ClassType.InvokeMethod.
74   GcRoot<mirror::Class> klass;
75   ArtMethod* const method;
76   const uint32_t arg_count;
77   std::unique_ptr<uint64_t[]> arg_values;   // will be null if arg_count_ == 0. We take ownership
78                                             // of this array so we must delete it upon destruction.
79   const uint32_t options;
80 
81   // Reply
82   JDWP::ExpandBuf* const reply;
83 
84   void VisitRoots(RootVisitor* visitor, const RootInfo& root_info)
85       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
86 
87  private:
88   DISALLOW_COPY_AND_ASSIGN(DebugInvokeReq);
89 };
90 
91 // Thread local data-structure that holds fields for controlling single-stepping.
92 class SingleStepControl {
93  public:
SingleStepControl(JDWP::JdwpStepSize step_size,JDWP::JdwpStepDepth step_depth,int stack_depth,ArtMethod * method)94   SingleStepControl(JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth,
95                     int stack_depth, ArtMethod* method)
96       : step_size_(step_size), step_depth_(step_depth),
97         stack_depth_(stack_depth), method_(method) {
98   }
99 
GetStepSize()100   JDWP::JdwpStepSize GetStepSize() const {
101     return step_size_;
102   }
103 
GetStepDepth()104   JDWP::JdwpStepDepth GetStepDepth() const {
105     return step_depth_;
106   }
107 
GetStackDepth()108   int GetStackDepth() const {
109     return stack_depth_;
110   }
111 
GetMethod()112   ArtMethod* GetMethod() const {
113     return method_;
114   }
115 
GetDexPcs()116   const std::set<uint32_t>& GetDexPcs() const {
117     return dex_pcs_;
118   }
119 
120   void AddDexPc(uint32_t dex_pc);
121 
122   bool ContainsDexPc(uint32_t dex_pc) const;
123 
124  private:
125   // See JdwpStepSize and JdwpStepDepth for details.
126   const JDWP::JdwpStepSize step_size_;
127   const JDWP::JdwpStepDepth step_depth_;
128 
129   // The stack depth when this single-step was initiated. This is used to support SD_OVER and SD_OUT
130   // single-step depth.
131   const int stack_depth_;
132 
133   // The location this single-step was initiated from.
134   // A single-step is initiated in a suspended thread. We save here the current method and the
135   // set of DEX pcs associated to the source line number where the suspension occurred.
136   // This is used to support SD_INTO and SD_OVER single-step depths so we detect when a single-step
137   // causes the execution of an instruction in a different method or at a different line number.
138   ArtMethod* method_;
139 
140   std::set<uint32_t> dex_pcs_;
141 
142   DISALLOW_COPY_AND_ASSIGN(SingleStepControl);
143 };
144 
145 // TODO rename to InstrumentationRequest.
146 class DeoptimizationRequest {
147  public:
148   enum Kind {
149     kNothing,                   // no action.
150     kRegisterForEvent,          // start listening for instrumentation event.
151     kUnregisterForEvent,        // stop listening for instrumentation event.
152     kFullDeoptimization,        // deoptimize everything.
153     kFullUndeoptimization,      // undeoptimize everything.
154     kSelectiveDeoptimization,   // deoptimize one method.
155     kSelectiveUndeoptimization  // undeoptimize one method.
156   };
157 
DeoptimizationRequest()158   DeoptimizationRequest() : kind_(kNothing), instrumentation_event_(0), method_(nullptr) {}
159 
160   DeoptimizationRequest(const DeoptimizationRequest& other)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)161       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
162       : kind_(other.kind_), instrumentation_event_(other.instrumentation_event_) {
163     // Create a new JNI global reference for the method.
164     SetMethod(other.Method());
165   }
166 
167   ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
168 
169   void SetMethod(ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
170 
171   // Name 'Kind()' would collide with the above enum name.
GetKind()172   Kind GetKind() const {
173     return kind_;
174   }
175 
SetKind(Kind kind)176   void SetKind(Kind kind) {
177     kind_ = kind;
178   }
179 
InstrumentationEvent()180   uint32_t InstrumentationEvent() const {
181     return instrumentation_event_;
182   }
183 
SetInstrumentationEvent(uint32_t instrumentation_event)184   void SetInstrumentationEvent(uint32_t instrumentation_event) {
185     instrumentation_event_ = instrumentation_event;
186   }
187 
188  private:
189   Kind kind_;
190 
191   // TODO we could use a union to hold the instrumentation_event and the method since they
192   // respectively have sense only for kRegisterForEvent/kUnregisterForEvent and
193   // kSelectiveDeoptimization/kSelectiveUndeoptimization.
194 
195   // Event to start or stop listening to. Only for kRegisterForEvent and kUnregisterForEvent.
196   uint32_t instrumentation_event_;
197 
198   // Method for selective deoptimization.
199   jmethodID method_;
200 };
201 std::ostream& operator<<(std::ostream& os, const DeoptimizationRequest::Kind& rhs);
202 
203 class Dbg {
204  public:
205   class TypeCache {
206    public:
207     // Returns a weak global for the input type. Deduplicates.
208     jobject Add(mirror::Class* t) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
209                                                         Locks::alloc_tracker_lock_);
210     // Clears the type cache and deletes all the weak global refs.
211     void Clear() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
212                                        Locks::alloc_tracker_lock_);
213 
214    private:
215     std::multimap<int32_t, jobject> objects_;
216   };
217 
218   static void SetJdwpAllowed(bool allowed);
219 
220   static void StartJdwp();
221   static void StopJdwp();
222 
223   // Invoked by the GC in case we need to keep DDMS informed.
224   static void GcDidFinish() LOCKS_EXCLUDED(Locks::mutator_lock_);
225 
226   // Return the DebugInvokeReq for the current thread.
227   static DebugInvokeReq* GetInvokeReq();
228 
229   static Thread* GetDebugThread();
230   static void ClearWaitForEventThread();
231 
232   /*
233    * Enable/disable breakpoints and step modes.  Used to provide a heads-up
234    * when the debugger attaches.
235    */
236   static void Connected();
237   static void GoActive()
238       LOCKS_EXCLUDED(Locks::breakpoint_lock_, Locks::deoptimization_lock_, Locks::mutator_lock_);
239   static void Disconnected() LOCKS_EXCLUDED(Locks::deoptimization_lock_, Locks::mutator_lock_);
Dispose()240   static void Dispose() {
241     gDisposed = true;
242   }
243 
244   // Returns true if we're actually debugging with a real debugger, false if it's
245   // just DDMS (or nothing at all).
IsDebuggerActive()246   static bool IsDebuggerActive() {
247     return gDebuggerActive;
248   }
249 
250   // Configures JDWP with parsed command-line options.
251   static void ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options);
252 
253   // Returns true if we had -Xrunjdwp or -agentlib:jdwp= on the command line.
254   static bool IsJdwpConfigured();
255 
256   // Returns true if a method has any breakpoints.
257   static bool MethodHasAnyBreakpoints(ArtMethod* method)
258       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
259       LOCKS_EXCLUDED(Locks::breakpoint_lock_);
260 
IsDisposed()261   static bool IsDisposed() {
262     return gDisposed;
263   }
264 
265   /*
266    * Time, in milliseconds, since the last debugger activity.  Does not
267    * include DDMS activity.  Returns -1 if there has been no activity.
268    * Returns 0 if we're in the middle of handling a debugger request.
269    */
270   static int64_t LastDebuggerActivity();
271 
272   static void UndoDebuggerSuspensions()
273     LOCKS_EXCLUDED(Locks::thread_list_lock_,
274                    Locks::thread_suspend_count_lock_);
275 
276   /*
277    * Class, Object, Array
278    */
279   static std::string GetClassName(JDWP::RefTypeId id)
280       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
281   static std::string GetClassName(mirror::Class* klass)
282       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
283   static JDWP::JdwpError GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id)
284       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
285   static JDWP::JdwpError GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id)
286       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
287   static JDWP::JdwpError GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply)
288       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
289   static JDWP::JdwpError GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply)
290       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
291   static JDWP::JdwpError GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply)
292       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
293   static void GetClassList(std::vector<JDWP::RefTypeId>* classes)
294       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
295   static JDWP::JdwpError GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
296                                       uint32_t* pStatus, std::string* pDescriptor)
297       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
298   static void FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids)
299       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
300   static JDWP::JdwpError GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
301       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
302   static JDWP::JdwpError GetSignature(JDWP::RefTypeId ref_type_id, std::string* signature)
303       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
304   static JDWP::JdwpError GetSourceFile(JDWP::RefTypeId ref_type_id, std::string* source_file)
305       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
306   static JDWP::JdwpError GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag)
307       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
308   static size_t GetTagWidth(JDWP::JdwpTag tag);
309 
310   static JDWP::JdwpError GetArrayLength(JDWP::ObjectId array_id, int32_t* length)
311       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
312   static JDWP::JdwpError OutputArray(JDWP::ObjectId array_id, int offset, int count,
313                                      JDWP::ExpandBuf* pReply)
314       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
315   static JDWP::JdwpError SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
316                                           JDWP::Request* request)
317       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
318 
319   static JDWP::JdwpError CreateString(const std::string& str, JDWP::ObjectId* new_string_id)
320       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
321   static JDWP::JdwpError CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id)
322       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
323   static JDWP::JdwpError CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
324                                            JDWP::ObjectId* new_array_id)
325       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
326 
327   //
328   // Event filtering.
329   //
330   static bool MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread)
331       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
332 
333   static bool MatchLocation(const JDWP::JdwpLocation& expected_location,
334                             const JDWP::EventLocation& event_location)
335       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
336 
337   static bool MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id)
338       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
339 
340   static bool MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
341                          ArtField* event_field)
342       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
343 
344   static bool MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance)
345       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
346 
347   //
348   // Monitors.
349   //
350   static JDWP::JdwpError GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
351       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
352   static JDWP::JdwpError GetOwnedMonitors(JDWP::ObjectId thread_id,
353                                           std::vector<JDWP::ObjectId>* monitors,
354                                           std::vector<uint32_t>* stack_depths)
355       LOCKS_EXCLUDED(Locks::thread_list_lock_)
356       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
357   static JDWP::JdwpError GetContendedMonitor(JDWP::ObjectId thread_id,
358                                              JDWP::ObjectId* contended_monitor)
359       LOCKS_EXCLUDED(Locks::thread_list_lock_)
360       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
361 
362   //
363   // Heap.
364   //
365   static JDWP::JdwpError GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
366                                            std::vector<uint64_t>* counts)
367       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
368   static JDWP::JdwpError GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
369                                       std::vector<JDWP::ObjectId>* instances)
370       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
371   static JDWP::JdwpError GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
372                                              std::vector<JDWP::ObjectId>* referring_objects)
373       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
374   static JDWP::JdwpError DisableCollection(JDWP::ObjectId object_id)
375       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
376   static JDWP::JdwpError EnableCollection(JDWP::ObjectId object_id)
377       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
378   static JDWP::JdwpError IsCollected(JDWP::ObjectId object_id, bool* is_collected)
379       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
380   static void DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
381       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
382 
383   //
384   // Methods and fields.
385   //
386   static std::string GetMethodName(JDWP::MethodId method_id)
387       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
388   static JDWP::JdwpError OutputDeclaredFields(JDWP::RefTypeId ref_type_id, bool with_generic,
389                                               JDWP::ExpandBuf* pReply)
390       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
391   static JDWP::JdwpError OutputDeclaredMethods(JDWP::RefTypeId ref_type_id, bool with_generic,
392                                                JDWP::ExpandBuf* pReply)
393       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
394   static JDWP::JdwpError OutputDeclaredInterfaces(JDWP::RefTypeId ref_type_id,
395                                                   JDWP::ExpandBuf* pReply)
396       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
397   static void OutputLineTable(JDWP::RefTypeId ref_type_id, JDWP::MethodId method_id,
398                               JDWP::ExpandBuf* pReply)
399       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
400   static void OutputVariableTable(JDWP::RefTypeId ref_type_id, JDWP::MethodId id, bool with_generic,
401                                   JDWP::ExpandBuf* pReply)
402       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
403   static void OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
404                                       JDWP::ExpandBuf* pReply)
405       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
406   static void OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
407                                JDWP::ExpandBuf* pReply)
408       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
409   static JDWP::JdwpError GetBytecodes(JDWP::RefTypeId class_id, JDWP::MethodId method_id,
410                                       std::vector<uint8_t>* bytecodes)
411       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
412 
413   static std::string GetFieldName(JDWP::FieldId field_id)
414       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
415   static JDWP::JdwpTag GetFieldBasicTag(JDWP::FieldId field_id)
416       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
417   static JDWP::JdwpTag GetStaticFieldBasicTag(JDWP::FieldId field_id)
418       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
419   static JDWP::JdwpError GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
420                                        JDWP::ExpandBuf* pReply)
421       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
422   static JDWP::JdwpError SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
423                                        uint64_t value, int width)
424       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
425   static JDWP::JdwpError GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
426                                              JDWP::ExpandBuf* pReply)
427       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
428   static JDWP::JdwpError SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width)
429       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
430 
431   static JDWP::JdwpError StringToUtf8(JDWP::ObjectId string_id, std::string* str)
432       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
433   static void OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply)
434       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
435 
436   /*
437    * Thread, ThreadGroup, Frame
438    */
439   static JDWP::JdwpError GetThreadName(JDWP::ObjectId thread_id, std::string* name)
440       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
441       LOCKS_EXCLUDED(Locks::thread_list_lock_);
442   static JDWP::JdwpError GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply)
443       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
444       LOCKS_EXCLUDED(Locks::thread_list_lock_);
445   static JDWP::JdwpError GetThreadGroupName(JDWP::ObjectId thread_group_id,
446                                             JDWP::ExpandBuf* pReply)
447       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
448   static JDWP::JdwpError GetThreadGroupParent(JDWP::ObjectId thread_group_id,
449                                               JDWP::ExpandBuf* pReply)
450       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
451   static JDWP::JdwpError GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
452                                                 JDWP::ExpandBuf* pReply)
453       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
454   static JDWP::ObjectId GetSystemThreadGroupId()
455       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
456 
457   static JDWP::JdwpThreadStatus ToJdwpThreadStatus(ThreadState state);
458   static JDWP::JdwpError GetThreadStatus(JDWP::ObjectId thread_id,
459                                          JDWP::JdwpThreadStatus* pThreadStatus,
460                                          JDWP::JdwpSuspendStatus* pSuspendStatus)
461       LOCKS_EXCLUDED(Locks::thread_list_lock_);
462   static JDWP::JdwpError GetThreadDebugSuspendCount(JDWP::ObjectId thread_id,
463                                                     JDWP::ExpandBuf* pReply)
464       LOCKS_EXCLUDED(Locks::thread_list_lock_,
465                      Locks::thread_suspend_count_lock_);
466   // static void WaitForSuspend(JDWP::ObjectId thread_id);
467 
468   // Fills 'thread_ids' with the threads in the given thread group. If thread_group_id == 0,
469   // returns all threads.
470   static void GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids)
471       LOCKS_EXCLUDED(Locks::thread_list_lock_)
472       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
473 
474   static JDWP::JdwpError GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result)
475       LOCKS_EXCLUDED(Locks::thread_list_lock_);
476   static JDWP::JdwpError GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
477                                          size_t frame_count, JDWP::ExpandBuf* buf)
478       LOCKS_EXCLUDED(Locks::thread_list_lock_)
479       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
480 
481   static JDWP::ObjectId GetThreadSelfId() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
482   static JDWP::ObjectId GetThreadId(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
483 
484   static void SuspendVM()
485       LOCKS_EXCLUDED(Locks::thread_list_lock_,
486                      Locks::thread_suspend_count_lock_);
487   static void ResumeVM()
488       LOCKS_EXCLUDED(Locks::thread_list_lock_,
489                      Locks::thread_suspend_count_lock_);
490   static JDWP::JdwpError SuspendThread(JDWP::ObjectId thread_id, bool request_suspension = true)
491       LOCKS_EXCLUDED(Locks::mutator_lock_,
492                      Locks::thread_list_lock_,
493                      Locks::thread_suspend_count_lock_);
494 
495   static void ResumeThread(JDWP::ObjectId thread_id)
496       LOCKS_EXCLUDED(Locks::thread_list_lock_,
497                      Locks::thread_suspend_count_lock_)
498       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
499   static void SuspendSelf();
500 
501   static JDWP::JdwpError GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
502                                        JDWP::ObjectId* result)
503       LOCKS_EXCLUDED(Locks::thread_list_lock_,
504                      Locks::thread_suspend_count_lock_)
505       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
506   static JDWP::JdwpError GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply)
507       LOCKS_EXCLUDED(Locks::thread_list_lock_)
508       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
509   static JDWP::JdwpError SetLocalValues(JDWP::Request* request)
510       LOCKS_EXCLUDED(Locks::thread_list_lock_)
511       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
512 
513   static JDWP::JdwpError Interrupt(JDWP::ObjectId thread_id)
514       LOCKS_EXCLUDED(Locks::thread_list_lock_);
515 
516   /*
517    * Debugger notification
518    */
519   enum EventFlag {
520     kBreakpoint     = 0x01,
521     kSingleStep     = 0x02,
522     kMethodEntry    = 0x04,
523     kMethodExit     = 0x08,
524   };
525   static void PostFieldAccessEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
526                                    ArtField* f)
527       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
528   static void PostFieldModificationEvent(ArtMethod* m, int dex_pc,
529                                          mirror::Object* this_object, ArtField* f,
530                                          const JValue* field_value)
531       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
532   static void PostException(mirror::Throwable* exception)
533       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
534   static void PostThreadStart(Thread* t)
535       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
536   static void PostThreadDeath(Thread* t)
537       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
538   static void PostClassPrepare(mirror::Class* c)
539       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
540 
541   static void UpdateDebugger(Thread* thread, mirror::Object* this_object,
542                              ArtMethod* method, uint32_t new_dex_pc,
543                              int event_flags, const JValue* return_value)
544       LOCKS_EXCLUDED(Locks::breakpoint_lock_)
545       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
546 
547   // Indicates whether we need deoptimization for debugging.
548   static bool RequiresDeoptimization();
549 
550   // Records deoptimization request in the queue.
551   static void RequestDeoptimization(const DeoptimizationRequest& req)
552       LOCKS_EXCLUDED(Locks::deoptimization_lock_)
553       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
554 
555   // Manage deoptimization after updating JDWP events list. Suspends all threads, processes each
556   // request and finally resumes all threads.
557   static void ManageDeoptimization()
558       LOCKS_EXCLUDED(Locks::deoptimization_lock_)
559       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
560 
561   // Breakpoints.
562   static void WatchLocation(const JDWP::JdwpLocation* pLoc, DeoptimizationRequest* req)
563       LOCKS_EXCLUDED(Locks::breakpoint_lock_)
564       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
565   static void UnwatchLocation(const JDWP::JdwpLocation* pLoc, DeoptimizationRequest* req)
566       LOCKS_EXCLUDED(Locks::breakpoint_lock_)
567       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
568 
569   /*
570    * Forced interpreter checkers for single-step and continue support.
571    */
572 
573   // Indicates whether we need to force the use of interpreter to invoke a method.
574   // This allows to single-step or continue into the called method.
IsForcedInterpreterNeededForCalling(Thread * thread,ArtMethod * m)575   static bool IsForcedInterpreterNeededForCalling(Thread* thread, ArtMethod* m)
576       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
577     if (!IsDebuggerActive()) {
578       return false;
579     }
580     return IsForcedInterpreterNeededForCallingImpl(thread, m);
581   }
582 
583   // Indicates whether we need to force the use of interpreter entrypoint when calling a
584   // method through the resolution trampoline. This allows to single-step or continue into
585   // the called method.
IsForcedInterpreterNeededForResolution(Thread * thread,ArtMethod * m)586   static bool IsForcedInterpreterNeededForResolution(Thread* thread, ArtMethod* m)
587       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
588     if (!IsDebuggerActive()) {
589       return false;
590     }
591     return IsForcedInterpreterNeededForResolutionImpl(thread, m);
592   }
593 
594   // Indicates whether we need to force the use of instrumentation entrypoint when calling
595   // a method through the resolution trampoline. This allows to deoptimize the stack for
596   // debugging when we returned from the called method.
IsForcedInstrumentationNeededForResolution(Thread * thread,ArtMethod * m)597   static bool IsForcedInstrumentationNeededForResolution(Thread* thread, ArtMethod* m)
598       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
599     if (!IsDebuggerActive()) {
600       return false;
601     }
602     return IsForcedInstrumentationNeededForResolutionImpl(thread, m);
603   }
604 
605   // Indicates whether we need to force the use of interpreter when returning from the
606   // interpreter into the runtime. This allows to deoptimize the stack and continue
607   // execution with interpreter for debugging.
IsForcedInterpreterNeededForUpcall(Thread * thread,ArtMethod * m)608   static bool IsForcedInterpreterNeededForUpcall(Thread* thread, ArtMethod* m)
609       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
610     if (!IsDebuggerActive()) {
611       return false;
612     }
613     return IsForcedInterpreterNeededForUpcallImpl(thread, m);
614   }
615 
616   // Single-stepping.
617   static JDWP::JdwpError ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize size,
618                                        JDWP::JdwpStepDepth depth)
619       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
620   static void UnconfigureStep(JDWP::ObjectId thread_id)
621       LOCKS_EXCLUDED(Locks::thread_list_lock_)
622       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
623 
624   /*
625    * Invoke support
626    */
627 
628   // Called by the JDWP thread to prepare invocation in the event thread (suspended on an event).
629   // If the information sent by the debugger is incorrect, it will send a reply with the
630   // appropriate error code. Otherwise, it will attach a DebugInvokeReq object to the event thread
631   // and resume it (and possibly other threads depending on the invoke options).
632   // Unlike other commands, the JDWP thread will not send the reply to the debugger (see
633   // JdwpState::ProcessRequest). The reply will be sent by the event thread itself after method
634   // invocation completes (see FinishInvokeMethod). This is required to allow the JDWP thread to
635   // process incoming commands from the debugger while the invocation is still in progress in the
636   // event thread, especially if it gets suspended by a debug event occurring in another thread.
637   static JDWP::JdwpError PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
638                                              JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
639                                              JDWP::MethodId method_id, uint32_t arg_count,
640                                              uint64_t arg_values[], JDWP::JdwpTag* arg_types,
641                                              uint32_t options)
642       LOCKS_EXCLUDED(Locks::thread_list_lock_,
643                      Locks::thread_suspend_count_lock_)
644       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
645 
646   // Called by the event thread to execute a method prepared by the JDWP thread in the given
647   // DebugInvokeReq object. Once the invocation completes, the event thread attaches a reply
648   // to that DebugInvokeReq object so it can be sent to the debugger only when the event thread
649   // is ready to suspend (see FinishInvokeMethod).
650   static void ExecuteMethod(DebugInvokeReq* pReq);
651 
652   // Called by the event thread to send the reply of the invoke (created in ExecuteMethod)
653   // before suspending itself. This is to ensure the thread is ready to suspend before the
654   // debugger receives the reply.
655   static void FinishInvokeMethod(DebugInvokeReq* pReq);
656 
657   /*
658    * DDM support.
659    */
660   static void DdmSendThreadNotification(Thread* t, uint32_t type)
661       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
662   static void DdmSetThreadNotification(bool enable)
663       LOCKS_EXCLUDED(Locks::thread_list_lock_);
664   static bool DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen);
665   static void DdmConnected() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
666   static void DdmDisconnected() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
667   static void DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes)
668       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
669   static void DdmSendChunk(uint32_t type, size_t len, const uint8_t* buf)
670       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
671   static void DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count)
672       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
673 
674   static void VisitRoots(RootVisitor* visitor)
675       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
676 
677   /*
678    * Recent allocation tracking support.
679    */
680   static void RecordAllocation(Thread* self, mirror::Class* type, size_t byte_count)
681       LOCKS_EXCLUDED(Locks::alloc_tracker_lock_)
682       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
683   static void SetAllocTrackingEnabled(bool enabled) LOCKS_EXCLUDED(Locks::alloc_tracker_lock_);
IsAllocTrackingEnabled()684   static bool IsAllocTrackingEnabled() {
685     return recent_allocation_records_ != nullptr;
686   }
687   static jbyteArray GetRecentAllocations()
688       LOCKS_EXCLUDED(Locks::alloc_tracker_lock_)
689       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
690   static size_t HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(Locks::alloc_tracker_lock_);
691   static void DumpRecentAllocations() LOCKS_EXCLUDED(Locks::alloc_tracker_lock_);
692 
693   enum HpifWhen {
694     HPIF_WHEN_NEVER = 0,
695     HPIF_WHEN_NOW = 1,
696     HPIF_WHEN_NEXT_GC = 2,
697     HPIF_WHEN_EVERY_GC = 3
698   };
699   static int DdmHandleHpifChunk(HpifWhen when)
700       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
701 
702   enum HpsgWhen {
703     HPSG_WHEN_NEVER = 0,
704     HPSG_WHEN_EVERY_GC = 1,
705   };
706   enum HpsgWhat {
707     HPSG_WHAT_MERGED_OBJECTS = 0,
708     HPSG_WHAT_DISTINCT_OBJECTS = 1,
709   };
710   static bool DdmHandleHpsgNhsgChunk(HpsgWhen when, HpsgWhat what, bool native);
711 
712   static void DdmSendHeapInfo(HpifWhen reason)
713       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
714   static void DdmSendHeapSegments(bool native)
715       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
716 
GetObjectRegistry()717   static ObjectRegistry* GetObjectRegistry() {
718     return gRegistry;
719   }
720 
721   static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
722       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
723 
724   static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
725       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
726 
727   static JDWP::FieldId ToFieldId(const ArtField* f)
728       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
729 
730   static void SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc)
731       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
732 
733   static JDWP::JdwpState* GetJdwpState();
734 
GetInstrumentationEvents()735   static uint32_t GetInstrumentationEvents() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
736     return instrumentation_events_;
737   }
738 
739  private:
740   static void ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq)
741       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
742 
743   static void BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id,
744                                JDWP::JdwpTag result_tag, uint64_t result_value,
745                                JDWP::ObjectId exception)
746       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
747 
748   static JDWP::JdwpError GetLocalValue(const StackVisitor& visitor,
749                                        ScopedObjectAccessUnchecked& soa, int slot,
750                                        JDWP::JdwpTag tag, uint8_t* buf, size_t width)
751       LOCKS_EXCLUDED(Locks::thread_list_lock_)
752       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
753   static JDWP::JdwpError SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
754                                        uint64_t value, size_t width)
755       LOCKS_EXCLUDED(Locks::thread_list_lock_)
756       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
757 
758   static void DdmBroadcast(bool connect) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
759   static void PostThreadStartOrStop(Thread*, uint32_t)
760       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
761 
762   static void PostLocationEvent(ArtMethod* method, int pcOffset,
763                                 mirror::Object* thisPtr, int eventFlags,
764                                 const JValue* return_value)
765       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
766 
767   static void ProcessDeoptimizationRequest(const DeoptimizationRequest& request)
768       EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_);
769 
770   static void RequestDeoptimizationLocked(const DeoptimizationRequest& req)
771       EXCLUSIVE_LOCKS_REQUIRED(Locks::deoptimization_lock_)
772       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
773 
774   static bool IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m)
775       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
776 
777   static bool IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m)
778       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
779 
780   static bool IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m)
781       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
782 
783   static bool IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m)
784       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
785 
786   static AllocRecord* recent_allocation_records_ PT_GUARDED_BY(Locks::alloc_tracker_lock_);
787   static size_t alloc_record_max_ GUARDED_BY(Locks::alloc_tracker_lock_);
788   static size_t alloc_record_head_ GUARDED_BY(Locks::alloc_tracker_lock_);
789   static size_t alloc_record_count_ GUARDED_BY(Locks::alloc_tracker_lock_);
790 
791   // Indicates whether the debugger is making requests.
792   static bool gDebuggerActive;
793 
794   // Indicates whether we should drop the JDWP connection because the runtime stops or the
795   // debugger called VirtualMachine.Dispose.
796   static bool gDisposed;
797 
798   // The registry mapping objects to JDWP ids.
799   static ObjectRegistry* gRegistry;
800 
801   // Deoptimization requests to be processed each time the event list is updated. This is used when
802   // registering and unregistering events so we do not deoptimize while holding the event list
803   // lock.
804   // TODO rename to instrumentation_requests.
805   static std::vector<DeoptimizationRequest> deoptimization_requests_ GUARDED_BY(Locks::deoptimization_lock_);
806 
807   // Count the number of events requiring full deoptimization. When the counter is > 0, everything
808   // is deoptimized, otherwise everything is undeoptimized.
809   // Note: we fully deoptimize on the first event only (when the counter is set to 1). We fully
810   // undeoptimize when the last event is unregistered (when the counter is set to 0).
811   static size_t full_deoptimization_event_count_ GUARDED_BY(Locks::deoptimization_lock_);
812 
813   static size_t* GetReferenceCounterForEvent(uint32_t instrumentation_event);
814 
815   // Weak global type cache, TODO improve this.
816   static TypeCache type_cache_ GUARDED_BY(Locks::alloc_tracker_lock_);
817 
818   // Instrumentation event reference counters.
819   // TODO we could use an array instead of having all these dedicated counters. Instrumentation
820   // events are bits of a mask so we could convert them to array index.
821   static size_t dex_pc_change_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
822   static size_t method_enter_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
823   static size_t method_exit_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
824   static size_t field_read_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
825   static size_t field_write_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
826   static size_t exception_catch_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_);
827   static uint32_t instrumentation_events_ GUARDED_BY(Locks::mutator_lock_);
828 
829   friend class AllocRecord;  // For type_cache_ with proper annotalysis.
830   DISALLOW_COPY_AND_ASSIGN(Dbg);
831 };
832 
833 #define CHUNK_TYPE(_name) \
834     static_cast<uint32_t>((_name)[0] << 24 | (_name)[1] << 16 | (_name)[2] << 8 | (_name)[3])
835 
836 }  // namespace art
837 
838 #endif  // ART_RUNTIME_DEBUGGER_H_
839