1 /*
   2  * Copyright (c) 2003, 2013, 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 package sun.reflect.annotation;
  27 
  28 import java.lang.annotation.*;
  29 import java.util.*;
  30 import java.nio.ByteBuffer;
  31 import java.nio.BufferUnderflowException;
  32 import java.lang.reflect.*;
  33 import java.security.AccessController;
  34 import java.security.PrivilegedAction;
  35 import jdk.internal.reflect.ConstantPool;
  36 
  37 import sun.reflect.generics.parser.SignatureParser;
  38 import sun.reflect.generics.tree.TypeSignature;
  39 import sun.reflect.generics.factory.GenericsFactory;
  40 import sun.reflect.generics.factory.CoreReflectionFactory;
  41 import sun.reflect.generics.visitor.Reifier;
  42 import sun.reflect.generics.scope.ClassScope;
  43 
  44 /**
  45  * Parser for Java programming language annotations.  Translates
  46  * annotation byte streams emitted by compiler into annotation objects.
  47  *
  48  * @author  Josh Bloch
  49  * @since   1.5
  50  */
  51 public class AnnotationParser {
  52     /**
  53      * Parses the annotations described by the specified byte array.
  54      * resolving constant references in the specified constant pool.
  55      * The array must contain an array of annotations as described
  56      * in the RuntimeVisibleAnnotations_attribute:
  57      *
  58      *   u2 num_annotations;
  59      *   annotation annotations[num_annotations];
  60      *
  61      * @throws AnnotationFormatError if an annotation is found to be
  62      *         malformed.
  63      */
  64     public static Map<Class<? extends Annotation>, Annotation> parseAnnotations(
  65                 byte[] rawAnnotations,
  66                 ConstantPool constPool,
  67                 Class<?> container) {
  68         if (rawAnnotations == null)
  69             return Collections.emptyMap();
  70 
  71         try {
  72             return parseAnnotations2(rawAnnotations, constPool, container, null);
  73         } catch(BufferUnderflowException e) {
  74             throw new AnnotationFormatError("Unexpected end of annotations.");
  75         } catch(IllegalArgumentException e) {
  76             // Type mismatch in constant pool
  77             throw new AnnotationFormatError(e);
  78         }
  79     }
  80 
  81     /**
  82      * Like {@link #parseAnnotations(byte[], sun.reflect.ConstantPool, Class)}
  83      * with an additional parameter {@code selectAnnotationClasses} which selects the
  84      * annotation types to parse (other than selected are quickly skipped).<p>
  85      * This method is only used to parse select meta annotations in the construction
  86      * phase of {@link AnnotationType} instances to prevent infinite recursion.
  87      *
  88      * @param selectAnnotationClasses an array of annotation types to select when parsing
  89      */
  90     @SafeVarargs
  91     @SuppressWarnings("varargs") // selectAnnotationClasses is used safely
  92     static Map<Class<? extends Annotation>, Annotation> parseSelectAnnotations(
  93                 byte[] rawAnnotations,
  94                 ConstantPool constPool,
  95                 Class<?> container,
  96                 Class<? extends Annotation> ... selectAnnotationClasses) {
  97         if (rawAnnotations == null)
  98             return Collections.emptyMap();
  99 
 100         try {
 101             return parseAnnotations2(rawAnnotations, constPool, container, selectAnnotationClasses);
 102         } catch(BufferUnderflowException e) {
 103             throw new AnnotationFormatError("Unexpected end of annotations.");
 104         } catch(IllegalArgumentException e) {
 105             // Type mismatch in constant pool
 106             throw new AnnotationFormatError(e);
 107         }
 108     }
 109 
 110     private static Map<Class<? extends Annotation>, Annotation> parseAnnotations2(
 111                 byte[] rawAnnotations,
 112                 ConstantPool constPool,
 113                 Class<?> container,
 114                 Class<? extends Annotation>[] selectAnnotationClasses) {
 115         Map<Class<? extends Annotation>, Annotation> result =
 116             new LinkedHashMap<Class<? extends Annotation>, Annotation>();
 117         ByteBuffer buf = ByteBuffer.wrap(rawAnnotations);
 118         int numAnnotations = buf.getShort() & 0xFFFF;
 119         for (int i = 0; i < numAnnotations; i++) {
 120             Annotation a = parseAnnotation2(buf, constPool, container, false, selectAnnotationClasses);
 121             if (a != null) {
 122                 Class<? extends Annotation> klass = a.annotationType();
 123                 if (AnnotationType.getInstance(klass).retention() == RetentionPolicy.RUNTIME &&
 124                     result.put(klass, a) != null) {
 125                         throw new AnnotationFormatError(
 126                             "Duplicate annotation for class: "+klass+": " + a);
 127                 }
 128             }
 129         }
 130         return result;
 131     }
 132 
 133     /**
 134      * Parses the parameter annotations described by the specified byte array.
 135      * resolving constant references in the specified constant pool.
 136      * The array must contain an array of annotations as described
 137      * in the RuntimeVisibleParameterAnnotations_attribute:
 138      *
 139      *    u1 num_parameters;
 140      *    {
 141      *        u2 num_annotations;
 142      *        annotation annotations[num_annotations];
 143      *    } parameter_annotations[num_parameters];
 144      *
 145      * Unlike parseAnnotations, rawAnnotations must not be null!
 146      * A null value must be handled by the caller.  This is so because
 147      * we cannot determine the number of parameters if rawAnnotations
 148      * is null.  Also, the caller should check that the number
 149      * of parameters indicated by the return value of this method
 150      * matches the actual number of method parameters.  A mismatch
 151      * indicates that an AnnotationFormatError should be thrown.
 152      *
 153      * @throws AnnotationFormatError if an annotation is found to be
 154      *         malformed.
 155      */
 156     public static Annotation[][] parseParameterAnnotations(
 157                     byte[] rawAnnotations,
 158                     ConstantPool constPool,
 159                     Class<?> container) {
 160         try {
 161             return parseParameterAnnotations2(rawAnnotations, constPool, container);
 162         } catch(BufferUnderflowException e) {
 163             throw new AnnotationFormatError(
 164                 "Unexpected end of parameter annotations.");
 165         } catch(IllegalArgumentException e) {
 166             // Type mismatch in constant pool
 167             throw new AnnotationFormatError(e);
 168         }
 169     }
 170 
 171     private static Annotation[][] parseParameterAnnotations2(
 172                     byte[] rawAnnotations,
 173                     ConstantPool constPool,
 174                     Class<?> container) {
 175         ByteBuffer buf = ByteBuffer.wrap(rawAnnotations);
 176         int numParameters = buf.get() & 0xFF;
 177         Annotation[][] result = new Annotation[numParameters][];
 178 
 179         for (int i = 0; i < numParameters; i++) {
 180             int numAnnotations = buf.getShort() & 0xFFFF;
 181             List<Annotation> annotations =
 182                 new ArrayList<Annotation>(numAnnotations);
 183             for (int j = 0; j < numAnnotations; j++) {
 184                 Annotation a = parseAnnotation(buf, constPool, container, false);
 185                 if (a != null) {
 186                     AnnotationType type = AnnotationType.getInstance(
 187                                               a.annotationType());
 188                     if (type.retention() == RetentionPolicy.RUNTIME)
 189                         annotations.add(a);
 190                 }
 191             }
 192             result[i] = annotations.toArray(EMPTY_ANNOTATIONS_ARRAY);
 193         }
 194         return result;
 195     }
 196 
 197     private static final Annotation[] EMPTY_ANNOTATIONS_ARRAY =
 198                     new Annotation[0];
 199 
 200     /**
 201      * Parses the annotation at the current position in the specified
 202      * byte buffer, resolving constant references in the specified constant
 203      * pool.  The cursor of the byte buffer must point to an "annotation
 204      * structure" as described in the RuntimeVisibleAnnotations_attribute:
 205      *
 206      * annotation {
 207      *    u2    type_index;
 208      *       u2    num_member_value_pairs;
 209      *       {    u2    member_name_index;
 210      *             member_value value;
 211      *       }    member_value_pairs[num_member_value_pairs];
 212      *    }
 213      * }
 214      *
 215      * Returns the annotation, or null if the annotation's type cannot
 216      * be found by the VM, or is not a valid annotation type.
 217      *
 218      * @param exceptionOnMissingAnnotationClass if true, throw
 219      * TypeNotPresentException if a referenced annotation type is not
 220      * available at runtime
 221      */
 222     static Annotation parseAnnotation(ByteBuffer buf,
 223                                               ConstantPool constPool,
 224                                               Class<?> container,
 225                                               boolean exceptionOnMissingAnnotationClass) {
 226        return parseAnnotation2(buf, constPool, container, exceptionOnMissingAnnotationClass, null);
 227     }
 228 
 229     @SuppressWarnings("unchecked")
 230     private static Annotation parseAnnotation2(ByteBuffer buf,
 231                                               ConstantPool constPool,
 232                                               Class<?> container,
 233                                               boolean exceptionOnMissingAnnotationClass,
 234                                               Class<? extends Annotation>[] selectAnnotationClasses) {
 235         int typeIndex = buf.getShort() & 0xFFFF;
 236         Class<? extends Annotation> annotationClass = null;
 237         String sig = "[unknown]";
 238         try {
 239             try {
 240                 sig = constPool.getUTF8At(typeIndex);
 241                 annotationClass = (Class<? extends Annotation>)parseSig(sig, container);
 242             } catch (IllegalArgumentException ex) {
 243                 // support obsolete early jsr175 format class files
 244                 annotationClass = (Class<? extends Annotation>)constPool.getClassAt(typeIndex);
 245             }
 246         } catch (NoClassDefFoundError e) {
 247             if (exceptionOnMissingAnnotationClass)
 248                 // note: at this point sig is "[unknown]" or VM-style
 249                 // name instead of a binary name
 250                 throw new TypeNotPresentException(sig, e);
 251             skipAnnotation(buf, false);
 252             return null;
 253         }
 254         catch (TypeNotPresentException e) {
 255             if (exceptionOnMissingAnnotationClass)
 256                 throw e;
 257             skipAnnotation(buf, false);
 258             return null;
 259         }
 260         if (selectAnnotationClasses != null && !contains(selectAnnotationClasses, annotationClass)) {
 261             skipAnnotation(buf, false);
 262             return null;
 263         }
 264         AnnotationType type = AnnotationType.getInstance(annotationClass);
 265 
 266         Map<String, Class<?>> memberTypes = type.memberTypes();
 267         Map<String, Object> memberValues =
 268             new LinkedHashMap<String, Object>(type.memberDefaults());
 269 
 270         int numMembers = buf.getShort() & 0xFFFF;
 271         for (int i = 0; i < numMembers; i++) {
 272             int memberNameIndex = buf.getShort() & 0xFFFF;
 273             String memberName = constPool.getUTF8At(memberNameIndex);
 274             Class<?> memberType = memberTypes.get(memberName);
 275 
 276             if (memberType == null) {
 277                 // Member is no longer present in annotation type; ignore it
 278                 skipMemberValue(buf);
 279             } else {
 280                 Object value = parseMemberValue(memberType, buf, constPool, container);
 281                 if (value instanceof AnnotationTypeMismatchExceptionProxy)
 282                     ((AnnotationTypeMismatchExceptionProxy) value).
 283                         setMember(type.members().get(memberName));
 284                 memberValues.put(memberName, value);
 285             }
 286         }
 287         return annotationForMap(annotationClass, memberValues);
 288     }
 289 
 290     /**
 291      * Returns an annotation of the given type backed by the given
 292      * member {@literal ->} value map.
 293      */
 294     public static Annotation annotationForMap(final Class<? extends Annotation> type,
 295                                               final Map<String, Object> memberValues)
 296     {
 297         return AccessController.doPrivileged(new PrivilegedAction<Annotation>() {
 298             public Annotation run() {
 299                 return (Annotation) Proxy.newProxyInstance(
 300                     type.getClassLoader(), new Class<?>[] { type },
 301                     new AnnotationInvocationHandler(type, memberValues));
 302             }});
 303     }
 304 
 305     /**
 306      * Parses the annotation member value at the current position in the
 307      * specified byte buffer, resolving constant references in the specified
 308      * constant pool.  The cursor of the byte buffer must point to a
 309      * "member_value structure" as described in the
 310      * RuntimeVisibleAnnotations_attribute:
 311      *
 312      *  member_value {
 313      *    u1 tag;
 314      *    union {
 315      *       u2   const_value_index;
 316      *       {
 317      *           u2   type_name_index;
 318      *           u2   const_name_index;
 319      *       } enum_const_value;
 320      *       u2   class_info_index;
 321      *       annotation annotation_value;
 322      *       {
 323      *           u2    num_values;
 324      *           member_value values[num_values];
 325      *       } array_value;
 326      *    } value;
 327      * }
 328      *
 329      * The member must be of the indicated type. If it is not, this
 330      * method returns an AnnotationTypeMismatchExceptionProxy.
 331      */
 332     @SuppressWarnings("unchecked")
 333     public static Object parseMemberValue(Class<?> memberType,
 334                                           ByteBuffer buf,
 335                                           ConstantPool constPool,
 336                                           Class<?> container) {
 337         Object result = null;
 338         int tag = buf.get();
 339         switch(tag) {
 340           case 'e':
 341               return parseEnumValue((Class<? extends Enum<?>>)memberType, buf, constPool, container);
 342           case 'c':
 343               result = parseClassValue(buf, constPool, container);
 344               break;
 345           case '@':
 346               result = parseAnnotation(buf, constPool, container, true);
 347               break;
 348           case '[':
 349               return parseArray(memberType, buf, constPool, container);
 350           default:
 351               result = parseConst(tag, buf, constPool);
 352         }
 353 
 354         if (!(result instanceof ExceptionProxy) &&
 355             !memberType.isInstance(result))
 356             result = new AnnotationTypeMismatchExceptionProxy(
 357                 result.getClass() + "[" + result + "]");
 358         return result;
 359     }
 360 
 361     /**
 362      * Parses the primitive or String annotation member value indicated by
 363      * the specified tag byte at the current position in the specified byte
 364      * buffer, resolving constant reference in the specified constant pool.
 365      * The cursor of the byte buffer must point to an annotation member value
 366      * of the type indicated by the specified tag, as described in the
 367      * RuntimeVisibleAnnotations_attribute:
 368      *
 369      *       u2   const_value_index;
 370      */
 371     private static Object parseConst(int tag,
 372                                      ByteBuffer buf, ConstantPool constPool) {
 373         int constIndex = buf.getShort() & 0xFFFF;
 374         switch(tag) {
 375           case 'B':
 376             return Byte.valueOf((byte) constPool.getIntAt(constIndex));
 377           case 'C':
 378             return Character.valueOf((char) constPool.getIntAt(constIndex));
 379           case 'D':
 380             return Double.valueOf(constPool.getDoubleAt(constIndex));
 381           case 'F':
 382             return Float.valueOf(constPool.getFloatAt(constIndex));
 383           case 'I':
 384             return Integer.valueOf(constPool.getIntAt(constIndex));
 385           case 'J':
 386             return Long.valueOf(constPool.getLongAt(constIndex));
 387           case 'S':
 388             return Short.valueOf((short) constPool.getIntAt(constIndex));
 389           case 'Z':
 390             return Boolean.valueOf(constPool.getIntAt(constIndex) != 0);
 391           case 's':
 392             return constPool.getUTF8At(constIndex);
 393           default:
 394             throw new AnnotationFormatError(
 395                 "Invalid member-value tag in annotation: " + tag);
 396         }
 397     }
 398 
 399     /**
 400      * Parses the Class member value at the current position in the
 401      * specified byte buffer, resolving constant references in the specified
 402      * constant pool.  The cursor of the byte buffer must point to a "class
 403      * info index" as described in the RuntimeVisibleAnnotations_attribute:
 404      *
 405      *       u2   class_info_index;
 406      */
 407     private static Object parseClassValue(ByteBuffer buf,
 408                                           ConstantPool constPool,
 409                                           Class<?> container) {
 410         int classIndex = buf.getShort() & 0xFFFF;
 411         try {
 412             try {
 413                 String sig = constPool.getUTF8At(classIndex);
 414                 return parseSig(sig, container);
 415             } catch (IllegalArgumentException ex) {
 416                 // support obsolete early jsr175 format class files
 417                 return constPool.getClassAt(classIndex);
 418             }
 419         } catch (NoClassDefFoundError e) {
 420             return new TypeNotPresentExceptionProxy("[unknown]", e);
 421         }
 422         catch (TypeNotPresentException e) {
 423             return new TypeNotPresentExceptionProxy(e.typeName(), e.getCause());
 424         }
 425     }
 426 
 427     private static Class<?> parseSig(String sig, Class<?> container) {
 428         if (sig.equals("V")) return void.class;
 429         SignatureParser parser = SignatureParser.make();
 430         TypeSignature typeSig = parser.parseTypeSig(sig);
 431         GenericsFactory factory = CoreReflectionFactory.make(container, ClassScope.make(container));
 432         Reifier reify = Reifier.make(factory);
 433         typeSig.accept(reify);
 434         Type result = reify.getResult();
 435         return toClass(result);
 436     }
 437     static Class<?> toClass(Type o) {
 438         if (o instanceof GenericArrayType)
 439             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
 440                                      0)
 441                 .getClass();
 442         return (Class)o;
 443     }
 444 
 445     /**
 446      * Parses the enum constant member value at the current position in the
 447      * specified byte buffer, resolving constant references in the specified
 448      * constant pool.  The cursor of the byte buffer must point to a
 449      * "enum_const_value structure" as described in the
 450      * RuntimeVisibleAnnotations_attribute:
 451      *
 452      *       {
 453      *           u2   type_name_index;
 454      *           u2   const_name_index;
 455      *       } enum_const_value;
 456      */
 457     @SuppressWarnings({"rawtypes", "unchecked"})
 458     private static Object parseEnumValue(Class<? extends Enum> enumType, ByteBuffer buf,
 459                                          ConstantPool constPool,
 460                                          Class<?> container) {
 461         int typeNameIndex = buf.getShort() & 0xFFFF;
 462         String typeName  = constPool.getUTF8At(typeNameIndex);
 463         int constNameIndex = buf.getShort() & 0xFFFF;
 464         String constName = constPool.getUTF8At(constNameIndex);
 465 
 466         if (!typeName.endsWith(";")) {
 467             // support now-obsolete early jsr175-format class files.
 468             if (!enumType.getName().equals(typeName))
 469             return new AnnotationTypeMismatchExceptionProxy(
 470                 typeName + "." + constName);
 471         } else if (enumType != parseSig(typeName, container)) {
 472             return new AnnotationTypeMismatchExceptionProxy(
 473                 typeName + "." + constName);
 474         }
 475 
 476         try {
 477             return  Enum.valueOf(enumType, constName);
 478         } catch(IllegalArgumentException e) {
 479             return new EnumConstantNotPresentExceptionProxy(
 480                 (Class<? extends Enum<?>>)enumType, constName);
 481         }
 482     }
 483 
 484     /**
 485      * Parses the array value at the current position in the specified byte
 486      * buffer, resolving constant references in the specified constant pool.
 487      * The cursor of the byte buffer must point to an array value struct
 488      * as specified in the RuntimeVisibleAnnotations_attribute:
 489      *
 490      *       {
 491      *           u2    num_values;
 492      *           member_value values[num_values];
 493      *       } array_value;
 494      *
 495      * If the array values do not match arrayType, an
 496      * AnnotationTypeMismatchExceptionProxy will be returned.
 497      */
 498     @SuppressWarnings("unchecked")
 499     private static Object parseArray(Class<?> arrayType,
 500                                      ByteBuffer buf,
 501                                      ConstantPool constPool,
 502                                      Class<?> container) {
 503         int length = buf.getShort() & 0xFFFF;  // Number of array components
 504         Class<?> componentType = arrayType.getComponentType();
 505 
 506         if (componentType == byte.class) {
 507             return parseByteArray(length, buf, constPool);
 508         } else if (componentType == char.class) {
 509             return parseCharArray(length, buf, constPool);
 510         } else if (componentType == double.class) {
 511             return parseDoubleArray(length, buf, constPool);
 512         } else if (componentType == float.class) {
 513             return parseFloatArray(length, buf, constPool);
 514         } else if (componentType == int.class) {
 515             return parseIntArray(length, buf, constPool);
 516         } else if (componentType == long.class) {
 517             return parseLongArray(length, buf, constPool);
 518         } else if (componentType == short.class) {
 519             return parseShortArray(length, buf, constPool);
 520         } else if (componentType == boolean.class) {
 521             return parseBooleanArray(length, buf, constPool);
 522         } else if (componentType == String.class) {
 523             return parseStringArray(length, buf, constPool);
 524         } else if (componentType == Class.class) {
 525             return parseClassArray(length, buf, constPool, container);
 526         } else if (componentType.isEnum()) {
 527             return parseEnumArray(length, (Class<? extends Enum<?>>)componentType, buf,
 528                                   constPool, container);
 529         } else {
 530             assert componentType.isAnnotation();
 531             return parseAnnotationArray(length, (Class <? extends Annotation>)componentType, buf,
 532                                         constPool, container);
 533         }
 534     }
 535 
 536     private static Object parseByteArray(int length,
 537                                   ByteBuffer buf, ConstantPool constPool) {
 538         byte[] result = new byte[length];
 539         boolean typeMismatch = false;
 540         int tag = 0;
 541 
 542         for (int i = 0; i < length; i++) {
 543             tag = buf.get();
 544             if (tag == 'B') {
 545                 int index = buf.getShort() & 0xFFFF;
 546                 result[i] = (byte) constPool.getIntAt(index);
 547             } else {
 548                 skipMemberValue(tag, buf);
 549                 typeMismatch = true;
 550             }
 551         }
 552         return typeMismatch ? exceptionProxy(tag) : result;
 553     }
 554 
 555     private static Object parseCharArray(int length,
 556                                   ByteBuffer buf, ConstantPool constPool) {
 557         char[] result = new char[length];
 558         boolean typeMismatch = false;
 559         byte tag = 0;
 560 
 561         for (int i = 0; i < length; i++) {
 562             tag = buf.get();
 563             if (tag == 'C') {
 564                 int index = buf.getShort() & 0xFFFF;
 565                 result[i] = (char) constPool.getIntAt(index);
 566             } else {
 567                 skipMemberValue(tag, buf);
 568                 typeMismatch = true;
 569             }
 570         }
 571         return typeMismatch ? exceptionProxy(tag) : result;
 572     }
 573 
 574     private static Object parseDoubleArray(int length,
 575                                     ByteBuffer buf, ConstantPool constPool) {
 576         double[] result = new  double[length];
 577         boolean typeMismatch = false;
 578         int tag = 0;
 579 
 580         for (int i = 0; i < length; i++) {
 581             tag = buf.get();
 582             if (tag == 'D') {
 583                 int index = buf.getShort() & 0xFFFF;
 584                 result[i] = constPool.getDoubleAt(index);
 585             } else {
 586                 skipMemberValue(tag, buf);
 587                 typeMismatch = true;
 588             }
 589         }
 590         return typeMismatch ? exceptionProxy(tag) : result;
 591     }
 592 
 593     private static Object parseFloatArray(int length,
 594                                    ByteBuffer buf, ConstantPool constPool) {
 595         float[] result = new float[length];
 596         boolean typeMismatch = false;
 597         int tag = 0;
 598 
 599         for (int i = 0; i < length; i++) {
 600             tag = buf.get();
 601             if (tag == 'F') {
 602                 int index = buf.getShort() & 0xFFFF;
 603                 result[i] = constPool.getFloatAt(index);
 604             } else {
 605                 skipMemberValue(tag, buf);
 606                 typeMismatch = true;
 607             }
 608         }
 609         return typeMismatch ? exceptionProxy(tag) : result;
 610     }
 611 
 612     private static Object parseIntArray(int length,
 613                                  ByteBuffer buf, ConstantPool constPool) {
 614         int[] result = new  int[length];
 615         boolean typeMismatch = false;
 616         int tag = 0;
 617 
 618         for (int i = 0; i < length; i++) {
 619             tag = buf.get();
 620             if (tag == 'I') {
 621                 int index = buf.getShort() & 0xFFFF;
 622                 result[i] = constPool.getIntAt(index);
 623             } else {
 624                 skipMemberValue(tag, buf);
 625                 typeMismatch = true;
 626             }
 627         }
 628         return typeMismatch ? exceptionProxy(tag) : result;
 629     }
 630 
 631     private static Object parseLongArray(int length,
 632                                   ByteBuffer buf, ConstantPool constPool) {
 633         long[] result = new long[length];
 634         boolean typeMismatch = false;
 635         int tag = 0;
 636 
 637         for (int i = 0; i < length; i++) {
 638             tag = buf.get();
 639             if (tag == 'J') {
 640                 int index = buf.getShort() & 0xFFFF;
 641                 result[i] = constPool.getLongAt(index);
 642             } else {
 643                 skipMemberValue(tag, buf);
 644                 typeMismatch = true;
 645             }
 646         }
 647         return typeMismatch ? exceptionProxy(tag) : result;
 648     }
 649 
 650     private static Object parseShortArray(int length,
 651                                    ByteBuffer buf, ConstantPool constPool) {
 652         short[] result = new short[length];
 653         boolean typeMismatch = false;
 654         int tag = 0;
 655 
 656         for (int i = 0; i < length; i++) {
 657             tag = buf.get();
 658             if (tag == 'S') {
 659                 int index = buf.getShort() & 0xFFFF;
 660                 result[i] = (short) constPool.getIntAt(index);
 661             } else {
 662                 skipMemberValue(tag, buf);
 663                 typeMismatch = true;
 664             }
 665         }
 666         return typeMismatch ? exceptionProxy(tag) : result;
 667     }
 668 
 669     private static Object parseBooleanArray(int length,
 670                                      ByteBuffer buf, ConstantPool constPool) {
 671         boolean[] result = new boolean[length];
 672         boolean typeMismatch = false;
 673         int tag = 0;
 674 
 675         for (int i = 0; i < length; i++) {
 676             tag = buf.get();
 677             if (tag == 'Z') {
 678                 int index = buf.getShort() & 0xFFFF;
 679                 result[i] = (constPool.getIntAt(index) != 0);
 680             } else {
 681                 skipMemberValue(tag, buf);
 682                 typeMismatch = true;
 683             }
 684         }
 685         return typeMismatch ? exceptionProxy(tag) : result;
 686     }
 687 
 688     private static Object parseStringArray(int length,
 689                                     ByteBuffer buf,  ConstantPool constPool) {
 690         String[] result = new String[length];
 691         boolean typeMismatch = false;
 692         int tag = 0;
 693 
 694         for (int i = 0; i < length; i++) {
 695             tag = buf.get();
 696             if (tag == 's') {
 697                 int index = buf.getShort() & 0xFFFF;
 698                 result[i] = constPool.getUTF8At(index);
 699             } else {
 700                 skipMemberValue(tag, buf);
 701                 typeMismatch = true;
 702             }
 703         }
 704         return typeMismatch ? exceptionProxy(tag) : result;
 705     }
 706 
 707     private static Object parseClassArray(int length,
 708                                           ByteBuffer buf,
 709                                           ConstantPool constPool,
 710                                           Class<?> container) {
 711         Object[] result = new Class<?>[length];
 712         boolean typeMismatch = false;
 713         int tag = 0;
 714 
 715         for (int i = 0; i < length; i++) {
 716             tag = buf.get();
 717             if (tag == 'c') {
 718                 result[i] = parseClassValue(buf, constPool, container);
 719             } else {
 720                 skipMemberValue(tag, buf);
 721                 typeMismatch = true;
 722             }
 723         }
 724         return typeMismatch ? exceptionProxy(tag) : result;
 725     }
 726 
 727     private static Object parseEnumArray(int length, Class<? extends Enum<?>> enumType,
 728                                          ByteBuffer buf,
 729                                          ConstantPool constPool,
 730                                          Class<?> container) {
 731         Object[] result = (Object[]) Array.newInstance(enumType, length);
 732         boolean typeMismatch = false;
 733         int tag = 0;
 734 
 735         for (int i = 0; i < length; i++) {
 736             tag = buf.get();
 737             if (tag == 'e') {
 738                 result[i] = parseEnumValue(enumType, buf, constPool, container);
 739             } else {
 740                 skipMemberValue(tag, buf);
 741                 typeMismatch = true;
 742             }
 743         }
 744         return typeMismatch ? exceptionProxy(tag) : result;
 745     }
 746 
 747     private static Object parseAnnotationArray(int length,
 748                                                Class<? extends Annotation> annotationType,
 749                                                ByteBuffer buf,
 750                                                ConstantPool constPool,
 751                                                Class<?> container) {
 752         Object[] result = (Object[]) Array.newInstance(annotationType, length);
 753         boolean typeMismatch = false;
 754         int tag = 0;
 755 
 756         for (int i = 0; i < length; i++) {
 757             tag = buf.get();
 758             if (tag == '@') {
 759                 result[i] = parseAnnotation(buf, constPool, container, true);
 760             } else {
 761                 skipMemberValue(tag, buf);
 762                 typeMismatch = true;
 763             }
 764         }
 765         return typeMismatch ? exceptionProxy(tag) : result;
 766     }
 767 
 768     /**
 769      * Returns an appropriate exception proxy for a mismatching array
 770      * annotation where the erroneous array has the specified tag.
 771      */
 772     private static ExceptionProxy exceptionProxy(int tag) {
 773         return new AnnotationTypeMismatchExceptionProxy(
 774             "Array with component tag: " + tag);
 775     }
 776 
 777     /**
 778      * Skips the annotation at the current position in the specified
 779      * byte buffer.  The cursor of the byte buffer must point to
 780      * an "annotation structure" OR two bytes into an annotation
 781      * structure (i.e., after the type index).
 782      *
 783      * @parameter complete true if the byte buffer points to the beginning
 784      *     of an annotation structure (rather than two bytes in).
 785      */
 786     private static void skipAnnotation(ByteBuffer buf, boolean complete) {
 787         if (complete)
 788             buf.getShort();   // Skip type index
 789         int numMembers = buf.getShort() & 0xFFFF;
 790         for (int i = 0; i < numMembers; i++) {
 791             buf.getShort();   // Skip memberNameIndex
 792             skipMemberValue(buf);
 793         }
 794     }
 795 
 796     /**
 797      * Skips the annotation member value at the current position in the
 798      * specified byte buffer.  The cursor of the byte buffer must point to a
 799      * "member_value structure."
 800      */
 801     private static void skipMemberValue(ByteBuffer buf) {
 802         int tag = buf.get();
 803         skipMemberValue(tag, buf);
 804     }
 805 
 806     /**
 807      * Skips the annotation member value at the current position in the
 808      * specified byte buffer.  The cursor of the byte buffer must point
 809      * immediately after the tag in a "member_value structure."
 810      */
 811     private static void skipMemberValue(int tag, ByteBuffer buf) {
 812         switch(tag) {
 813           case 'e': // Enum value
 814             buf.getInt();  // (Two shorts, actually.)
 815             break;
 816           case '@':
 817             skipAnnotation(buf, true);
 818             break;
 819           case '[':
 820             skipArray(buf);
 821             break;
 822           default:
 823             // Class, primitive, or String
 824             buf.getShort();
 825         }
 826     }
 827 
 828     /**
 829      * Skips the array value at the current position in the specified byte
 830      * buffer.  The cursor of the byte buffer must point to an array value
 831      * struct.
 832      */
 833     private static void skipArray(ByteBuffer buf) {
 834         int length = buf.getShort() & 0xFFFF;
 835         for (int i = 0; i < length; i++)
 836             skipMemberValue(buf);
 837     }
 838 
 839     /**
 840      * Searches for given {@code element} in given {@code array} by identity.
 841      * Returns {@code true} if found {@code false} if not.
 842      */
 843     private static boolean contains(Object[] array, Object element) {
 844         for (Object e : array)
 845             if (e == element)
 846                 return true;
 847         return false;
 848     }
 849 
 850     /*
 851      * This method converts the annotation map returned by the parseAnnotations()
 852      * method to an array.  It is called by Field.getDeclaredAnnotations(),
 853      * Method.getDeclaredAnnotations(), and Constructor.getDeclaredAnnotations().
 854      * This avoids the reflection classes to load the Annotation class until
 855      * it is needed.
 856      */
 857     private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0];
 858     public static Annotation[] toArray(Map<Class<? extends Annotation>, Annotation> annotations) {
 859         return annotations.values().toArray(EMPTY_ANNOTATION_ARRAY);
 860     }
 861 
 862     static Annotation[] getEmptyAnnotationArray() { return EMPTY_ANNOTATION_ARRAY; }
 863 }