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