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 #ifndef ART_RUNTIME_JDWP_JDWP_H_
18 #define ART_RUNTIME_JDWP_JDWP_H_
19 
20 #include "atomic.h"
21 #include "base/mutex.h"
22 #include "jdwp/jdwp_bits.h"
23 #include "jdwp/jdwp_constants.h"
24 #include "jdwp/jdwp_expand_buf.h"
25 #include "obj_ptr.h"
26 
27 #include <pthread.h>
28 #include <stddef.h>
29 #include <stdint.h>
30 #include <string.h>
31 #include <vector>
32 
33 struct iovec;
34 
35 namespace art {
36 
37 class ArtField;
38 class ArtMethod;
39 union JValue;
40 class Thread;
41 
42 namespace mirror {
43   class Class;
44   class Object;
45   class Throwable;
46 }  // namespace mirror
47 class Thread;
48 
49 namespace JDWP {
50 
51 /*
52  * Fundamental types.
53  *
54  * ObjectId and RefTypeId must be the same size.
55  * Its OK to change MethodId and FieldId sizes as long as the size is <= 8 bytes.
56  * Note that ArtFields are 64 bit pointers on 64 bit targets. So this one must remain 8 bytes.
57  */
58 typedef uint64_t FieldId;     /* static or instance field */
59 typedef uint64_t MethodId;    /* any kind of method, including constructors */
60 typedef uint64_t ObjectId;    /* any object (threadID, stringID, arrayID, etc) */
61 typedef uint64_t RefTypeId;   /* like ObjectID, but unique for Class objects */
62 typedef uint64_t FrameId;     /* short-lived stack frame ID */
63 
64 ObjectId ReadObjectId(const uint8_t** pBuf);
65 
SetFieldId(uint8_t * buf,FieldId val)66 static inline void SetFieldId(uint8_t* buf, FieldId val) { return Set8BE(buf, val); }
SetMethodId(uint8_t * buf,MethodId val)67 static inline void SetMethodId(uint8_t* buf, MethodId val) { return Set8BE(buf, val); }
SetObjectId(uint8_t * buf,ObjectId val)68 static inline void SetObjectId(uint8_t* buf, ObjectId val) { return Set8BE(buf, val); }
SetRefTypeId(uint8_t * buf,RefTypeId val)69 static inline void SetRefTypeId(uint8_t* buf, RefTypeId val) { return Set8BE(buf, val); }
SetFrameId(uint8_t * buf,FrameId val)70 static inline void SetFrameId(uint8_t* buf, FrameId val) { return Set8BE(buf, val); }
expandBufAddFieldId(ExpandBuf * pReply,FieldId id)71 static inline void expandBufAddFieldId(ExpandBuf* pReply, FieldId id) { expandBufAdd8BE(pReply, id); }
expandBufAddMethodId(ExpandBuf * pReply,MethodId id)72 static inline void expandBufAddMethodId(ExpandBuf* pReply, MethodId id) { expandBufAdd8BE(pReply, id); }
expandBufAddObjectId(ExpandBuf * pReply,ObjectId id)73 static inline void expandBufAddObjectId(ExpandBuf* pReply, ObjectId id) { expandBufAdd8BE(pReply, id); }
expandBufAddRefTypeId(ExpandBuf * pReply,RefTypeId id)74 static inline void expandBufAddRefTypeId(ExpandBuf* pReply, RefTypeId id) { expandBufAdd8BE(pReply, id); }
expandBufAddFrameId(ExpandBuf * pReply,FrameId id)75 static inline void expandBufAddFrameId(ExpandBuf* pReply, FrameId id) { expandBufAdd8BE(pReply, id); }
76 
77 struct EventLocation {
78   ArtMethod* method;
79   uint32_t dex_pc;
80 };
81 
82 /*
83  * Holds a JDWP "location".
84  */
85 struct JdwpLocation {
86   JdwpTypeTag type_tag;
87   RefTypeId class_id;
88   MethodId method_id;
89   uint64_t dex_pc;
90 };
91 std::ostream& operator<<(std::ostream& os, const JdwpLocation& rhs)
92     REQUIRES_SHARED(Locks::mutator_lock_);
93 bool operator==(const JdwpLocation& lhs, const JdwpLocation& rhs);
94 bool operator!=(const JdwpLocation& lhs, const JdwpLocation& rhs);
95 
96 /*
97  * How we talk to the debugger.
98  */
99 enum JdwpTransportType {
100   kJdwpTransportUnknown = 0,
101   kJdwpTransportSocket,       // transport=dt_socket
102   kJdwpTransportAndroidAdb,   // transport=dt_android_adb
103 };
104 std::ostream& operator<<(std::ostream& os, const JdwpTransportType& rhs);
105 
106 struct JdwpOptions {
107   JdwpTransportType transport = kJdwpTransportUnknown;
108   bool server = false;
109   bool suspend = false;
110   std::string host = "";
111   uint16_t port = static_cast<uint16_t>(-1);
112 };
113 
114 bool operator==(const JdwpOptions& lhs, const JdwpOptions& rhs);
115 
116 struct JdwpEvent;
117 class JdwpNetStateBase;
118 struct ModBasket;
119 class Request;
120 
121 /*
122  * State for JDWP functions.
123  */
124 struct JdwpState {
125   /*
126    * Perform one-time initialization.
127    *
128    * Among other things, this binds to a port to listen for a connection from
129    * the debugger.
130    *
131    * Returns a newly-allocated JdwpState struct on success, or nullptr on failure.
132    *
133    * NO_THREAD_SAFETY_ANALYSIS since we can't annotate that we do not have
134    * state->thread_start_lock_ held.
135    */
136   static JdwpState* Create(const JdwpOptions* options)
137       REQUIRES(!Locks::mutator_lock_) NO_THREAD_SAFETY_ANALYSIS;
138 
139   ~JdwpState();
140 
141   /*
142    * Returns "true" if a debugger or DDM is connected.
143    */
144   bool IsActive();
145 
146   /**
147    * Returns the Thread* for the JDWP daemon thread.
148    */
149   Thread* GetDebugThread();
150 
151   /*
152    * Get time, in milliseconds, since the last debugger activity.
153    */
154   int64_t LastDebuggerActivity();
155 
156   void ExitAfterReplying(int exit_status);
157 
158   // Acquires/releases the JDWP synchronization token for the debugger
159   // thread (command handler) so no event thread posts an event while
160   // it processes a command. This must be called only from the debugger
161   // thread.
162   void AcquireJdwpTokenForCommand() REQUIRES(!jdwp_token_lock_);
163   void ReleaseJdwpTokenForCommand() REQUIRES(!jdwp_token_lock_);
164 
165   // Acquires/releases the JDWP synchronization token for the event thread
166   // so no other thread (debugger thread or event thread) interleaves with
167   // it when posting an event. This must NOT be called from the debugger
168   // thread, only event thread.
169   void AcquireJdwpTokenForEvent(ObjectId threadId) REQUIRES(!jdwp_token_lock_);
170   void ReleaseJdwpTokenForEvent() REQUIRES(!jdwp_token_lock_);
171 
172   /*
173    * These notify the debug code that something interesting has happened.  This
174    * could be a thread starting or ending, an exception, or an opportunity
175    * for a breakpoint.  These calls do not mean that an event the debugger
176    * is interested has happened, just that something has happened that the
177    * debugger *might* be interested in.
178    *
179    * The item of interest may trigger multiple events, some or all of which
180    * are grouped together in a single response.
181    *
182    * The event may cause the current thread or all threads (except the
183    * JDWP support thread) to be suspended.
184    */
185 
186   /*
187    * The VM has finished initializing.  Only called when the debugger is
188    * connected at the time initialization completes.
189    */
190   void PostVMStart() REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!jdwp_token_lock_);
191 
192   /*
193    * A location of interest has been reached.  This is used for breakpoints,
194    * single-stepping, and method entry/exit.  (JDWP requires that these four
195    * events are grouped together in a single response.)
196    *
197    * In some cases "*pLoc" will just have a method and class name, e.g. when
198    * issuing a MethodEntry on a native method.
199    *
200    * "eventFlags" indicates the types of events that have occurred.
201    *
202    * "returnValue" is non-null for MethodExit events only.
203    */
204   void PostLocationEvent(const EventLocation* pLoc, mirror::Object* thisPtr, int eventFlags,
205                          const JValue* returnValue)
206      REQUIRES(!event_list_lock_, !jdwp_token_lock_) REQUIRES_SHARED(Locks::mutator_lock_);
207 
208   /*
209    * A field of interest has been accessed or modified. This is used for field access and field
210    * modification events.
211    *
212    * "fieldValue" is non-null for field modification events only.
213    * "is_modification" is true for field modification, false for field access.
214    */
215   void PostFieldEvent(const EventLocation* pLoc, ArtField* field, mirror::Object* thisPtr,
216                       const JValue* fieldValue, bool is_modification)
217       REQUIRES(!event_list_lock_, !jdwp_token_lock_) REQUIRES_SHARED(Locks::mutator_lock_);
218 
219   /*
220    * An exception has been thrown.
221    *
222    * Pass in a zeroed-out "*pCatchLoc" if the exception wasn't caught.
223    */
224   void PostException(const EventLocation* pThrowLoc, mirror::Throwable* exception_object,
225                      const EventLocation* pCatchLoc, mirror::Object* thisPtr)
226       REQUIRES(!event_list_lock_, !jdwp_token_lock_) REQUIRES_SHARED(Locks::mutator_lock_);
227 
228   /*
229    * A thread has started or stopped.
230    */
231   void PostThreadChange(Thread* thread, bool start)
232       REQUIRES(!event_list_lock_, !jdwp_token_lock_) REQUIRES_SHARED(Locks::mutator_lock_);
233 
234   /*
235    * Class has been prepared.
236    */
237   void PostClassPrepare(mirror::Class* klass)
238       REQUIRES(!event_list_lock_, !jdwp_token_lock_) REQUIRES_SHARED(Locks::mutator_lock_);
239 
240   /*
241    * The VM is about to stop.
242    */
243   bool PostVMDeath();
244 
245   // Called if/when we realize we're talking to DDMS.
246   void NotifyDdmsActive() REQUIRES_SHARED(Locks::mutator_lock_);
247 
248 
249   void SetupChunkHeader(uint32_t type, size_t data_len, size_t header_size, uint8_t* out_header);
250 
251   /*
252    * Send up a chunk of DDM data.
253    */
254   void DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count)
255       REQUIRES_SHARED(Locks::mutator_lock_);
256 
257   bool HandlePacket() REQUIRES(!shutdown_lock_, !jdwp_token_lock_);
258 
259   void SendRequest(ExpandBuf* pReq);
260 
261   void ResetState()
262       REQUIRES(!event_list_lock_)
263       REQUIRES_SHARED(Locks::mutator_lock_);
264 
265   /* atomic ops to get next serial number */
266   uint32_t NextRequestSerial();
267   uint32_t NextEventSerial();
268 
269   void Run()
270       REQUIRES(!Locks::mutator_lock_, !Locks::thread_suspend_count_lock_, !thread_start_lock_,
271                !attach_lock_, !event_list_lock_);
272 
273   /*
274    * Register an event by adding it to the event list.
275    *
276    * "*pEvent" must be storage allocated with jdwpEventAlloc().  The caller
277    * may discard its pointer after calling this.
278    */
279   JdwpError RegisterEvent(JdwpEvent* pEvent)
280       REQUIRES(!event_list_lock_)
281       REQUIRES_SHARED(Locks::mutator_lock_);
282 
283   /*
284    * Unregister an event, given the requestId.
285    */
286   void UnregisterEventById(uint32_t requestId)
287       REQUIRES(!event_list_lock_)
288       REQUIRES_SHARED(Locks::mutator_lock_);
289 
290   void UnregisterLocationEventsOnClass(ObjPtr<mirror::Class> klass)
291       REQUIRES(!event_list_lock_)
292       REQUIRES_SHARED(Locks::mutator_lock_);
293 
294   /*
295    * Unregister all events.
296    */
297   void UnregisterAll()
298       REQUIRES(!event_list_lock_)
299       REQUIRES_SHARED(Locks::mutator_lock_);
300 
301  private:
302   explicit JdwpState(const JdwpOptions* options);
303   size_t ProcessRequest(Request* request, ExpandBuf* pReply, bool* skip_reply)
304       REQUIRES(!jdwp_token_lock_);
305   bool InvokeInProgress();
306   bool IsConnected();
307   void SuspendByPolicy(JdwpSuspendPolicy suspend_policy, JDWP::ObjectId thread_self_id)
308       REQUIRES(!Locks::mutator_lock_);
309   void SendRequestAndPossiblySuspend(ExpandBuf* pReq, JdwpSuspendPolicy suspend_policy,
310                                      ObjectId threadId)
311       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!jdwp_token_lock_);
312   void CleanupMatchList(const std::vector<JdwpEvent*>& match_list)
313       REQUIRES(event_list_lock_) REQUIRES_SHARED(Locks::mutator_lock_);
314   void EventFinish(ExpandBuf* pReq);
315   bool FindMatchingEvents(JdwpEventKind eventKind, const ModBasket& basket,
316                           std::vector<JdwpEvent*>* match_list)
317       REQUIRES(!event_list_lock_) REQUIRES_SHARED(Locks::mutator_lock_);
318   void FindMatchingEventsLocked(JdwpEventKind eventKind, const ModBasket& basket,
319                                 std::vector<JdwpEvent*>* match_list)
320       REQUIRES(event_list_lock_) REQUIRES_SHARED(Locks::mutator_lock_);
321   void UnregisterEvent(JdwpEvent* pEvent)
322       REQUIRES(event_list_lock_) REQUIRES_SHARED(Locks::mutator_lock_);
323   void SendBufferedRequest(uint32_t type, const std::vector<iovec>& iov);
324 
325   /*
326    * When we hit a debugger event that requires suspension, it's important
327    * that we wait for the thread to suspend itself before processing any
328    * additional requests. Otherwise, if the debugger immediately sends a
329    * "resume thread" command, the resume might arrive before the thread has
330    * suspended itself.
331    *
332    * It's also important no event thread suspends while we process a command
333    * from the debugger. Otherwise we could post an event ("thread death")
334    * before sending the reply of the command being processed ("resume") and
335    * cause bad synchronization with the debugger.
336    *
337    * The thread wanting "exclusive" access to the JDWP world must call the
338    * SetWaitForJdwpToken method before processing a command from the
339    * debugger or sending an event to the debugger.
340    * Once the command is processed or the event thread has posted its event,
341    * it must call the ClearWaitForJdwpToken method to allow another thread
342    * to do JDWP stuff.
343    *
344    * Therefore the main JDWP handler loop will wait for the event thread
345    * suspension before processing the next command. Once the event thread
346    * has suspended itself and cleared the token, the JDWP handler continues
347    * processing commands. This works in the suspend-all case because the
348    * event thread doesn't suspend itself until everything else has suspended.
349    *
350    * It's possible that multiple threads could encounter thread-suspending
351    * events at the same time, so we grab a mutex in the SetWaitForJdwpToken
352    * call, and release it in the ClearWaitForJdwpToken call.
353    */
354   void SetWaitForJdwpToken(ObjectId threadId) REQUIRES(!jdwp_token_lock_);
355   void ClearWaitForJdwpToken() REQUIRES(!jdwp_token_lock_);
356 
357  public:  // TODO: fix privacy
358   const JdwpOptions* options_;
359 
360  private:
361   /* wait for creation of the JDWP thread */
362   Mutex thread_start_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
363   ConditionVariable thread_start_cond_ GUARDED_BY(thread_start_lock_);
364 
365   pthread_t pthread_;
366   Thread* thread_;
367 
368   volatile int32_t debug_thread_started_ GUARDED_BY(thread_start_lock_);
369   ObjectId debug_thread_id_;
370 
371  private:
372   bool run;
373 
374  public:  // TODO: fix privacy
375   JdwpNetStateBase* netState;
376 
377  private:
378   // For wait-for-debugger.
379   Mutex attach_lock_ ACQUIRED_AFTER(thread_start_lock_);
380   ConditionVariable attach_cond_ GUARDED_BY(attach_lock_);
381 
382   // Time of last debugger activity, in milliseconds.
383   Atomic<int64_t> last_activity_time_ms_;
384 
385   // Global counters and a mutex to protect them.
386   AtomicInteger request_serial_;
387   AtomicInteger event_serial_;
388 
389   // Linked list of events requested by the debugger (breakpoints, class prep, etc).
390   Mutex event_list_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER ACQUIRED_BEFORE(Locks::breakpoint_lock_);
391   JdwpEvent* event_list_ GUARDED_BY(event_list_lock_);
392   size_t event_list_size_ GUARDED_BY(event_list_lock_);  // Number of elements in event_list_.
393 
394   // Used to synchronize JDWP command handler thread and event threads so only one
395   // thread does JDWP stuff at a time. This prevent from interleaving command handling
396   // and event notification. Otherwise we could receive a "resume" command for an
397   // event thread that is not suspended yet, or post a "thread death" or event "VM death"
398   // event before sending the reply of the "resume" command that caused it.
399   Mutex jdwp_token_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
400   ConditionVariable jdwp_token_cond_ GUARDED_BY(jdwp_token_lock_);
401   ObjectId jdwp_token_owner_thread_id_;
402 
403   bool ddm_is_active_;
404 
405   // Used for VirtualMachine.Exit command handling.
406   bool should_exit_;
407   int exit_status_;
408 
409   // Used to synchronize runtime shutdown with JDWP command handler thread.
410   // When the runtime shuts down, it needs to stop JDWP command handler thread by closing the
411   // JDWP connection. However, if the JDWP thread is processing a command, it needs to wait
412   // for the command to finish so we can send its reply before closing the connection.
413   Mutex shutdown_lock_ ACQUIRED_AFTER(event_list_lock_);
414   ConditionVariable shutdown_cond_ GUARDED_BY(shutdown_lock_);
415   bool processing_request_ GUARDED_BY(shutdown_lock_);
416 };
417 
418 std::string DescribeField(const FieldId& field_id) REQUIRES_SHARED(Locks::mutator_lock_);
419 std::string DescribeMethod(const MethodId& method_id) REQUIRES_SHARED(Locks::mutator_lock_);
420 std::string DescribeRefTypeId(const RefTypeId& ref_type_id) REQUIRES_SHARED(Locks::mutator_lock_);
421 
422 class Request {
423  public:
424   Request(const uint8_t* bytes, uint32_t available);
425   ~Request();
426 
427   std::string ReadUtf8String();
428 
429   // Helper function: read a variable-width value from the input buffer.
430   uint64_t ReadValue(size_t width);
431 
432   int32_t ReadSigned32(const char* what);
433 
434   uint32_t ReadUnsigned32(const char* what);
435 
436   FieldId ReadFieldId() REQUIRES_SHARED(Locks::mutator_lock_);
437 
438   MethodId ReadMethodId() REQUIRES_SHARED(Locks::mutator_lock_);
439 
440   ObjectId ReadObjectId(const char* specific_kind);
441 
442   ObjectId ReadArrayId();
443 
444   ObjectId ReadObjectId();
445 
446   ObjectId ReadThreadId();
447 
448   ObjectId ReadThreadGroupId();
449 
450   RefTypeId ReadRefTypeId() REQUIRES_SHARED(Locks::mutator_lock_);
451 
452   FrameId ReadFrameId();
453 
ReadEnum1(const char * specific_kind)454   template <typename T> T ReadEnum1(const char* specific_kind) {
455     T value = static_cast<T>(Read1());
456     VLOG(jdwp) << "    " << specific_kind << " " << value;
457     return value;
458   }
459 
460   JdwpTag ReadTag();
461 
462   JdwpTypeTag ReadTypeTag();
463 
464   JdwpLocation ReadLocation() REQUIRES_SHARED(Locks::mutator_lock_);
465 
466   JdwpModKind ReadModKind();
467 
468   //
469   // Return values from this JDWP packet's header.
470   //
GetLength()471   size_t GetLength() { return byte_count_; }
GetId()472   uint32_t GetId() { return id_; }
GetCommandSet()473   uint8_t GetCommandSet() { return command_set_; }
GetCommand()474   uint8_t GetCommand() { return command_; }
475 
476   // Returns the number of bytes remaining.
size()477   size_t size() { return end_ - p_; }
478 
479   // Returns a pointer to the next byte.
data()480   const uint8_t* data() { return p_; }
481 
Skip(size_t count)482   void Skip(size_t count) { p_ += count; }
483 
484   void CheckConsumed();
485 
486  private:
487   uint8_t Read1();
488   uint16_t Read2BE();
489   uint32_t Read4BE();
490   uint64_t Read8BE();
491 
492   uint32_t byte_count_;
493   uint32_t id_;
494   uint8_t command_set_;
495   uint8_t command_;
496 
497   const uint8_t* p_;
498   const uint8_t* end_;
499 
500   DISALLOW_COPY_AND_ASSIGN(Request);
501 };
502 
503 }  // namespace JDWP
504 
505 }  // namespace art
506 
507 #endif  // ART_RUNTIME_JDWP_JDWP_H_
508