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 * Send events to the debugger. 18 */ 19 #include "jdwp/JdwpPriv.h" 20 #include "jdwp/JdwpConstants.h" 21 #include "jdwp/JdwpHandler.h" 22 #include "jdwp/JdwpEvent.h" 23 #include "jdwp/ExpandBuf.h" 24 25 #include <stdlib.h> 26 #include <string.h> 27 #include <stddef.h> /* for offsetof() */ 28 #include <unistd.h> 29 30 /* 31 General notes: 32 33 The event add/remove stuff usually happens from the debugger thread, 34 in response to requests from the debugger, but can also happen as the 35 result of an event in an arbitrary thread (e.g. an event with a "count" 36 mod expires). It's important to keep the event list locked when processing 37 events. 38 39 Event posting can happen from any thread. The JDWP thread will not usually 40 post anything but VM start/death, but if a JDWP request causes a class 41 to be loaded, the ClassPrepare event will come from the JDWP thread. 42 43 44 We can have serialization issues when we post an event to the debugger. 45 For example, a thread could send an "I hit a breakpoint and am suspending 46 myself" message to the debugger. Before it manages to suspend itself, the 47 debugger's response ("not interested, resume thread") arrives and is 48 processed. We try to resume a thread that hasn't yet suspended. 49 50 This means that, after posting an event to the debugger, we need to wait 51 for the event thread to suspend itself (and, potentially, all other threads) 52 before processing any additional requests from the debugger. While doing 53 so we need to be aware that multiple threads may be hitting breakpoints 54 or other events simultaneously, so we either need to wait for all of them 55 or serialize the events with each other. 56 57 The current mechanism works like this: 58 Event thread: 59 - If I'm going to suspend, grab the "I am posting an event" token. Wait 60 for it if it's not currently available. 61 - Post the event to the debugger. 62 - If appropriate, suspend others and then myself. As part of suspending 63 myself, release the "I am posting" token. 64 JDWP thread: 65 - When an event arrives, see if somebody is posting an event. If so, 66 sleep until we can acquire the "I am posting an event" token. Release 67 it immediately and continue processing -- the event we have already 68 received should not interfere with other events that haven't yet 69 been posted. 70 71 Some care must be taken to avoid deadlock: 72 73 - thread A and thread B exit near-simultaneously, and post thread-death 74 events with a "suspend all" clause 75 - thread A gets the event token, thread B sits and waits for it 76 - thread A wants to suspend all other threads, but thread B is waiting 77 for the token and can't be suspended 78 79 So we need to mark thread B in such a way that thread A doesn't wait for it. 80 81 If we just bracket the "grab event token" call with a change to VMWAIT 82 before sleeping, the switch back to RUNNING state when we get the token 83 will cause thread B to suspend (remember, thread A's global suspend is 84 still in force, even after it releases the token). Suspending while 85 holding the event token is very bad, because it prevents the JDWP thread 86 from processing incoming messages. 87 88 We need to change to VMWAIT state at the *start* of posting an event, 89 and stay there until we either finish posting the event or decide to 90 put ourselves to sleep. That way we don't interfere with anyone else and 91 don't allow anyone else to interfere with us. 92 */ 93 94 95 #define kJdwpEventCommandSet 64 96 #define kJdwpCompositeCommand 100 97 98 /* 99 * Stuff to compare against when deciding if a mod matches. Only the 100 * values for mods valid for the event being evaluated will be filled in. 101 * The rest will be zeroed. 102 */ 103 struct ModBasket { 104 const JdwpLocation* pLoc; /* LocationOnly */ 105 const char* className; /* ClassMatch/ClassExclude */ 106 ObjectId threadId; /* ThreadOnly */ 107 RefTypeId classId; /* ClassOnly */ 108 RefTypeId excepClassId; /* ExceptionOnly */ 109 bool caught; /* ExceptionOnly */ 110 FieldId field; /* FieldOnly */ 111 ObjectId thisPtr; /* InstanceOnly */ 112 /* nothing for StepOnly -- handled differently */ 113 }; 114 115 /* 116 * Get the next "request" serial number. We use this when sending 117 * packets to the debugger. 118 */ 119 u4 dvmJdwpNextRequestSerial(JdwpState* state) 120 { 121 dvmDbgLockMutex(&state->serialLock); 122 u4 result = state->requestSerial++; 123 dvmDbgUnlockMutex(&state->serialLock); 124 125 return result; 126 } 127 128 /* 129 * Get the next "event" serial number. We use this in the response to 130 * message type EventRequest.Set. 131 */ 132 u4 dvmJdwpNextEventSerial(JdwpState* state) 133 { 134 dvmDbgLockMutex(&state->serialLock); 135 u4 result = state->eventSerial++; 136 dvmDbgUnlockMutex(&state->serialLock); 137 138 return result; 139 } 140 141 /* 142 * Lock the "event" mutex, which guards the list of registered events. 143 */ 144 static void lockEventMutex(JdwpState* state) 145 { 146 //dvmDbgThreadWaiting(); 147 dvmDbgLockMutex(&state->eventLock); 148 //dvmDbgThreadRunning(); 149 } 150 151 /* 152 * Unlock the "event" mutex. 153 */ 154 static void unlockEventMutex(JdwpState* state) 155 { 156 dvmDbgUnlockMutex(&state->eventLock); 157 } 158 159 /* 160 * Dump an event to the log file. 161 */ 162 static void dumpEvent(const JdwpEvent* pEvent) 163 { 164 LOGI("Event id=0x%4x %p (prev=%p next=%p):", 165 pEvent->requestId, pEvent, pEvent->prev, pEvent->next); 166 LOGI(" kind=%s susp=%s modCount=%d", 167 dvmJdwpEventKindStr(pEvent->eventKind), 168 dvmJdwpSuspendPolicyStr(pEvent->suspendPolicy), 169 pEvent->modCount); 170 171 for (int i = 0; i < pEvent->modCount; i++) { 172 const JdwpEventMod* pMod = &pEvent->mods[i]; 173 JdwpModKind kind = static_cast<JdwpModKind>(pMod->modKind); 174 LOGI(" %s", dvmJdwpModKindStr(kind)); 175 /* TODO - show details */ 176 } 177 } 178 179 /* 180 * Add an event to the list. Ordering is not important. 181 * 182 * If something prevents the event from being registered, e.g. it's a 183 * single-step request on a thread that doesn't exist, the event will 184 * not be added to the list, and an appropriate error will be returned. 185 */ 186 JdwpError dvmJdwpRegisterEvent(JdwpState* state, JdwpEvent* pEvent) 187 { 188 lockEventMutex(state); 189 190 assert(state != NULL); 191 assert(pEvent != NULL); 192 assert(pEvent->prev == NULL); 193 assert(pEvent->next == NULL); 194 195 /* 196 * If one or more "break"-type mods are used, register them with 197 * the interpreter. 198 */ 199 for (int i = 0; i < pEvent->modCount; i++) { 200 const JdwpEventMod* pMod = &pEvent->mods[i]; 201 if (pMod->modKind == MK_LOCATION_ONLY) { 202 /* should only be for Breakpoint, Step, and Exception */ 203 dvmDbgWatchLocation(&pMod->locationOnly.loc); 204 } else if (pMod->modKind == MK_STEP) { 205 /* should only be for EK_SINGLE_STEP; should only be one */ 206 JdwpStepSize size = static_cast<JdwpStepSize>(pMod->step.size); 207 JdwpStepDepth depth = static_cast<JdwpStepDepth>(pMod->step.depth); 208 dvmDbgConfigureStep(pMod->step.threadId, size, depth); 209 } else if (pMod->modKind == MK_FIELD_ONLY) { 210 /* should be for EK_FIELD_ACCESS or EK_FIELD_MODIFICATION */ 211 dumpEvent(pEvent); /* TODO - need for field watches */ 212 } 213 } 214 215 /* 216 * Add to list. 217 */ 218 if (state->eventList != NULL) { 219 pEvent->next = state->eventList; 220 state->eventList->prev = pEvent; 221 } 222 state->eventList = pEvent; 223 state->numEvents++; 224 225 unlockEventMutex(state); 226 227 return ERR_NONE; 228 } 229 230 /* 231 * Remove an event from the list. This will also remove the event from 232 * any optimization tables, e.g. breakpoints. 233 * 234 * Does not free the JdwpEvent. 235 * 236 * Grab the eventLock before calling here. 237 */ 238 static void unregisterEvent(JdwpState* state, JdwpEvent* pEvent) 239 { 240 if (pEvent->prev == NULL) { 241 /* head of the list */ 242 assert(state->eventList == pEvent); 243 244 state->eventList = pEvent->next; 245 } else { 246 pEvent->prev->next = pEvent->next; 247 } 248 249 if (pEvent->next != NULL) { 250 pEvent->next->prev = pEvent->prev; 251 pEvent->next = NULL; 252 } 253 pEvent->prev = NULL; 254 255 /* 256 * Unhook us from the interpreter, if necessary. 257 */ 258 for (int i = 0; i < pEvent->modCount; i++) { 259 JdwpEventMod* pMod = &pEvent->mods[i]; 260 if (pMod->modKind == MK_LOCATION_ONLY) { 261 /* should only be for Breakpoint, Step, and Exception */ 262 dvmDbgUnwatchLocation(&pMod->locationOnly.loc); 263 } 264 if (pMod->modKind == MK_STEP) { 265 /* should only be for EK_SINGLE_STEP; should only be one */ 266 dvmDbgUnconfigureStep(pMod->step.threadId); 267 } 268 } 269 270 state->numEvents--; 271 assert(state->numEvents != 0 || state->eventList == NULL); 272 } 273 274 /* 275 * Remove the event with the given ID from the list. 276 * 277 * Failure to find the event isn't really an error, but it is a little 278 * weird. (It looks like Eclipse will try to be extra careful and will 279 * explicitly remove one-off single-step events.) 280 */ 281 void dvmJdwpUnregisterEventById(JdwpState* state, u4 requestId) 282 { 283 lockEventMutex(state); 284 285 JdwpEvent* pEvent = state->eventList; 286 while (pEvent != NULL) { 287 if (pEvent->requestId == requestId) { 288 unregisterEvent(state, pEvent); 289 dvmJdwpEventFree(pEvent); 290 goto done; /* there can be only one with a given ID */ 291 } 292 293 pEvent = pEvent->next; 294 } 295 296 //LOGD("Odd: no match when removing event reqId=0x%04x", requestId); 297 298 done: 299 unlockEventMutex(state); 300 } 301 302 /* 303 * Remove all entries from the event list. 304 */ 305 void dvmJdwpUnregisterAll(JdwpState* state) 306 { 307 lockEventMutex(state); 308 309 JdwpEvent* pEvent = state->eventList; 310 while (pEvent != NULL) { 311 JdwpEvent* pNextEvent = pEvent->next; 312 313 unregisterEvent(state, pEvent); 314 dvmJdwpEventFree(pEvent); 315 pEvent = pNextEvent; 316 } 317 318 state->eventList = NULL; 319 320 unlockEventMutex(state); 321 } 322 323 324 325 /* 326 * Allocate a JdwpEvent struct with enough space to hold the specified 327 * number of mod records. 328 */ 329 JdwpEvent* dvmJdwpEventAlloc(int numMods) 330 { 331 JdwpEvent* newEvent; 332 int allocSize = offsetof(JdwpEvent, mods) + 333 numMods * sizeof(newEvent->mods[0]); 334 335 newEvent = (JdwpEvent*)malloc(allocSize); 336 memset(newEvent, 0, allocSize); 337 return newEvent; 338 } 339 340 /* 341 * Free a JdwpEvent. 342 * 343 * Do not call this until the event has been removed from the list. 344 */ 345 void dvmJdwpEventFree(JdwpEvent* pEvent) 346 { 347 if (pEvent == NULL) 348 return; 349 350 /* make sure it was removed from the list */ 351 assert(pEvent->prev == NULL); 352 assert(pEvent->next == NULL); 353 /* want to assert state->eventList != pEvent */ 354 355 /* 356 * Free any hairy bits in the mods. 357 */ 358 for (int i = 0; i < pEvent->modCount; i++) { 359 if (pEvent->mods[i].modKind == MK_CLASS_MATCH) { 360 free(pEvent->mods[i].classMatch.classPattern); 361 pEvent->mods[i].classMatch.classPattern = NULL; 362 } 363 if (pEvent->mods[i].modKind == MK_CLASS_EXCLUDE) { 364 free(pEvent->mods[i].classExclude.classPattern); 365 pEvent->mods[i].classExclude.classPattern = NULL; 366 } 367 } 368 369 free(pEvent); 370 } 371 372 /* 373 * Allocate storage for matching events. To keep things simple we 374 * use an array with enough storage for the entire list. 375 * 376 * The state->eventLock should be held before calling. 377 */ 378 static JdwpEvent** allocMatchList(JdwpState* state) 379 { 380 return (JdwpEvent**) malloc(sizeof(JdwpEvent*) * state->numEvents); 381 } 382 383 /* 384 * Run through the list and remove any entries with an expired "count" mod 385 * from the event list, then free the match list. 386 */ 387 static void cleanupMatchList(JdwpState* state, JdwpEvent** matchList, 388 int matchCount) 389 { 390 JdwpEvent** ppEvent = matchList; 391 392 while (matchCount--) { 393 JdwpEvent* pEvent = *ppEvent; 394 395 for (int i = 0; i < pEvent->modCount; i++) { 396 if (pEvent->mods[i].modKind == MK_COUNT && 397 pEvent->mods[i].count.count == 0) 398 { 399 LOGV("##### Removing expired event"); 400 unregisterEvent(state, pEvent); 401 dvmJdwpEventFree(pEvent); 402 break; 403 } 404 } 405 406 ppEvent++; 407 } 408 409 free(matchList); 410 } 411 412 /* 413 * Match a string against a "restricted regular expression", which is just 414 * a string that may start or end with '*' (e.g. "*.Foo" or "java.*"). 415 * 416 * ("Restricted name globbing" might have been a better term.) 417 */ 418 static bool patternMatch(const char* pattern, const char* target) 419 { 420 int patLen = strlen(pattern); 421 422 if (pattern[0] == '*') { 423 int targetLen = strlen(target); 424 patLen--; 425 // TODO: remove printf when we find a test case to verify this 426 LOGE(">>> comparing '%s' to '%s'", 427 pattern+1, target + (targetLen-patLen)); 428 429 if (targetLen < patLen) 430 return false; 431 return strcmp(pattern+1, target + (targetLen-patLen)) == 0; 432 } else if (pattern[patLen-1] == '*') { 433 return strncmp(pattern, target, patLen-1) == 0; 434 } else { 435 return strcmp(pattern, target) == 0; 436 } 437 } 438 439 /* 440 * See if two locations are equal. 441 * 442 * It's tempting to do a bitwise compare ("struct ==" or memcmp), but if 443 * the storage wasn't zeroed out there could be undefined values in the 444 * padding. Besides, the odds of "idx" being equal while the others aren't 445 * is very small, so this is usually just a simple integer comparison. 446 */ 447 static inline bool locationMatch(const JdwpLocation* pLoc1, 448 const JdwpLocation* pLoc2) 449 { 450 return pLoc1->idx == pLoc2->idx && 451 pLoc1->methodId == pLoc2->methodId && 452 pLoc1->classId == pLoc2->classId && 453 pLoc1->typeTag == pLoc2->typeTag; 454 } 455 456 /* 457 * See if the event's mods match up with the contents of "basket". 458 * 459 * If we find a Count mod before rejecting an event, we decrement it. We 460 * need to do this even if later mods cause us to ignore the event. 461 */ 462 static bool modsMatch(JdwpState* state, JdwpEvent* pEvent, ModBasket* basket) 463 { 464 JdwpEventMod* pMod = pEvent->mods; 465 466 for (int i = pEvent->modCount; i > 0; i--, pMod++) { 467 switch (pMod->modKind) { 468 case MK_COUNT: 469 assert(pMod->count.count > 0); 470 pMod->count.count--; 471 break; 472 case MK_CONDITIONAL: 473 assert(false); // should not be getting these 474 break; 475 case MK_THREAD_ONLY: 476 if (pMod->threadOnly.threadId != basket->threadId) 477 return false; 478 break; 479 case MK_CLASS_ONLY: 480 if (!dvmDbgMatchType(basket->classId, pMod->classOnly.refTypeId)) 481 return false; 482 break; 483 case MK_CLASS_MATCH: 484 if (!patternMatch(pMod->classMatch.classPattern, 485 basket->className)) 486 return false; 487 break; 488 case MK_CLASS_EXCLUDE: 489 if (patternMatch(pMod->classMatch.classPattern, 490 basket->className)) 491 return false; 492 break; 493 case MK_LOCATION_ONLY: 494 if (!locationMatch(&pMod->locationOnly.loc, basket->pLoc)) 495 return false; 496 break; 497 case MK_EXCEPTION_ONLY: 498 if (pMod->exceptionOnly.refTypeId != 0 && 499 !dvmDbgMatchType(basket->excepClassId, 500 pMod->exceptionOnly.refTypeId)) 501 return false; 502 if ((basket->caught && !pMod->exceptionOnly.caught) || 503 (!basket->caught && !pMod->exceptionOnly.uncaught)) 504 return false; 505 break; 506 case MK_FIELD_ONLY: 507 if (!dvmDbgMatchType(basket->classId, pMod->fieldOnly.refTypeId) || 508 pMod->fieldOnly.fieldId != basket->field) 509 return false; 510 break; 511 case MK_STEP: 512 if (pMod->step.threadId != basket->threadId) 513 return false; 514 break; 515 case MK_INSTANCE_ONLY: 516 if (pMod->instanceOnly.objectId != basket->thisPtr) 517 return false; 518 break; 519 default: 520 LOGE("unhandled mod kind %d", pMod->modKind); 521 assert(false); 522 break; 523 } 524 } 525 526 return true; 527 } 528 529 /* 530 * Find all events of type "eventKind" with mods that match up with the 531 * rest of the arguments. 532 * 533 * Found events are appended to "matchList", and "*pMatchCount" is advanced, 534 * so this may be called multiple times for grouped events. 535 * 536 * DO NOT call this multiple times for the same eventKind, as Count mods are 537 * decremented during the scan. 538 */ 539 static void findMatchingEvents(JdwpState* state, JdwpEventKind eventKind, 540 ModBasket* basket, JdwpEvent** matchList, int* pMatchCount) 541 { 542 /* start after the existing entries */ 543 matchList += *pMatchCount; 544 545 JdwpEvent* pEvent = state->eventList; 546 while (pEvent != NULL) { 547 if (pEvent->eventKind == eventKind && modsMatch(state, pEvent, basket)) 548 { 549 *matchList++ = pEvent; 550 (*pMatchCount)++; 551 } 552 553 pEvent = pEvent->next; 554 } 555 } 556 557 /* 558 * Scan through the list of matches and determine the most severe 559 * suspension policy. 560 */ 561 static JdwpSuspendPolicy scanSuspendPolicy(JdwpEvent** matchList, 562 int matchCount) 563 { 564 JdwpSuspendPolicy policy = SP_NONE; 565 566 while (matchCount--) { 567 if ((*matchList)->suspendPolicy > policy) 568 policy = (*matchList)->suspendPolicy; 569 matchList++; 570 } 571 572 return policy; 573 } 574 575 /* 576 * Three possibilities: 577 * SP_NONE - do nothing 578 * SP_EVENT_THREAD - suspend ourselves 579 * SP_ALL - suspend everybody except JDWP support thread 580 */ 581 static void suspendByPolicy(JdwpState* state, JdwpSuspendPolicy suspendPolicy) 582 { 583 if (suspendPolicy == SP_NONE) 584 return; 585 586 if (suspendPolicy == SP_ALL) { 587 dvmDbgSuspendVM(true); 588 } else { 589 assert(suspendPolicy == SP_EVENT_THREAD); 590 } 591 592 /* this is rare but possible -- see CLASS_PREPARE handling */ 593 if (dvmDbgGetThreadSelfId() == state->debugThreadId) { 594 LOGI("NOTE: suspendByPolicy not suspending JDWP thread"); 595 return; 596 } 597 598 DebugInvokeReq* pReq = dvmDbgGetInvokeReq(); 599 while (true) { 600 pReq->ready = true; 601 dvmDbgSuspendSelf(); 602 pReq->ready = false; 603 604 /* 605 * The JDWP thread has told us (and possibly all other threads) to 606 * resume. See if it has left anything in our DebugInvokeReq mailbox. 607 */ 608 if (!pReq->invokeNeeded) { 609 /*LOGD("suspendByPolicy: no invoke needed");*/ 610 break; 611 } 612 613 /* grab this before posting/suspending again */ 614 dvmJdwpSetWaitForEventThread(state, dvmDbgGetThreadSelfId()); 615 616 /* leave pReq->invokeNeeded raised so we can check reentrancy */ 617 LOGV("invoking method..."); 618 dvmDbgExecuteMethod(pReq); 619 620 pReq->err = ERR_NONE; 621 622 /* clear this before signaling */ 623 pReq->invokeNeeded = false; 624 625 LOGV("invoke complete, signaling and self-suspending"); 626 dvmDbgLockMutex(&pReq->lock); 627 dvmDbgCondSignal(&pReq->cv); 628 dvmDbgUnlockMutex(&pReq->lock); 629 } 630 } 631 632 /* 633 * Determine if there is a method invocation in progress in the current 634 * thread. 635 * 636 * We look at the "invokeNeeded" flag in the per-thread DebugInvokeReq 637 * state. If set, we're in the process of invoking a method. 638 */ 639 static bool invokeInProgress(JdwpState* state) 640 { 641 DebugInvokeReq* pReq = dvmDbgGetInvokeReq(); 642 return pReq->invokeNeeded; 643 } 644 645 /* 646 * We need the JDWP thread to hold off on doing stuff while we post an 647 * event and then suspend ourselves. 648 * 649 * Call this with a threadId of zero if you just want to wait for the 650 * current thread operation to complete. 651 * 652 * This could go to sleep waiting for another thread, so it's important 653 * that the thread be marked as VMWAIT before calling here. 654 */ 655 void dvmJdwpSetWaitForEventThread(JdwpState* state, ObjectId threadId) 656 { 657 bool waited = false; 658 659 /* this is held for very brief periods; contention is unlikely */ 660 dvmDbgLockMutex(&state->eventThreadLock); 661 662 /* 663 * If another thread is already doing stuff, wait for it. This can 664 * go to sleep indefinitely. 665 */ 666 while (state->eventThreadId != 0) { 667 LOGV("event in progress (0x%llx), 0x%llx sleeping", 668 state->eventThreadId, threadId); 669 waited = true; 670 dvmDbgCondWait(&state->eventThreadCond, &state->eventThreadLock); 671 } 672 673 if (waited || threadId != 0) 674 LOGV("event token grabbed (0x%llx)", threadId); 675 if (threadId != 0) 676 state->eventThreadId = threadId; 677 678 dvmDbgUnlockMutex(&state->eventThreadLock); 679 } 680 681 /* 682 * Clear the threadId and signal anybody waiting. 683 */ 684 void dvmJdwpClearWaitForEventThread(JdwpState* state) 685 { 686 /* 687 * Grab the mutex. Don't try to go in/out of VMWAIT mode, as this 688 * function is called by dvmSuspendSelf(), and the transition back 689 * to RUNNING would confuse it. 690 */ 691 dvmDbgLockMutex(&state->eventThreadLock); 692 693 assert(state->eventThreadId != 0); 694 LOGV("cleared event token (0x%llx)", state->eventThreadId); 695 696 state->eventThreadId = 0; 697 698 dvmDbgCondSignal(&state->eventThreadCond); 699 700 dvmDbgUnlockMutex(&state->eventThreadLock); 701 } 702 703 704 /* 705 * Prep an event. Allocates storage for the message and leaves space for 706 * the header. 707 */ 708 static ExpandBuf* eventPrep() 709 { 710 ExpandBuf* pReq = expandBufAlloc(); 711 expandBufAddSpace(pReq, kJDWPHeaderLen); 712 713 return pReq; 714 } 715 716 /* 717 * Write the header into the buffer and send the packet off to the debugger. 718 * 719 * Takes ownership of "pReq" (currently discards it). 720 */ 721 static void eventFinish(JdwpState* state, ExpandBuf* pReq) 722 { 723 u1* buf = expandBufGetBuffer(pReq); 724 725 set4BE(buf, expandBufGetLength(pReq)); 726 set4BE(buf+4, dvmJdwpNextRequestSerial(state)); 727 set1(buf+8, 0); /* flags */ 728 set1(buf+9, kJdwpEventCommandSet); 729 set1(buf+10, kJdwpCompositeCommand); 730 731 dvmJdwpSendRequest(state, pReq); 732 733 expandBufFree(pReq); 734 } 735 736 737 /* 738 * Tell the debugger that we have finished initializing. This is always 739 * sent, even if the debugger hasn't requested it. 740 * 741 * This should be sent "before the main thread is started and before 742 * any application code has been executed". The thread ID in the message 743 * must be for the main thread. 744 */ 745 bool dvmJdwpPostVMStart(JdwpState* state, bool suspend) 746 { 747 JdwpSuspendPolicy suspendPolicy; 748 ObjectId threadId = dvmDbgGetThreadSelfId(); 749 750 if (suspend) 751 suspendPolicy = SP_ALL; 752 else 753 suspendPolicy = SP_NONE; 754 755 /* probably don't need this here */ 756 lockEventMutex(state); 757 758 ExpandBuf* pReq = NULL; 759 if (true) { 760 LOGV("EVENT: %s", dvmJdwpEventKindStr(EK_VM_START)); 761 LOGV(" suspendPolicy=%s", dvmJdwpSuspendPolicyStr(suspendPolicy)); 762 763 pReq = eventPrep(); 764 expandBufAdd1(pReq, suspendPolicy); 765 expandBufAdd4BE(pReq, 1); 766 767 expandBufAdd1(pReq, EK_VM_START); 768 expandBufAdd4BE(pReq, 0); /* requestId */ 769 expandBufAdd8BE(pReq, threadId); 770 } 771 772 unlockEventMutex(state); 773 774 /* send request and possibly suspend ourselves */ 775 if (pReq != NULL) { 776 int oldStatus = dvmDbgThreadWaiting(); 777 if (suspendPolicy != SP_NONE) 778 dvmJdwpSetWaitForEventThread(state, threadId); 779 780 eventFinish(state, pReq); 781 782 suspendByPolicy(state, suspendPolicy); 783 dvmDbgThreadContinuing(oldStatus); 784 } 785 786 return true; 787 } 788 789 /* 790 * A location of interest has been reached. This handles: 791 * Breakpoint 792 * SingleStep 793 * MethodEntry 794 * MethodExit 795 * These four types must be grouped together in a single response. The 796 * "eventFlags" indicates the type of event(s) that have happened. 797 * 798 * Valid mods: 799 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, InstanceOnly 800 * LocationOnly (for breakpoint/step only) 801 * Step (for step only) 802 * 803 * Interesting test cases: 804 * - Put a breakpoint on a native method. Eclipse creates METHOD_ENTRY 805 * and METHOD_EXIT events with a ClassOnly mod on the method's class. 806 * - Use "run to line". Eclipse creates a BREAKPOINT with Count=1. 807 * - Single-step to a line with a breakpoint. Should get a single 808 * event message with both events in it. 809 */ 810 bool dvmJdwpPostLocationEvent(JdwpState* state, const JdwpLocation* pLoc, 811 ObjectId thisPtr, int eventFlags) 812 { 813 JdwpSuspendPolicy suspendPolicy = SP_NONE; 814 ModBasket basket; 815 char* nameAlloc = NULL; 816 817 memset(&basket, 0, sizeof(basket)); 818 basket.pLoc = pLoc; 819 basket.classId = pLoc->classId; 820 basket.thisPtr = thisPtr; 821 basket.threadId = dvmDbgGetThreadSelfId(); 822 basket.className = nameAlloc = 823 dvmDescriptorToName(dvmDbgGetClassDescriptor(pLoc->classId)); 824 825 /* 826 * On rare occasions we may need to execute interpreted code in the VM 827 * while handling a request from the debugger. Don't fire breakpoints 828 * while doing so. (I don't think we currently do this at all, so 829 * this is mostly paranoia.) 830 */ 831 if (basket.threadId == state->debugThreadId) { 832 LOGV("Ignoring location event in JDWP thread"); 833 free(nameAlloc); 834 return false; 835 } 836 837 /* 838 * The debugger variable display tab may invoke the interpreter to format 839 * complex objects. We want to ignore breakpoints and method entry/exit 840 * traps while working on behalf of the debugger. 841 * 842 * If we don't ignore them, the VM will get hung up, because we'll 843 * suspend on a breakpoint while the debugger is still waiting for its 844 * method invocation to complete. 845 */ 846 if (invokeInProgress(state)) { 847 LOGV("Not checking breakpoints during invoke (%s)", basket.className); 848 free(nameAlloc); 849 return false; 850 } 851 852 /* don't allow the list to be updated while we scan it */ 853 lockEventMutex(state); 854 855 JdwpEvent** matchList = allocMatchList(state); 856 int matchCount = 0; 857 858 if ((eventFlags & DBG_BREAKPOINT) != 0) 859 findMatchingEvents(state, EK_BREAKPOINT, &basket, matchList, 860 &matchCount); 861 if ((eventFlags & DBG_SINGLE_STEP) != 0) 862 findMatchingEvents(state, EK_SINGLE_STEP, &basket, matchList, 863 &matchCount); 864 if ((eventFlags & DBG_METHOD_ENTRY) != 0) 865 findMatchingEvents(state, EK_METHOD_ENTRY, &basket, matchList, 866 &matchCount); 867 if ((eventFlags & DBG_METHOD_EXIT) != 0) 868 findMatchingEvents(state, EK_METHOD_EXIT, &basket, matchList, 869 &matchCount); 870 871 ExpandBuf* pReq = NULL; 872 if (matchCount != 0) { 873 LOGV("EVENT: %s(%d total) %s.%s thread=%llx code=%llx)", 874 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount, 875 basket.className, 876 dvmDbgGetMethodName(pLoc->classId, pLoc->methodId), 877 basket.threadId, pLoc->idx); 878 879 suspendPolicy = scanSuspendPolicy(matchList, matchCount); 880 LOGV(" suspendPolicy=%s", 881 dvmJdwpSuspendPolicyStr(suspendPolicy)); 882 883 pReq = eventPrep(); 884 expandBufAdd1(pReq, suspendPolicy); 885 expandBufAdd4BE(pReq, matchCount); 886 887 for (int i = 0; i < matchCount; i++) { 888 expandBufAdd1(pReq, matchList[i]->eventKind); 889 expandBufAdd4BE(pReq, matchList[i]->requestId); 890 expandBufAdd8BE(pReq, basket.threadId); 891 dvmJdwpAddLocation(pReq, pLoc); 892 } 893 } 894 895 cleanupMatchList(state, matchList, matchCount); 896 unlockEventMutex(state); 897 898 /* send request and possibly suspend ourselves */ 899 if (pReq != NULL) { 900 int oldStatus = dvmDbgThreadWaiting(); 901 if (suspendPolicy != SP_NONE) 902 dvmJdwpSetWaitForEventThread(state, basket.threadId); 903 904 eventFinish(state, pReq); 905 906 suspendByPolicy(state, suspendPolicy); 907 dvmDbgThreadContinuing(oldStatus); 908 } 909 910 free(nameAlloc); 911 return matchCount != 0; 912 } 913 914 /* 915 * A thread is starting or stopping. 916 * 917 * Valid mods: 918 * Count, ThreadOnly 919 */ 920 bool dvmJdwpPostThreadChange(JdwpState* state, ObjectId threadId, bool start) 921 { 922 JdwpSuspendPolicy suspendPolicy = SP_NONE; 923 924 assert(threadId = dvmDbgGetThreadSelfId()); 925 926 /* 927 * I don't think this can happen. 928 */ 929 if (invokeInProgress(state)) { 930 LOGW("Not posting thread change during invoke"); 931 return false; 932 } 933 934 ModBasket basket; 935 memset(&basket, 0, sizeof(basket)); 936 basket.threadId = threadId; 937 938 /* don't allow the list to be updated while we scan it */ 939 lockEventMutex(state); 940 941 JdwpEvent** matchList = allocMatchList(state); 942 int matchCount = 0; 943 944 if (start) 945 findMatchingEvents(state, EK_THREAD_START, &basket, matchList, 946 &matchCount); 947 else 948 findMatchingEvents(state, EK_THREAD_DEATH, &basket, matchList, 949 &matchCount); 950 951 ExpandBuf* pReq = NULL; 952 if (matchCount != 0) { 953 LOGV("EVENT: %s(%d total) thread=%llx)", 954 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount, 955 basket.threadId); 956 957 suspendPolicy = scanSuspendPolicy(matchList, matchCount); 958 LOGV(" suspendPolicy=%s", 959 dvmJdwpSuspendPolicyStr(suspendPolicy)); 960 961 pReq = eventPrep(); 962 expandBufAdd1(pReq, suspendPolicy); 963 expandBufAdd4BE(pReq, matchCount); 964 965 for (int i = 0; i < matchCount; i++) { 966 expandBufAdd1(pReq, matchList[i]->eventKind); 967 expandBufAdd4BE(pReq, matchList[i]->requestId); 968 expandBufAdd8BE(pReq, basket.threadId); 969 } 970 971 } 972 973 cleanupMatchList(state, matchList, matchCount); 974 unlockEventMutex(state); 975 976 /* send request and possibly suspend ourselves */ 977 if (pReq != NULL) { 978 int oldStatus = dvmDbgThreadWaiting(); 979 if (suspendPolicy != SP_NONE) 980 dvmJdwpSetWaitForEventThread(state, basket.threadId); 981 982 eventFinish(state, pReq); 983 984 suspendByPolicy(state, suspendPolicy); 985 dvmDbgThreadContinuing(oldStatus); 986 } 987 988 return matchCount != 0; 989 } 990 991 /* 992 * Send a polite "VM is dying" message to the debugger. 993 * 994 * Skips the usual "event token" stuff. 995 */ 996 bool dvmJdwpPostVMDeath(JdwpState* state) 997 { 998 LOGV("EVENT: %s", dvmJdwpEventKindStr(EK_VM_DEATH)); 999 1000 ExpandBuf* pReq = eventPrep(); 1001 expandBufAdd1(pReq, SP_NONE); 1002 expandBufAdd4BE(pReq, 1); 1003 1004 expandBufAdd1(pReq, EK_VM_DEATH); 1005 expandBufAdd4BE(pReq, 0); 1006 eventFinish(state, pReq); 1007 return true; 1008 } 1009 1010 1011 /* 1012 * An exception has been thrown. It may or may not have been caught. 1013 * 1014 * Valid mods: 1015 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, LocationOnly, 1016 * ExceptionOnly, InstanceOnly 1017 * 1018 * The "exceptionId" has not been added to the GC-visible object registry, 1019 * because there's a pretty good chance that we're not going to send it 1020 * up the debugger. 1021 */ 1022 bool dvmJdwpPostException(JdwpState* state, const JdwpLocation* pThrowLoc, 1023 ObjectId exceptionId, RefTypeId exceptionClassId, 1024 const JdwpLocation* pCatchLoc, ObjectId thisPtr) 1025 { 1026 JdwpSuspendPolicy suspendPolicy = SP_NONE; 1027 ModBasket basket; 1028 char* nameAlloc = NULL; 1029 1030 memset(&basket, 0, sizeof(basket)); 1031 basket.pLoc = pThrowLoc; 1032 basket.classId = pThrowLoc->classId; 1033 basket.threadId = dvmDbgGetThreadSelfId(); 1034 basket.className = nameAlloc = 1035 dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId)); 1036 basket.excepClassId = exceptionClassId; 1037 basket.caught = (pCatchLoc->classId != 0); 1038 basket.thisPtr = thisPtr; 1039 1040 /* don't try to post an exception caused by the debugger */ 1041 if (invokeInProgress(state)) { 1042 LOGV("Not posting exception hit during invoke (%s)",basket.className); 1043 free(nameAlloc); 1044 return false; 1045 } 1046 1047 /* don't allow the list to be updated while we scan it */ 1048 lockEventMutex(state); 1049 1050 JdwpEvent** matchList = allocMatchList(state); 1051 int matchCount = 0; 1052 1053 findMatchingEvents(state, EK_EXCEPTION, &basket, matchList, &matchCount); 1054 1055 ExpandBuf* pReq = NULL; 1056 if (matchCount != 0) { 1057 LOGV("EVENT: %s(%d total) thread=%llx exceptId=%llx caught=%d)", 1058 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount, 1059 basket.threadId, exceptionId, basket.caught); 1060 LOGV(" throw: %d %llx %x %lld (%s.%s)", pThrowLoc->typeTag, 1061 pThrowLoc->classId, pThrowLoc->methodId, pThrowLoc->idx, 1062 dvmDbgGetClassDescriptor(pThrowLoc->classId), 1063 dvmDbgGetMethodName(pThrowLoc->classId, pThrowLoc->methodId)); 1064 if (pCatchLoc->classId == 0) { 1065 LOGV(" catch: (not caught)"); 1066 } else { 1067 LOGV(" catch: %d %llx %x %lld (%s.%s)", pCatchLoc->typeTag, 1068 pCatchLoc->classId, pCatchLoc->methodId, pCatchLoc->idx, 1069 dvmDbgGetClassDescriptor(pCatchLoc->classId), 1070 dvmDbgGetMethodName(pCatchLoc->classId, pCatchLoc->methodId)); 1071 } 1072 1073 suspendPolicy = scanSuspendPolicy(matchList, matchCount); 1074 LOGV(" suspendPolicy=%s", 1075 dvmJdwpSuspendPolicyStr(suspendPolicy)); 1076 1077 pReq = eventPrep(); 1078 expandBufAdd1(pReq, suspendPolicy); 1079 expandBufAdd4BE(pReq, matchCount); 1080 1081 for (int i = 0; i < matchCount; i++) { 1082 expandBufAdd1(pReq, matchList[i]->eventKind); 1083 expandBufAdd4BE(pReq, matchList[i]->requestId); 1084 expandBufAdd8BE(pReq, basket.threadId); 1085 1086 dvmJdwpAddLocation(pReq, pThrowLoc); 1087 expandBufAdd1(pReq, JT_OBJECT); 1088 expandBufAdd8BE(pReq, exceptionId); 1089 dvmJdwpAddLocation(pReq, pCatchLoc); 1090 } 1091 1092 /* don't let the GC discard it */ 1093 dvmDbgRegisterObjectId(exceptionId); 1094 } 1095 1096 cleanupMatchList(state, matchList, matchCount); 1097 unlockEventMutex(state); 1098 1099 /* send request and possibly suspend ourselves */ 1100 if (pReq != NULL) { 1101 int oldStatus = dvmDbgThreadWaiting(); 1102 if (suspendPolicy != SP_NONE) 1103 dvmJdwpSetWaitForEventThread(state, basket.threadId); 1104 1105 eventFinish(state, pReq); 1106 1107 suspendByPolicy(state, suspendPolicy); 1108 dvmDbgThreadContinuing(oldStatus); 1109 } 1110 1111 free(nameAlloc); 1112 return matchCount != 0; 1113 } 1114 1115 /* 1116 * Announce that a class has been loaded. 1117 * 1118 * Valid mods: 1119 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude 1120 */ 1121 bool dvmJdwpPostClassPrepare(JdwpState* state, int tag, RefTypeId refTypeId, 1122 const char* signature, int status) 1123 { 1124 JdwpSuspendPolicy suspendPolicy = SP_NONE; 1125 ModBasket basket; 1126 char* nameAlloc = NULL; 1127 1128 memset(&basket, 0, sizeof(basket)); 1129 basket.classId = refTypeId; 1130 basket.threadId = dvmDbgGetThreadSelfId(); 1131 basket.className = nameAlloc = 1132 dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId)); 1133 1134 /* suppress class prep caused by debugger */ 1135 if (invokeInProgress(state)) { 1136 LOGV("Not posting class prep caused by invoke (%s)",basket.className); 1137 free(nameAlloc); 1138 return false; 1139 } 1140 1141 /* don't allow the list to be updated while we scan it */ 1142 lockEventMutex(state); 1143 1144 JdwpEvent** matchList = allocMatchList(state); 1145 int matchCount = 0; 1146 1147 findMatchingEvents(state, EK_CLASS_PREPARE, &basket, matchList, 1148 &matchCount); 1149 1150 ExpandBuf* pReq = NULL; 1151 if (matchCount != 0) { 1152 LOGV("EVENT: %s(%d total) thread=%llx)", 1153 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount, 1154 basket.threadId); 1155 1156 suspendPolicy = scanSuspendPolicy(matchList, matchCount); 1157 LOGV(" suspendPolicy=%s", 1158 dvmJdwpSuspendPolicyStr(suspendPolicy)); 1159 1160 if (basket.threadId == state->debugThreadId) { 1161 /* 1162 * JDWP says that, for a class prep in the debugger thread, we 1163 * should set threadId to null and if any threads were supposed 1164 * to be suspended then we suspend all other threads. 1165 */ 1166 LOGV(" NOTE: class prepare in debugger thread!"); 1167 basket.threadId = 0; 1168 if (suspendPolicy == SP_EVENT_THREAD) 1169 suspendPolicy = SP_ALL; 1170 } 1171 1172 pReq = eventPrep(); 1173 expandBufAdd1(pReq, suspendPolicy); 1174 expandBufAdd4BE(pReq, matchCount); 1175 1176 for (int i = 0; i < matchCount; i++) { 1177 expandBufAdd1(pReq, matchList[i]->eventKind); 1178 expandBufAdd4BE(pReq, matchList[i]->requestId); 1179 expandBufAdd8BE(pReq, basket.threadId); 1180 1181 expandBufAdd1(pReq, tag); 1182 expandBufAdd8BE(pReq, refTypeId); 1183 expandBufAddUtf8String(pReq, (const u1*) signature); 1184 expandBufAdd4BE(pReq, status); 1185 } 1186 } 1187 1188 cleanupMatchList(state, matchList, matchCount); 1189 1190 unlockEventMutex(state); 1191 1192 /* send request and possibly suspend ourselves */ 1193 if (pReq != NULL) { 1194 int oldStatus = dvmDbgThreadWaiting(); 1195 if (suspendPolicy != SP_NONE) 1196 dvmJdwpSetWaitForEventThread(state, basket.threadId); 1197 1198 eventFinish(state, pReq); 1199 1200 suspendByPolicy(state, suspendPolicy); 1201 dvmDbgThreadContinuing(oldStatus); 1202 } 1203 1204 free(nameAlloc); 1205 return matchCount != 0; 1206 } 1207 1208 /* 1209 * Unload a class. 1210 * 1211 * Valid mods: 1212 * Count, ClassMatch, ClassExclude 1213 */ 1214 bool dvmJdwpPostClassUnload(JdwpState* state, RefTypeId refTypeId) 1215 { 1216 assert(false); // TODO 1217 return false; 1218 } 1219 1220 /* 1221 * Get or set a field. 1222 * 1223 * Valid mods: 1224 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, FieldOnly, 1225 * InstanceOnly 1226 */ 1227 bool dvmJdwpPostFieldAccess(JdwpState* state, int STUFF, ObjectId thisPtr, 1228 bool modified, JValue newValue) 1229 { 1230 assert(false); // TODO 1231 return false; 1232 } 1233 1234 /* 1235 * Send up a chunk of DDM data. 1236 * 1237 * While this takes the form of a JDWP "event", it doesn't interact with 1238 * other debugger traffic, and can't suspend the VM, so we skip all of 1239 * the fun event token gymnastics. 1240 */ 1241 void dvmJdwpDdmSendChunkV(JdwpState* state, int type, const struct iovec* iov, 1242 int iovcnt) 1243 { 1244 u1 header[kJDWPHeaderLen + 8]; 1245 size_t dataLen = 0; 1246 1247 assert(iov != NULL); 1248 assert(iovcnt > 0 && iovcnt < 10); 1249 1250 /* 1251 * "Wrap" the contents of the iovec with a JDWP/DDMS header. We do 1252 * this by creating a new copy of the vector with space for the header. 1253 */ 1254 struct iovec wrapiov[iovcnt+1]; 1255 for (int i = 0; i < iovcnt; i++) { 1256 wrapiov[i+1].iov_base = iov[i].iov_base; 1257 wrapiov[i+1].iov_len = iov[i].iov_len; 1258 dataLen += iov[i].iov_len; 1259 } 1260 1261 /* form the header (JDWP plus DDMS) */ 1262 set4BE(header, sizeof(header) + dataLen); 1263 set4BE(header+4, dvmJdwpNextRequestSerial(state)); 1264 set1(header+8, 0); /* flags */ 1265 set1(header+9, kJDWPDdmCmdSet); 1266 set1(header+10, kJDWPDdmCmd); 1267 set4BE(header+11, type); 1268 set4BE(header+15, dataLen); 1269 1270 wrapiov[0].iov_base = header; 1271 wrapiov[0].iov_len = sizeof(header); 1272 1273 /* 1274 * Make sure we're in VMWAIT in case the write blocks. 1275 */ 1276 int oldStatus = dvmDbgThreadWaiting(); 1277 dvmJdwpSendBufferedRequest(state, wrapiov, iovcnt+1); 1278 dvmDbgThreadContinuing(oldStatus); 1279 } 1280