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