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