1 /*
   2  * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include <ctype.h>
  27 
  28 #include "util.h"
  29 #include "transport.h"
  30 #include "eventHandler.h"
  31 #include "threadControl.h"
  32 #include "outStream.h"
  33 #include "inStream.h"
  34 #include "invoker.h"
  35 
  36 /* Global data area */
  37 BackendGlobalData *gdata = NULL;
  38 
  39 /* Forward declarations */
  40 static jboolean isInterface(jclass clazz);
  41 static jboolean isArrayClass(jclass clazz);
  42 static char * getPropertyUTF8(JNIEnv *env, char *propertyName);
  43 
  44 /* Save an object reference for use later (create a NewGlobalRef) */
  45 void
  46 saveGlobalRef(JNIEnv *env, jobject obj, jobject *pobj)
  47 {
  48     jobject newobj;
  49 
  50     if ( pobj == NULL ) {
  51         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"saveGlobalRef pobj");
  52     }
  53     if ( *pobj != NULL ) {
  54         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"saveGlobalRef *pobj");
  55     }
  56     if ( env == NULL ) {
  57         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"saveGlobalRef env");
  58     }
  59     if ( obj == NULL ) {
  60         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"saveGlobalRef obj");
  61     }
  62     newobj = JNI_FUNC_PTR(env,NewGlobalRef)(env, obj);
  63     if ( newobj == NULL ) {
  64         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,"NewGlobalRef");
  65     }
  66     *pobj = newobj;
  67 }
  68 
  69 /* Toss a previously saved object reference */
  70 void
  71 tossGlobalRef(JNIEnv *env, jobject *pobj)
  72 {
  73     jobject obj;
  74 
  75     if ( pobj == NULL ) {
  76         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"tossGlobalRef pobj");
  77     }
  78     obj = *pobj;
  79     if ( env == NULL ) {
  80         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"tossGlobalRef env");
  81     }
  82     if ( obj == NULL ) {
  83         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,"tossGlobalRef obj");
  84     }
  85     JNI_FUNC_PTR(env,DeleteGlobalRef)(env, obj);
  86     *pobj = NULL;
  87 }
  88 
  89 jclass
  90 findClass(JNIEnv *env, const char * name)
  91 {
  92     jclass x;
  93 
  94     if ( env == NULL ) {
  95         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"findClass env");
  96     }
  97     if ( name == NULL || name[0] == 0 ) {
  98         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"findClass name");
  99     }
 100     x = JNI_FUNC_PTR(env,FindClass)(env, name);
 101     if (x == NULL) {
 102         ERROR_MESSAGE(("JDWP Can't find class %s", name));
 103         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 104     }
 105     if ( JNI_FUNC_PTR(env,ExceptionOccurred)(env) ) {
 106         ERROR_MESSAGE(("JDWP Exception occurred finding class %s", name));
 107         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 108     }
 109     return x;
 110 }
 111 
 112 jmethodID
 113 getMethod(JNIEnv *env, jclass clazz, const char * name, const char *signature)
 114 {
 115     jmethodID method;
 116 
 117     if ( env == NULL ) {
 118         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getMethod env");
 119     }
 120     if ( clazz == NULL ) {
 121         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getMethod clazz");
 122     }
 123     if ( name == NULL || name[0] == 0 ) {
 124         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getMethod name");
 125     }
 126     if ( signature == NULL || signature[0] == 0 ) {
 127         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getMethod signature");
 128     }
 129     method = JNI_FUNC_PTR(env,GetMethodID)(env, clazz, name, signature);
 130     if (method == NULL) {
 131         ERROR_MESSAGE(("JDWP Can't find method %s with signature %s",
 132                                 name, signature));
 133         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 134     }
 135     if ( JNI_FUNC_PTR(env,ExceptionOccurred)(env) ) {
 136         ERROR_MESSAGE(("JDWP Exception occurred finding method %s with signature %s",
 137                                 name, signature));
 138         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 139     }
 140     return method;
 141 }
 142 
 143 static jmethodID
 144 getStaticMethod(JNIEnv *env, jclass clazz, const char * name, const char *signature)
 145 {
 146     jmethodID method;
 147 
 148     if ( env == NULL ) {
 149         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getStaticMethod env");
 150     }
 151     if ( clazz == NULL ) {
 152         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getStaticMethod clazz");
 153     }
 154     if ( name == NULL || name[0] == 0 ) {
 155         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getStaticMethod name");
 156     }
 157     if ( signature == NULL || signature[0] == 0 ) {
 158         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getStaticMethod signature");
 159     }
 160     method = JNI_FUNC_PTR(env,GetStaticMethodID)(env, clazz, name, signature);
 161     if (method == NULL) {
 162         ERROR_MESSAGE(("JDWP Can't find method %s with signature %s",
 163                                 name, signature));
 164         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 165     }
 166     if ( JNI_FUNC_PTR(env,ExceptionOccurred)(env) ) {
 167         ERROR_MESSAGE(("JDWP Exception occurred finding method %s with signature %s",
 168                                 name, signature));
 169         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 170     }
 171     return method;
 172 }
 173 
 174 void
 175 util_initialize(JNIEnv *env)
 176 {
 177     WITH_LOCAL_REFS(env, 6) {
 178 
 179         jvmtiError error;
 180         jclass localClassClass;
 181         jclass localThreadClass;
 182         jclass localThreadGroupClass;
 183         jclass localClassLoaderClass;
 184         jclass localStringClass;
 185         jclass localSystemClass;
 186         jclass localPropertiesClass;
 187         jclass localVMSupportClass;
 188         jobject localAgentProperties;
 189         jmethodID getAgentProperties;
 190         jint groupCount;
 191         jthreadGroup *groups;
 192         jthreadGroup localSystemThreadGroup;
 193 
 194         /* Find some standard classes */
 195 
 196         localClassClass         = findClass(env,"java/lang/Class");
 197         localThreadClass        = findClass(env,"java/lang/Thread");
 198         localThreadGroupClass   = findClass(env,"java/lang/ThreadGroup");
 199         localClassLoaderClass   = findClass(env,"java/lang/ClassLoader");
 200         localStringClass        = findClass(env,"java/lang/String");
 201         localSystemClass        = findClass(env,"java/lang/System");
 202         localPropertiesClass    = findClass(env,"java/util/Properties");
 203 
 204         /* Save references */
 205 
 206         saveGlobalRef(env, localClassClass,       &(gdata->classClass));
 207         saveGlobalRef(env, localThreadClass,      &(gdata->threadClass));
 208         saveGlobalRef(env, localThreadGroupClass, &(gdata->threadGroupClass));
 209         saveGlobalRef(env, localClassLoaderClass, &(gdata->classLoaderClass));
 210         saveGlobalRef(env, localStringClass,      &(gdata->stringClass));
 211         saveGlobalRef(env, localSystemClass,      &(gdata->systemClass));
 212 
 213         /* Find some standard methods */
 214 
 215         gdata->threadConstructor =
 216                 getMethod(env, gdata->threadClass,
 217                     "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V");
 218         gdata->threadSetDaemon =
 219                 getMethod(env, gdata->threadClass, "setDaemon", "(Z)V");
 220         gdata->threadResume =
 221                 getMethod(env, gdata->threadClass, "resume", "()V");
 222         gdata->systemGetProperty =
 223                 getStaticMethod(env, gdata->systemClass,
 224                     "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
 225         gdata->setProperty =
 226                 getMethod(env, localPropertiesClass,
 227                     "setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;");
 228 
 229         /* Find the system thread group */
 230 
 231         groups = NULL;
 232         groupCount = 0;
 233         error = JVMTI_FUNC_PTR(gdata->jvmti,GetTopThreadGroups)
 234                     (gdata->jvmti, &groupCount, &groups);
 235         if (error != JVMTI_ERROR_NONE ) {
 236             EXIT_ERROR(error, "Can't get system thread group");
 237         }
 238         if ( groupCount == 0 ) {
 239             EXIT_ERROR(AGENT_ERROR_NULL_POINTER, "Can't get system thread group");
 240         }
 241         localSystemThreadGroup = groups[0];
 242         saveGlobalRef(env, localSystemThreadGroup, &(gdata->systemThreadGroup));
 243 
 244         /* Get some basic Java property values we will need at some point */
 245         gdata->property_java_version
 246                         = getPropertyUTF8(env, "java.version");
 247         gdata->property_java_vm_name
 248                         = getPropertyUTF8(env, "java.vm.name");
 249         gdata->property_java_vm_info
 250                         = getPropertyUTF8(env, "java.vm.info");
 251         gdata->property_java_class_path
 252                         = getPropertyUTF8(env, "java.class.path");
 253         gdata->property_sun_boot_library_path
 254                         = getPropertyUTF8(env, "sun.boot.library.path");
 255         gdata->property_path_separator
 256                         = getPropertyUTF8(env, "path.separator");
 257         gdata->property_user_dir
 258                         = getPropertyUTF8(env, "user.dir");
 259 
 260         /* Get agent properties: invoke VMSupport.getAgentProperties */
 261         localVMSupportClass = JNI_FUNC_PTR(env,FindClass)
 262                                           (env, "jdk/internal/vm/VMSupport");
 263         if (localVMSupportClass == NULL) {
 264             gdata->agent_properties = NULL;
 265             if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
 266                 JNI_FUNC_PTR(env,ExceptionClear)(env);
 267             }
 268         } else {
 269             getAgentProperties  =
 270                 getStaticMethod(env, localVMSupportClass,
 271                                 "getAgentProperties", "()Ljava/util/Properties;");
 272             localAgentProperties =
 273                 JNI_FUNC_PTR(env,CallStaticObjectMethod)
 274                             (env, localVMSupportClass, getAgentProperties);
 275             saveGlobalRef(env, localAgentProperties, &(gdata->agent_properties));
 276             if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
 277                 JNI_FUNC_PTR(env,ExceptionClear)(env);
 278                 EXIT_ERROR(AGENT_ERROR_INTERNAL,
 279                     "Exception occurred calling VMSupport.getAgentProperties");
 280             }
 281         }
 282 
 283     } END_WITH_LOCAL_REFS(env);
 284 
 285 }
 286 
 287 void
 288 util_reset(void)
 289 {
 290 }
 291 
 292 jboolean
 293 isObjectTag(jbyte tag) {
 294     return (tag == JDWP_TAG(OBJECT)) ||
 295            (tag == JDWP_TAG(STRING)) ||
 296            (tag == JDWP_TAG(THREAD)) ||
 297            (tag == JDWP_TAG(THREAD_GROUP)) ||
 298            (tag == JDWP_TAG(CLASS_LOADER)) ||
 299            (tag == JDWP_TAG(CLASS_OBJECT)) ||
 300            (tag == JDWP_TAG(ARRAY));
 301 }
 302 
 303 jbyte
 304 specificTypeKey(JNIEnv *env, jobject object)
 305 {
 306     if (object == NULL) {
 307         return JDWP_TAG(OBJECT);
 308     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->stringClass)) {
 309         return JDWP_TAG(STRING);
 310     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->threadClass)) {
 311         return JDWP_TAG(THREAD);
 312     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->threadGroupClass)) {
 313         return JDWP_TAG(THREAD_GROUP);
 314     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->classLoaderClass)) {
 315         return JDWP_TAG(CLASS_LOADER);
 316     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->classClass)) {
 317         return JDWP_TAG(CLASS_OBJECT);
 318     } else {
 319         jboolean classIsArray;
 320 
 321         WITH_LOCAL_REFS(env, 1) {
 322             jclass clazz;
 323             clazz = JNI_FUNC_PTR(env,GetObjectClass)(env, object);
 324             classIsArray = isArrayClass(clazz);
 325         } END_WITH_LOCAL_REFS(env);
 326 
 327         return (classIsArray ? JDWP_TAG(ARRAY) : JDWP_TAG(OBJECT));
 328     }
 329 }
 330 
 331 static void
 332 writeFieldValue(JNIEnv *env, PacketOutputStream *out, jobject object,
 333                 jfieldID field)
 334 {
 335     jclass clazz;
 336     char *signature = NULL;
 337     jvmtiError error;
 338     jbyte typeKey;
 339 
 340     clazz = JNI_FUNC_PTR(env,GetObjectClass)(env, object);
 341     error = fieldSignature(clazz, field, NULL, &signature, NULL);
 342     if (error != JVMTI_ERROR_NONE) {
 343         outStream_setError(out, map2jdwpError(error));
 344         return;
 345     }
 346     typeKey = signature[0];
 347     jvmtiDeallocate(signature);
 348 
 349     /*
 350      * For primitive types, the type key is bounced back as is. Objects
 351      * are handled in the switch statement below.
 352      */
 353     if ((typeKey != JDWP_TAG(OBJECT)) && (typeKey != JDWP_TAG(ARRAY))) {
 354         (void)outStream_writeByte(out, typeKey);
 355     }
 356 
 357     switch (typeKey) {
 358         case JDWP_TAG(OBJECT):
 359         case JDWP_TAG(ARRAY):   {
 360             jobject value = JNI_FUNC_PTR(env,GetObjectField)(env, object, field);
 361             (void)outStream_writeByte(out, specificTypeKey(env, value));
 362             (void)outStream_writeObjectRef(env, out, value);
 363             break;
 364         }
 365 
 366         case JDWP_TAG(BYTE):
 367             (void)outStream_writeByte(out,
 368                       JNI_FUNC_PTR(env,GetByteField)(env, object, field));
 369             break;
 370 
 371         case JDWP_TAG(CHAR):
 372             (void)outStream_writeChar(out,
 373                       JNI_FUNC_PTR(env,GetCharField)(env, object, field));
 374             break;
 375 
 376         case JDWP_TAG(FLOAT):
 377             (void)outStream_writeFloat(out,
 378                       JNI_FUNC_PTR(env,GetFloatField)(env, object, field));
 379             break;
 380 
 381         case JDWP_TAG(DOUBLE):
 382             (void)outStream_writeDouble(out,
 383                       JNI_FUNC_PTR(env,GetDoubleField)(env, object, field));
 384             break;
 385 
 386         case JDWP_TAG(INT):
 387             (void)outStream_writeInt(out,
 388                       JNI_FUNC_PTR(env,GetIntField)(env, object, field));
 389             break;
 390 
 391         case JDWP_TAG(LONG):
 392             (void)outStream_writeLong(out,
 393                       JNI_FUNC_PTR(env,GetLongField)(env, object, field));
 394             break;
 395 
 396         case JDWP_TAG(SHORT):
 397             (void)outStream_writeShort(out,
 398                       JNI_FUNC_PTR(env,GetShortField)(env, object, field));
 399             break;
 400 
 401         case JDWP_TAG(BOOLEAN):
 402             (void)outStream_writeBoolean(out,
 403                       JNI_FUNC_PTR(env,GetBooleanField)(env, object, field));
 404             break;
 405     }
 406 }
 407 
 408 static void
 409 writeStaticFieldValue(JNIEnv *env, PacketOutputStream *out, jclass clazz,
 410                       jfieldID field)
 411 {
 412     jvmtiError error;
 413     char *signature = NULL;
 414     jbyte typeKey;
 415 
 416     error = fieldSignature(clazz, field, NULL, &signature, NULL);
 417     if (error != JVMTI_ERROR_NONE) {
 418         outStream_setError(out, map2jdwpError(error));
 419         return;
 420     }
 421     typeKey = signature[0];
 422     jvmtiDeallocate(signature);
 423 
 424     /*
 425      * For primitive types, the type key is bounced back as is. Objects
 426      * are handled in the switch statement below.
 427      */
 428     if ((typeKey != JDWP_TAG(OBJECT)) && (typeKey != JDWP_TAG(ARRAY))) {
 429         (void)outStream_writeByte(out, typeKey);
 430     }
 431 
 432     switch (typeKey) {
 433         case JDWP_TAG(OBJECT):
 434         case JDWP_TAG(ARRAY):   {
 435             jobject value = JNI_FUNC_PTR(env,GetStaticObjectField)(env, clazz, field);
 436             (void)outStream_writeByte(out, specificTypeKey(env, value));
 437             (void)outStream_writeObjectRef(env, out, value);
 438             break;
 439         }
 440 
 441         case JDWP_TAG(BYTE):
 442             (void)outStream_writeByte(out,
 443                       JNI_FUNC_PTR(env,GetStaticByteField)(env, clazz, field));
 444             break;
 445 
 446         case JDWP_TAG(CHAR):
 447             (void)outStream_writeChar(out,
 448                       JNI_FUNC_PTR(env,GetStaticCharField)(env, clazz, field));
 449             break;
 450 
 451         case JDWP_TAG(FLOAT):
 452             (void)outStream_writeFloat(out,
 453                       JNI_FUNC_PTR(env,GetStaticFloatField)(env, clazz, field));
 454             break;
 455 
 456         case JDWP_TAG(DOUBLE):
 457             (void)outStream_writeDouble(out,
 458                       JNI_FUNC_PTR(env,GetStaticDoubleField)(env, clazz, field));
 459             break;
 460 
 461         case JDWP_TAG(INT):
 462             (void)outStream_writeInt(out,
 463                       JNI_FUNC_PTR(env,GetStaticIntField)(env, clazz, field));
 464             break;
 465 
 466         case JDWP_TAG(LONG):
 467             (void)outStream_writeLong(out,
 468                       JNI_FUNC_PTR(env,GetStaticLongField)(env, clazz, field));
 469             break;
 470 
 471         case JDWP_TAG(SHORT):
 472             (void)outStream_writeShort(out,
 473                       JNI_FUNC_PTR(env,GetStaticShortField)(env, clazz, field));
 474             break;
 475 
 476         case JDWP_TAG(BOOLEAN):
 477             (void)outStream_writeBoolean(out,
 478                       JNI_FUNC_PTR(env,GetStaticBooleanField)(env, clazz, field));
 479             break;
 480     }
 481 }
 482 
 483 void
 484 sharedGetFieldValues(PacketInputStream *in, PacketOutputStream *out,
 485                      jboolean isStatic)
 486 {
 487     JNIEnv *env = getEnv();
 488     jint length;
 489     jobject object;
 490     jclass clazz;
 491 
 492     object = NULL;
 493     clazz  = NULL;
 494 
 495     if (isStatic) {
 496         clazz = inStream_readClassRef(env, in);
 497     } else {
 498         object = inStream_readObjectRef(env, in);
 499     }
 500 
 501     length = inStream_readInt(in);
 502     if (inStream_error(in)) {
 503         return;
 504     }
 505 
 506     WITH_LOCAL_REFS(env, length + 1) { /* +1 for class with instance fields */
 507 
 508         int i;
 509 
 510         (void)outStream_writeInt(out, length);
 511         for (i = 0; (i < length) && !outStream_error(out); i++) {
 512             jfieldID field = inStream_readFieldID(in);
 513 
 514             if (isStatic) {
 515                 writeStaticFieldValue(env, out, clazz, field);
 516             } else {
 517                 writeFieldValue(env, out, object, field);
 518             }
 519         }
 520 
 521     } END_WITH_LOCAL_REFS(env);
 522 }
 523 
 524 jboolean
 525 sharedInvoke(PacketInputStream *in, PacketOutputStream *out)
 526 {
 527     jvalue *arguments = NULL;
 528     jint options;
 529     jvmtiError error;
 530     jbyte invokeType;
 531     jclass clazz;
 532     jmethodID method;
 533     jint argumentCount;
 534     jobject instance;
 535     jthread thread;
 536     JNIEnv *env;
 537 
 538     /*
 539      * Instance methods start with the instance, thread and class,
 540      * and statics and constructors start with the class and then the
 541      * thread.
 542      */
 543     env = getEnv();
 544     if (inStream_command(in) == JDWP_COMMAND(ObjectReference, InvokeMethod)) {
 545         instance = inStream_readObjectRef(env, in);
 546         thread = inStream_readThreadRef(env, in);
 547         clazz = inStream_readClassRef(env, in);
 548     } else { /* static method or constructor */
 549         instance = NULL;
 550         clazz = inStream_readClassRef(env, in);
 551         thread = inStream_readThreadRef(env, in);
 552     }
 553 
 554     /*
 555      * ... and the rest of the packet is identical for all commands
 556      */
 557     method = inStream_readMethodID(in);
 558     argumentCount = inStream_readInt(in);
 559     if (inStream_error(in)) {
 560         return JNI_TRUE;
 561     }
 562 
 563     /* If count == 0, don't try and allocate 0 bytes, you'll get NULL */
 564     if ( argumentCount > 0 ) {
 565         int i;
 566         /*LINTED*/
 567         arguments = jvmtiAllocate(argumentCount * (jint)sizeof(*arguments));
 568         if (arguments == NULL) {
 569             outStream_setError(out, JDWP_ERROR(OUT_OF_MEMORY));
 570             return JNI_TRUE;
 571         }
 572         for (i = 0; (i < argumentCount) && !inStream_error(in); i++) {
 573             arguments[i] = inStream_readValue(in, NULL);
 574         }
 575         if (inStream_error(in)) {
 576             return JNI_TRUE;
 577         }
 578     }
 579 
 580     options = inStream_readInt(in);
 581     if (inStream_error(in)) {
 582         if ( arguments != NULL ) {
 583             jvmtiDeallocate(arguments);
 584         }
 585         return JNI_TRUE;
 586     }
 587 
 588     if (inStream_command(in) == JDWP_COMMAND(ClassType, NewInstance)) {
 589         invokeType = INVOKE_CONSTRUCTOR;
 590     } else if (inStream_command(in) == JDWP_COMMAND(ClassType, InvokeMethod)) {
 591         invokeType = INVOKE_STATIC;
 592     } else if (inStream_command(in) == JDWP_COMMAND(InterfaceType, InvokeMethod)) {
 593         invokeType = INVOKE_STATIC;
 594     } else if (inStream_command(in) == JDWP_COMMAND(ObjectReference, InvokeMethod)) {
 595         invokeType = INVOKE_INSTANCE;
 596     } else {
 597         outStream_setError(out, JDWP_ERROR(INTERNAL));
 598         if ( arguments != NULL ) {
 599             jvmtiDeallocate(arguments);
 600         }
 601         return JNI_TRUE;
 602     }
 603 
 604     /*
 605      * Request the invoke. If there are no errors in the request,
 606      * the interrupting thread will actually do the invoke and a
 607      * reply will be generated subsequently, so we don't reply here.
 608      */
 609     error = invoker_requestInvoke(invokeType, (jbyte)options, inStream_id(in),
 610                                   thread, clazz, method,
 611                                   instance, arguments, argumentCount);
 612     if (error != JVMTI_ERROR_NONE) {
 613         outStream_setError(out, map2jdwpError(error));
 614         if ( arguments != NULL ) {
 615             jvmtiDeallocate(arguments);
 616         }
 617         return JNI_TRUE;
 618     }
 619 
 620     return JNI_FALSE;   /* Don't reply */
 621 }
 622 
 623 jint
 624 uniqueID(void)
 625 {
 626     static jint currentID = 0;
 627     return currentID++;
 628 }
 629 
 630 int
 631 filterDebugThreads(jthread *threads, int count)
 632 {
 633     int i;
 634     int current;
 635 
 636     /* Squish out all of the debugger-spawned threads */
 637     for (i = 0, current = 0; i < count; i++) {
 638         jthread thread = threads[i];
 639         if (!threadControl_isDebugThread(thread)) {
 640             if (i > current) {
 641                 threads[current] = thread;
 642             }
 643             current++;
 644         }
 645     }
 646     return current;
 647 }
 648 
 649 jbyte
 650 referenceTypeTag(jclass clazz)
 651 {
 652     jbyte tag;
 653 
 654     if (isInterface(clazz)) {
 655         tag = JDWP_TYPE_TAG(INTERFACE);
 656     } else if (isArrayClass(clazz)) {
 657         tag = JDWP_TYPE_TAG(ARRAY);
 658     } else {
 659         tag = JDWP_TYPE_TAG(CLASS);
 660     }
 661 
 662     return tag;
 663 }
 664 
 665 /**
 666  * Get field modifiers
 667  */
 668 jvmtiError
 669 fieldModifiers(jclass clazz, jfieldID field, jint *pmodifiers)
 670 {
 671     jvmtiError error;
 672 
 673     *pmodifiers = 0;
 674     error = JVMTI_FUNC_PTR(gdata->jvmti,GetFieldModifiers)
 675             (gdata->jvmti, clazz, field, pmodifiers);
 676     return error;
 677 }
 678 
 679 /**
 680  * Get method modifiers
 681  */
 682 jvmtiError
 683 methodModifiers(jmethodID method, jint *pmodifiers)
 684 {
 685     jvmtiError error;
 686 
 687     *pmodifiers = 0;
 688     error = JVMTI_FUNC_PTR(gdata->jvmti,GetMethodModifiers)
 689             (gdata->jvmti, method, pmodifiers);
 690     return error;
 691 }
 692 
 693 /* Returns a local ref to the declaring class for a method, or NULL. */
 694 jvmtiError
 695 methodClass(jmethodID method, jclass *pclazz)
 696 {
 697     jvmtiError error;
 698 
 699     *pclazz = NULL;
 700     error = FUNC_PTR(gdata->jvmti,GetMethodDeclaringClass)
 701                                 (gdata->jvmti, method, pclazz);
 702     return error;
 703 }
 704 
 705 /* Returns a local ref to the declaring class for a method, or NULL. */
 706 jvmtiError
 707 methodLocation(jmethodID method, jlocation *ploc1, jlocation *ploc2)
 708 {
 709     jvmtiError error;
 710 
 711     error = JVMTI_FUNC_PTR(gdata->jvmti,GetMethodLocation)
 712                                 (gdata->jvmti, method, ploc1, ploc2);
 713     return error;
 714 }
 715 
 716 /**
 717  * Get method signature
 718  */
 719 jvmtiError
 720 methodSignature(jmethodID method,
 721         char **pname, char **psignature, char **pgeneric_signature)
 722 {
 723     jvmtiError error;
 724     char *name = NULL;
 725     char *signature = NULL;
 726     char *generic_signature = NULL;
 727 
 728     error = FUNC_PTR(gdata->jvmti,GetMethodName)
 729             (gdata->jvmti, method, &name, &signature, &generic_signature);
 730 
 731     if ( pname != NULL ) {
 732         *pname = name;
 733     } else if ( name != NULL )  {
 734         jvmtiDeallocate(name);
 735     }
 736     if ( psignature != NULL ) {
 737         *psignature = signature;
 738     } else if ( signature != NULL ) {
 739         jvmtiDeallocate(signature);
 740     }
 741     if ( pgeneric_signature != NULL ) {
 742         *pgeneric_signature = generic_signature;
 743     } else if ( generic_signature != NULL )  {
 744         jvmtiDeallocate(generic_signature);
 745     }
 746     return error;
 747 }
 748 
 749 /*
 750  * Get the return type key of the method
 751  *     V or B C D F I J S Z L  [
 752  */
 753 jvmtiError
 754 methodReturnType(jmethodID method, char *typeKey)
 755 {
 756     char       *signature;
 757     jvmtiError  error;
 758 
 759     signature = NULL;
 760     error     = methodSignature(method, NULL, &signature, NULL);
 761     if (error == JVMTI_ERROR_NONE) {
 762         if (signature == NULL ) {
 763             error = AGENT_ERROR_INVALID_TAG;
 764         } else {
 765             char * xx;
 766 
 767             xx = strchr(signature, ')');
 768             if (xx == NULL || *(xx + 1) == 0) {
 769                 error = AGENT_ERROR_INVALID_TAG;
 770             } else {
 771                *typeKey = *(xx + 1);
 772             }
 773             jvmtiDeallocate(signature);
 774         }
 775     }
 776     return error;
 777 }
 778 
 779 
 780 /**
 781  * Return class loader for a class (must be inside a WITH_LOCAL_REFS)
 782  */
 783 jvmtiError
 784 classLoader(jclass clazz, jobject *pclazz)
 785 {
 786     jvmtiError error;
 787 
 788     *pclazz = NULL;
 789     error = JVMTI_FUNC_PTR(gdata->jvmti,GetClassLoader)
 790             (gdata->jvmti, clazz, pclazz);
 791     return error;
 792 }
 793 
 794 /**
 795  * Get field signature
 796  */
 797 jvmtiError
 798 fieldSignature(jclass clazz, jfieldID field,
 799         char **pname, char **psignature, char **pgeneric_signature)
 800 {
 801     jvmtiError error;
 802     char *name = NULL;
 803     char *signature = NULL;
 804     char *generic_signature = NULL;
 805 
 806     error = JVMTI_FUNC_PTR(gdata->jvmti,GetFieldName)
 807             (gdata->jvmti, clazz, field, &name, &signature, &generic_signature);
 808 
 809     if ( pname != NULL ) {
 810         *pname = name;
 811     } else if ( name != NULL )  {
 812         jvmtiDeallocate(name);
 813     }
 814     if ( psignature != NULL ) {
 815         *psignature = signature;
 816     } else if ( signature != NULL )  {
 817         jvmtiDeallocate(signature);
 818     }
 819     if ( pgeneric_signature != NULL ) {
 820         *pgeneric_signature = generic_signature;
 821     } else if ( generic_signature != NULL )  {
 822         jvmtiDeallocate(generic_signature);
 823     }
 824     return error;
 825 }
 826 
 827 JNIEnv *
 828 getEnv(void)
 829 {
 830     JNIEnv *env = NULL;
 831     jint rc;
 832 
 833     rc = FUNC_PTR(gdata->jvm,GetEnv)
 834                 (gdata->jvm, (void **)&env, JNI_VERSION_1_2);
 835     if (rc != JNI_OK) {
 836         ERROR_MESSAGE(("JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = %d",
 837                 rc));
 838         EXIT_ERROR(AGENT_ERROR_NO_JNI_ENV,NULL);
 839     }
 840     return env;
 841 }
 842 
 843 jvmtiError
 844 spawnNewThread(jvmtiStartFunction func, void *arg, char *name)
 845 {
 846     JNIEnv *env = getEnv();
 847     jvmtiError error;
 848 
 849     LOG_MISC(("Spawning new thread: %s", name));
 850 
 851     WITH_LOCAL_REFS(env, 3) {
 852 
 853         jthread thread;
 854         jstring nameString;
 855 
 856         nameString = JNI_FUNC_PTR(env,NewStringUTF)(env, name);
 857         if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
 858             JNI_FUNC_PTR(env,ExceptionClear)(env);
 859             error = AGENT_ERROR_OUT_OF_MEMORY;
 860             goto err;
 861         }
 862 
 863         thread = JNI_FUNC_PTR(env,NewObject)
 864                         (env, gdata->threadClass, gdata->threadConstructor,
 865                                    gdata->systemThreadGroup, nameString);
 866         if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
 867             JNI_FUNC_PTR(env,ExceptionClear)(env);
 868             error = AGENT_ERROR_OUT_OF_MEMORY;
 869             goto err;
 870         }
 871 
 872         /*
 873          * Make the debugger thread a daemon
 874          */
 875         JNI_FUNC_PTR(env,CallVoidMethod)
 876                         (env, thread, gdata->threadSetDaemon, JNI_TRUE);
 877         if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
 878             JNI_FUNC_PTR(env,ExceptionClear)(env);
 879             error = AGENT_ERROR_JNI_EXCEPTION;
 880             goto err;
 881         }
 882 
 883         error = threadControl_addDebugThread(thread);
 884         if (error == JVMTI_ERROR_NONE) {
 885             /*
 886              * Debugger threads need cycles in all sorts of strange
 887              * situations (e.g. infinite cpu-bound loops), so give the
 888              * thread a high priority. Note that if the VM has an application
 889              * thread running at the max priority, there is still a chance
 890              * that debugger threads will be starved. (There needs to be
 891              * a way to give debugger threads a priority higher than any
 892              * application thread).
 893              */
 894             error = JVMTI_FUNC_PTR(gdata->jvmti,RunAgentThread)
 895                         (gdata->jvmti, thread, func, arg,
 896                                         JVMTI_THREAD_MAX_PRIORITY);
 897         }
 898 
 899         err: ;
 900 
 901     } END_WITH_LOCAL_REFS(env);
 902 
 903     return error;
 904 }
 905 
 906 jvmtiError
 907 jvmtiGetCapabilities(jvmtiCapabilities *caps)
 908 {
 909     if ( gdata->vmDead ) {
 910         return AGENT_ERROR_VM_DEAD;
 911     }
 912     if (!gdata->haveCachedJvmtiCapabilities) {
 913         jvmtiError error;
 914 
 915         error = JVMTI_FUNC_PTR(gdata->jvmti,GetCapabilities)
 916                         (gdata->jvmti, &(gdata->cachedJvmtiCapabilities));
 917         if (error != JVMTI_ERROR_NONE) {
 918             return error;
 919         }
 920         gdata->haveCachedJvmtiCapabilities = JNI_TRUE;
 921     }
 922 
 923     *caps = gdata->cachedJvmtiCapabilities;
 924 
 925     return JVMTI_ERROR_NONE;
 926 }
 927 
 928 static jint
 929 jvmtiVersion(void)
 930 {
 931     if (gdata->cachedJvmtiVersion == 0) {
 932         jvmtiError error;
 933         error = JVMTI_FUNC_PTR(gdata->jvmti,GetVersionNumber)
 934                         (gdata->jvmti, &(gdata->cachedJvmtiVersion));
 935         if (error != JVMTI_ERROR_NONE) {
 936             EXIT_ERROR(error, "on getting the JVMTI version number");
 937         }
 938     }
 939     return gdata->cachedJvmtiVersion;
 940 }
 941 
 942 jint
 943 jvmtiMajorVersion(void)
 944 {
 945     return (jvmtiVersion() & JVMTI_VERSION_MASK_MAJOR)
 946                     >> JVMTI_VERSION_SHIFT_MAJOR;
 947 }
 948 
 949 jint
 950 jvmtiMinorVersion(void)
 951 {
 952     return (jvmtiVersion() & JVMTI_VERSION_MASK_MINOR)
 953                     >> JVMTI_VERSION_SHIFT_MINOR;
 954 }
 955 
 956 jint
 957 jvmtiMicroVersion(void)
 958 {
 959     return (jvmtiVersion() & JVMTI_VERSION_MASK_MICRO)
 960                     >> JVMTI_VERSION_SHIFT_MICRO;
 961 }
 962 
 963 jboolean
 964 canSuspendResumeThreadLists(void)
 965 {
 966     jvmtiError error;
 967     jvmtiCapabilities cap;
 968 
 969     error = jvmtiGetCapabilities(&cap);
 970     return (error == JVMTI_ERROR_NONE && cap.can_suspend);
 971 }
 972 
 973 jvmtiError
 974 getSourceDebugExtension(jclass clazz, char **extensionPtr)
 975 {
 976     return JVMTI_FUNC_PTR(gdata->jvmti,GetSourceDebugExtension)
 977                 (gdata->jvmti, clazz, extensionPtr);
 978 }
 979 
 980 /*
 981  * Convert the signature "Ljava/lang/Foo;" to a
 982  * classname "java.lang.Foo" compatible with the pattern.
 983  * Signature is overwritten in-place.
 984  */
 985 void
 986 convertSignatureToClassname(char *convert)
 987 {
 988     char *p;
 989 
 990     p = convert + 1;
 991     while ((*p != ';') && (*p != '\0')) {
 992         char c = *p;
 993         if (c == '/') {
 994             *(p-1) = '.';
 995         } else {
 996             *(p-1) = c;
 997         }
 998         p++;
 999     }
1000     *(p-1) = '\0';
1001 }
1002 
1003 static void
1004 handleInterrupt(void)
1005 {
1006     /*
1007      * An interrupt is handled:
1008      *
1009      * 1) for running application threads by deferring the interrupt
1010      * until the current event handler has concluded.
1011      *
1012      * 2) for debugger threads by ignoring the interrupt; this is the
1013      * most robust solution since debugger threads don't use interrupts
1014      * to signal any condition.
1015      *
1016      * 3) for application threads that have not started or already
1017      * ended by ignoring the interrupt. In the former case, the application
1018      * is relying on timing to determine whether or not the thread sees
1019      * the interrupt; in the latter case, the interrupt is meaningless.
1020      */
1021     jthread thread = threadControl_currentThread();
1022     if ((thread != NULL) && (!threadControl_isDebugThread(thread))) {
1023         threadControl_setPendingInterrupt(thread);
1024     }
1025 }
1026 
1027 static jvmtiError
1028 ignore_vm_death(jvmtiError error)
1029 {
1030     if (error == JVMTI_ERROR_WRONG_PHASE) {
1031         LOG_MISC(("VM_DEAD, in debugMonitor*()?"));
1032         return JVMTI_ERROR_NONE; /* JVMTI does this, not JVMDI? */
1033     }
1034     return error;
1035 }
1036 
1037 void
1038 debugMonitorEnter(jrawMonitorID monitor)
1039 {
1040     jvmtiError error;
1041     while (JNI_TRUE) {
1042         error = FUNC_PTR(gdata->jvmti,RawMonitorEnter)
1043                         (gdata->jvmti, monitor);
1044         error = ignore_vm_death(error);
1045         if (error == JVMTI_ERROR_INTERRUPT) {
1046             handleInterrupt();
1047         } else {
1048             break;
1049         }
1050     }
1051     if (error != JVMTI_ERROR_NONE) {
1052         EXIT_ERROR(error, "on raw monitor enter");
1053     }
1054 }
1055 
1056 void
1057 debugMonitorExit(jrawMonitorID monitor)
1058 {
1059     jvmtiError error;
1060 
1061     error = FUNC_PTR(gdata->jvmti,RawMonitorExit)
1062                 (gdata->jvmti, monitor);
1063     error = ignore_vm_death(error);
1064     if (error != JVMTI_ERROR_NONE) {
1065         EXIT_ERROR(error, "on raw monitor exit");
1066     }
1067 }
1068 
1069 void
1070 debugMonitorWait(jrawMonitorID monitor)
1071 {
1072     jvmtiError error;
1073     error = FUNC_PTR(gdata->jvmti,RawMonitorWait)
1074         (gdata->jvmti, monitor, ((jlong)(-1)));
1075 
1076     /*
1077      * According to the JLS (17.8), here we have
1078      * either :
1079      * a- been notified
1080      * b- gotten a suprious wakeup
1081      * c- been interrupted
1082      * If both a and c have happened, the VM must choose
1083      * which way to return - a or c.  If it chooses c
1084      * then the notify is gone - either to some other
1085      * thread that is also waiting, or it is dropped
1086      * on the floor.
1087      *
1088      * a is what we expect.  b won't hurt us any -
1089      * callers should be programmed to handle
1090      * spurious wakeups.  In case of c,
1091      * then the interrupt has been cleared, but
1092      * we don't want to consume it.  It came from
1093      * user code and is intended for user code, not us.
1094      * So, we will remember that the interrupt has
1095      * occurred and re-activate it when this thread
1096      * goes back into user code.
1097      * That being said, what do we do here?  Since
1098      * we could have been notified too, here we will
1099      * just pretend that we have been.  It won't hurt
1100      * anything to return in the same way as if
1101      * we were notified since callers have to be able to
1102      * handle spurious wakeups anyway.
1103      */
1104     if (error == JVMTI_ERROR_INTERRUPT) {
1105         handleInterrupt();
1106         error = JVMTI_ERROR_NONE;
1107     }
1108     error = ignore_vm_death(error);
1109     if (error != JVMTI_ERROR_NONE) {
1110         EXIT_ERROR(error, "on raw monitor wait");
1111     }
1112 }
1113 
1114 void
1115 debugMonitorTimedWait(jrawMonitorID monitor, jlong millis)
1116 {
1117     jvmtiError error;
1118     error = FUNC_PTR(gdata->jvmti,RawMonitorWait)
1119         (gdata->jvmti, monitor, millis);
1120     if (error == JVMTI_ERROR_INTERRUPT) {
1121         /* See comment above */
1122         handleInterrupt();
1123         error = JVMTI_ERROR_NONE;
1124     }
1125     error = ignore_vm_death(error);
1126     if (error != JVMTI_ERROR_NONE) {
1127         EXIT_ERROR(error, "on raw monitor timed wait");
1128     }
1129 }
1130 
1131 void
1132 debugMonitorNotify(jrawMonitorID monitor)
1133 {
1134     jvmtiError error;
1135 
1136     error = FUNC_PTR(gdata->jvmti,RawMonitorNotify)
1137                 (gdata->jvmti, monitor);
1138     error = ignore_vm_death(error);
1139     if (error != JVMTI_ERROR_NONE) {
1140         EXIT_ERROR(error, "on raw monitor notify");
1141     }
1142 }
1143 
1144 void
1145 debugMonitorNotifyAll(jrawMonitorID monitor)
1146 {
1147     jvmtiError error;
1148 
1149     error = FUNC_PTR(gdata->jvmti,RawMonitorNotifyAll)
1150                 (gdata->jvmti, monitor);
1151     error = ignore_vm_death(error);
1152     if (error != JVMTI_ERROR_NONE) {
1153         EXIT_ERROR(error, "on raw monitor notify all");
1154     }
1155 }
1156 
1157 jrawMonitorID
1158 debugMonitorCreate(char *name)
1159 {
1160     jrawMonitorID monitor;
1161     jvmtiError error;
1162 
1163     error = FUNC_PTR(gdata->jvmti,CreateRawMonitor)
1164                 (gdata->jvmti, name, &monitor);
1165     if (error != JVMTI_ERROR_NONE) {
1166         EXIT_ERROR(error, "on creation of a raw monitor");
1167     }
1168     return monitor;
1169 }
1170 
1171 void
1172 debugMonitorDestroy(jrawMonitorID monitor)
1173 {
1174     jvmtiError error;
1175 
1176     error = FUNC_PTR(gdata->jvmti,DestroyRawMonitor)
1177                 (gdata->jvmti, monitor);
1178     error = ignore_vm_death(error);
1179     if (error != JVMTI_ERROR_NONE) {
1180         EXIT_ERROR(error, "on destruction of raw monitor");
1181     }
1182 }
1183 
1184 /**
1185  * Return array of all threads (must be inside a WITH_LOCAL_REFS)
1186  */
1187 jthread *
1188 allThreads(jint *count)
1189 {
1190     jthread *threads;
1191     jvmtiError error;
1192 
1193     *count = 0;
1194     threads = NULL;
1195     error = JVMTI_FUNC_PTR(gdata->jvmti,GetAllThreads)
1196                 (gdata->jvmti, count, &threads);
1197     if (error == AGENT_ERROR_OUT_OF_MEMORY) {
1198         return NULL; /* Let caller deal with no memory? */
1199     }
1200     if (error != JVMTI_ERROR_NONE) {
1201         EXIT_ERROR(error, "getting all threads");
1202     }
1203     return threads;
1204 }
1205 
1206 /**
1207  * Fill the passed in structure with thread group info.
1208  * name field is JVMTI allocated.  parent is global ref.
1209  */
1210 void
1211 threadGroupInfo(jthreadGroup group, jvmtiThreadGroupInfo *info)
1212 {
1213     jvmtiError error;
1214 
1215     error = JVMTI_FUNC_PTR(gdata->jvmti,GetThreadGroupInfo)
1216                 (gdata->jvmti, group, info);
1217     if (error != JVMTI_ERROR_NONE) {
1218         EXIT_ERROR(error, "on getting thread group info");
1219     }
1220 }
1221 
1222 /**
1223  * Return class signature string
1224  */
1225 jvmtiError
1226 classSignature(jclass clazz, char **psignature, char **pgeneric_signature)
1227 {
1228     jvmtiError error;
1229     char *signature = NULL;
1230 
1231     /*
1232      * pgeneric_signature can be NULL, and GetClassSignature
1233      * accepts NULL.
1234      */
1235     error = FUNC_PTR(gdata->jvmti,GetClassSignature)
1236                 (gdata->jvmti, clazz, &signature, pgeneric_signature);
1237 
1238     if ( psignature != NULL ) {
1239         *psignature = signature;
1240     } else if ( signature != NULL )  {
1241         jvmtiDeallocate(signature);
1242     }
1243     return error;
1244 }
1245 
1246 /* Get class name (not signature) */
1247 char *
1248 getClassname(jclass clazz)
1249 {
1250     char *classname;
1251 
1252     classname = NULL;
1253     if ( clazz != NULL ) {
1254         if (classSignature(clazz, &classname, NULL) != JVMTI_ERROR_NONE) {
1255             classname = NULL;
1256         } else {
1257             /* Convert in place */
1258             convertSignatureToClassname(classname);
1259         }
1260     }
1261     return classname; /* Caller must free this memory */
1262 }
1263 
1264 void
1265 writeGenericSignature(PacketOutputStream *out, char *genericSignature)
1266 {
1267     if (genericSignature == NULL) {
1268         (void)outStream_writeString(out, "");
1269     } else {
1270         (void)outStream_writeString(out, genericSignature);
1271     }
1272 }
1273 
1274 jint
1275 classStatus(jclass clazz)
1276 {
1277     jint status;
1278     jvmtiError error;
1279 
1280     error = JVMTI_FUNC_PTR(gdata->jvmti,GetClassStatus)
1281                 (gdata->jvmti, clazz, &status);
1282     if (error != JVMTI_ERROR_NONE) {
1283         EXIT_ERROR(error, "on getting class status");
1284     }
1285     return status;
1286 }
1287 
1288 static jboolean
1289 isArrayClass(jclass clazz)
1290 {
1291     jboolean isArray = JNI_FALSE;
1292     jvmtiError error;
1293 
1294     error = JVMTI_FUNC_PTR(gdata->jvmti,IsArrayClass)
1295                 (gdata->jvmti, clazz, &isArray);
1296     if (error != JVMTI_ERROR_NONE) {
1297         EXIT_ERROR(error, "on checking for an array class");
1298     }
1299     return isArray;
1300 }
1301 
1302 static jboolean
1303 isInterface(jclass clazz)
1304 {
1305     jboolean isInterface = JNI_FALSE;
1306     jvmtiError error;
1307 
1308     error = JVMTI_FUNC_PTR(gdata->jvmti,IsInterface)
1309                 (gdata->jvmti, clazz, &isInterface);
1310     if (error != JVMTI_ERROR_NONE) {
1311         EXIT_ERROR(error, "on checking for an interface");
1312     }
1313     return isInterface;
1314 }
1315 
1316 jvmtiError
1317 isFieldSynthetic(jclass clazz, jfieldID field, jboolean *psynthetic)
1318 {
1319     jvmtiError error;
1320 
1321     error = JVMTI_FUNC_PTR(gdata->jvmti,IsFieldSynthetic)
1322                 (gdata->jvmti, clazz, field, psynthetic);
1323     if ( error == JVMTI_ERROR_MUST_POSSESS_CAPABILITY ) {
1324         /* If the query is not supported, we assume it is not synthetic. */
1325         *psynthetic = JNI_FALSE;
1326         return JVMTI_ERROR_NONE;
1327     }
1328     return error;
1329 }
1330 
1331 jvmtiError
1332 isMethodSynthetic(jmethodID method, jboolean *psynthetic)
1333 {
1334     jvmtiError error;
1335 
1336     error = JVMTI_FUNC_PTR(gdata->jvmti,IsMethodSynthetic)
1337                 (gdata->jvmti, method, psynthetic);
1338     if ( error == JVMTI_ERROR_MUST_POSSESS_CAPABILITY ) {
1339         /* If the query is not supported, we assume it is not synthetic. */
1340         *psynthetic = JNI_FALSE;
1341         return JVMTI_ERROR_NONE;
1342     }
1343     return error;
1344 }
1345 
1346 jboolean
1347 isMethodNative(jmethodID method)
1348 {
1349     jboolean isNative = JNI_FALSE;
1350     jvmtiError error;
1351 
1352     error = JVMTI_FUNC_PTR(gdata->jvmti,IsMethodNative)
1353                 (gdata->jvmti, method, &isNative);
1354     if (error != JVMTI_ERROR_NONE) {
1355         EXIT_ERROR(error, "on checking for a native interface");
1356     }
1357     return isNative;
1358 }
1359 
1360 jboolean
1361 isSameObject(JNIEnv *env, jobject o1, jobject o2)
1362 {
1363     if ( o1==o2 ) {
1364         return JNI_TRUE;
1365     }
1366     return FUNC_PTR(env,IsSameObject)(env, o1, o2);
1367 }
1368 
1369 jint
1370 objectHashCode(jobject object)
1371 {
1372     jint hashCode = 0;
1373     jvmtiError error;
1374 
1375     if ( object!=NULL ) {
1376         error = JVMTI_FUNC_PTR(gdata->jvmti,GetObjectHashCode)
1377                     (gdata->jvmti, object, &hashCode);
1378         if (error != JVMTI_ERROR_NONE) {
1379             EXIT_ERROR(error, "on getting an object hash code");
1380         }
1381     }
1382     return hashCode;
1383 }
1384 
1385 /* Get all implemented interfaces (must be inside a WITH_LOCAL_REFS) */
1386 jvmtiError
1387 allInterfaces(jclass clazz, jclass **ppinterfaces, jint *pcount)
1388 {
1389     jvmtiError error;
1390 
1391     *pcount = 0;
1392     *ppinterfaces = NULL;
1393     error = JVMTI_FUNC_PTR(gdata->jvmti,GetImplementedInterfaces)
1394                 (gdata->jvmti, clazz, pcount, ppinterfaces);
1395     return error;
1396 }
1397 
1398 /* Get all loaded classes (must be inside a WITH_LOCAL_REFS) */
1399 jvmtiError
1400 allLoadedClasses(jclass **ppclasses, jint *pcount)
1401 {
1402     jvmtiError error;
1403 
1404     *pcount = 0;
1405     *ppclasses = NULL;
1406     error = JVMTI_FUNC_PTR(gdata->jvmti,GetLoadedClasses)
1407                 (gdata->jvmti, pcount, ppclasses);
1408     return error;
1409 }
1410 
1411 /* Get all loaded classes for a loader (must be inside a WITH_LOCAL_REFS) */
1412 jvmtiError
1413 allClassLoaderClasses(jobject loader, jclass **ppclasses, jint *pcount)
1414 {
1415     jvmtiError error;
1416 
1417     *pcount = 0;
1418     *ppclasses = NULL;
1419     error = JVMTI_FUNC_PTR(gdata->jvmti,GetClassLoaderClasses)
1420                 (gdata->jvmti, loader, pcount, ppclasses);
1421     return error;
1422 }
1423 
1424 static jboolean
1425 is_a_nested_class(char *outer_sig, int outer_sig_len, char *sig, int sep)
1426 {
1427     char *inner;
1428 
1429     /* Assumed outer class signature is  "LOUTERCLASSNAME;"
1430      *         inner class signature is  "LOUTERCLASSNAME$INNERNAME;"
1431      *
1432      * INNERNAME can take the form:
1433      *    [0-9][1-9]*        anonymous class somewhere in the file
1434      *    [0-9][1-9]*NAME    local class somewhere in the OUTER class
1435      *    NAME               nested class in OUTER
1436      *
1437      * If NAME itself contains a $ (sep) then classname is further nested
1438      *    inside another class.
1439      *
1440      */
1441 
1442     /* Check prefix first */
1443     if ( strncmp(sig, outer_sig, outer_sig_len-1) != 0 ) {
1444         return JNI_FALSE;
1445     }
1446 
1447     /* Prefix must be followed by a $ (sep) */
1448     if ( sig[outer_sig_len-1] != sep ) {
1449         return JNI_FALSE;  /* No sep follows the match, must not be nested. */
1450     }
1451 
1452     /* Walk past any digits, if we reach the end, must be pure anonymous */
1453     inner = sig + outer_sig_len;
1454 #if 1 /* We want to return local classes */
1455     while ( *inner && isdigit(*inner) ) {
1456         inner++;
1457     }
1458     /* But anonymous class names can't be trusted. */
1459     if ( *inner == ';' ) {
1460         return JNI_FALSE;  /* A pure anonymous class */
1461     }
1462 #else
1463     if ( *inner && isdigit(*inner) ) {
1464         return JNI_FALSE;  /* A pure anonymous or local class */
1465     }
1466 #endif
1467 
1468     /* Nested deeper? */
1469     if ( strchr(inner, sep) != NULL ) {
1470         return JNI_FALSE;  /* Nested deeper than we want? */
1471     }
1472     return JNI_TRUE;
1473 }
1474 
1475 /* Get all nested classes for a class (must be inside a WITH_LOCAL_REFS) */
1476 jvmtiError
1477 allNestedClasses(jclass parent_clazz, jclass **ppnested, jint *pcount)
1478 {
1479     jvmtiError error;
1480     jobject parent_loader;
1481     jclass *classes;
1482     char *signature;
1483     size_t len;
1484     jint count;
1485     jint ncount;
1486     int i;
1487 
1488     *ppnested   = NULL;
1489     *pcount     = 0;
1490 
1491     parent_loader = NULL;
1492     classes       = NULL;
1493     signature     = NULL;
1494     count         = 0;
1495     ncount        = 0;
1496 
1497     error = classLoader(parent_clazz, &parent_loader);
1498     if (error != JVMTI_ERROR_NONE) {
1499         return error;
1500     }
1501     error = classSignature(parent_clazz, &signature, NULL);
1502     if (error != JVMTI_ERROR_NONE) {
1503         return error;
1504     }
1505     len = strlen(signature);
1506 
1507     error = allClassLoaderClasses(parent_loader, &classes, &count);
1508     if ( error != JVMTI_ERROR_NONE ) {
1509         jvmtiDeallocate(signature);
1510         return error;
1511     }
1512 
1513     for (i=0; i<count; i++) {
1514         jclass clazz;
1515         char *candidate_signature;
1516 
1517         clazz = classes[i];
1518         candidate_signature = NULL;
1519         error = classSignature(clazz, &candidate_signature, NULL);
1520         if (error != JVMTI_ERROR_NONE) {
1521             break;
1522         }
1523 
1524         if ( is_a_nested_class(signature, (int)len, candidate_signature, '$') ||
1525              is_a_nested_class(signature, (int)len, candidate_signature, '#') ) {
1526             /* Float nested classes to top */
1527             classes[i] = classes[ncount];
1528             classes[ncount++] = clazz;
1529         }
1530         jvmtiDeallocate(candidate_signature);
1531     }
1532 
1533     jvmtiDeallocate(signature);
1534 
1535     if ( count != 0 &&  ncount == 0 ) {
1536         jvmtiDeallocate(classes);
1537         classes = NULL;
1538     }
1539 
1540     *ppnested = classes;
1541     *pcount = ncount;
1542     return error;
1543 }
1544 
1545 void
1546 createLocalRefSpace(JNIEnv *env, jint capacity)
1547 {
1548     /*
1549      * Save current exception since it might get overwritten by
1550      * the calls below. Note we must depend on space in the existing
1551      * frame because asking for a new frame may generate an exception.
1552      */
1553     jobject throwable = JNI_FUNC_PTR(env,ExceptionOccurred)(env);
1554 
1555     /*
1556      * Use the current frame if necessary; otherwise create a new one
1557      */
1558     if (JNI_FUNC_PTR(env,PushLocalFrame)(env, capacity) < 0) {
1559         EXIT_ERROR(AGENT_ERROR_OUT_OF_MEMORY,"PushLocalFrame: Unable to push JNI frame");
1560     }
1561 
1562     /*
1563      * TO DO: This could be more efficient if it used EnsureLocalCapacity,
1564      * but that would not work if two functions on the call stack
1565      * use this function. We would need to either track reserved
1566      * references on a per-thread basis or come up with a convention
1567      * that would prevent two functions from depending on this function
1568      * at the same time.
1569      */
1570 
1571     /*
1572      * Restore exception state from before call
1573      */
1574     if (throwable != NULL) {
1575         JNI_FUNC_PTR(env,Throw)(env, throwable);
1576     } else {
1577         JNI_FUNC_PTR(env,ExceptionClear)(env);
1578     }
1579 }
1580 
1581 jboolean
1582 isClass(jobject object)
1583 {
1584     JNIEnv *env = getEnv();
1585     return JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->classClass);
1586 }
1587 
1588 jboolean
1589 isThread(jobject object)
1590 {
1591     JNIEnv *env = getEnv();
1592     return JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->threadClass);
1593 }
1594 
1595 jboolean
1596 isThreadGroup(jobject object)
1597 {
1598     JNIEnv *env = getEnv();
1599     return JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->threadGroupClass);
1600 }
1601 
1602 jboolean
1603 isString(jobject object)
1604 {
1605     JNIEnv *env = getEnv();
1606     return JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->stringClass);
1607 }
1608 
1609 jboolean
1610 isClassLoader(jobject object)
1611 {
1612     JNIEnv *env = getEnv();
1613     return JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->classLoaderClass);
1614 }
1615 
1616 jboolean
1617 isArray(jobject object)
1618 {
1619     JNIEnv *env = getEnv();
1620     jboolean is;
1621 
1622     WITH_LOCAL_REFS(env, 1) {
1623         jclass clazz;
1624         clazz = JNI_FUNC_PTR(env,GetObjectClass)(env, object);
1625         is = isArrayClass(clazz);
1626     } END_WITH_LOCAL_REFS(env);
1627 
1628     return is;
1629 }
1630 
1631 /**
1632  * Return property value as jstring
1633  */
1634 static jstring
1635 getPropertyValue(JNIEnv *env, char *propertyName)
1636 {
1637     jstring valueString;
1638     jstring nameString;
1639 
1640     valueString = NULL;
1641 
1642     /* Create new String object to hold the property name */
1643     nameString = JNI_FUNC_PTR(env,NewStringUTF)(env, propertyName);
1644     if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
1645         JNI_FUNC_PTR(env,ExceptionClear)(env);
1646         /* NULL will be returned below */
1647     } else {
1648         /* Call valueString = System.getProperty(nameString) */
1649         valueString = JNI_FUNC_PTR(env,CallStaticObjectMethod)
1650             (env, gdata->systemClass, gdata->systemGetProperty, nameString);
1651         if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
1652             JNI_FUNC_PTR(env,ExceptionClear)(env);
1653             valueString = NULL;
1654         }
1655     }
1656     return valueString;
1657 }
1658 
1659 /**
1660  * Set an agent property
1661  */
1662 void
1663 setAgentPropertyValue(JNIEnv *env, char *propertyName, char* propertyValue)
1664 {
1665     jstring nameString;
1666     jstring valueString;
1667 
1668     if (gdata->agent_properties == NULL) {
1669         /* VMSupport doesn't exist; so ignore */
1670         return;
1671     }
1672 
1673     /* Create jstrings for property name and value */
1674     nameString = JNI_FUNC_PTR(env,NewStringUTF)(env, propertyName);
1675     if (nameString != NULL) {
1676         valueString = JNI_FUNC_PTR(env,NewStringUTF)(env, propertyValue);
1677         if (valueString != NULL) {
1678             /* invoke Properties.setProperty */
1679             JNI_FUNC_PTR(env,CallObjectMethod)
1680                 (env, gdata->agent_properties,
1681                  gdata->setProperty,
1682                  nameString, valueString);
1683         }
1684     }
1685     if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
1686         JNI_FUNC_PTR(env,ExceptionClear)(env);
1687     }
1688 }
1689 
1690 /**
1691  * Return property value as JDWP allocated string in UTF8 encoding
1692  */
1693 static char *
1694 getPropertyUTF8(JNIEnv *env, char *propertyName)
1695 {
1696     jvmtiError  error;
1697     char       *value;
1698 
1699     value = NULL;
1700     error = JVMTI_FUNC_PTR(gdata->jvmti,GetSystemProperty)
1701                 (gdata->jvmti, (const char *)propertyName, &value);
1702     if (error != JVMTI_ERROR_NONE) {
1703         jstring valueString;
1704 
1705         value = NULL;
1706         valueString = getPropertyValue(env, propertyName);
1707 
1708         if (valueString != NULL) {
1709             const char *utf;
1710 
1711             /* Get the UTF8 encoding for this property value string */
1712             utf = JNI_FUNC_PTR(env,GetStringUTFChars)(env, valueString, NULL);
1713             /* Make a copy for returning, release the JNI copy */
1714             value = jvmtiAllocate((int)strlen(utf) + 1);
1715             if (value != NULL) {
1716                 (void)strcpy(value, utf);
1717             }
1718             JNI_FUNC_PTR(env,ReleaseStringUTFChars)(env, valueString, utf);
1719         }
1720     }
1721     if ( value == NULL ) {
1722         ERROR_MESSAGE(("JDWP Can't get property value for %s", propertyName));
1723         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
1724     }
1725     return value;
1726 }
1727 
1728 jboolean
1729 isMethodObsolete(jmethodID method)
1730 {
1731     jvmtiError error;
1732     jboolean obsolete = JNI_TRUE;
1733 
1734     if ( method != NULL ) {
1735         error = JVMTI_FUNC_PTR(gdata->jvmti,IsMethodObsolete)
1736                     (gdata->jvmti, method, &obsolete);
1737         if (error != JVMTI_ERROR_NONE) {
1738             obsolete = JNI_TRUE;
1739         }
1740     }
1741     return obsolete;
1742 }
1743 
1744 /* Get the jvmti environment to be used with tags */
1745 static jvmtiEnv *
1746 getSpecialJvmti(void)
1747 {
1748     jvmtiEnv  *jvmti;
1749     jvmtiError error;
1750     int        rc;
1751 
1752     /* Get one time use JVMTI Env */
1753     jvmtiCapabilities caps;
1754 
1755     rc = JVM_FUNC_PTR(gdata->jvm,GetEnv)
1756                      (gdata->jvm, (void **)&jvmti, JVMTI_VERSION_1);
1757     if (rc != JNI_OK) {
1758         return NULL;
1759     }
1760     (void)memset(&caps, 0, (int)sizeof(caps));
1761     caps.can_tag_objects = 1;
1762     error = JVMTI_FUNC_PTR(jvmti,AddCapabilities)(jvmti, &caps);
1763     if ( error != JVMTI_ERROR_NONE ) {
1764         return NULL;
1765     }
1766     return jvmti;
1767 }
1768 
1769 void
1770 writeCodeLocation(PacketOutputStream *out, jclass clazz,
1771                        jmethodID method, jlocation location)
1772 {
1773     jbyte tag;
1774 
1775     if (clazz != NULL) {
1776         tag = referenceTypeTag(clazz);
1777     } else {
1778         tag = JDWP_TYPE_TAG(CLASS);
1779     }
1780     (void)outStream_writeByte(out, tag);
1781     (void)outStream_writeObjectRef(getEnv(), out, clazz);
1782     (void)outStream_writeMethodID(out, isMethodObsolete(method)?NULL:method);
1783     (void)outStream_writeLocation(out, location);
1784 }
1785 
1786 void *
1787 jvmtiAllocate(jint numBytes)
1788 {
1789     void *ptr;
1790     jvmtiError error;
1791 
1792     if (gdata->vmDead) {
1793       EXIT_ERROR(AGENT_ERROR_INTERNAL,"Attempt to allocate after VM death");
1794     }
1795 
1796     if ( numBytes == 0 ) {
1797         return NULL;
1798     }
1799     error = FUNC_PTR(gdata->jvmti,Allocate)
1800                 (gdata->jvmti, numBytes, (unsigned char**)&ptr);
1801     if (error != JVMTI_ERROR_NONE ) {
1802         EXIT_ERROR(error, "Can't allocate jvmti memory");
1803     }
1804     return ptr;
1805 }
1806 
1807 void
1808 jvmtiDeallocate(void *ptr)
1809 {
1810     jvmtiError error;
1811     if ( ptr == NULL ) {
1812         return;
1813     }
1814     error = FUNC_PTR(gdata->jvmti,Deallocate)
1815                 (gdata->jvmti, ptr);
1816     if (error != JVMTI_ERROR_NONE ) {
1817         EXIT_ERROR(error, "Can't deallocate jvmti memory");
1818     }
1819 }
1820 
1821 /* Rarely needed, transport library uses JDWP errors, only use? */
1822 jvmtiError
1823 map2jvmtiError(jdwpError error)
1824 {
1825     switch ( error ) {
1826         case JDWP_ERROR(NONE):
1827             return JVMTI_ERROR_NONE;
1828         case JDWP_ERROR(INVALID_THREAD):
1829             return JVMTI_ERROR_INVALID_THREAD;
1830         case JDWP_ERROR(INVALID_THREAD_GROUP):
1831             return JVMTI_ERROR_INVALID_THREAD_GROUP;
1832         case JDWP_ERROR(INVALID_PRIORITY):
1833             return JVMTI_ERROR_INVALID_PRIORITY;
1834         case JDWP_ERROR(THREAD_NOT_SUSPENDED):
1835             return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1836         case JDWP_ERROR(THREAD_SUSPENDED):
1837             return JVMTI_ERROR_THREAD_SUSPENDED;
1838         case JDWP_ERROR(INVALID_OBJECT):
1839             return JVMTI_ERROR_INVALID_OBJECT;
1840         case JDWP_ERROR(INVALID_CLASS):
1841             return JVMTI_ERROR_INVALID_CLASS;
1842         case JDWP_ERROR(CLASS_NOT_PREPARED):
1843             return JVMTI_ERROR_CLASS_NOT_PREPARED;
1844         case JDWP_ERROR(INVALID_METHODID):
1845             return JVMTI_ERROR_INVALID_METHODID;
1846         case JDWP_ERROR(INVALID_LOCATION):
1847             return JVMTI_ERROR_INVALID_LOCATION;
1848         case JDWP_ERROR(INVALID_FIELDID):
1849             return JVMTI_ERROR_INVALID_FIELDID;
1850         case JDWP_ERROR(INVALID_FRAMEID):
1851             return AGENT_ERROR_INVALID_FRAMEID;
1852         case JDWP_ERROR(NO_MORE_FRAMES):
1853             return JVMTI_ERROR_NO_MORE_FRAMES;
1854         case JDWP_ERROR(OPAQUE_FRAME):
1855             return JVMTI_ERROR_OPAQUE_FRAME;
1856         case JDWP_ERROR(NOT_CURRENT_FRAME):
1857             return AGENT_ERROR_NOT_CURRENT_FRAME;
1858         case JDWP_ERROR(TYPE_MISMATCH):
1859             return JVMTI_ERROR_TYPE_MISMATCH;
1860         case JDWP_ERROR(INVALID_SLOT):
1861             return JVMTI_ERROR_INVALID_SLOT;
1862         case JDWP_ERROR(DUPLICATE):
1863             return JVMTI_ERROR_DUPLICATE;
1864         case JDWP_ERROR(NOT_FOUND):
1865             return JVMTI_ERROR_NOT_FOUND;
1866         case JDWP_ERROR(INVALID_MONITOR):
1867             return JVMTI_ERROR_INVALID_MONITOR;
1868         case JDWP_ERROR(NOT_MONITOR_OWNER):
1869             return JVMTI_ERROR_NOT_MONITOR_OWNER;
1870         case JDWP_ERROR(INTERRUPT):
1871             return JVMTI_ERROR_INTERRUPT;
1872         case JDWP_ERROR(INVALID_CLASS_FORMAT):
1873             return JVMTI_ERROR_INVALID_CLASS_FORMAT;
1874         case JDWP_ERROR(CIRCULAR_CLASS_DEFINITION):
1875             return JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION;
1876         case JDWP_ERROR(FAILS_VERIFICATION):
1877             return JVMTI_ERROR_FAILS_VERIFICATION;
1878         case JDWP_ERROR(ADD_METHOD_NOT_IMPLEMENTED):
1879             return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED;
1880         case JDWP_ERROR(SCHEMA_CHANGE_NOT_IMPLEMENTED):
1881             return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;
1882         case JDWP_ERROR(INVALID_TYPESTATE):
1883             return JVMTI_ERROR_INVALID_TYPESTATE;
1884         case JDWP_ERROR(HIERARCHY_CHANGE_NOT_IMPLEMENTED):
1885             return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;
1886         case JDWP_ERROR(DELETE_METHOD_NOT_IMPLEMENTED):
1887             return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED;
1888         case JDWP_ERROR(UNSUPPORTED_VERSION):
1889             return JVMTI_ERROR_UNSUPPORTED_VERSION;
1890         case JDWP_ERROR(NAMES_DONT_MATCH):
1891             return JVMTI_ERROR_NAMES_DONT_MATCH;
1892         case JDWP_ERROR(CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED):
1893             return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED;
1894         case JDWP_ERROR(METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED):
1895             return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED;
1896         case JDWP_ERROR(NOT_IMPLEMENTED):
1897             return JVMTI_ERROR_NOT_AVAILABLE;
1898         case JDWP_ERROR(NULL_POINTER):
1899             return JVMTI_ERROR_NULL_POINTER;
1900         case JDWP_ERROR(ABSENT_INFORMATION):
1901             return JVMTI_ERROR_ABSENT_INFORMATION;
1902         case JDWP_ERROR(INVALID_EVENT_TYPE):
1903             return JVMTI_ERROR_INVALID_EVENT_TYPE;
1904         case JDWP_ERROR(ILLEGAL_ARGUMENT):
1905             return JVMTI_ERROR_ILLEGAL_ARGUMENT;
1906         case JDWP_ERROR(OUT_OF_MEMORY):
1907             return JVMTI_ERROR_OUT_OF_MEMORY;
1908         case JDWP_ERROR(ACCESS_DENIED):
1909             return JVMTI_ERROR_ACCESS_DENIED;
1910         case JDWP_ERROR(VM_DEAD):
1911             return JVMTI_ERROR_WRONG_PHASE;
1912         case JDWP_ERROR(UNATTACHED_THREAD):
1913             return JVMTI_ERROR_UNATTACHED_THREAD;
1914         case JDWP_ERROR(INVALID_TAG):
1915             return AGENT_ERROR_INVALID_TAG;
1916         case JDWP_ERROR(ALREADY_INVOKING):
1917             return AGENT_ERROR_ALREADY_INVOKING;
1918         case JDWP_ERROR(INVALID_INDEX):
1919             return AGENT_ERROR_INVALID_INDEX;
1920         case JDWP_ERROR(INVALID_LENGTH):
1921             return AGENT_ERROR_INVALID_LENGTH;
1922         case JDWP_ERROR(INVALID_STRING):
1923             return AGENT_ERROR_INVALID_STRING;
1924         case JDWP_ERROR(INVALID_CLASS_LOADER):
1925             return AGENT_ERROR_INVALID_CLASS_LOADER;
1926         case JDWP_ERROR(INVALID_ARRAY):
1927             return AGENT_ERROR_INVALID_ARRAY;
1928         case JDWP_ERROR(TRANSPORT_LOAD):
1929             return AGENT_ERROR_TRANSPORT_LOAD;
1930         case JDWP_ERROR(TRANSPORT_INIT):
1931             return AGENT_ERROR_TRANSPORT_INIT;
1932         case JDWP_ERROR(NATIVE_METHOD):
1933             return AGENT_ERROR_NATIVE_METHOD;
1934         case JDWP_ERROR(INVALID_COUNT):
1935             return AGENT_ERROR_INVALID_COUNT;
1936         case JDWP_ERROR(INTERNAL):
1937             return AGENT_ERROR_JDWP_INTERNAL;
1938     }
1939     return AGENT_ERROR_INTERNAL;
1940 }
1941 
1942 static jvmtiEvent index2jvmti[EI_max-EI_min+1];
1943 static jdwpEvent  index2jdwp [EI_max-EI_min+1];
1944 
1945 void
1946 eventIndexInit(void)
1947 {
1948     (void)memset(index2jvmti, 0, (int)sizeof(index2jvmti));
1949     (void)memset(index2jdwp,  0, (int)sizeof(index2jdwp));
1950 
1951     index2jvmti[EI_SINGLE_STEP        -EI_min] = JVMTI_EVENT_SINGLE_STEP;
1952     index2jvmti[EI_BREAKPOINT         -EI_min] = JVMTI_EVENT_BREAKPOINT;
1953     index2jvmti[EI_FRAME_POP          -EI_min] = JVMTI_EVENT_FRAME_POP;
1954     index2jvmti[EI_EXCEPTION          -EI_min] = JVMTI_EVENT_EXCEPTION;
1955     index2jvmti[EI_THREAD_START       -EI_min] = JVMTI_EVENT_THREAD_START;
1956     index2jvmti[EI_THREAD_END         -EI_min] = JVMTI_EVENT_THREAD_END;
1957     index2jvmti[EI_CLASS_PREPARE      -EI_min] = JVMTI_EVENT_CLASS_PREPARE;
1958     index2jvmti[EI_GC_FINISH          -EI_min] = JVMTI_EVENT_GARBAGE_COLLECTION_FINISH;
1959     index2jvmti[EI_CLASS_LOAD         -EI_min] = JVMTI_EVENT_CLASS_LOAD;
1960     index2jvmti[EI_FIELD_ACCESS       -EI_min] = JVMTI_EVENT_FIELD_ACCESS;
1961     index2jvmti[EI_FIELD_MODIFICATION -EI_min] = JVMTI_EVENT_FIELD_MODIFICATION;
1962     index2jvmti[EI_EXCEPTION_CATCH    -EI_min] = JVMTI_EVENT_EXCEPTION_CATCH;
1963     index2jvmti[EI_METHOD_ENTRY       -EI_min] = JVMTI_EVENT_METHOD_ENTRY;
1964     index2jvmti[EI_METHOD_EXIT        -EI_min] = JVMTI_EVENT_METHOD_EXIT;
1965     index2jvmti[EI_MONITOR_CONTENDED_ENTER      -EI_min] = JVMTI_EVENT_MONITOR_CONTENDED_ENTER;
1966     index2jvmti[EI_MONITOR_CONTENDED_ENTERED    -EI_min] = JVMTI_EVENT_MONITOR_CONTENDED_ENTERED;
1967     index2jvmti[EI_MONITOR_WAIT       -EI_min] = JVMTI_EVENT_MONITOR_WAIT;
1968     index2jvmti[EI_MONITOR_WAITED     -EI_min] = JVMTI_EVENT_MONITOR_WAITED;
1969     index2jvmti[EI_VM_INIT            -EI_min] = JVMTI_EVENT_VM_INIT;
1970     index2jvmti[EI_VM_DEATH           -EI_min] = JVMTI_EVENT_VM_DEATH;
1971 
1972     index2jdwp[EI_SINGLE_STEP         -EI_min] = JDWP_EVENT(SINGLE_STEP);
1973     index2jdwp[EI_BREAKPOINT          -EI_min] = JDWP_EVENT(BREAKPOINT);
1974     index2jdwp[EI_FRAME_POP           -EI_min] = JDWP_EVENT(FRAME_POP);
1975     index2jdwp[EI_EXCEPTION           -EI_min] = JDWP_EVENT(EXCEPTION);
1976     index2jdwp[EI_THREAD_START        -EI_min] = JDWP_EVENT(THREAD_START);
1977     index2jdwp[EI_THREAD_END          -EI_min] = JDWP_EVENT(THREAD_END);
1978     index2jdwp[EI_CLASS_PREPARE       -EI_min] = JDWP_EVENT(CLASS_PREPARE);
1979     index2jdwp[EI_GC_FINISH           -EI_min] = JDWP_EVENT(CLASS_UNLOAD);
1980     index2jdwp[EI_CLASS_LOAD          -EI_min] = JDWP_EVENT(CLASS_LOAD);
1981     index2jdwp[EI_FIELD_ACCESS        -EI_min] = JDWP_EVENT(FIELD_ACCESS);
1982     index2jdwp[EI_FIELD_MODIFICATION  -EI_min] = JDWP_EVENT(FIELD_MODIFICATION);
1983     index2jdwp[EI_EXCEPTION_CATCH     -EI_min] = JDWP_EVENT(EXCEPTION_CATCH);
1984     index2jdwp[EI_METHOD_ENTRY        -EI_min] = JDWP_EVENT(METHOD_ENTRY);
1985     index2jdwp[EI_METHOD_EXIT         -EI_min] = JDWP_EVENT(METHOD_EXIT);
1986     index2jdwp[EI_MONITOR_CONTENDED_ENTER             -EI_min] = JDWP_EVENT(MONITOR_CONTENDED_ENTER);
1987     index2jdwp[EI_MONITOR_CONTENDED_ENTERED           -EI_min] = JDWP_EVENT(MONITOR_CONTENDED_ENTERED);
1988     index2jdwp[EI_MONITOR_WAIT        -EI_min] = JDWP_EVENT(MONITOR_WAIT);
1989     index2jdwp[EI_MONITOR_WAITED      -EI_min] = JDWP_EVENT(MONITOR_WAITED);
1990     index2jdwp[EI_VM_INIT             -EI_min] = JDWP_EVENT(VM_INIT);
1991     index2jdwp[EI_VM_DEATH            -EI_min] = JDWP_EVENT(VM_DEATH);
1992 }
1993 
1994 jdwpEvent
1995 eventIndex2jdwp(EventIndex i)
1996 {
1997     if ( i < EI_min || i > EI_max ) {
1998         EXIT_ERROR(AGENT_ERROR_INVALID_INDEX,"bad EventIndex");
1999     }
2000     return index2jdwp[i-EI_min];
2001 }
2002 
2003 jvmtiEvent
2004 eventIndex2jvmti(EventIndex i)
2005 {
2006     if ( i < EI_min || i > EI_max ) {
2007         EXIT_ERROR(AGENT_ERROR_INVALID_INDEX,"bad EventIndex");
2008     }
2009     return index2jvmti[i-EI_min];
2010 }
2011 
2012 EventIndex
2013 jdwp2EventIndex(jdwpEvent eventType)
2014 {
2015     switch ( eventType ) {
2016         case JDWP_EVENT(SINGLE_STEP):
2017             return EI_SINGLE_STEP;
2018         case JDWP_EVENT(BREAKPOINT):
2019             return EI_BREAKPOINT;
2020         case JDWP_EVENT(FRAME_POP):
2021             return EI_FRAME_POP;
2022         case JDWP_EVENT(EXCEPTION):
2023             return EI_EXCEPTION;
2024         case JDWP_EVENT(THREAD_START):
2025             return EI_THREAD_START;
2026         case JDWP_EVENT(THREAD_END):
2027             return EI_THREAD_END;
2028         case JDWP_EVENT(CLASS_PREPARE):
2029             return EI_CLASS_PREPARE;
2030         case JDWP_EVENT(CLASS_UNLOAD):
2031             return EI_GC_FINISH;
2032         case JDWP_EVENT(CLASS_LOAD):
2033             return EI_CLASS_LOAD;
2034         case JDWP_EVENT(FIELD_ACCESS):
2035             return EI_FIELD_ACCESS;
2036         case JDWP_EVENT(FIELD_MODIFICATION):
2037             return EI_FIELD_MODIFICATION;
2038         case JDWP_EVENT(EXCEPTION_CATCH):
2039             return EI_EXCEPTION_CATCH;
2040         case JDWP_EVENT(METHOD_ENTRY):
2041             return EI_METHOD_ENTRY;
2042         case JDWP_EVENT(METHOD_EXIT):
2043             return EI_METHOD_EXIT;
2044         case JDWP_EVENT(METHOD_EXIT_WITH_RETURN_VALUE):
2045             return EI_METHOD_EXIT;
2046         case JDWP_EVENT(MONITOR_CONTENDED_ENTER):
2047             return EI_MONITOR_CONTENDED_ENTER;
2048         case JDWP_EVENT(MONITOR_CONTENDED_ENTERED):
2049             return EI_MONITOR_CONTENDED_ENTERED;
2050         case JDWP_EVENT(MONITOR_WAIT):
2051             return EI_MONITOR_WAIT;
2052         case JDWP_EVENT(MONITOR_WAITED):
2053             return EI_MONITOR_WAITED;
2054         case JDWP_EVENT(VM_INIT):
2055             return EI_VM_INIT;
2056         case JDWP_EVENT(VM_DEATH):
2057             return EI_VM_DEATH;
2058         default:
2059             break;
2060     }
2061 
2062     /*
2063      * Event type not recognized - don't exit with error as caller
2064      * may wish to return error to debugger.
2065      */
2066     return (EventIndex)0;
2067 }
2068 
2069 EventIndex
2070 jvmti2EventIndex(jvmtiEvent kind)
2071 {
2072     switch ( kind ) {
2073         case JVMTI_EVENT_SINGLE_STEP:
2074             return EI_SINGLE_STEP;
2075         case JVMTI_EVENT_BREAKPOINT:
2076             return EI_BREAKPOINT;
2077         case JVMTI_EVENT_FRAME_POP:
2078             return EI_FRAME_POP;
2079         case JVMTI_EVENT_EXCEPTION:
2080             return EI_EXCEPTION;
2081         case JVMTI_EVENT_THREAD_START:
2082             return EI_THREAD_START;
2083         case JVMTI_EVENT_THREAD_END:
2084             return EI_THREAD_END;
2085         case JVMTI_EVENT_CLASS_PREPARE:
2086             return EI_CLASS_PREPARE;
2087         case JVMTI_EVENT_GARBAGE_COLLECTION_FINISH:
2088             return EI_GC_FINISH;
2089         case JVMTI_EVENT_CLASS_LOAD:
2090             return EI_CLASS_LOAD;
2091         case JVMTI_EVENT_FIELD_ACCESS:
2092             return EI_FIELD_ACCESS;
2093         case JVMTI_EVENT_FIELD_MODIFICATION:
2094             return EI_FIELD_MODIFICATION;
2095         case JVMTI_EVENT_EXCEPTION_CATCH:
2096             return EI_EXCEPTION_CATCH;
2097         case JVMTI_EVENT_METHOD_ENTRY:
2098             return EI_METHOD_ENTRY;
2099         case JVMTI_EVENT_METHOD_EXIT:
2100             return EI_METHOD_EXIT;
2101         /*
2102          * There is no JVMTI_EVENT_METHOD_EXIT_WITH_RETURN_VALUE.
2103          * The normal JVMTI_EVENT_METHOD_EXIT always contains the return value.
2104          */
2105         case JVMTI_EVENT_MONITOR_CONTENDED_ENTER:
2106             return EI_MONITOR_CONTENDED_ENTER;
2107         case JVMTI_EVENT_MONITOR_CONTENDED_ENTERED:
2108             return EI_MONITOR_CONTENDED_ENTERED;
2109         case JVMTI_EVENT_MONITOR_WAIT:
2110             return EI_MONITOR_WAIT;
2111         case JVMTI_EVENT_MONITOR_WAITED:
2112             return EI_MONITOR_WAITED;
2113         case JVMTI_EVENT_VM_INIT:
2114             return EI_VM_INIT;
2115         case JVMTI_EVENT_VM_DEATH:
2116             return EI_VM_DEATH;
2117         default:
2118             EXIT_ERROR(AGENT_ERROR_INVALID_INDEX,"JVMTI to EventIndex mapping");
2119             break;
2120     }
2121     return (EventIndex)0;
2122 }
2123 
2124 /* This routine is commonly used, maps jvmti and agent errors to the best
2125  *    jdwp error code we can map to.
2126  */
2127 jdwpError
2128 map2jdwpError(jvmtiError error)
2129 {
2130     switch ( (int)error ) {
2131         case JVMTI_ERROR_NONE:
2132             return JDWP_ERROR(NONE);
2133         case AGENT_ERROR_INVALID_THREAD:
2134         case JVMTI_ERROR_INVALID_THREAD:
2135             return JDWP_ERROR(INVALID_THREAD);
2136         case JVMTI_ERROR_INVALID_THREAD_GROUP:
2137             return JDWP_ERROR(INVALID_THREAD_GROUP);
2138         case JVMTI_ERROR_INVALID_PRIORITY:
2139             return JDWP_ERROR(INVALID_PRIORITY);
2140         case JVMTI_ERROR_THREAD_NOT_SUSPENDED:
2141             return JDWP_ERROR(THREAD_NOT_SUSPENDED);
2142         case JVMTI_ERROR_THREAD_SUSPENDED:
2143             return JDWP_ERROR(THREAD_SUSPENDED);
2144         case JVMTI_ERROR_THREAD_NOT_ALIVE:
2145             return JDWP_ERROR(INVALID_THREAD);
2146         case AGENT_ERROR_INVALID_OBJECT:
2147         case JVMTI_ERROR_INVALID_OBJECT:
2148             return JDWP_ERROR(INVALID_OBJECT);
2149         case JVMTI_ERROR_INVALID_CLASS:
2150             return JDWP_ERROR(INVALID_CLASS);
2151         case JVMTI_ERROR_CLASS_NOT_PREPARED:
2152             return JDWP_ERROR(CLASS_NOT_PREPARED);
2153         case JVMTI_ERROR_INVALID_METHODID:
2154             return JDWP_ERROR(INVALID_METHODID);
2155         case JVMTI_ERROR_INVALID_LOCATION:
2156             return JDWP_ERROR(INVALID_LOCATION);
2157         case JVMTI_ERROR_INVALID_FIELDID:
2158             return JDWP_ERROR(INVALID_FIELDID);
2159         case AGENT_ERROR_NO_MORE_FRAMES:
2160         case JVMTI_ERROR_NO_MORE_FRAMES:
2161             return JDWP_ERROR(NO_MORE_FRAMES);
2162         case JVMTI_ERROR_OPAQUE_FRAME:
2163             return JDWP_ERROR(OPAQUE_FRAME);
2164         case JVMTI_ERROR_TYPE_MISMATCH:
2165             return JDWP_ERROR(TYPE_MISMATCH);
2166         case JVMTI_ERROR_INVALID_SLOT:
2167             return JDWP_ERROR(INVALID_SLOT);
2168         case JVMTI_ERROR_DUPLICATE:
2169             return JDWP_ERROR(DUPLICATE);
2170         case JVMTI_ERROR_NOT_FOUND:
2171             return JDWP_ERROR(NOT_FOUND);
2172         case JVMTI_ERROR_INVALID_MONITOR:
2173             return JDWP_ERROR(INVALID_MONITOR);
2174         case JVMTI_ERROR_NOT_MONITOR_OWNER:
2175             return JDWP_ERROR(NOT_MONITOR_OWNER);
2176         case JVMTI_ERROR_INTERRUPT:
2177             return JDWP_ERROR(INTERRUPT);
2178         case JVMTI_ERROR_INVALID_CLASS_FORMAT:
2179             return JDWP_ERROR(INVALID_CLASS_FORMAT);
2180         case JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION:
2181             return JDWP_ERROR(CIRCULAR_CLASS_DEFINITION);
2182         case JVMTI_ERROR_FAILS_VERIFICATION:
2183             return JDWP_ERROR(FAILS_VERIFICATION);
2184         case JVMTI_ERROR_INVALID_TYPESTATE:
2185             return JDWP_ERROR(INVALID_TYPESTATE);
2186         case JVMTI_ERROR_UNSUPPORTED_VERSION:
2187             return JDWP_ERROR(UNSUPPORTED_VERSION);
2188         case JVMTI_ERROR_NAMES_DONT_MATCH:
2189             return JDWP_ERROR(NAMES_DONT_MATCH);
2190         case AGENT_ERROR_NULL_POINTER:
2191         case JVMTI_ERROR_NULL_POINTER:
2192             return JDWP_ERROR(NULL_POINTER);
2193         case JVMTI_ERROR_ABSENT_INFORMATION:
2194             return JDWP_ERROR(ABSENT_INFORMATION);
2195         case AGENT_ERROR_INVALID_EVENT_TYPE:
2196         case JVMTI_ERROR_INVALID_EVENT_TYPE:
2197             return JDWP_ERROR(INVALID_EVENT_TYPE);
2198         case AGENT_ERROR_ILLEGAL_ARGUMENT:
2199         case JVMTI_ERROR_ILLEGAL_ARGUMENT:
2200             return JDWP_ERROR(ILLEGAL_ARGUMENT);
2201         case JVMTI_ERROR_OUT_OF_MEMORY:
2202         case AGENT_ERROR_OUT_OF_MEMORY:
2203             return JDWP_ERROR(OUT_OF_MEMORY);
2204         case JVMTI_ERROR_ACCESS_DENIED:
2205             return JDWP_ERROR(ACCESS_DENIED);
2206         case JVMTI_ERROR_WRONG_PHASE:
2207         case AGENT_ERROR_VM_DEAD:
2208         case AGENT_ERROR_NO_JNI_ENV:
2209             return JDWP_ERROR(VM_DEAD);
2210         case AGENT_ERROR_JNI_EXCEPTION:
2211         case JVMTI_ERROR_UNATTACHED_THREAD:
2212             return JDWP_ERROR(UNATTACHED_THREAD);
2213         case JVMTI_ERROR_NOT_AVAILABLE:
2214         case JVMTI_ERROR_MUST_POSSESS_CAPABILITY:
2215             return JDWP_ERROR(NOT_IMPLEMENTED);
2216         case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED:
2217             return JDWP_ERROR(HIERARCHY_CHANGE_NOT_IMPLEMENTED);
2218         case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED:
2219             return JDWP_ERROR(DELETE_METHOD_NOT_IMPLEMENTED);
2220         case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED:
2221             return JDWP_ERROR(ADD_METHOD_NOT_IMPLEMENTED);
2222         case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED:
2223             return JDWP_ERROR(SCHEMA_CHANGE_NOT_IMPLEMENTED);
2224         case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED:
2225             return JDWP_ERROR(CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED);
2226         case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED:
2227             return JDWP_ERROR(METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED);
2228         case AGENT_ERROR_NOT_CURRENT_FRAME:
2229             return JDWP_ERROR(NOT_CURRENT_FRAME);
2230         case AGENT_ERROR_INVALID_TAG:
2231             return JDWP_ERROR(INVALID_TAG);
2232         case AGENT_ERROR_ALREADY_INVOKING:
2233             return JDWP_ERROR(ALREADY_INVOKING);
2234         case AGENT_ERROR_INVALID_INDEX:
2235             return JDWP_ERROR(INVALID_INDEX);
2236         case AGENT_ERROR_INVALID_LENGTH:
2237             return JDWP_ERROR(INVALID_LENGTH);
2238         case AGENT_ERROR_INVALID_STRING:
2239             return JDWP_ERROR(INVALID_STRING);
2240         case AGENT_ERROR_INVALID_CLASS_LOADER:
2241             return JDWP_ERROR(INVALID_CLASS_LOADER);
2242         case AGENT_ERROR_INVALID_ARRAY:
2243             return JDWP_ERROR(INVALID_ARRAY);
2244         case AGENT_ERROR_TRANSPORT_LOAD:
2245             return JDWP_ERROR(TRANSPORT_LOAD);
2246         case AGENT_ERROR_TRANSPORT_INIT:
2247             return JDWP_ERROR(TRANSPORT_INIT);
2248         case AGENT_ERROR_NATIVE_METHOD:
2249             return JDWP_ERROR(NATIVE_METHOD);
2250         case AGENT_ERROR_INVALID_COUNT:
2251             return JDWP_ERROR(INVALID_COUNT);
2252         case AGENT_ERROR_INVALID_FRAMEID:
2253             return JDWP_ERROR(INVALID_FRAMEID);
2254         case JVMTI_ERROR_INTERNAL:
2255         case JVMTI_ERROR_INVALID_ENVIRONMENT:
2256         case AGENT_ERROR_INTERNAL:
2257         case AGENT_ERROR_JVMTI_INTERNAL:
2258         case AGENT_ERROR_JDWP_INTERNAL:
2259             return JDWP_ERROR(INTERNAL);
2260         default:
2261             break;
2262     }
2263     return JDWP_ERROR(INTERNAL);
2264 }
2265 
2266 jint
2267 map2jdwpSuspendStatus(jint state)
2268 {
2269     jint status = 0;
2270     if ( ( state & JVMTI_THREAD_STATE_SUSPENDED ) != 0 )  {
2271         status = JDWP_SUSPEND_STATUS(SUSPENDED);
2272     }
2273     return status;
2274 }
2275 
2276 jdwpThreadStatus
2277 map2jdwpThreadStatus(jint state)
2278 {
2279     jdwpThreadStatus status;
2280 
2281     status = (jdwpThreadStatus)(-1);
2282 
2283     if ( ! ( state & JVMTI_THREAD_STATE_ALIVE ) ) {
2284         if ( state & JVMTI_THREAD_STATE_TERMINATED ) {
2285             status = JDWP_THREAD_STATUS(ZOMBIE);
2286         } else {
2287             /* FIXUP? New JDWP #define for not started? */
2288             status = (jdwpThreadStatus)(-1);
2289         }
2290     } else {
2291         if ( state & JVMTI_THREAD_STATE_SLEEPING ) {
2292             status = JDWP_THREAD_STATUS(SLEEPING);
2293         } else if ( state & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER ) {
2294             status = JDWP_THREAD_STATUS(MONITOR);
2295         } else if ( state & JVMTI_THREAD_STATE_WAITING ) {
2296             status = JDWP_THREAD_STATUS(WAIT);
2297         } else if ( state & JVMTI_THREAD_STATE_RUNNABLE ) {
2298             status = JDWP_THREAD_STATUS(RUNNING);
2299         }
2300     }
2301     return status;
2302 }
2303 
2304 jint
2305 map2jdwpClassStatus(jint classStatus)
2306 {
2307     jint status = 0;
2308     if ( ( classStatus & JVMTI_CLASS_STATUS_VERIFIED ) != 0 ) {
2309         status |= JDWP_CLASS_STATUS(VERIFIED);
2310     }
2311     if ( ( classStatus & JVMTI_CLASS_STATUS_PREPARED ) != 0 ) {
2312         status |= JDWP_CLASS_STATUS(PREPARED);
2313     }
2314     if ( ( classStatus & JVMTI_CLASS_STATUS_INITIALIZED ) != 0 ) {
2315         status |= JDWP_CLASS_STATUS(INITIALIZED);
2316     }
2317     if ( ( classStatus & JVMTI_CLASS_STATUS_ERROR ) != 0 ) {
2318         status |= JDWP_CLASS_STATUS(ERROR);
2319     }
2320     return status;
2321 }
2322 
2323 void
2324 log_debugee_location(const char *func,
2325         jthread thread, jmethodID method, jlocation location)
2326 {
2327     int logging_locations = LOG_TEST(JDWP_LOG_LOC);
2328 
2329     if ( logging_locations ) {
2330         char *method_name;
2331         char *class_sig;
2332         jvmtiError error;
2333         jvmtiThreadInfo info;
2334         jint state;
2335 
2336         /* Get thread information */
2337         info.name = NULL;
2338         error = FUNC_PTR(gdata->jvmti,GetThreadInfo)
2339                                 (gdata->jvmti, thread, &info);
2340         if ( error != JVMTI_ERROR_NONE) {
2341             info.name = NULL;
2342         }
2343         error = FUNC_PTR(gdata->jvmti,GetThreadState)
2344                                 (gdata->jvmti, thread, &state);
2345         if ( error != JVMTI_ERROR_NONE) {
2346             state = 0;
2347         }
2348 
2349         /* Get method if necessary */
2350         if ( method==NULL ) {
2351             error = FUNC_PTR(gdata->jvmti,GetFrameLocation)
2352                         (gdata->jvmti, thread, 0, &method, &location);
2353             if ( error != JVMTI_ERROR_NONE ) {
2354                 method = NULL;
2355                 location = 0;
2356             }
2357         }
2358 
2359         /* Get method name */
2360         method_name = NULL;
2361         if ( method != NULL ) {
2362             error = methodSignature(method, &method_name, NULL, NULL);
2363             if ( error != JVMTI_ERROR_NONE ) {
2364                 method_name = NULL;
2365             }
2366         }
2367 
2368         /* Get class signature */
2369         class_sig = NULL;
2370         if ( method != NULL ) {
2371             jclass clazz;
2372 
2373             error = methodClass(method, &clazz);
2374             if ( error == JVMTI_ERROR_NONE ) {
2375                 error = classSignature(clazz, &class_sig, NULL);
2376                 if ( error != JVMTI_ERROR_NONE ) {
2377                     class_sig = NULL;
2378                 }
2379             }
2380         }
2381 
2382         /* Issue log message */
2383         LOG_LOC(("%s: debugee: thread=%p(%s:0x%x),method=%p(%s@%d;%s)",
2384                 func,
2385                 thread, info.name==NULL ? "?" : info.name, state,
2386                 method, method_name==NULL ? "?" : method_name,
2387                 (int)location, class_sig==NULL ? "?" : class_sig));
2388 
2389         /* Free memory */
2390         if ( class_sig != NULL ) {
2391             jvmtiDeallocate(class_sig);
2392         }
2393         if ( method_name != NULL ) {
2394             jvmtiDeallocate(method_name);
2395         }
2396         if ( info.name != NULL ) {
2397             jvmtiDeallocate(info.name);
2398         }
2399     }
2400 }
2401 
2402 /* ********************************************************************* */
2403 /* JDK 6.0: Use of new Heap Iteration functions */
2404 /* ********************************************************************* */
2405 
2406 /* ********************************************************************* */
2407 /* Instances */
2408 
2409 /* Structure to hold class instances heap iteration data (arg user_data) */
2410 typedef struct ClassInstancesData {
2411     jint         instCount;
2412     jint         maxInstances;
2413     jlong        objTag;
2414     jvmtiError   error;
2415 } ClassInstancesData;
2416 
2417 /* Callback for instance object tagging (heap_reference_callback). */
2418 static jint JNICALL
2419 cbObjectTagInstance(jvmtiHeapReferenceKind reference_kind,
2420      const jvmtiHeapReferenceInfo* reference_info, jlong class_tag,
2421      jlong referrer_class_tag, jlong size,
2422      jlong* tag_ptr, jlong* referrer_tag_ptr, jint length, void* user_data)
2423 {
2424     ClassInstancesData  *data;
2425 
2426     /* Check data structure */
2427     data = (ClassInstancesData*)user_data;
2428     if (data == NULL) {
2429         data->error = AGENT_ERROR_ILLEGAL_ARGUMENT;
2430         return JVMTI_VISIT_ABORT;
2431     }
2432 
2433     /* If we have tagged enough objects, just abort */
2434     if ( data->maxInstances != 0 && data->instCount >= data->maxInstances ) {
2435         return JVMTI_VISIT_ABORT;
2436     }
2437 
2438     /* If tagged already, just continue */
2439     if ( (*tag_ptr) != (jlong)0 ) {
2440         return JVMTI_VISIT_OBJECTS;
2441     }
2442 
2443     /* Tag the object so we don't count it again, and so we can retrieve it */
2444     (*tag_ptr) = data->objTag;
2445     data->instCount++;
2446     return JVMTI_VISIT_OBJECTS;
2447 }
2448 
2449 /* Get instances for one class */
2450 jvmtiError
2451 classInstances(jclass klass, ObjectBatch *instances, int maxInstances)
2452 {
2453     ClassInstancesData data;
2454     jvmtiHeapCallbacks heap_callbacks;
2455     jvmtiError         error;
2456     jvmtiEnv          *jvmti;
2457 
2458     /* Check interface assumptions */
2459 
2460     if (klass == NULL) {
2461         return AGENT_ERROR_INVALID_OBJECT;
2462     }
2463 
2464     if ( maxInstances < 0 || instances == NULL) {
2465         return AGENT_ERROR_ILLEGAL_ARGUMENT;
2466     }
2467 
2468     /* Initialize return information */
2469     instances->count   = 0;
2470     instances->objects = NULL;
2471 
2472     /* Get jvmti environment to use */
2473     jvmti = getSpecialJvmti();
2474     if ( jvmti == NULL ) {
2475         return AGENT_ERROR_INTERNAL;
2476     }
2477 
2478     /* Setup data to passed around the callbacks */
2479     data.instCount    = 0;
2480     data.maxInstances = maxInstances;
2481     data.objTag       = (jlong)1;
2482     data.error        = JVMTI_ERROR_NONE;
2483 
2484     /* Clear out callbacks structure */
2485     (void)memset(&heap_callbacks,0,sizeof(heap_callbacks));
2486 
2487     /* Set the callbacks we want */
2488     heap_callbacks.heap_reference_callback = &cbObjectTagInstance;
2489 
2490     /* Follow references, no initiating object, just this class, all objects */
2491     error = JVMTI_FUNC_PTR(jvmti,FollowReferences)
2492                  (jvmti, 0, klass, NULL, &heap_callbacks, &data);
2493     if ( error == JVMTI_ERROR_NONE ) {
2494         error = data.error;
2495     }
2496 
2497     /* Get all the instances now that they are tagged */
2498     if ( error == JVMTI_ERROR_NONE ) {
2499         error = JVMTI_FUNC_PTR(jvmti,GetObjectsWithTags)
2500                       (jvmti, 1, &(data.objTag), &(instances->count),
2501                        &(instances->objects), NULL);
2502         /* Verify we got the count we expected */
2503         if ( data.instCount != instances->count ) {
2504             error = AGENT_ERROR_INTERNAL;
2505         }
2506     }
2507 
2508     /* Dispose of any special jvmti environment */
2509     (void)JVMTI_FUNC_PTR(jvmti,DisposeEnvironment)(jvmti);
2510     return error;
2511 }
2512 
2513 /* ********************************************************************* */
2514 /* Instance counts. */
2515 
2516 /* Macros to convert a class or instance tag to an index and back again */
2517 #define INDEX2CLASSTAG(i)      ((jlong)((i)+1))
2518 #define CLASSTAG2INDEX(t)      (((int)(t))-1)
2519 #define JLONG_ABS(x)           (((x)<(jlong)0)?-(x):(x))
2520 
2521 /* Structure to hold class count heap traversal data (arg user_data) */
2522 typedef struct ClassCountData {
2523     int          classCount;
2524     jlong       *counts;
2525     jlong        negObjTag;
2526     jvmtiError   error;
2527 } ClassCountData;
2528 
2529 /* Two different cbObjectCounter's, one for FollowReferences, one for
2530  *    IterateThroughHeap. Pick a card, any card.
2531  */
2532 
2533 /* Callback for object count heap traversal (heap_reference_callback) */
2534 static jint JNICALL
2535 cbObjectCounterFromRef(jvmtiHeapReferenceKind reference_kind,
2536      const jvmtiHeapReferenceInfo* reference_info, jlong class_tag,
2537      jlong referrer_class_tag, jlong size,
2538      jlong* tag_ptr, jlong* referrer_tag_ptr, jint length, void* user_data)
2539 {
2540     ClassCountData  *data;
2541     int              index;
2542     jlong            jindex;
2543     jlong            tag;
2544 
2545     /* Check data structure */
2546     data = (ClassCountData*)user_data;
2547     if (data == NULL) {
2548         data->error = AGENT_ERROR_ILLEGAL_ARGUMENT;
2549         return JVMTI_VISIT_ABORT;
2550     }
2551 
2552     /* Classes with no class_tag should have been filtered out. */
2553     if ( class_tag == (jlong)0 ) {
2554         data->error = AGENT_ERROR_INTERNAL;
2555         return JVMTI_VISIT_ABORT;
2556     }
2557 
2558     /* Class tag not one we really want (jclass not in supplied list) */
2559     if ( class_tag == data->negObjTag ) {
2560         return JVMTI_VISIT_OBJECTS;
2561     }
2562 
2563     /* If object tag is negative, just continue, we counted it */
2564     tag = (*tag_ptr);
2565     if ( tag < (jlong)0 ) {
2566         return JVMTI_VISIT_OBJECTS;
2567     }
2568 
2569     /* Tag the object with a negative value just so we don't count it again */
2570     if ( tag == (jlong)0 ) {
2571         /* This object had no tag value, so we give it the negObjTag value */
2572         (*tag_ptr) = data->negObjTag;
2573     } else {
2574         /* If this object had a positive tag value, it must be one of the
2575          *    jclass objects we tagged. We need to preserve the value of
2576          *    this tag for later objects that might have this as a class
2577          *    tag, so we just make the existing tag value negative.
2578          */
2579         (*tag_ptr) = -tag;
2580     }
2581 
2582     /* Absolute value of class tag is an index into the counts[] array */
2583     jindex = JLONG_ABS(class_tag);
2584     index = CLASSTAG2INDEX(jindex);
2585     if (index < 0 || index >= data->classCount) {
2586         data->error = AGENT_ERROR_ILLEGAL_ARGUMENT;
2587         return JVMTI_VISIT_ABORT;
2588     }
2589 
2590     /* Bump instance count on this class */
2591     data->counts[index]++;
2592     return JVMTI_VISIT_OBJECTS;
2593 }
2594 
2595 /* Callback for instance count heap traversal (heap_iteration_callback) */
2596 static jint JNICALL
2597 cbObjectCounter(jlong class_tag, jlong size, jlong* tag_ptr, jint length,
2598                         void* user_data)
2599 {
2600     ClassCountData  *data;
2601     int              index;
2602 
2603     /* Check data structure */
2604     data = (ClassCountData*)user_data;
2605     if (data == NULL) {
2606         data->error = AGENT_ERROR_ILLEGAL_ARGUMENT;
2607         return JVMTI_VISIT_ABORT;
2608     }
2609 
2610     /* Classes with no tag should be filtered out. */
2611     if ( class_tag == (jlong)0 ) {
2612         data->error = AGENT_ERROR_INTERNAL;
2613         return JVMTI_VISIT_ABORT;
2614     }
2615 
2616     /* Class tag is actually an index into data arrays */
2617     index = CLASSTAG2INDEX(class_tag);
2618     if (index < 0 || index >= data->classCount) {
2619         data->error = AGENT_ERROR_ILLEGAL_ARGUMENT;
2620         return JVMTI_VISIT_ABORT;
2621     }
2622 
2623     /* Bump instance count on this class */
2624     data->counts[index]++;
2625     return JVMTI_VISIT_OBJECTS;
2626 }
2627 
2628 /* Get instance counts for a set of classes */
2629 jvmtiError
2630 classInstanceCounts(jint classCount, jclass *classes, jlong *counts)
2631 {
2632     jvmtiHeapCallbacks heap_callbacks;
2633     ClassCountData     data;
2634     jvmtiError         error;
2635     jvmtiEnv          *jvmti;
2636     int                i;
2637 
2638     /* Check interface assumptions */
2639     if ( classes == NULL || classCount <= 0 || counts == NULL ) {
2640         return AGENT_ERROR_ILLEGAL_ARGUMENT;
2641     }
2642 
2643     /* Initialize return information */
2644     for ( i = 0 ; i < classCount ; i++ ) {
2645         counts[i] = (jlong)0;
2646     }
2647 
2648     /* Get jvmti environment to use */
2649     jvmti = getSpecialJvmti();
2650     if ( jvmti == NULL ) {
2651         return AGENT_ERROR_INTERNAL;
2652     }
2653 
2654     /* Setup class data structure */
2655     data.error        = JVMTI_ERROR_NONE;
2656     data.classCount   = classCount;
2657     data.counts       = counts;
2658 
2659     error = JVMTI_ERROR_NONE;
2660     /* Set tags on classes, use index in classes[] as the tag value. */
2661     error             = JVMTI_ERROR_NONE;
2662     for ( i = 0 ; i < classCount ; i++ ) {
2663         if (classes[i] != NULL) {
2664             jlong tag;
2665 
2666             tag = INDEX2CLASSTAG(i);
2667             error = JVMTI_FUNC_PTR(jvmti,SetTag) (jvmti, classes[i], tag);
2668             if ( error != JVMTI_ERROR_NONE ) {
2669                 break;
2670             }
2671         }
2672     }
2673 
2674     /* Traverse heap, two ways to do this for instance counts. */
2675     if ( error == JVMTI_ERROR_NONE ) {
2676 
2677         /* Clear out callbacks structure */
2678         (void)memset(&heap_callbacks,0,sizeof(heap_callbacks));
2679 
2680         /* Check debug flags to see how to do this. */
2681         if ( (gdata->debugflags & USE_ITERATE_THROUGH_HEAP) == 0 ) {
2682 
2683             /* Using FollowReferences only gives us live objects, but we
2684              *   need to tag the objects to avoid counting them twice since
2685              *   the callback is per reference.
2686              *   The jclass objects have been tagged with their index in the
2687              *   supplied list, and that tag may flip to negative if it
2688              *   is also an object of interest.
2689              *   All other objects being counted that weren't in the
2690              *   supplied classes list will have a negative classCount
2691              *   tag value. So all objects counted will have negative tags.
2692              *   If the absolute tag value is an index in the supplied
2693              *   list, then it's one of the supplied classes.
2694              */
2695             data.negObjTag = -INDEX2CLASSTAG(classCount);
2696 
2697             /* Setup callbacks, only using object reference callback */
2698             heap_callbacks.heap_reference_callback = &cbObjectCounterFromRef;
2699 
2700             /* Follow references, no initiating object, tagged classes only */
2701             error = JVMTI_FUNC_PTR(jvmti,FollowReferences)
2702                           (jvmti, JVMTI_HEAP_FILTER_CLASS_UNTAGGED,
2703                            NULL, NULL, &heap_callbacks, &data);
2704 
2705         } else {
2706 
2707             /* Using IterateThroughHeap means that we will visit each object
2708              *   once, so no special tag tricks here. Just simple counting.
2709              *   However in this case the object might not be live, so we do
2710              *   a GC beforehand to make sure we minimize this.
2711              */
2712 
2713             /* FIXUP: Need some kind of trigger here to avoid excessive GC's? */
2714             error = JVMTI_FUNC_PTR(jvmti,ForceGarbageCollection)(jvmti);
2715             if ( error != JVMTI_ERROR_NONE ) {
2716 
2717                 /* Setup callbacks, just need object callback */
2718                 heap_callbacks.heap_iteration_callback = &cbObjectCounter;
2719 
2720                 /* Iterate through entire heap, tagged classes only */
2721                 error = JVMTI_FUNC_PTR(jvmti,IterateThroughHeap)
2722                               (jvmti, JVMTI_HEAP_FILTER_CLASS_UNTAGGED,
2723                                NULL, &heap_callbacks, &data);
2724 
2725             }
2726         }
2727 
2728         /* Use data error if needed */
2729         if ( error == JVMTI_ERROR_NONE ) {
2730             error = data.error;
2731         }
2732 
2733     }
2734 
2735     /* Dispose of any special jvmti environment */
2736     (void)JVMTI_FUNC_PTR(jvmti,DisposeEnvironment)(jvmti);
2737     return error;
2738 }
2739 
2740 /* ********************************************************************* */
2741 /* Referrers */
2742 
2743 /* Structure to hold object referrer heap traversal data (arg user_data) */
2744 typedef struct ReferrerData {
2745   int        refCount;
2746   int        maxObjects;
2747   jlong      refTag;
2748   jlong      objTag;
2749   jboolean   selfRef;
2750   jvmtiError error;
2751 } ReferrerData;
2752 
2753 /* Callback for referrers object tagging (heap_reference_callback). */
2754 static jint JNICALL
2755 cbObjectTagReferrer(jvmtiHeapReferenceKind reference_kind,
2756      const jvmtiHeapReferenceInfo* reference_info, jlong class_tag,
2757      jlong referrer_class_tag, jlong size,
2758      jlong* tag_ptr, jlong* referrer_tag_ptr, jint length, void* user_data)
2759 {
2760     ReferrerData  *data;
2761 
2762     /* Check data structure */
2763     data = (ReferrerData*)user_data;
2764     if (data == NULL) {
2765         data->error = AGENT_ERROR_ILLEGAL_ARGUMENT;
2766         return JVMTI_VISIT_ABORT;
2767     }
2768 
2769     /* If we have tagged enough objects, just abort */
2770     if ( data->maxObjects != 0 && data->refCount >= data->maxObjects ) {
2771         return JVMTI_VISIT_ABORT;
2772     }
2773 
2774     /* If not of interest, just continue */
2775     if ( (*tag_ptr) != data->objTag ) {
2776         return JVMTI_VISIT_OBJECTS;
2777     }
2778 
2779     /* Self reference that we haven't counted? */
2780     if ( tag_ptr == referrer_tag_ptr ) {
2781         if ( data->selfRef == JNI_FALSE ) {
2782             data->selfRef = JNI_TRUE;
2783             data->refCount++;
2784         }
2785         return JVMTI_VISIT_OBJECTS;
2786     }
2787 
2788     /* If the referrer can be tagged, and hasn't been tagged, tag it */
2789     if ( referrer_tag_ptr != NULL ) {
2790         if ( (*referrer_tag_ptr) == (jlong)0 ) {
2791             *referrer_tag_ptr = data->refTag;
2792             data->refCount++;
2793         }
2794     }
2795     return JVMTI_VISIT_OBJECTS;
2796 }
2797 
2798 /* Heap traversal to find referrers of an object */
2799 jvmtiError
2800 objectReferrers(jobject obj, ObjectBatch *referrers, int maxObjects)
2801 {
2802     jvmtiHeapCallbacks heap_callbacks;
2803     ReferrerData       data;
2804     jvmtiError         error;
2805     jvmtiEnv          *jvmti;
2806 
2807     /* Check interface assumptions */
2808     if (obj == NULL) {
2809         return AGENT_ERROR_INVALID_OBJECT;
2810     }
2811     if (referrers == NULL || maxObjects < 0 ) {
2812         return AGENT_ERROR_ILLEGAL_ARGUMENT;
2813     }
2814 
2815     /* Initialize return information */
2816     referrers->count = 0;
2817     referrers->objects = NULL;
2818 
2819     /* Get jvmti environment to use */
2820     jvmti = getSpecialJvmti();
2821     if ( jvmti == NULL ) {
2822         return AGENT_ERROR_INTERNAL;
2823     }
2824 
2825     /* Fill in the data structure passed around the callbacks */
2826     data.refCount   = 0;
2827     data.maxObjects = maxObjects;
2828     data.objTag     = (jlong)1;
2829     data.refTag     = (jlong)2;
2830     data.selfRef    = JNI_FALSE;
2831     data.error      = JVMTI_ERROR_NONE;
2832 
2833     /* Tag the object of interest */
2834     error = JVMTI_FUNC_PTR(jvmti,SetTag) (jvmti, obj, data.objTag);
2835 
2836     /* No need to go any further if we can't tag the object */
2837     if ( error == JVMTI_ERROR_NONE ) {
2838 
2839         /* Clear out callbacks structure */
2840         (void)memset(&heap_callbacks,0,sizeof(heap_callbacks));
2841 
2842         /* Setup callbacks we want */
2843         heap_callbacks.heap_reference_callback = &cbObjectTagReferrer;
2844 
2845         /* Follow references, no initiating object, all classes, 1 tagged objs */
2846         error = JVMTI_FUNC_PTR(jvmti,FollowReferences)
2847                       (jvmti, JVMTI_HEAP_FILTER_UNTAGGED,
2848                        NULL, NULL, &heap_callbacks, &data);
2849 
2850         /* Use data error if needed */
2851         if ( error == JVMTI_ERROR_NONE ) {
2852             error = data.error;
2853         }
2854 
2855     }
2856 
2857     /* Watch out for self-reference */
2858     if ( error == JVMTI_ERROR_NONE && data.selfRef == JNI_TRUE ) {
2859         /* Tag itself as a referer */
2860         error = JVMTI_FUNC_PTR(jvmti,SetTag) (jvmti, obj, data.refTag);
2861     }
2862 
2863     /* Get the jobjects for the tagged referrer objects.  */
2864     if ( error == JVMTI_ERROR_NONE ) {
2865         error = JVMTI_FUNC_PTR(jvmti,GetObjectsWithTags)
2866                     (jvmti, 1, &(data.refTag), &(referrers->count),
2867                           &(referrers->objects), NULL);
2868         /* Verify we got the count we expected */
2869         if ( data.refCount != referrers->count ) {
2870             error = AGENT_ERROR_INTERNAL;
2871         }
2872     }
2873 
2874     /* Dispose of any special jvmti environment */
2875     (void)JVMTI_FUNC_PTR(jvmti,DisposeEnvironment)(jvmti);
2876     return error;
2877 }