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