1 /*
   2  * Copyright (c) 2003, 2014, 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.io.ObjectInputStream;
  29 import java.lang.annotation.*;
  30 import java.lang.reflect.*;
  31 import java.io.Serializable;
  32 import java.util.*;
  33 import java.security.AccessController;
  34 import java.security.PrivilegedAction;
  35 
  36 /**
  37  * InvocationHandler for dynamic proxy implementation of Annotation.
  38  *
  39  * @author  Josh Bloch
  40  * @since   1.5
  41  */
  42 class AnnotationInvocationHandler implements InvocationHandler, Serializable {
  43     private static final long serialVersionUID = 6182022883658399397L;
  44     private final Class<? extends Annotation> type;
  45     private final Map<String, Object> memberValues;
  46 
  47     AnnotationInvocationHandler(Class<? extends Annotation> type, Map<String, Object> memberValues) {
  48         Class<?>[] superInterfaces = type.getInterfaces();
  49         if (!type.isAnnotation() ||
  50             superInterfaces.length != 1 ||
  51             superInterfaces[0] != java.lang.annotation.Annotation.class)
  52             throw new AnnotationFormatError("Attempt to create proxy for a non-annotation type.");
  53         this.type = type;
  54         this.memberValues = memberValues;
  55     }
  56 
  57     public Object invoke(Object proxy, Method method, Object[] args) {
  58         String member = method.getName();
  59         Class<?>[] paramTypes = method.getParameterTypes();
  60 
  61         // Handle Object and Annotation methods
  62         if (member.equals("equals") && paramTypes.length == 1 &&
  63             paramTypes[0] == Object.class)
  64             return equalsImpl(args[0]);
  65         if (paramTypes.length != 0)
  66             throw new AssertionError("Too many parameters for an annotation method");
  67 
  68         switch(member) {
  69         case "toString":
  70             return toStringImpl();
  71         case "hashCode":
  72             return hashCodeImpl();
  73         case "annotationType":
  74             return type;
  75         }
  76 
  77         // Handle annotation member accessors
  78         Object result = memberValues.get(member);
  79 
  80         if (result == null)
  81             throw new IncompleteAnnotationException(type, member);
  82 
  83         if (result instanceof ExceptionProxy)
  84             throw ((ExceptionProxy) result).generateException();
  85 
  86         if (result.getClass().isArray() && Array.getLength(result) != 0)
  87             result = cloneArray(result);
  88 
  89         return result;
  90     }
  91 
  92     /**
  93      * This method, which clones its array argument, would not be necessary
  94      * if Cloneable had a public clone method.
  95      */
  96     private Object cloneArray(Object array) {
  97         Class<?> type = array.getClass();
  98 
  99         if (type == byte[].class) {
 100             byte[] byteArray = (byte[])array;
 101             return byteArray.clone();
 102         }
 103         if (type == char[].class) {
 104             char[] charArray = (char[])array;
 105             return charArray.clone();
 106         }
 107         if (type == double[].class) {
 108             double[] doubleArray = (double[])array;
 109             return doubleArray.clone();
 110         }
 111         if (type == float[].class) {
 112             float[] floatArray = (float[])array;
 113             return floatArray.clone();
 114         }
 115         if (type == int[].class) {
 116             int[] intArray = (int[])array;
 117             return intArray.clone();
 118         }
 119         if (type == long[].class) {
 120             long[] longArray = (long[])array;
 121             return longArray.clone();
 122         }
 123         if (type == short[].class) {
 124             short[] shortArray = (short[])array;
 125             return shortArray.clone();
 126         }
 127         if (type == boolean[].class) {
 128             boolean[] booleanArray = (boolean[])array;
 129             return booleanArray.clone();
 130         }
 131 
 132         Object[] objectArray = (Object[])array;
 133         return objectArray.clone();
 134     }
 135 
 136 
 137     /**
 138      * Implementation of dynamicProxy.toString()
 139      */
 140     private String toStringImpl() {
 141         StringBuilder result = new StringBuilder(128);
 142         result.append('@');
 143         result.append(type.getName());
 144         result.append('(');
 145         boolean firstMember = true;
 146         for (Map.Entry<String, Object> e : memberValues.entrySet()) {
 147             if (firstMember)
 148                 firstMember = false;
 149             else
 150                 result.append(", ");
 151 
 152             result.append(e.getKey());
 153             result.append('=');
 154             result.append(memberValueToString(e.getValue()));
 155         }
 156         result.append(')');
 157         return result.toString();
 158     }
 159 
 160     /**
 161      * Translates a member value (in "dynamic proxy return form") into a string
 162      */
 163     private static String memberValueToString(Object value) {
 164         Class<?> type = value.getClass();
 165         if (!type.isArray())    // primitive, string, class, enum const,
 166                                 // or annotation
 167             return value.toString();
 168 
 169         if (type == byte[].class)
 170             return Arrays.toString((byte[]) value);
 171         if (type == char[].class)
 172             return Arrays.toString((char[]) value);
 173         if (type == double[].class)
 174             return Arrays.toString((double[]) value);
 175         if (type == float[].class)
 176             return Arrays.toString((float[]) value);
 177         if (type == int[].class)
 178             return Arrays.toString((int[]) value);
 179         if (type == long[].class)
 180             return Arrays.toString((long[]) value);
 181         if (type == short[].class)
 182             return Arrays.toString((short[]) value);
 183         if (type == boolean[].class)
 184             return Arrays.toString((boolean[]) value);
 185         return Arrays.toString((Object[]) value);
 186     }
 187 
 188     /**
 189      * Implementation of dynamicProxy.equals(Object o)
 190      */
 191     private Boolean equalsImpl(Object o) {
 192         if (o == this)
 193             return true;
 194 
 195         if (!type.isInstance(o))
 196             return false;
 197         for (Method memberMethod : getMemberMethods()) {
 198             String member = memberMethod.getName();
 199             Object ourValue = memberValues.get(member);
 200             Object hisValue = null;
 201             AnnotationInvocationHandler hisHandler = asOneOfUs(o);
 202             if (hisHandler != null) {
 203                 hisValue = hisHandler.memberValues.get(member);
 204             } else {
 205                 try {
 206                     hisValue = memberMethod.invoke(o);
 207                 } catch (InvocationTargetException e) {
 208                     return false;
 209                 } catch (IllegalAccessException e) {
 210                     throw new AssertionError(e);
 211                 }
 212             }
 213             if (!memberValueEquals(ourValue, hisValue))
 214                 return false;
 215         }
 216         return true;
 217     }
 218 
 219     /**
 220      * Returns an object's invocation handler if that object is a dynamic
 221      * proxy with a handler of type AnnotationInvocationHandler.
 222      * Returns null otherwise.
 223      */
 224     private AnnotationInvocationHandler asOneOfUs(Object o) {
 225         if (Proxy.isProxyClass(o.getClass())) {
 226             InvocationHandler handler = Proxy.getInvocationHandler(o);
 227             if (handler instanceof AnnotationInvocationHandler)
 228                 return (AnnotationInvocationHandler) handler;
 229         }
 230         return null;
 231     }
 232 
 233     /**
 234      * Returns true iff the two member values in "dynamic proxy return form"
 235      * are equal using the appropriate equality function depending on the
 236      * member type.  The two values will be of the same type unless one of
 237      * the containing annotations is ill-formed.  If one of the containing
 238      * annotations is ill-formed, this method will return false unless the
 239      * two members are identical object references.
 240      */
 241     private static boolean memberValueEquals(Object v1, Object v2) {
 242         Class<?> type = v1.getClass();
 243 
 244         // Check for primitive, string, class, enum const, annotation,
 245         // or ExceptionProxy
 246         if (!type.isArray())
 247             return v1.equals(v2);
 248 
 249         // Check for array of string, class, enum const, annotation,
 250         // or ExceptionProxy
 251         if (v1 instanceof Object[] && v2 instanceof Object[])
 252             return Arrays.equals((Object[]) v1, (Object[]) v2);
 253 
 254         // Check for ill formed annotation(s)
 255         if (v2.getClass() != type)
 256             return false;
 257 
 258         // Deal with array of primitives
 259         if (type == byte[].class)
 260             return Arrays.equals((byte[]) v1, (byte[]) v2);
 261         if (type == char[].class)
 262             return Arrays.equals((char[]) v1, (char[]) v2);
 263         if (type == double[].class)
 264             return Arrays.equals((double[]) v1, (double[]) v2);
 265         if (type == float[].class)
 266             return Arrays.equals((float[]) v1, (float[]) v2);
 267         if (type == int[].class)
 268             return Arrays.equals((int[]) v1, (int[]) v2);
 269         if (type == long[].class)
 270             return Arrays.equals((long[]) v1, (long[]) v2);
 271         if (type == short[].class)
 272             return Arrays.equals((short[]) v1, (short[]) v2);
 273         assert type == boolean[].class;
 274         return Arrays.equals((boolean[]) v1, (boolean[]) v2);
 275     }
 276 
 277     /**
 278      * Returns the member methods for our annotation type.  These are
 279      * obtained lazily and cached, as they're expensive to obtain
 280      * and we only need them if our equals method is invoked (which should
 281      * be rare).
 282      */
 283     private Method[] getMemberMethods() {
 284         Method[] value = memberMethods;
 285         if (value == null) {
 286             value = computeMemberMethods();
 287             memberMethods = value;
 288         }
 289         return value;
 290     }
 291 
 292     private Method[] computeMemberMethods() {
 293         return AccessController.doPrivileged(
 294             new PrivilegedAction<Method[]>() {
 295                 public Method[] run() {
 296                     final Method[] methods = type.getDeclaredMethods();
 297                     validateAnnotationMethods(methods);
 298                     AccessibleObject.setAccessible(methods, true);
 299                     return methods;
 300                 }});
 301     }
 302 
 303     private transient volatile Method[] memberMethods;
 304 
 305     /**
 306      * Validates that a method is structurally appropriate for an
 307      * annotation type. As of Java SE 8, annotation types cannot
 308      * contain static methods and the declared methods of an
 309      * annotation type must take zero arguments and there are
 310      * restrictions on the return type.
 311      */
 312     private void validateAnnotationMethods(Method[] memberMethods) {
 313         /*
 314          * Specification citations below are from JLS
 315          * 9.6.1. Annotation Type Elements
 316          */
 317         boolean valid = true;
 318         for(Method method : memberMethods) {
 319             /*
 320              * "By virtue of the AnnotationTypeElementDeclaration
 321              * production, a method declaration in an annotation type
 322              * declaration cannot have formal parameters, type
 323              * parameters, or a throws clause.
 324              *
 325              * "By virtue of the AnnotationTypeElementModifier
 326              * production, a method declaration in an annotation type
 327              * declaration cannot be default or static."
 328              */
 329             if (method.getModifiers() != (Modifier.PUBLIC | Modifier.ABSTRACT) ||
 330                 method.isDefault() ||
 331                 method.getParameterCount() != 0 ||
 332                 method.getExceptionTypes().length != 0) {
 333                 valid = false;
 334                 break;
 335             }
 336 
 337             /*
 338              * "It is a compile-time error if the return type of a
 339              * method declared in an annotation type is not one of the
 340              * following: a primitive type, String, Class, any
 341              * parameterized invocation of Class, an enum type
 342              * (section 8.9), an annotation type, or an array type
 343              * (chapter 10) whose element type is one of the preceding
 344              * types."
 345              */
 346             Class<?> returnType = method.getReturnType();
 347             if (returnType.isArray()) {
 348                 returnType = returnType.getComponentType();
 349                 if (returnType.isArray()) { // Only single dimensional arrays
 350                     valid = false;
 351                     break;
 352                 }
 353             }
 354 
 355             if (!((returnType.isPrimitive() && returnType != void.class) ||
 356                   returnType == java.lang.String.class ||
 357                   returnType == java.lang.Class.class ||
 358                   returnType.isEnum() ||
 359                   returnType.isAnnotation())) {
 360                 valid = false;
 361                 break;
 362             }
 363 
 364             /*
 365              * "It is a compile-time error if any method declared in an
 366              * annotation type has a signature that is
 367              * override-equivalent to that of any public or protected
 368              * method declared in class Object or in the interface
 369              * java.lang.annotation.Annotation."
 370              *
 371              * The methods in Object or Annotation meeting the other
 372              * criteria (no arguments, contrained return type, etc.)
 373              * above are:
 374              *
 375              * String toString()
 376              * int hashCode()
 377              * Class<? extends Annotation> annotationType()
 378              */
 379             String methodName = method.getName();
 380             if ((methodName.equals("toString") && returnType == java.lang.String.class) ||
 381                 (methodName.equals("hashCode") && returnType == int.class) ||
 382                 (methodName.equals("annotationType") && returnType == java.lang.Class.class)) {
 383                 valid = false;
 384                 break;
 385             }
 386         }
 387         if (valid)
 388             return;
 389         else
 390             throw new AnnotationFormatError("Malformed method on an annotation type");
 391     }
 392 
 393     /**
 394      * Implementation of dynamicProxy.hashCode()
 395      */
 396     private int hashCodeImpl() {
 397         int result = 0;
 398         for (Map.Entry<String, Object> e : memberValues.entrySet()) {
 399             result += (127 * e.getKey().hashCode()) ^
 400                 memberValueHashCode(e.getValue());
 401         }
 402         return result;
 403     }
 404 
 405     /**
 406      * Computes hashCode of a member value (in "dynamic proxy return form")
 407      */
 408     private static int memberValueHashCode(Object value) {
 409         Class<?> type = value.getClass();
 410         if (!type.isArray())    // primitive, string, class, enum const,
 411                                 // or annotation
 412             return value.hashCode();
 413 
 414         if (type == byte[].class)
 415             return Arrays.hashCode((byte[]) value);
 416         if (type == char[].class)
 417             return Arrays.hashCode((char[]) value);
 418         if (type == double[].class)
 419             return Arrays.hashCode((double[]) value);
 420         if (type == float[].class)
 421             return Arrays.hashCode((float[]) value);
 422         if (type == int[].class)
 423             return Arrays.hashCode((int[]) value);
 424         if (type == long[].class)
 425             return Arrays.hashCode((long[]) value);
 426         if (type == short[].class)
 427             return Arrays.hashCode((short[]) value);
 428         if (type == boolean[].class)
 429             return Arrays.hashCode((boolean[]) value);
 430         return Arrays.hashCode((Object[]) value);
 431     }
 432 
 433     private void readObject(java.io.ObjectInputStream s)
 434         throws java.io.IOException, ClassNotFoundException {
 435         ObjectInputStream.GetField fields = s.readFields();
 436 
 437         @SuppressWarnings("unchecked")
 438         Class<? extends Annotation> t = (Class<? extends Annotation>)fields.get("type", null);
 439         @SuppressWarnings("unchecked")
 440         Map<String, Object> streamVals = (Map<String, Object>)fields.get("memberValues", null);
 441 
 442         // Check to make sure that types have not evolved incompatibly
 443 
 444         AnnotationType annotationType = null;
 445         try {
 446             annotationType = AnnotationType.getInstance(t);
 447         } catch(IllegalArgumentException e) {
 448             // Class is no longer an annotation type; time to punch out
 449             throw new java.io.InvalidObjectException("Non-annotation type in annotation serial stream");
 450         }
 451 
 452         Map<String, Class<?>> memberTypes = annotationType.memberTypes();
 453         // consistent with runtime Map type
 454         Map<String, Object> mv = new LinkedHashMap<>();
 455 
 456         // If there are annotation members without values, that
 457         // situation is handled by the invoke method.
 458         for (Map.Entry<String, Object> memberValue : streamVals.entrySet()) {
 459             String name = memberValue.getKey();
 460             Object value = null;
 461             Class<?> memberType = memberTypes.get(name);
 462             if (memberType != null) {  // i.e. member still exists
 463                 value = memberValue.getValue();
 464                 if (!(memberType.isInstance(value) ||
 465                       value instanceof ExceptionProxy)) {
 466                     value = new AnnotationTypeMismatchExceptionProxy(
 467                             value.getClass() + "[" + value + "]").setMember(
 468                                 annotationType.members().get(name));
 469                 }
 470             }
 471             mv.put(name, value);
 472         }
 473 
 474         UnsafeAccessor.setType(this, t);
 475         UnsafeAccessor.setMemberValues(this, mv);
 476     }
 477 
 478     private static class UnsafeAccessor {
 479         private static final jdk.internal.misc.Unsafe unsafe;
 480         private static final long typeOffset;
 481         private static final long memberValuesOffset;
 482         static {
 483             try {
 484                 unsafe = jdk.internal.misc.Unsafe.getUnsafe();
 485                 typeOffset = unsafe.objectFieldOffset
 486                         (AnnotationInvocationHandler.class.getDeclaredField("type"));
 487                 memberValuesOffset = unsafe.objectFieldOffset
 488                         (AnnotationInvocationHandler.class.getDeclaredField("memberValues"));
 489             } catch (Exception ex) {
 490                 throw new ExceptionInInitializerError(ex);
 491             }
 492         }
 493         static void setType(AnnotationInvocationHandler o,
 494                             Class<? extends Annotation> type) {
 495             unsafe.putObject(o, typeOffset, type);
 496         }
 497 
 498         static void setMemberValues(AnnotationInvocationHandler o,
 499                                     Map<String, Object> memberValues) {
 500             unsafe.putObject(o, memberValuesOffset, memberValues);
 501         }
 502     }
 503 }