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.Objects;
  95 import java.util.StringTokenizer;
  96 import java.util.WeakHashMap;
  97 import jdk.internal.dynalink.CallSiteDescriptor;
  98 
  99 /**
 100  * Usable as a default factory for call site descriptor implementations. It is weakly canonicalizing, meaning it will
 101  * return the same immutable call site descriptor for identical inputs, i.e. repeated requests for a descriptor
 102  * signifying public lookup for "dyn:getProp:color" of type "Object(Object)" will return the same object as long as
 103  * a previously created, at least softly reachable one exists. It also uses several different implementations of the
 104  * {@link CallSiteDescriptor} internally, and chooses the most space-efficient one based on the input.
 105  * @author Attila Szegedi
 106  */
 107 public class CallSiteDescriptorFactory {
 108     private static final WeakHashMap<CallSiteDescriptor, Reference<CallSiteDescriptor>> publicDescs =
 109             new WeakHashMap<>();
 110 
 111 
 112     private CallSiteDescriptorFactory() {
 113     }
 114 
 115     /**
 116      * Creates a new call site descriptor instance. The actual underlying class of the instance is dependent on the
 117      * passed arguments to be space efficient; i.e. if you  only use the public lookup, you'll get back an
 118      * implementation that doesn't waste space on storing the lookup object.
 119      * @param lookup the lookup that determines access rights at the call site. If your language runtime doesn't have
 120      * equivalents of Java access concepts, just use {@link MethodHandles#publicLookup()}. Must not be null.
 121      * @param name the name of the method at the call site. Must not be null.
 122      * @param methodType the type of the method at the call site. Must not be null.
 123      * @return a call site descriptor representing the input. Note that although the method name is "create", it will
 124      * in fact return a weakly-referenced canonical instance.
 125      */
 126     public static CallSiteDescriptor create(final Lookup lookup, final String name, final MethodType methodType) {
 127         Objects.requireNonNull(name);
 128         Objects.requireNonNull(methodType);
 129         Objects.requireNonNull(lookup);
 130         final String[] tokenizedName = tokenizeName(name);
 131         if(isPublicLookup(lookup)) {
 132             return getCanonicalPublicDescriptor(createPublicCallSiteDescriptor(tokenizedName, methodType));
 133         }
 134         return new LookupCallSiteDescriptor(tokenizedName, methodType, lookup);
 135     }
 136 
 137     static CallSiteDescriptor getCanonicalPublicDescriptor(final CallSiteDescriptor desc) {
 138         synchronized(publicDescs) {
 139             final Reference<CallSiteDescriptor> ref = publicDescs.get(desc);
 140             if(ref != null) {
 141                 final CallSiteDescriptor canonical = ref.get();
 142                 if(canonical != null) {
 143                     return canonical;
 144                 }
 145             }
 146             publicDescs.put(desc, createReference(desc));
 147         }
 148         return desc;
 149     }
 150 
 151     /**
 152      * Override this to use a different kind of references for the cache
 153      * @param desc desc
 154      * @return reference
 155      */
 156     protected static Reference<CallSiteDescriptor> createReference(final CallSiteDescriptor desc) {
 157         return new WeakReference<>(desc);
 158     }
 159 
 160     private static CallSiteDescriptor createPublicCallSiteDescriptor(final String[] tokenizedName, final MethodType methodType) {
 161         final int l = tokenizedName.length;
 162         if(l > 0 && tokenizedName[0] == "dyn") {
 163             if(l == 2) {
 164                 return new UnnamedDynCallSiteDescriptor(tokenizedName[1], methodType);
 165             } if (l == 3) {
 166                 return new NamedDynCallSiteDescriptor(tokenizedName[1], tokenizedName[2], methodType);
 167             }
 168         }
 169         return new DefaultCallSiteDescriptor(tokenizedName, methodType);
 170     }
 171 
 172     private static boolean isPublicLookup(final Lookup lookup) {
 173         return lookup == MethodHandles.publicLookup();
 174     }
 175 
 176     /**
 177      * Tokenizes the composite name along colons, as well as {@link NameCodec#decode(String) demangles} and interns
 178      * the tokens. The first two tokens are not demangled as they are supposed to be the naming scheme and the name of
 179      * the operation which can be expected to consist of just alphabetical characters.
 180      * @param name the composite name consisting of colon-separated, possibly mangled tokens.
 181      * @return an array of tokens
 182      */
 183     public static String[] tokenizeName(final String name) {
 184         final StringTokenizer tok = new StringTokenizer(name, CallSiteDescriptor.TOKEN_DELIMITER);
 185         final String[] tokens = new String[tok.countTokens()];
 186         for(int i = 0; i < tokens.length; ++i) {
 187             String token = tok.nextToken();
 188             if(i > 1) {
 189                 token = NameCodec.decode(token);
 190             }
 191             tokens[i] = token.intern();
 192         }
 193         return tokens;
 194     }
 195 
 196     /**
 197      * Tokenizes a composite operation name along pipe characters. I.e. if you have a "dyn:getElem|getProp|getMethod"
 198      * operation, returns a list of ["getElem", "getProp", "getMethod"]. The tokens are not interned.
 199      * @param desc the call site descriptor with the operation
 200      * @return a list of tokens
 201      */
 202     public static List<String> tokenizeOperators(final CallSiteDescriptor desc) {
 203         final String ops = desc.getNameToken(CallSiteDescriptor.OPERATOR);
 204         final StringTokenizer tok = new StringTokenizer(ops, CallSiteDescriptor.OPERATOR_DELIMITER);
 205         final int count = tok.countTokens();
 206         if(count == 1) {
 207             return Collections.singletonList(ops);
 208         }
 209         final String[] tokens = new String[count];
 210         for(int i = 0; i < count; ++i) {
 211             tokens[i] = tok.nextToken();
 212         }
 213         return Arrays.asList(tokens);
 214     }
 215 
 216     /**
 217      * Returns a new call site descriptor that is identical to the passed one, except that it has some parameter types
 218      * removed from its method type.
 219      * @param desc the original call site descriptor
 220      * @param start index of the first parameter to remove
 221      * @param end index of the first parameter to not remove
 222      * @return a new call site descriptor with modified method type
 223      */
 224     public static CallSiteDescriptor dropParameterTypes(final CallSiteDescriptor desc, final int start, final int end) {
 225         return desc.changeMethodType(desc.getMethodType().dropParameterTypes(start, end));
 226     }
 227 
 228     /**
 229      * Returns a new call site descriptor that is identical to the passed one, except that it has a single parameter
 230      * type changed in its method type.
 231      * @param desc the original call site descriptor
 232      * @param num index of the parameter to change
 233      * @param nptype the new parameter type
 234      * @return a new call site descriptor with modified method type
 235      */
 236     public static CallSiteDescriptor changeParameterType(final CallSiteDescriptor desc, final int num, final Class<?> nptype) {
 237         return desc.changeMethodType(desc.getMethodType().changeParameterType(num, nptype));
 238     }
 239 
 240     /**
 241      * Returns a new call site descriptor that is identical to the passed one, except that it has the return type
 242      * changed in its method type.
 243      * @param desc the original call site descriptor
 244      * @param nrtype the new return type
 245      * @return a new call site descriptor with modified method type
 246      */
 247     public static CallSiteDescriptor changeReturnType(final CallSiteDescriptor desc, final Class<?> nrtype) {
 248         return desc.changeMethodType(desc.getMethodType().changeReturnType(nrtype));
 249     }
 250 
 251     /**
 252      * Returns a new call site descriptor that is identical to the passed one, except that it has additional parameter
 253      * types inserted into its method type.
 254      * @param desc the original call site descriptor
 255      * @param num index at which the new parameters are inserted
 256      * @param ptypesToInsert the new types to insert
 257      * @return a new call site descriptor with modified method type
 258      */
 259     public static CallSiteDescriptor insertParameterTypes(final CallSiteDescriptor desc, final int num, final Class<?>... ptypesToInsert) {
 260         return desc.changeMethodType(desc.getMethodType().insertParameterTypes(num, ptypesToInsert));
 261     }
 262 
 263     /**
 264      * Returns a new call site descriptor that is identical to the passed one, except that it has additional parameter
 265      * types inserted into its method type.
 266      * @param desc the original call site descriptor
 267      * @param num index at which the new parameters are inserted
 268      * @param ptypesToInsert the new types to insert
 269      * @return a new call site descriptor with modified method type
 270      */
 271     public static CallSiteDescriptor insertParameterTypes(final CallSiteDescriptor desc, final int num, final List<Class<?>> ptypesToInsert) {
 272         return desc.changeMethodType(desc.getMethodType().insertParameterTypes(num, ptypesToInsert));
 273     }
 274 }