1 /*
   2  * Copyright (c) 1998, 2021, 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 "utf_util.h"
  30 #include "transport.h"
  31 #include "eventHandler.h"
  32 #include "threadControl.h"
  33 #include "outStream.h"
  34 #include "inStream.h"
  35 #include "invoker.h"
  36 #include "signature.h"
  37 
  38 
  39 /* Global data area */
  40 BackendGlobalData *gdata = NULL;
  41 
  42 /* Forward declarations */
  43 static jboolean isInterface(jclass clazz);
  44 static jboolean isArrayClass(jclass clazz);
  45 static char * getPropertyUTF8(JNIEnv *env, char *propertyName);
  46 
  47 /* Save an object reference for use later (create a NewGlobalRef) */
  48 void
  49 saveGlobalRef(JNIEnv *env, jobject obj, jobject *pobj)
  50 {
  51     jobject newobj;
  52 
  53     if ( pobj == NULL ) {
  54         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"saveGlobalRef pobj");
  55     }
  56     if ( *pobj != NULL ) {
  57         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"saveGlobalRef *pobj");
  58     }
  59     if ( env == NULL ) {
  60         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"saveGlobalRef env");
  61     }
  62     if ( obj == NULL ) {
  63         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"saveGlobalRef obj");
  64     }
  65     newobj = JNI_FUNC_PTR(env,NewGlobalRef)(env, obj);
  66     if ( newobj == NULL ) {
  67         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,"NewGlobalRef");
  68     }
  69     *pobj = newobj;
  70 }
  71 
  72 /* Toss a previously saved object reference */
  73 void
  74 tossGlobalRef(JNIEnv *env, jobject *pobj)
  75 {
  76     jobject obj;
  77 
  78     if ( pobj == NULL ) {
  79         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"tossGlobalRef pobj");
  80     }
  81     obj = *pobj;
  82     if ( env == NULL ) {
  83         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"tossGlobalRef env");
  84     }
  85     if ( obj == NULL ) {
  86         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,"tossGlobalRef obj");
  87     }
  88     JNI_FUNC_PTR(env,DeleteGlobalRef)(env, obj);
  89     *pobj = NULL;
  90 }
  91 
  92 jclass
  93 findClass(JNIEnv *env, const char * name)
  94 {
  95     jclass x;
  96 
  97     if ( env == NULL ) {
  98         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"findClass env");
  99     }
 100     if ( name == NULL || name[0] == 0 ) {
 101         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"findClass name");
 102     }
 103     x = JNI_FUNC_PTR(env,FindClass)(env, name);
 104     if (x == NULL) {
 105         ERROR_MESSAGE(("JDWP Can't find class %s", name));
 106         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 107     }
 108     if ( JNI_FUNC_PTR(env,ExceptionOccurred)(env) ) {
 109         ERROR_MESSAGE(("JDWP Exception occurred finding class %s", name));
 110         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 111     }
 112     return x;
 113 }
 114 
 115 jmethodID
 116 getMethod(JNIEnv *env, jclass clazz, const char * name, const char *signature)
 117 {
 118     jmethodID method;
 119 
 120     if ( env == NULL ) {
 121         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getMethod env");
 122     }
 123     if ( clazz == NULL ) {
 124         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getMethod clazz");
 125     }
 126     if ( name == NULL || name[0] == 0 ) {
 127         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getMethod name");
 128     }
 129     if ( signature == NULL || signature[0] == 0 ) {
 130         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getMethod signature");
 131     }
 132     method = JNI_FUNC_PTR(env,GetMethodID)(env, clazz, name, signature);
 133     if (method == NULL) {
 134         ERROR_MESSAGE(("JDWP Can't find method %s with signature %s",
 135                                 name, signature));
 136         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 137     }
 138     if ( JNI_FUNC_PTR(env,ExceptionOccurred)(env) ) {
 139         ERROR_MESSAGE(("JDWP Exception occurred finding method %s with signature %s",
 140                                 name, signature));
 141         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 142     }
 143     return method;
 144 }
 145 
 146 static jmethodID
 147 getStaticMethod(JNIEnv *env, jclass clazz, const char * name, const char *signature)
 148 {
 149     jmethodID method;
 150 
 151     if ( env == NULL ) {
 152         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getStaticMethod env");
 153     }
 154     if ( clazz == NULL ) {
 155         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getStaticMethod clazz");
 156     }
 157     if ( name == NULL || name[0] == 0 ) {
 158         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getStaticMethod name");
 159     }
 160     if ( signature == NULL || signature[0] == 0 ) {
 161         EXIT_ERROR(AGENT_ERROR_ILLEGAL_ARGUMENT,"getStaticMethod signature");
 162     }
 163     method = JNI_FUNC_PTR(env,GetStaticMethodID)(env, clazz, name, signature);
 164     if (method == NULL) {
 165         ERROR_MESSAGE(("JDWP Can't find method %s with signature %s",
 166                                 name, signature));
 167         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 168     }
 169     if ( JNI_FUNC_PTR(env,ExceptionOccurred)(env) ) {
 170         ERROR_MESSAGE(("JDWP Exception occurred finding method %s with signature %s",
 171                                 name, signature));
 172         EXIT_ERROR(AGENT_ERROR_NULL_POINTER,NULL);
 173     }
 174     return method;
 175 }
 176 
 177 
 178 
 179 void
 180 util_initialize(JNIEnv *env)
 181 {
 182     WITH_LOCAL_REFS(env, 6) {
 183 
 184         jvmtiError error;
 185         jclass localClassClass;
 186         jclass localThreadClass;
 187         jclass localThreadGroupClass;
 188         jclass localClassLoaderClass;
 189         jclass localStringClass;
 190         jclass localSystemClass;
 191         jclass localPropertiesClass;
 192         jclass localVMSupportClass;
 193         jobject localAgentProperties;
 194         jmethodID getAgentProperties;
 195         jint groupCount;
 196         jthreadGroup *groups;
 197         jthreadGroup localSystemThreadGroup;
 198 
 199         /* Find some standard classes */
 200 
 201         localClassClass         = findClass(env,"java/lang/Class");
 202         localThreadClass        = findClass(env,"java/lang/Thread");
 203         localThreadGroupClass   = findClass(env,"java/lang/ThreadGroup");
 204         localClassLoaderClass   = findClass(env,"java/lang/ClassLoader");
 205         localStringClass        = findClass(env,"java/lang/String");
 206         localSystemClass        = findClass(env,"java/lang/System");
 207         localPropertiesClass    = findClass(env,"java/util/Properties");
 208 
 209         /* Save references */
 210 
 211         saveGlobalRef(env, localClassClass,       &(gdata->classClass));
 212         saveGlobalRef(env, localThreadClass,      &(gdata->threadClass));
 213         saveGlobalRef(env, localThreadGroupClass, &(gdata->threadGroupClass));
 214         saveGlobalRef(env, localClassLoaderClass, &(gdata->classLoaderClass));
 215         saveGlobalRef(env, localStringClass,      &(gdata->stringClass));
 216         saveGlobalRef(env, localSystemClass,      &(gdata->systemClass));
 217 
 218         /* Find some standard methods */
 219 
 220         gdata->threadConstructor =
 221                 getMethod(env, gdata->threadClass,
 222                     "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V");
 223         gdata->threadSetDaemon =
 224                 getMethod(env, gdata->threadClass, "setDaemon", "(Z)V");
 225         gdata->threadResume =
 226                 getMethod(env, gdata->threadClass, "resume", "()V");
 227         gdata->systemGetProperty =
 228                 getStaticMethod(env, gdata->systemClass,
 229                     "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
 230         gdata->setProperty =
 231                 getMethod(env, localPropertiesClass,
 232                     "setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;");
 233 
 234         /* Find the system thread group */
 235 
 236         groups = NULL;
 237         groupCount = 0;
 238         error = JVMTI_FUNC_PTR(gdata->jvmti,GetTopThreadGroups)
 239                     (gdata->jvmti, &groupCount, &groups);
 240         if (error != JVMTI_ERROR_NONE ) {
 241             EXIT_ERROR(error, "Can't get system thread group");
 242         }
 243         if ( groupCount == 0 ) {
 244             EXIT_ERROR(AGENT_ERROR_NULL_POINTER, "Can't get system thread group");
 245         }
 246         localSystemThreadGroup = groups[0];
 247         saveGlobalRef(env, localSystemThreadGroup, &(gdata->systemThreadGroup));
 248 
 249         /* Get some basic Java property values we will need at some point */
 250         gdata->property_java_version
 251                         = getPropertyUTF8(env, "java.version");
 252         gdata->property_java_vm_name
 253                         = getPropertyUTF8(env, "java.vm.name");
 254         gdata->property_java_vm_info
 255                         = getPropertyUTF8(env, "java.vm.info");
 256         gdata->property_java_class_path
 257                         = getPropertyUTF8(env, "java.class.path");
 258         gdata->property_sun_boot_library_path
 259                         = getPropertyUTF8(env, "sun.boot.library.path");
 260         gdata->property_path_separator
 261                         = getPropertyUTF8(env, "path.separator");
 262         gdata->property_user_dir
 263                         = getPropertyUTF8(env, "user.dir");
 264 
 265         /* Get agent properties: invoke VMSupport.getAgentProperties */
 266         localVMSupportClass = JNI_FUNC_PTR(env,FindClass)
 267                                           (env, "jdk/internal/vm/VMSupport");
 268         if (localVMSupportClass == NULL) {
 269             gdata->agent_properties = NULL;
 270             if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
 271                 JNI_FUNC_PTR(env,ExceptionClear)(env);
 272             }
 273         } else {
 274             getAgentProperties  =
 275                 getStaticMethod(env, localVMSupportClass,
 276                                 "getAgentProperties", "()Ljava/util/Properties;");
 277             localAgentProperties =
 278                 JNI_FUNC_PTR(env,CallStaticObjectMethod)
 279                             (env, localVMSupportClass, getAgentProperties);
 280             saveGlobalRef(env, localAgentProperties, &(gdata->agent_properties));
 281             if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) {
 282                 JNI_FUNC_PTR(env,ExceptionClear)(env);
 283                 EXIT_ERROR(AGENT_ERROR_INTERNAL,
 284                     "Exception occurred calling VMSupport.getAgentProperties");
 285             }
 286         }
 287 
 288     } END_WITH_LOCAL_REFS(env);
 289 
 290 }
 291 
 292 void
 293 util_reset(void)
 294 {
 295 }
 296 
 297 jboolean
 298 isObjectTag(jbyte tag) {
 299     return (tag == JDWP_TAG(OBJECT)) ||
 300            (tag == JDWP_TAG(STRING)) ||
 301            (tag == JDWP_TAG(THREAD)) ||
 302            (tag == JDWP_TAG(THREAD_GROUP)) ||
 303            (tag == JDWP_TAG(CLASS_LOADER)) ||
 304            (tag == JDWP_TAG(CLASS_OBJECT)) ||
 305            (tag == JDWP_TAG(ARRAY));
 306 }
 307 
 308 jbyte
 309 specificTypeKey(JNIEnv *env, jobject object)
 310 {
 311     if (object == NULL) {
 312         return JDWP_TAG(OBJECT);
 313     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->stringClass)) {
 314         return JDWP_TAG(STRING);
 315     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->threadClass)) {
 316         return JDWP_TAG(THREAD);
 317     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->threadGroupClass)) {
 318         return JDWP_TAG(THREAD_GROUP);
 319     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->classLoaderClass)) {
 320         return JDWP_TAG(CLASS_LOADER);
 321     } else if (JNI_FUNC_PTR(env,IsInstanceOf)(env, object, gdata->classClass)) {
 322         return JDWP_TAG(CLASS_OBJECT);
 323     } else {
 324         jboolean classIsArray;
 325 
 326         WITH_LOCAL_REFS(env, 1) {
 327             jclass clazz;
 328             clazz = JNI_FUNC_PTR(env,GetObjectClass)(env, object);
 329             classIsArray = isArrayClass(clazz);
 330         } END_WITH_LOCAL_REFS(env);
 331 
 332         return (classIsArray ? JDWP_TAG(ARRAY) : JDWP_TAG(OBJECT));
 333     }
 334 }
 335 
 336 static void
 337 writeFieldValue(JNIEnv *env, PacketOutputStream *out, jobject object,
 338                 jfieldID field)
 339 {
 340     jclass clazz;
 341     char *signature = NULL;
 342     jvmtiError error;
 343     jbyte typeKey;
 344 
 345     clazz = JNI_FUNC_PTR(env,GetObjectClass)(env, object);
 346     error = fieldSignature(clazz, field, NULL, &signature, NULL);
 347     if (error != JVMTI_ERROR_NONE) {
 348         outStream_setError(out, map2jdwpError(error));
 349         return;
 350     }
 351     typeKey = jdwpTag(signature);
 352     jvmtiDeallocate(signature);
 353 
 354     if (isReferenceTag(typeKey)) {
 355 
 356         jobject value = JNI_FUNC_PTR(env,GetObjectField)(env, object, field);
 357         (void)outStream_writeByte(out, specificTypeKey(env, value));
 358         (void)outStream_writeObjectRef(env, out, value);
 359         return;
 360 
 361     }
 362 
 363     /*
 364      * For primitive types, the type key is bounced back as is.
 365      */

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