1 /*
   2  * Copyright (c) 2010, 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 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file, and Oracle licenses the original version of this file under the BSD
  31  * license:
  32  */
  33 /*
  34    Copyright 2009-2013 Attila Szegedi
  35 
  36    Licensed under both the Apache License, Version 2.0 (the "Apache License")
  37    and the BSD License (the "BSD License"), with licensee being free to
  38    choose either of the two at their discretion.
  39 
  40    You may not use this file except in compliance with either the Apache
  41    License or the BSD License.
  42 
  43    If you choose to use this file in compliance with the Apache License, the
  44    following notice applies to you:
  45 
  46        You may obtain a copy of the Apache License at
  47 
  48            http://www.apache.org/licenses/LICENSE-2.0
  49 
  50        Unless required by applicable law or agreed to in writing, software
  51        distributed under the License is distributed on an "AS IS" BASIS,
  52        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  53        implied. See the License for the specific language governing
  54        permissions and limitations under the License.
  55 
  56    If you choose to use this file in compliance with the BSD License, the
  57    following notice applies to you:
  58 
  59        Redistribution and use in source and binary forms, with or without
  60        modification, are permitted provided that the following conditions are
  61        met:
  62        * Redistributions of source code must retain the above copyright
  63          notice, this list of conditions and the following disclaimer.
  64        * Redistributions in binary form must reproduce the above copyright
  65          notice, this list of conditions and the following disclaimer in the
  66          documentation and/or other materials provided with the distribution.
  67        * Neither the name of the copyright holder nor the names of
  68          contributors may be used to endorse or promote products derived from
  69          this software without specific prior written permission.
  70 
  71        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  72        IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  73        TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  74        PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
  75        BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  76        CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  77        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  78        BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  79        WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  80        OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  81        ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  82 */
  83 
  84 package jdk.internal.dynalink.support;
  85 
  86 import java.lang.invoke.MethodHandles;
  87 import java.lang.invoke.MethodHandles.Lookup;
  88 import java.lang.invoke.MethodType;
  89 import java.lang.ref.Reference;
  90 import java.lang.ref.WeakReference;
  91 import java.util.Arrays;
  92 import java.util.Collections;
  93 import java.util.List;
  94 import java.util.StringTokenizer;
  95 import java.util.WeakHashMap;
  96 import jdk.internal.dynalink.CallSiteDescriptor;
  97 
  98 /**
  99  * Usable as a default factory for call site descriptor implementations. It is weakly canonicalizing, meaning it will
 100  * return the same immutable call site descriptor for identical inputs, i.e. repeated requests for a descriptor
 101  * signifying public lookup for "dyn:getProp:color" of type "Object(Object)" will return the same object as long as
 102  * a previously created, at least softly reachable one exists. It also uses several different implementations of the
 103  * {@link CallSiteDescriptor} internally, and chooses the most space-efficient one based on the input.
 104  * @author Attila Szegedi
 105  */
 106 public class CallSiteDescriptorFactory {
 107     private static final WeakHashMap<CallSiteDescriptor, Reference<CallSiteDescriptor>> publicDescs =
 108             new WeakHashMap<>();
 109 
 110 
 111     private CallSiteDescriptorFactory() {
 112     }
 113 
 114     /**
 115      * Creates a new call site descriptor instance. The actual underlying class of the instance is dependent on the
 116      * passed arguments to be space efficient; i.e. if you  only use the public lookup, you'll get back an
 117      * implementation that doesn't waste space on storing the lookup object.
 118      * @param lookup the lookup that determines access rights at the call site. If your language runtime doesn't have
 119      * equivalents of Java access concepts, just use {@link MethodHandles#publicLookup()}. Must not be null.
 120      * @param name the name of the method at the call site. Must not be null.
 121      * @param methodType the type of the method at the call site. Must not be null.
 122      * @return a call site descriptor representing the input. Note that although the method name is "create", it will
 123      * in fact return a weakly-referenced canonical instance.
 124      */
 125     public static CallSiteDescriptor create(final Lookup lookup, final String name, final MethodType methodType) {
 126         name.getClass(); // NPE check
 127         methodType.getClass(); // NPE check
 128         lookup.getClass(); // NPE check
 129         final String[] tokenizedName = tokenizeName(name);
 130         if(isPublicLookup(lookup)) {
 131             return getCanonicalPublicDescriptor(createPublicCallSiteDescriptor(tokenizedName, methodType));
 132         }
 133         return new LookupCallSiteDescriptor(tokenizedName, methodType, lookup);
 134     }
 135 
 136     static CallSiteDescriptor getCanonicalPublicDescriptor(final CallSiteDescriptor desc) {
 137         synchronized(publicDescs) {
 138             final Reference<CallSiteDescriptor> ref = publicDescs.get(desc);
 139             if(ref != null) {
 140                 final CallSiteDescriptor canonical = ref.get();
 141                 if(canonical != null) {
 142                     return canonical;
 143                 }
 144             }
 145             publicDescs.put(desc, createReference(desc));
 146         }
 147         return desc;
 148     }
 149 
 150     /**
 151      * Override this to use a different kind of references for the cache
 152      * @param desc desc
 153      * @return reference
 154      */
 155     protected static Reference<CallSiteDescriptor> createReference(final CallSiteDescriptor desc) {
 156         return new WeakReference<>(desc);
 157     }
 158 
 159     private static CallSiteDescriptor createPublicCallSiteDescriptor(final String[] tokenizedName, final MethodType methodType) {
 160         final int l = tokenizedName.length;
 161         if(l > 0 && tokenizedName[0] == "dyn") {
 162             if(l == 2) {
 163                 return new UnnamedDynCallSiteDescriptor(tokenizedName[1], methodType);
 164             } if (l == 3) {
 165                 return new NamedDynCallSiteDescriptor(tokenizedName[1], tokenizedName[2], methodType);
 166             }
 167         }
 168         return new DefaultCallSiteDescriptor(tokenizedName, methodType);
 169     }
 170 
 171     private static boolean isPublicLookup(final Lookup lookup) {
 172         return lookup == MethodHandles.publicLookup();
 173     }
 174 
 175     /**
 176      * Tokenizes the composite name along colons, as well as {@link NameCodec#decode(String) demangles} and interns
 177      * the tokens. The first two tokens are not demangled as they are supposed to be the naming scheme and the name of
 178      * the operation which can be expected to consist of just alphabetical characters.
 179      * @param name the composite name consisting of colon-separated, possibly mangled tokens.
 180      * @return an array of tokens
 181      */
 182     public static String[] tokenizeName(final String name) {
 183         final StringTokenizer tok = new StringTokenizer(name, CallSiteDescriptor.TOKEN_DELIMITER);
 184         final String[] tokens = new String[tok.countTokens()];
 185         for(int i = 0; i < tokens.length; ++i) {
 186             String token = tok.nextToken();
 187             if(i > 1) {
 188                 token = NameCodec.decode(token);
 189             }
 190             tokens[i] = token.intern();
 191         }
 192         return tokens;
 193     }
 194 
 195     /**
 196      * Tokenizes a composite operation name along pipe characters. I.e. if you have a "dyn:getElem|getProp|getMethod"
 197      * operation, returns a list of ["getElem", "getProp", "getMethod"]. The tokens are not interned.
 198      * @param desc the call site descriptor with the operation
 199      * @return a list of tokens
 200      */
 201     public static List<String> tokenizeOperators(final CallSiteDescriptor desc) {
 202         final String ops = desc.getNameToken(CallSiteDescriptor.OPERATOR);
 203         final StringTokenizer tok = new StringTokenizer(ops, CallSiteDescriptor.OPERATOR_DELIMITER);
 204         final int count = tok.countTokens();
 205         if(count == 1) {
 206             return Collections.singletonList(ops);
 207         }
 208         final String[] tokens = new String[count];
 209         for(int i = 0; i < count; ++i) {
 210             tokens[i] = tok.nextToken();
 211         }
 212         return Arrays.asList(tokens);
 213     }
 214 
 215     /**
 216      * Returns a new call site descriptor that is identical to the passed one, except that it has some parameter types
 217      * removed from its method type.
 218      * @param desc the original call site descriptor
 219      * @param start index of the first parameter to remove
 220      * @param end index of the first parameter to not remove
 221      * @return a new call site descriptor with modified method type
 222      */
 223     public static CallSiteDescriptor dropParameterTypes(final CallSiteDescriptor desc, final int start, final int end) {
 224         return desc.changeMethodType(desc.getMethodType().dropParameterTypes(start, end));
 225     }
 226 
 227     /**
 228      * Returns a new call site descriptor that is identical to the passed one, except that it has a single parameter
 229      * type changed in its method type.
 230      * @param desc the original call site descriptor
 231      * @param num index of the parameter to change
 232      * @param nptype the new parameter type
 233      * @return a new call site descriptor with modified method type
 234      */
 235     public static CallSiteDescriptor changeParameterType(final CallSiteDescriptor desc, final int num, final Class<?> nptype) {
 236         return desc.changeMethodType(desc.getMethodType().changeParameterType(num, nptype));
 237     }
 238 
 239     /**
 240      * Returns a new call site descriptor that is identical to the passed one, except that it has the return type
 241      * changed in its method type.
 242      * @param desc the original call site descriptor
 243      * @param nrtype the new return type
 244      * @return a new call site descriptor with modified method type
 245      */
 246     public static CallSiteDescriptor changeReturnType(final CallSiteDescriptor desc, final Class<?> nrtype) {
 247         return desc.changeMethodType(desc.getMethodType().changeReturnType(nrtype));
 248     }
 249 
 250     /**
 251      * Returns a new call site descriptor that is identical to the passed one, except that it has additional parameter
 252      * types inserted into its method type.
 253      * @param desc the original call site descriptor
 254      * @param num index at which the new parameters are inserted
 255      * @param ptypesToInsert the new types to insert
 256      * @return a new call site descriptor with modified method type
 257      */
 258     public static CallSiteDescriptor insertParameterTypes(final CallSiteDescriptor desc, final int num, final Class<?>... ptypesToInsert) {
 259         return desc.changeMethodType(desc.getMethodType().insertParameterTypes(num, ptypesToInsert));
 260     }
 261 
 262     /**
 263      * Returns a new call site descriptor that is identical to the passed one, except that it has additional parameter
 264      * types inserted into its method type.
 265      * @param desc the original call site descriptor
 266      * @param num index at which the new parameters are inserted
 267      * @param ptypesToInsert the new types to insert
 268      * @return a new call site descriptor with modified method type
 269      */
 270     public static CallSiteDescriptor insertParameterTypes(final CallSiteDescriptor desc, final int num, final List<Class<?>> ptypesToInsert) {
 271         return desc.changeMethodType(desc.getMethodType().insertParameterTypes(num, ptypesToInsert));
 272     }
 273 }