JdwpEvent.cpp revision 1e1433e78f560a01744e870c19c162ab88df9dc1
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/* 31General notes: 32 33The event add/remove stuff usually happens from the debugger thread, 34in response to requests from the debugger, but can also happen as the 35result of an event in an arbitrary thread (e.g. an event with a "count" 36mod expires). It's important to keep the event list locked when processing 37events. 38 39Event posting can happen from any thread. The JDWP thread will not usually 40post anything but VM start/death, but if a JDWP request causes a class 41to be loaded, the ClassPrepare event will come from the JDWP thread. 42 43 44We can have serialization issues when we post an event to the debugger. 45For example, a thread could send an "I hit a breakpoint and am suspending 46myself" message to the debugger. Before it manages to suspend itself, the 47debugger's response ("not interested, resume thread") arrives and is 48processed. We try to resume a thread that hasn't yet suspended. 49 50This means that, after posting an event to the debugger, we need to wait 51for the event thread to suspend itself (and, potentially, all other threads) 52before processing any additional requests from the debugger. While doing 53so we need to be aware that multiple threads may be hitting breakpoints 54or other events simultaneously, so we either need to wait for all of them 55or serialize the events with each other. 56 57The 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 71Some 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 79So we need to mark thread B in such a way that thread A doesn't wait for it. 80 81If we just bracket the "grab event token" call with a change to VMWAIT 82before sleeping, the switch back to RUNNING state when we get the token 83will cause thread B to suspend (remember, thread A's global suspend is 84still in force, even after it releases the token). Suspending while 85holding the event token is very bad, because it prevents the JDWP thread 86from processing incoming messages. 87 88We need to change to VMWAIT state at the *start* of posting an event, 89and stay there until we either finish posting the event or decide to 90put ourselves to sleep. That way we don't interfere with anyone else and 91don'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 */ 103typedef 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} ModBasket; 114 115/* 116 * Get the next "request" serial number. We use this when sending 117 * packets to the debugger. 118 */ 119u4 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 */ 132u4 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 */ 144static void lockEventMutex(JdwpState* state) 145{ 146 //dvmDbgThreadWaiting(); 147 dvmDbgLockMutex(&state->eventLock); 148 //dvmDbgThreadRunning(); 149} 150 151/* 152 * Unlock the "event" mutex. 153 */ 154static void unlockEventMutex(JdwpState* state) 155{ 156 dvmDbgUnlockMutex(&state->eventLock); 157} 158 159/* 160 * Dump an event to the log file. 161 */ 162static void dumpEvent(const JdwpEvent* pEvent) 163{ 164 LOGI("Event id=0x%4x %p (prev=%p next=%p):\n", 165 pEvent->requestId, pEvent, pEvent->prev, pEvent->next); 166 LOGI(" kind=%s susp=%s modCount=%d\n", 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\n", 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 */ 186JdwpError 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 */ 238static 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 */ 281void 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\n", requestId); 297 298done: 299 unlockEventMutex(state); 300} 301 302/* 303 * Remove all entries from the event list. 304 */ 305void 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 */ 329JdwpEvent* 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 */ 345void 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 */ 378static 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 */ 387static 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\n"); 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 */ 418static 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'\n", 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 */ 447static 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 */ 462static 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\n", 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 */ 539static void findMatchingEvents(JdwpState* state, enum 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 */ 561static enum JdwpSuspendPolicy scanSuspendPolicy(JdwpEvent** matchList, 562 int matchCount) 563{ 564 enum 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 */ 581static void suspendByPolicy(JdwpState* state, 582 enum JdwpSuspendPolicy suspendPolicy) 583{ 584 if (suspendPolicy == SP_NONE) 585 return; 586 587 if (suspendPolicy == SP_ALL) { 588 dvmDbgSuspendVM(true); 589 } else { 590 assert(suspendPolicy == SP_EVENT_THREAD); 591 } 592 593 /* this is rare but possible -- see CLASS_PREPARE handling */ 594 if (dvmDbgGetThreadSelfId() == state->debugThreadId) { 595 LOGI("NOTE: suspendByPolicy not suspending JDWP thread\n"); 596 return; 597 } 598 599 DebugInvokeReq* pReq = dvmDbgGetInvokeReq(); 600 while (true) { 601 pReq->ready = true; 602 dvmDbgSuspendSelf(); 603 pReq->ready = false; 604 605 /* 606 * The JDWP thread has told us (and possibly all other threads) to 607 * resume. See if it has left anything in our DebugInvokeReq mailbox. 608 */ 609 if (!pReq->invokeNeeded) { 610 /*LOGD("suspendByPolicy: no invoke needed\n");*/ 611 break; 612 } 613 614 /* grab this before posting/suspending again */ 615 dvmJdwpSetWaitForEventThread(state, dvmDbgGetThreadSelfId()); 616 617 /* leave pReq->invokeNeeded raised so we can check reentrancy */ 618 LOGV("invoking method...\n"); 619 dvmDbgExecuteMethod(pReq); 620 621 pReq->err = ERR_NONE; 622 623 /* clear this before signaling */ 624 pReq->invokeNeeded = false; 625 626 LOGV("invoke complete, signaling and self-suspending\n"); 627 dvmDbgLockMutex(&pReq->lock); 628 dvmDbgCondSignal(&pReq->cv); 629 dvmDbgUnlockMutex(&pReq->lock); 630 } 631} 632 633/* 634 * Determine if there is a method invocation in progress in the current 635 * thread. 636 * 637 * We look at the "invokeNeeded" flag in the per-thread DebugInvokeReq 638 * state. If set, we're in the process of invoking a method. 639 */ 640static bool invokeInProgress(JdwpState* state) 641{ 642 DebugInvokeReq* pReq = dvmDbgGetInvokeReq(); 643 return pReq->invokeNeeded; 644} 645 646/* 647 * We need the JDWP thread to hold off on doing stuff while we post an 648 * event and then suspend ourselves. 649 * 650 * Call this with a threadId of zero if you just want to wait for the 651 * current thread operation to complete. 652 * 653 * This could go to sleep waiting for another thread, so it's important 654 * that the thread be marked as VMWAIT before calling here. 655 */ 656void dvmJdwpSetWaitForEventThread(JdwpState* state, ObjectId threadId) 657{ 658 bool waited = false; 659 660 /* this is held for very brief periods; contention is unlikely */ 661 dvmDbgLockMutex(&state->eventThreadLock); 662 663 /* 664 * If another thread is already doing stuff, wait for it. This can 665 * go to sleep indefinitely. 666 */ 667 while (state->eventThreadId != 0) { 668 LOGV("event in progress (0x%llx), 0x%llx sleeping\n", 669 state->eventThreadId, threadId); 670 waited = true; 671 dvmDbgCondWait(&state->eventThreadCond, &state->eventThreadLock); 672 } 673 674 if (waited || threadId != 0) 675 LOGV("event token grabbed (0x%llx)\n", threadId); 676 if (threadId != 0) 677 state->eventThreadId = threadId; 678 679 dvmDbgUnlockMutex(&state->eventThreadLock); 680} 681 682/* 683 * Clear the threadId and signal anybody waiting. 684 */ 685void dvmJdwpClearWaitForEventThread(JdwpState* state) 686{ 687 /* 688 * Grab the mutex. Don't try to go in/out of VMWAIT mode, as this 689 * function is called by dvmSuspendSelf(), and the transition back 690 * to RUNNING would confuse it. 691 */ 692 dvmDbgLockMutex(&state->eventThreadLock); 693 694 assert(state->eventThreadId != 0); 695 LOGV("cleared event token (0x%llx)\n", state->eventThreadId); 696 697 state->eventThreadId = 0; 698 699 dvmDbgCondSignal(&state->eventThreadCond); 700 701 dvmDbgUnlockMutex(&state->eventThreadLock); 702} 703 704 705/* 706 * Prep an event. Allocates storage for the message and leaves space for 707 * the header. 708 */ 709static ExpandBuf* eventPrep() 710{ 711 ExpandBuf* pReq = expandBufAlloc(); 712 expandBufAddSpace(pReq, kJDWPHeaderLen); 713 714 return pReq; 715} 716 717/* 718 * Write the header into the buffer and send the packet off to the debugger. 719 * 720 * Takes ownership of "pReq" (currently discards it). 721 */ 722static void eventFinish(JdwpState* state, ExpandBuf* pReq) 723{ 724 u1* buf = expandBufGetBuffer(pReq); 725 726 set4BE(buf, expandBufGetLength(pReq)); 727 set4BE(buf+4, dvmJdwpNextRequestSerial(state)); 728 set1(buf+8, 0); /* flags */ 729 set1(buf+9, kJdwpEventCommandSet); 730 set1(buf+10, kJdwpCompositeCommand); 731 732 dvmJdwpSendRequest(state, pReq); 733 734 expandBufFree(pReq); 735} 736 737 738/* 739 * Tell the debugger that we have finished initializing. This is always 740 * sent, even if the debugger hasn't requested it. 741 * 742 * This should be sent "before the main thread is started and before 743 * any application code has been executed". The thread ID in the message 744 * must be for the main thread. 745 */ 746bool dvmJdwpPostVMStart(JdwpState* state, bool suspend) 747{ 748 enum JdwpSuspendPolicy suspendPolicy; 749 ObjectId threadId = dvmDbgGetThreadSelfId(); 750 751 if (suspend) 752 suspendPolicy = SP_ALL; 753 else 754 suspendPolicy = SP_NONE; 755 756 /* probably don't need this here */ 757 lockEventMutex(state); 758 759 ExpandBuf* pReq = NULL; 760 if (true) { 761 LOGV("EVENT: %s\n", dvmJdwpEventKindStr(EK_VM_START)); 762 LOGV(" suspendPolicy=%s\n", dvmJdwpSuspendPolicyStr(suspendPolicy)); 763 764 pReq = eventPrep(); 765 expandBufAdd1(pReq, suspendPolicy); 766 expandBufAdd4BE(pReq, 1); 767 768 expandBufAdd1(pReq, EK_VM_START); 769 expandBufAdd4BE(pReq, 0); /* requestId */ 770 expandBufAdd8BE(pReq, threadId); 771 } 772 773 unlockEventMutex(state); 774 775 /* send request and possibly suspend ourselves */ 776 if (pReq != NULL) { 777 int oldStatus = dvmDbgThreadWaiting(); 778 if (suspendPolicy != SP_NONE) 779 dvmJdwpSetWaitForEventThread(state, threadId); 780 781 eventFinish(state, pReq); 782 783 suspendByPolicy(state, suspendPolicy); 784 dvmDbgThreadContinuing(oldStatus); 785 } 786 787 return true; 788} 789 790/* 791 * A location of interest has been reached. This handles: 792 * Breakpoint 793 * SingleStep 794 * MethodEntry 795 * MethodExit 796 * These four types must be grouped together in a single response. The 797 * "eventFlags" indicates the type of event(s) that have happened. 798 * 799 * Valid mods: 800 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, InstanceOnly 801 * LocationOnly (for breakpoint/step only) 802 * Step (for step only) 803 * 804 * Interesting test cases: 805 * - Put a breakpoint on a native method. Eclipse creates METHOD_ENTRY 806 * and METHOD_EXIT events with a ClassOnly mod on the method's class. 807 * - Use "run to line". Eclipse creates a BREAKPOINT with Count=1. 808 * - Single-step to a line with a breakpoint. Should get a single 809 * event message with both events in it. 810 */ 811bool dvmJdwpPostLocationEvent(JdwpState* state, const JdwpLocation* pLoc, 812 ObjectId thisPtr, int eventFlags) 813{ 814 enum JdwpSuspendPolicy suspendPolicy = SP_NONE; 815 ModBasket basket; 816 char* nameAlloc = NULL; 817 818 memset(&basket, 0, sizeof(basket)); 819 basket.pLoc = pLoc; 820 basket.classId = pLoc->classId; 821 basket.thisPtr = thisPtr; 822 basket.threadId = dvmDbgGetThreadSelfId(); 823 basket.className = nameAlloc = 824 dvmDescriptorToName(dvmDbgGetClassDescriptor(pLoc->classId)); 825 826 /* 827 * On rare occasions we may need to execute interpreted code in the VM 828 * while handling a request from the debugger. Don't fire breakpoints 829 * while doing so. (I don't think we currently do this at all, so 830 * this is mostly paranoia.) 831 */ 832 if (basket.threadId == state->debugThreadId) { 833 LOGV("Ignoring location event in JDWP thread\n"); 834 free(nameAlloc); 835 return false; 836 } 837 838 /* 839 * The debugger variable display tab may invoke the interpreter to format 840 * complex objects. We want to ignore breakpoints and method entry/exit 841 * traps while working on behalf of the debugger. 842 * 843 * If we don't ignore them, the VM will get hung up, because we'll 844 * suspend on a breakpoint while the debugger is still waiting for its 845 * method invocation to complete. 846 */ 847 if (invokeInProgress(state)) { 848 LOGV("Not checking breakpoints during invoke (%s)\n", basket.className); 849 free(nameAlloc); 850 return false; 851 } 852 853 /* don't allow the list to be updated while we scan it */ 854 lockEventMutex(state); 855 856 JdwpEvent** matchList = allocMatchList(state); 857 int matchCount = 0; 858 859 if ((eventFlags & DBG_BREAKPOINT) != 0) 860 findMatchingEvents(state, EK_BREAKPOINT, &basket, matchList, 861 &matchCount); 862 if ((eventFlags & DBG_SINGLE_STEP) != 0) 863 findMatchingEvents(state, EK_SINGLE_STEP, &basket, matchList, 864 &matchCount); 865 if ((eventFlags & DBG_METHOD_ENTRY) != 0) 866 findMatchingEvents(state, EK_METHOD_ENTRY, &basket, matchList, 867 &matchCount); 868 if ((eventFlags & DBG_METHOD_EXIT) != 0) 869 findMatchingEvents(state, EK_METHOD_EXIT, &basket, matchList, 870 &matchCount); 871 872 ExpandBuf* pReq = NULL; 873 if (matchCount != 0) { 874 LOGV("EVENT: %s(%d total) %s.%s thread=%llx code=%llx)\n", 875 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount, 876 basket.className, 877 dvmDbgGetMethodName(pLoc->classId, pLoc->methodId), 878 basket.threadId, pLoc->idx); 879 880 suspendPolicy = scanSuspendPolicy(matchList, matchCount); 881 LOGV(" suspendPolicy=%s\n", 882 dvmJdwpSuspendPolicyStr(suspendPolicy)); 883 884 pReq = eventPrep(); 885 expandBufAdd1(pReq, suspendPolicy); 886 expandBufAdd4BE(pReq, matchCount); 887 888 for (int i = 0; i < matchCount; i++) { 889 expandBufAdd1(pReq, matchList[i]->eventKind); 890 expandBufAdd4BE(pReq, matchList[i]->requestId); 891 expandBufAdd8BE(pReq, basket.threadId); 892 dvmJdwpAddLocation(pReq, pLoc); 893 } 894 } 895 896 cleanupMatchList(state, matchList, matchCount); 897 unlockEventMutex(state); 898 899 /* send request and possibly suspend ourselves */ 900 if (pReq != NULL) { 901 int oldStatus = dvmDbgThreadWaiting(); 902 if (suspendPolicy != SP_NONE) 903 dvmJdwpSetWaitForEventThread(state, basket.threadId); 904 905 eventFinish(state, pReq); 906 907 suspendByPolicy(state, suspendPolicy); 908 dvmDbgThreadContinuing(oldStatus); 909 } 910 911 free(nameAlloc); 912 return matchCount != 0; 913} 914 915/* 916 * A thread is starting or stopping. 917 * 918 * Valid mods: 919 * Count, ThreadOnly 920 */ 921bool dvmJdwpPostThreadChange(JdwpState* state, ObjectId threadId, bool start) 922{ 923 enum JdwpSuspendPolicy suspendPolicy = SP_NONE; 924 925 assert(threadId = dvmDbgGetThreadSelfId()); 926 927 /* 928 * I don't think this can happen. 929 */ 930 if (invokeInProgress(state)) { 931 LOGW("Not posting thread change during invoke\n"); 932 return false; 933 } 934 935 ModBasket basket; 936 memset(&basket, 0, sizeof(basket)); 937 basket.threadId = threadId; 938 939 /* don't allow the list to be updated while we scan it */ 940 lockEventMutex(state); 941 942 JdwpEvent** matchList = allocMatchList(state); 943 int matchCount = 0; 944 945 if (start) 946 findMatchingEvents(state, EK_THREAD_START, &basket, matchList, 947 &matchCount); 948 else 949 findMatchingEvents(state, EK_THREAD_DEATH, &basket, matchList, 950 &matchCount); 951 952 ExpandBuf* pReq = NULL; 953 if (matchCount != 0) { 954 LOGV("EVENT: %s(%d total) thread=%llx)\n", 955 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount, 956 basket.threadId); 957 958 suspendPolicy = scanSuspendPolicy(matchList, matchCount); 959 LOGV(" suspendPolicy=%s\n", 960 dvmJdwpSuspendPolicyStr(suspendPolicy)); 961 962 pReq = eventPrep(); 963 expandBufAdd1(pReq, suspendPolicy); 964 expandBufAdd4BE(pReq, matchCount); 965 966 for (int i = 0; i < matchCount; i++) { 967 expandBufAdd1(pReq, matchList[i]->eventKind); 968 expandBufAdd4BE(pReq, matchList[i]->requestId); 969 expandBufAdd8BE(pReq, basket.threadId); 970 } 971 972 } 973 974 cleanupMatchList(state, matchList, matchCount); 975 unlockEventMutex(state); 976 977 /* send request and possibly suspend ourselves */ 978 if (pReq != NULL) { 979 int oldStatus = dvmDbgThreadWaiting(); 980 if (suspendPolicy != SP_NONE) 981 dvmJdwpSetWaitForEventThread(state, basket.threadId); 982 983 eventFinish(state, pReq); 984 985 suspendByPolicy(state, suspendPolicy); 986 dvmDbgThreadContinuing(oldStatus); 987 } 988 989 return matchCount != 0; 990} 991 992/* 993 * Send a polite "VM is dying" message to the debugger. 994 * 995 * Skips the usual "event token" stuff. 996 */ 997bool dvmJdwpPostVMDeath(JdwpState* state) 998{ 999 LOGV("EVENT: %s\n", dvmJdwpEventKindStr(EK_VM_DEATH)); 1000 1001 ExpandBuf* pReq = eventPrep(); 1002 expandBufAdd1(pReq, SP_NONE); 1003 expandBufAdd4BE(pReq, 1); 1004 1005 expandBufAdd1(pReq, EK_VM_DEATH); 1006 expandBufAdd4BE(pReq, 0); 1007 eventFinish(state, pReq); 1008 return true; 1009} 1010 1011 1012/* 1013 * An exception has been thrown. It may or may not have been caught. 1014 * 1015 * Valid mods: 1016 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, LocationOnly, 1017 * ExceptionOnly, InstanceOnly 1018 * 1019 * The "exceptionId" has not been added to the GC-visible object registry, 1020 * because there's a pretty good chance that we're not going to send it 1021 * up the debugger. 1022 */ 1023bool dvmJdwpPostException(JdwpState* state, const JdwpLocation* pThrowLoc, 1024 ObjectId exceptionId, RefTypeId exceptionClassId, 1025 const JdwpLocation* pCatchLoc, ObjectId thisPtr) 1026{ 1027 enum JdwpSuspendPolicy suspendPolicy = SP_NONE; 1028 ModBasket basket; 1029 char* nameAlloc = NULL; 1030 1031 memset(&basket, 0, sizeof(basket)); 1032 basket.pLoc = pThrowLoc; 1033 basket.classId = pThrowLoc->classId; 1034 basket.threadId = dvmDbgGetThreadSelfId(); 1035 basket.className = nameAlloc = 1036 dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId)); 1037 basket.excepClassId = exceptionClassId; 1038 basket.caught = (pCatchLoc->classId != 0); 1039 basket.thisPtr = thisPtr; 1040 1041 /* don't try to post an exception caused by the debugger */ 1042 if (invokeInProgress(state)) { 1043 LOGV("Not posting exception hit during invoke (%s)\n",basket.className); 1044 free(nameAlloc); 1045 return false; 1046 } 1047 1048 /* don't allow the list to be updated while we scan it */ 1049 lockEventMutex(state); 1050 1051 JdwpEvent** matchList = allocMatchList(state); 1052 int matchCount = 0; 1053 1054 findMatchingEvents(state, EK_EXCEPTION, &basket, matchList, &matchCount); 1055 1056 ExpandBuf* pReq = NULL; 1057 if (matchCount != 0) { 1058 LOGV("EVENT: %s(%d total) thread=%llx exceptId=%llx caught=%d)\n", 1059 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount, 1060 basket.threadId, exceptionId, basket.caught); 1061 LOGV(" throw: %d %llx %x %lld (%s.%s)\n", pThrowLoc->typeTag, 1062 pThrowLoc->classId, pThrowLoc->methodId, pThrowLoc->idx, 1063 dvmDbgGetClassDescriptor(pThrowLoc->classId), 1064 dvmDbgGetMethodName(pThrowLoc->classId, pThrowLoc->methodId)); 1065 if (pCatchLoc->classId == 0) { 1066 LOGV(" catch: (not caught)\n"); 1067 } else { 1068 LOGV(" catch: %d %llx %x %lld (%s.%s)\n", pCatchLoc->typeTag, 1069 pCatchLoc->classId, pCatchLoc->methodId, pCatchLoc->idx, 1070 dvmDbgGetClassDescriptor(pCatchLoc->classId), 1071 dvmDbgGetMethodName(pCatchLoc->classId, pCatchLoc->methodId)); 1072 } 1073 1074 suspendPolicy = scanSuspendPolicy(matchList, matchCount); 1075 LOGV(" suspendPolicy=%s\n", 1076 dvmJdwpSuspendPolicyStr(suspendPolicy)); 1077 1078 pReq = eventPrep(); 1079 expandBufAdd1(pReq, suspendPolicy); 1080 expandBufAdd4BE(pReq, matchCount); 1081 1082 for (int i = 0; i < matchCount; i++) { 1083 expandBufAdd1(pReq, matchList[i]->eventKind); 1084 expandBufAdd4BE(pReq, matchList[i]->requestId); 1085 expandBufAdd8BE(pReq, basket.threadId); 1086 1087 dvmJdwpAddLocation(pReq, pThrowLoc); 1088 expandBufAdd1(pReq, JT_OBJECT); 1089 expandBufAdd8BE(pReq, exceptionId); 1090 dvmJdwpAddLocation(pReq, pCatchLoc); 1091 } 1092 1093 /* don't let the GC discard it */ 1094 dvmDbgRegisterObjectId(exceptionId); 1095 } 1096 1097 cleanupMatchList(state, matchList, matchCount); 1098 unlockEventMutex(state); 1099 1100 /* send request and possibly suspend ourselves */ 1101 if (pReq != NULL) { 1102 int oldStatus = dvmDbgThreadWaiting(); 1103 if (suspendPolicy != SP_NONE) 1104 dvmJdwpSetWaitForEventThread(state, basket.threadId); 1105 1106 eventFinish(state, pReq); 1107 1108 suspendByPolicy(state, suspendPolicy); 1109 dvmDbgThreadContinuing(oldStatus); 1110 } 1111 1112 free(nameAlloc); 1113 return matchCount != 0; 1114} 1115 1116/* 1117 * Announce that a class has been loaded. 1118 * 1119 * Valid mods: 1120 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude 1121 */ 1122bool dvmJdwpPostClassPrepare(JdwpState* state, int tag, RefTypeId refTypeId, 1123 const char* signature, int status) 1124{ 1125 enum JdwpSuspendPolicy suspendPolicy = SP_NONE; 1126 ModBasket basket; 1127 char* nameAlloc = NULL; 1128 1129 memset(&basket, 0, sizeof(basket)); 1130 basket.classId = refTypeId; 1131 basket.threadId = dvmDbgGetThreadSelfId(); 1132 basket.className = nameAlloc = 1133 dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId)); 1134 1135 /* suppress class prep caused by debugger */ 1136 if (invokeInProgress(state)) { 1137 LOGV("Not posting class prep caused by invoke (%s)\n",basket.className); 1138 free(nameAlloc); 1139 return false; 1140 } 1141 1142 /* don't allow the list to be updated while we scan it */ 1143 lockEventMutex(state); 1144 1145 JdwpEvent** matchList = allocMatchList(state); 1146 int matchCount = 0; 1147 1148 findMatchingEvents(state, EK_CLASS_PREPARE, &basket, matchList, 1149 &matchCount); 1150 1151 ExpandBuf* pReq = NULL; 1152 if (matchCount != 0) { 1153 LOGV("EVENT: %s(%d total) thread=%llx)\n", 1154 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount, 1155 basket.threadId); 1156 1157 suspendPolicy = scanSuspendPolicy(matchList, matchCount); 1158 LOGV(" suspendPolicy=%s\n", 1159 dvmJdwpSuspendPolicyStr(suspendPolicy)); 1160 1161 if (basket.threadId == state->debugThreadId) { 1162 /* 1163 * JDWP says that, for a class prep in the debugger thread, we 1164 * should set threadId to null and if any threads were supposed 1165 * to be suspended then we suspend all other threads. 1166 */ 1167 LOGV(" NOTE: class prepare in debugger thread!\n"); 1168 basket.threadId = 0; 1169 if (suspendPolicy == SP_EVENT_THREAD) 1170 suspendPolicy = SP_ALL; 1171 } 1172 1173 pReq = eventPrep(); 1174 expandBufAdd1(pReq, suspendPolicy); 1175 expandBufAdd4BE(pReq, matchCount); 1176 1177 for (int i = 0; i < matchCount; i++) { 1178 expandBufAdd1(pReq, matchList[i]->eventKind); 1179 expandBufAdd4BE(pReq, matchList[i]->requestId); 1180 expandBufAdd8BE(pReq, basket.threadId); 1181 1182 expandBufAdd1(pReq, tag); 1183 expandBufAdd8BE(pReq, refTypeId); 1184 expandBufAddUtf8String(pReq, (const u1*) signature); 1185 expandBufAdd4BE(pReq, status); 1186 } 1187 } 1188 1189 cleanupMatchList(state, matchList, matchCount); 1190 1191 unlockEventMutex(state); 1192 1193 /* send request and possibly suspend ourselves */ 1194 if (pReq != NULL) { 1195 int oldStatus = dvmDbgThreadWaiting(); 1196 if (suspendPolicy != SP_NONE) 1197 dvmJdwpSetWaitForEventThread(state, basket.threadId); 1198 1199 eventFinish(state, pReq); 1200 1201 suspendByPolicy(state, suspendPolicy); 1202 dvmDbgThreadContinuing(oldStatus); 1203 } 1204 1205 free(nameAlloc); 1206 return matchCount != 0; 1207} 1208 1209/* 1210 * Unload a class. 1211 * 1212 * Valid mods: 1213 * Count, ClassMatch, ClassExclude 1214 */ 1215bool dvmJdwpPostClassUnload(JdwpState* state, RefTypeId refTypeId) 1216{ 1217 assert(false); // TODO 1218 return false; 1219} 1220 1221/* 1222 * Get or set a field. 1223 * 1224 * Valid mods: 1225 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, FieldOnly, 1226 * InstanceOnly 1227 */ 1228bool dvmJdwpPostFieldAccess(JdwpState* state, int STUFF, ObjectId thisPtr, 1229 bool modified, JValue newValue) 1230{ 1231 assert(false); // TODO 1232 return false; 1233} 1234 1235/* 1236 * Send up a chunk of DDM data. 1237 * 1238 * While this takes the form of a JDWP "event", it doesn't interact with 1239 * other debugger traffic, and can't suspend the VM, so we skip all of 1240 * the fun event token gymnastics. 1241 */ 1242void dvmJdwpDdmSendChunkV(JdwpState* state, int type, const struct iovec* iov, 1243 int iovcnt) 1244{ 1245 u1 header[kJDWPHeaderLen + 8]; 1246 size_t dataLen = 0; 1247 1248 assert(iov != NULL); 1249 assert(iovcnt > 0 && iovcnt < 10); 1250 1251 /* 1252 * "Wrap" the contents of the iovec with a JDWP/DDMS header. We do 1253 * this by creating a new copy of the vector with space for the header. 1254 */ 1255 struct iovec wrapiov[iovcnt+1]; 1256 for (int i = 0; i < iovcnt; i++) { 1257 wrapiov[i+1].iov_base = iov[i].iov_base; 1258 wrapiov[i+1].iov_len = iov[i].iov_len; 1259 dataLen += iov[i].iov_len; 1260 } 1261 1262 /* form the header (JDWP plus DDMS) */ 1263 set4BE(header, sizeof(header) + dataLen); 1264 set4BE(header+4, dvmJdwpNextRequestSerial(state)); 1265 set1(header+8, 0); /* flags */ 1266 set1(header+9, kJDWPDdmCmdSet); 1267 set1(header+10, kJDWPDdmCmd); 1268 set4BE(header+11, type); 1269 set4BE(header+15, dataLen); 1270 1271 wrapiov[0].iov_base = header; 1272 wrapiov[0].iov_len = sizeof(header); 1273 1274 /* 1275 * Make sure we're in VMWAIT in case the write blocks. 1276 */ 1277 int oldStatus = dvmDbgThreadWaiting(); 1278 dvmJdwpSendBufferedRequest(state, wrapiov, iovcnt+1); 1279 dvmDbgThreadContinuing(oldStatus); 1280} 1281