6829144: JSR 292 JVM features need a provisional Java API
authorjrose
Tue, 05 May 2009 22:40:09 -0700
changeset 1193d201987cb76c
parent 1192 b3720710a4ba
child 1194 9ba256e2e5c1
6829144: JSR 292 JVM features need a provisional Java API
Summary: JDK API and runtime (partial) for anonk, meth, indy
Reviewed-by: mr
make/docs/CORE_PKGS.gmk
make/java/Makefile
make/java/dyn/Makefile
src/share/classes/java/dyn/CallSite.java
src/share/classes/java/dyn/InvokeDynamic.java
src/share/classes/java/dyn/InvokeDynamicBootstrapError.java
src/share/classes/java/dyn/JavaMethodHandle.java
src/share/classes/java/dyn/Linkage.java
src/share/classes/java/dyn/LinkagePermission.java
src/share/classes/java/dyn/MethodHandle.java
src/share/classes/java/dyn/MethodHandles.java
src/share/classes/java/dyn/MethodType.java
src/share/classes/java/dyn/MethodTypeForm.java
src/share/classes/java/dyn/NoAccessException.java
src/share/classes/java/dyn/WrongMethodTypeException.java
src/share/classes/java/dyn/package-info.java
src/share/classes/sun/dyn/Access.java
src/share/classes/sun/dyn/AdapterMethodHandle.java
src/share/classes/sun/dyn/BoundMethodHandle.java
src/share/classes/sun/dyn/CallSiteImpl.java
src/share/classes/sun/dyn/DirectMethodHandle.java
src/share/classes/sun/dyn/FilterGeneric.java
src/share/classes/sun/dyn/FilterOneArgument.java
src/share/classes/sun/dyn/FromGeneric.java
src/share/classes/sun/dyn/Invokers.java
src/share/classes/sun/dyn/MemberName.java
src/share/classes/sun/dyn/MethodHandleImpl.java
src/share/classes/sun/dyn/MethodHandleNatives.java
src/share/classes/sun/dyn/MethodTypeImpl.java
src/share/classes/sun/dyn/ToGeneric.java
src/share/classes/sun/dyn/anon/AnonymousClassLoader.java
src/share/classes/sun/dyn/anon/ConstantPoolParser.java
src/share/classes/sun/dyn/anon/ConstantPoolPatch.java
src/share/classes/sun/dyn/anon/ConstantPoolVisitor.java
src/share/classes/sun/dyn/anon/InvalidConstantPoolFormatException.java
src/share/classes/sun/dyn/empty/Empty.java
src/share/classes/sun/dyn/package-info.java
src/share/classes/sun/dyn/util/BytecodeName.java
src/share/classes/sun/dyn/util/BytecodeSignature.java
src/share/classes/sun/dyn/util/ValueConversions.java
src/share/classes/sun/dyn/util/VerifyAccess.java
src/share/classes/sun/dyn/util/VerifyType.java
src/share/classes/sun/dyn/util/Wrapper.java
src/share/classes/sun/dyn/util/package-info.java
src/share/classes/sun/misc/Unsafe.java
src/share/javavm/export/classfile_constants.h
src/share/native/common/check_code.c
src/share/native/common/opcodes.in_out
     1.1 --- a/make/docs/CORE_PKGS.gmk	Mon May 04 22:16:02 2009 -0700
     1.2 +++ b/make/docs/CORE_PKGS.gmk	Tue May 05 22:40:09 2009 -0700
     1.3 @@ -1,5 +1,5 @@
     1.4  #
     1.5 -# Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
     1.6 +# Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
     1.7  # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.8  #
     1.9  # This code is free software; you can redistribute it and/or modify it
    1.10 @@ -55,6 +55,7 @@
    1.11  # This is a list of regular expressions. So foo.* matches "foo" and "foo.bar".
    1.12  #
    1.13  ACTIVE_JSR_PKGS= \
    1.14 +  java.dyn \
    1.15    java.sql  \
    1.16    javax.activation  \
    1.17    javax.annotation.*  \
     2.1 --- a/make/java/Makefile	Mon May 04 22:16:02 2009 -0700
     2.2 +++ b/make/java/Makefile	Tue May 05 22:40:09 2009 -0700
     2.3 @@ -1,5 +1,5 @@
     2.4  #
     2.5 -# Copyright 1995-2006 Sun Microsystems, Inc.  All Rights Reserved.
     2.6 +# Copyright 1995-2009 Sun Microsystems, Inc.  All Rights Reserved.
     2.7  # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     2.8  #
     2.9  # This code is free software; you can redistribute it and/or modify it
    2.10 @@ -39,7 +39,7 @@
    2.11  # Others
    2.12  #    Note: java_crw_demo java_hprof_demo are demos but must be delivered built in sdk
    2.13  SUBDIRS += security npt java_crw_demo java_hprof_demo \
    2.14 -	    math awt util text applet net nio \
    2.15 +	    math awt util text applet net nio dyn \
    2.16  	    sql rmi jar beans logging management instrument
    2.17  
    2.18  
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/make/java/dyn/Makefile	Tue May 05 22:40:09 2009 -0700
     3.3 @@ -0,0 +1,44 @@
     3.4 +#
     3.5 +# Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
     3.6 +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     3.7 +#
     3.8 +# This code is free software; you can redistribute it and/or modify it
     3.9 +# under the terms of the GNU General Public License version 2 only, as
    3.10 +# published by the Free Software Foundation.  Sun designates this
    3.11 +# particular file as subject to the "Classpath" exception as provided
    3.12 +# by Sun in the LICENSE file that accompanied this code.
    3.13 +#
    3.14 +# This code is distributed in the hope that it will be useful, but WITHOUT
    3.15 +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    3.16 +# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    3.17 +# version 2 for more details (a copy is included in the LICENSE file that
    3.18 +# accompanied this code).
    3.19 +#
    3.20 +# You should have received a copy of the GNU General Public License version
    3.21 +# 2 along with this work; if not, write to the Free Software Foundation,
    3.22 +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    3.23 +#
    3.24 +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    3.25 +# CA 95054 USA or visit www.sun.com if you need additional information or
    3.26 +# have any questions.
    3.27 +#
    3.28 +
    3.29 +BUILDDIR = ../..
    3.30 +
    3.31 +PACKAGE = java.dyn
    3.32 +PRODUCT = java
    3.33 +include $(BUILDDIR)/common/Defs.gmk
    3.34 +
    3.35 +AUTO_FILES_JAVA_DIRS = java/dyn sun/dyn
    3.36 +
    3.37 +# The sources built here use new language syntax to generate
    3.38 +# method handle calls.  Let's be sure we are using that format.
    3.39 +#LANGUAGE_VERSION = -source 7
    3.40 +#CLASS_VERSION = -target 7
    3.41 +
    3.42 +# Actually, it will be less disruptive to compile with the same
    3.43 +# -target option as the rest of the system, and just turn on
    3.44 +# the specific compiler option we need here:
    3.45 +OTHER_JAVACFLAGS = -XDinvokedynamic
    3.46 +
    3.47 +include $(BUILDDIR)/common/Classes.gmk
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/src/share/classes/java/dyn/CallSite.java	Tue May 05 22:40:09 2009 -0700
     4.3 @@ -0,0 +1,201 @@
     4.4 +/*
     4.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
     4.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4.7 + *
     4.8 + * This code is free software; you can redistribute it and/or modify it
     4.9 + * under the terms of the GNU General Public License version 2 only, as
    4.10 + * published by the Free Software Foundation.  Sun designates this
    4.11 + * particular file as subject to the "Classpath" exception as provided
    4.12 + * by Sun in the LICENSE file that accompanied this code.
    4.13 + *
    4.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    4.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    4.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    4.17 + * version 2 for more details (a copy is included in the LICENSE file that
    4.18 + * accompanied this code).
    4.19 + *
    4.20 + * You should have received a copy of the GNU General Public License version
    4.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    4.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    4.23 + *
    4.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    4.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
    4.26 + * have any questions.
    4.27 + */
    4.28 +
    4.29 +package java.dyn;
    4.30 +
    4.31 +import sun.dyn.util.BytecodeName;
    4.32 +
    4.33 +/**
    4.34 + * An <code>invokedynamic</code> call site, as reified to the bootstrap method.
    4.35 + * Every instance of a call site corresponds to a distinct instance
    4.36 + * of the <code>invokedynamic</code> instruction.
    4.37 + * Call sites have state, one reference word, called the <code>target</code>,
    4.38 + * and typed as a {@link MethodHandle}.  When this state is null (as it is
    4.39 + * initially) the call site is in the unlinked state.  Otherwise, it is said
    4.40 + * to be linked to its target.
    4.41 + * <p>
    4.42 + * When an unlinked call site is executed, a bootstrap routine is called
    4.43 + * to finish the execution of the call site, and optionally to link
    4.44 + * the call site.
    4.45 + * <p>
    4.46 + * @author John Rose, JSR 292 EG
    4.47 + */
    4.48 +public class CallSite {
    4.49 +    // Fields used only by the JVM.  Do not use or change.
    4.50 +    private Object vmmethod;
    4.51 +    int callerMID, callerBCI;  // supplied by the JVM
    4.52 +
    4.53 +    MethodHandle target;
    4.54 +    final Object caller;  // usually a class
    4.55 +    final String name;
    4.56 +    final MethodType type;
    4.57 +
    4.58 +    public CallSite(Object caller, String name, MethodType type) {
    4.59 +        this.caller = caller;
    4.60 +        this.name = name;
    4.61 +        this.type = type;
    4.62 +    }
    4.63 +
    4.64 +    private static void privateInitializeCallSite(CallSite site, int callerMID, int callerBCI) {
    4.65 +        site.callerMID = callerMID;
    4.66 +        site.callerBCI = callerBCI;
    4.67 +        if (site.target == null)
    4.68 +            site.setTarget(site.initialTarget());
    4.69 +    }
    4.70 +
    4.71 +    /**
    4.72 +     * Just after a call site is created by a bootstrap method handle,
    4.73 +     * if the target has not been initialized by the factory method itself,
    4.74 +     * the method {@code initialTarget} is called to produce an initial
    4.75 +     * non-null target.  (Live call sites must never have null targets.)
    4.76 +     * <p>
    4.77 +     * If the bootstrap method itself does not initialize the call site,
    4.78 +     * this method must be overridden, because it just raises an
    4.79 +     * {@code InvokeDynamicBootstrapError}.
    4.80 +     */
    4.81 +    protected MethodHandle initialTarget() {
    4.82 +        throw new InvokeDynamicBootstrapError("target must be initialized before call site is linked: "+this);
    4.83 +    }
    4.84 +
    4.85 +    /**
    4.86 +     * Report the current linkage state of the call site.  (This is mutable.)
    4.87 +     * The value is null if and only if the call site is currently unlinked.
    4.88 +     * When a linked call site is invoked, the target method is used directly.
    4.89 +     * When an unlinked call site is invoked, its bootstrap method receives
    4.90 +     * the call, as if via {@link Linkage#bootstrapInvokeDynamic}.
    4.91 +     * <p>
    4.92 +     * The interactions of {@code getTarget} with memory are the same
    4.93 +     * as of a read from an ordinary variable, such as an array element or a
    4.94 +     * non-volatile, non-final field.
    4.95 +     * <p>
    4.96 +     * In particular, the current thread may choose to reuse the result
    4.97 +     * of a previous read of the target from memory, and may fail to see
    4.98 +     * a recent update to the target by another thread.
    4.99 +     * @return the current linkage state of the call site
   4.100 +     * @see #setTarget
   4.101 +     */
   4.102 +    public MethodHandle getTarget() {
   4.103 +        return target;
   4.104 +    }
   4.105 +
   4.106 +    /**
   4.107 +     * Link or relink the call site, by setting its target method.
   4.108 +     * <p>
   4.109 +     * The interactions of {@code setTarget} with memory are the same
   4.110 +     * as of a write to an ordinary variable, such as an array element or a
   4.111 +     * non-volatile, non-final field.
   4.112 +     * <p>
   4.113 +     * In particular, unrelated threads may fail to see the updated target
   4.114 +     * until they perform a read from memory.
   4.115 +     * Stronger guarantees can be created by putting appropriate operations
   4.116 +     * into the bootstrap method and/or the target methods used
   4.117 +     * at any given call site.
   4.118 +     * @param target the new target, or null if it is to be unlinked
   4.119 +     * @throws WrongMethodTypeException if the new target is not null
   4.120 +     *         and has a method type that differs from the call site's {@link #type}
   4.121 +     */
   4.122 +    public void setTarget(MethodHandle target) {
   4.123 +        checkTarget(target);
   4.124 +        this.target = target;
   4.125 +    }
   4.126 +
   4.127 +    protected void checkTarget(MethodHandle target) {
   4.128 +        if (!canSetTarget(target))
   4.129 +            throw new WrongMethodTypeException(String.valueOf(target));
   4.130 +    }
   4.131 +
   4.132 +    protected boolean canSetTarget(MethodHandle target) {
   4.133 +        return (target != null && target.type() == type());
   4.134 +    }
   4.135 +
   4.136 +    /**
   4.137 +     * Report the class containing the call site.
   4.138 +     * This is immutable static context.
   4.139 +     * @return class containing the call site
   4.140 +     */
   4.141 +    public Class<?> callerClass() {
   4.142 +        return (Class) caller;
   4.143 +    }
   4.144 +
   4.145 +    /**
   4.146 +     * Report the method name specified in the {@code invokedynamic} instruction.
   4.147 +     * This is immutable static context.
   4.148 +     * <p>
   4.149 +     * Note that the name is a JVM bytecode name, and as such can be any
   4.150 +     * non-empty string, as long as it does not contain certain "dangerous"
   4.151 +     * characters such as slash {@code '/'} and dot {@code '.'}.
   4.152 +     * See the Java Virtual Machine specification for more details.
   4.153 +     * <p>
   4.154 +     * Application such as a language runtimes may need to encode
   4.155 +     * arbitrary program element names and other configuration information
   4.156 +     * into the name.  A standard convention for doing this is
   4.157 +     * <a href="http://blogs.sun.com/jrose/entry/symbolic_freedom_in_the_vm">specified here</a>.
   4.158 +     * @return method name specified by the call site
   4.159 +     */
   4.160 +    public String name() {
   4.161 +        return name;
   4.162 +    }
   4.163 +
   4.164 +    /**
   4.165 +     * Report the method name specified in the {@code invokedynamic} instruction,
   4.166 +     * as a series of components, individually demangled according to
   4.167 +     * the standard convention
   4.168 +     * <a href="http://blogs.sun.com/jrose/entry/symbolic_freedom_in_the_vm">specified here</a>.
   4.169 +     * <p>
   4.170 +     * Non-empty runs of characters between dangerous characters are demangled.
   4.171 +     * Each component is either a completely arbitrary demangled string,
   4.172 +     * or else a character constant for a punctuation character, typically ':'.
   4.173 +     * (In principle, the character can be any dangerous character that the
   4.174 +     * JVM lets through in a method name, such as '$' or ']'.
   4.175 +     * Runtime implementors are encouraged to use colon ':' for building
   4.176 +     * structured names.)
   4.177 +     * <p>
   4.178 +     * In the common case where the name contains no dangerous characters,
   4.179 +     * the result is an array whose only element array is the demangled
   4.180 +     * name at the call site.  Such a demangled name can be any sequence
   4.181 +     * of any number of any unicode characters.
   4.182 +     * @return method name components specified by the call site
   4.183 +     */
   4.184 +    public Object[] nameComponents() {
   4.185 +        return BytecodeName.parseBytecodeName(name);
   4.186 +    }
   4.187 +
   4.188 +    /**
   4.189 +     * Report the resolved result and parameter types of this call site,
   4.190 +     * which are derived from its bytecode-level invocation descriptor.
   4.191 +     * The types are packaged into a {@link MethodType}.
   4.192 +     * Any linked target of this call site must be exactly this method type.
   4.193 +     * This is immutable static context.
   4.194 +     * @return method type specified by the call site
   4.195 +     */
   4.196 +    public MethodType type() {
   4.197 +        return type;
   4.198 +    }
   4.199 +
   4.200 +    @Override
   4.201 +    public String toString() {
   4.202 +        return "CallSite#"+hashCode()+"["+name+type+" => "+target+"]";
   4.203 +    }
   4.204 +}
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/src/share/classes/java/dyn/InvokeDynamic.java	Tue May 05 22:40:09 2009 -0700
     5.3 @@ -0,0 +1,39 @@
     5.4 +/*
     5.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
     5.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     5.7 + *
     5.8 + * This code is free software; you can redistribute it and/or modify it
     5.9 + * under the terms of the GNU General Public License version 2 only, as
    5.10 + * published by the Free Software Foundation.  Sun designates this
    5.11 + * particular file as subject to the "Classpath" exception as provided
    5.12 + * by Sun in the LICENSE file that accompanied this code.
    5.13 + *
    5.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    5.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    5.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    5.17 + * version 2 for more details (a copy is included in the LICENSE file that
    5.18 + * accompanied this code).
    5.19 + *
    5.20 + * You should have received a copy of the GNU General Public License version
    5.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    5.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    5.23 + *
    5.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    5.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
    5.26 + * have any questions.
    5.27 + */
    5.28 +
    5.29 +package java.dyn;
    5.30 +
    5.31 +/**
    5.32 + * Syntactic marker interface to request javac to emit an {@code invokedynamic} instruction.
    5.33 + * <p>
    5.34 + * This type has no particular meaning as a class or interface supertype, and can never be instantiated.
    5.35 + * Logically, it denotes a source of all dynamically typed methods.
    5.36 + * @author John Rose, JSR 292 EG
    5.37 + */
    5.38 +public final class InvokeDynamic {
    5.39 +    private InvokeDynamic() { throw new InternalError(); }  // do not instantiate
    5.40 +
    5.41 +    // no statically defined static methods
    5.42 +}
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/src/share/classes/java/dyn/InvokeDynamicBootstrapError.java	Tue May 05 22:40:09 2009 -0700
     6.3 @@ -0,0 +1,55 @@
     6.4 +/*
     6.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
     6.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     6.7 + *
     6.8 + * This code is free software; you can redistribute it and/or modify it
     6.9 + * under the terms of the GNU General Public License version 2 only, as
    6.10 + * published by the Free Software Foundation.  Sun designates this
    6.11 + * particular file as subject to the "Classpath" exception as provided
    6.12 + * by Sun in the LICENSE file that accompanied this code.
    6.13 + *
    6.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    6.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    6.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    6.17 + * version 2 for more details (a copy is included in the LICENSE file that
    6.18 + * accompanied this code).
    6.19 + *
    6.20 + * You should have received a copy of the GNU General Public License version
    6.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    6.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    6.23 + *
    6.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    6.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
    6.26 + * have any questions.
    6.27 + */
    6.28 +
    6.29 +package java.dyn;
    6.30 +
    6.31 +/**
    6.32 + * Thrown to indicate that an {@code invokedynamic} instruction has
    6.33 + * failed to find its bootstrap method, or the bootstrap method has
    6.34 + * failed to provide a call site with a non-null target.
    6.35 + * <p>
    6.36 + * The boostrap method must have been declared during a class's initialization
    6.37 + * by a call to {@link Linkage#registerBootstrapMethod}.
    6.38 + *
    6.39 + * @author John Rose, JSR 292 EG
    6.40 + */
    6.41 +public class InvokeDynamicBootstrapError extends LinkageError {
    6.42 +    /**
    6.43 +     * Constructs a {@code InvokeDynamicBootstrapError} with no detail message.
    6.44 +     */
    6.45 +    public InvokeDynamicBootstrapError() {
    6.46 +        super();
    6.47 +    }
    6.48 +
    6.49 +    /**
    6.50 +     * Constructs a {@code InvokeDynamicBootstrapError} with the specified
    6.51 +     * detail message.
    6.52 +     *
    6.53 +     * @param s the detail message.
    6.54 +     */
    6.55 +    public InvokeDynamicBootstrapError(String s) {
    6.56 +        super(s);
    6.57 +    }
    6.58 +}
     7.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     7.2 +++ b/src/share/classes/java/dyn/JavaMethodHandle.java	Tue May 05 22:40:09 2009 -0700
     7.3 @@ -0,0 +1,83 @@
     7.4 +/*
     7.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
     7.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     7.7 + *
     7.8 + * This code is free software; you can redistribute it and/or modify it
     7.9 + * under the terms of the GNU General Public License version 2 only, as
    7.10 + * published by the Free Software Foundation.  Sun designates this
    7.11 + * particular file as subject to the "Classpath" exception as provided
    7.12 + * by Sun in the LICENSE file that accompanied this code.
    7.13 + *
    7.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    7.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    7.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    7.17 + * version 2 for more details (a copy is included in the LICENSE file that
    7.18 + * accompanied this code).
    7.19 + *
    7.20 + * You should have received a copy of the GNU General Public License version
    7.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    7.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    7.23 + *
    7.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    7.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
    7.26 + * have any questions.
    7.27 + */
    7.28 +
    7.29 +package java.dyn;
    7.30 +
    7.31 +/**
    7.32 + * A Java method handle extends the basic method handle type with additional
    7.33 + * programmer defined methods and fields.
    7.34 + * Its behavior as a method handle is determined at instance creation time,
    7.35 + * by providing the new instance with an "entry point" method handle
    7.36 + * to handle calls.  This entry point must accept a leading argument
    7.37 + * whose type is the Java method handle itself or a supertype, and the
    7.38 + * entry point is always called with the Java method handle itself as
    7.39 + * the first argument.  This is similar to ordinary virtual methods, which also
    7.40 + * accept the receiver object {@code this} as an implicit leading argument.
    7.41 + * The {@code MethodType} of the Java method handle is the same as that
    7.42 + * of the entry point method handle, with the leading parameter type
    7.43 + * omitted.
    7.44 + * <p>
    7.45 + * Here is an example of usage:
    7.46 + * <p><blockquote><pre>
    7.47 + *     class Greeter extends JavaMethodHandle {
    7.48 + *         public void run() { System.out.println("hello, "+greetee); }
    7.49 + *         private final String greetee;
    7.50 + *         Greeter(String greetee) {
    7.51 + *             super(RUN);
    7.52 + *             this.greetee = greetee;
    7.53 + *         }
    7.54 + *         // the entry point function is computed once:
    7.55 + *         private static final MethodHandle RUN
    7.56 + *             = MethodHandles.findVirtual(MyMethodHandle.class, "run",
    7.57 + *                   MethodType.make(void.class));
    7.58 + *     }
    7.59 + *     Greeter greeter = new Greeter("world");
    7.60 + *     greeter.run();  // prints "hello, world"
    7.61 + *     MethodHandle mh = greeter;
    7.62 + *     mh.invoke();  // also prints "hello, world"
    7.63 + * </pre></blockquote>
    7.64 + * <p>
    7.65 + * In this example, the method {@code run} provides the entry point.
    7.66 + * The entry point need not be a constant value; it may be independently
    7.67 + * computed in each call to the constructor.  The entry point does not
    7.68 + * even need to be a method on the Java method handle class, though
    7.69 + * that is the typical case.
    7.70 + * @see MethodHandle
    7.71 + * @author John Rose, JSR 292 EG
    7.72 + */
    7.73 +public abstract class JavaMethodHandle
    7.74 +        // Note: This is an implementation inheritance hack, and will be removed
    7.75 +        // with a JVM change which moves the required hidden behavior onto this class.
    7.76 +        extends sun.dyn.BoundMethodHandle
    7.77 +{
    7.78 +    /**
    7.79 +     * When creating a, pass in {@code entryPoint}, any method handle which
    7.80 +     * can take the current object
    7.81 +     * @param entryPoint
    7.82 +     */
    7.83 +    protected JavaMethodHandle(MethodHandle entryPoint) {
    7.84 +        super(entryPoint, 0);
    7.85 +    }
    7.86 +}
     8.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     8.2 +++ b/src/share/classes/java/dyn/Linkage.java	Tue May 05 22:40:09 2009 -0700
     8.3 @@ -0,0 +1,199 @@
     8.4 +/*
     8.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
     8.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     8.7 + *
     8.8 + * This code is free software; you can redistribute it and/or modify it
     8.9 + * under the terms of the GNU General Public License version 2 only, as
    8.10 + * published by the Free Software Foundation.  Sun designates this
    8.11 + * particular file as subject to the "Classpath" exception as provided
    8.12 + * by Sun in the LICENSE file that accompanied this code.
    8.13 + *
    8.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    8.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    8.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    8.17 + * version 2 for more details (a copy is included in the LICENSE file that
    8.18 + * accompanied this code).
    8.19 + *
    8.20 + * You should have received a copy of the GNU General Public License version
    8.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    8.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    8.23 + *
    8.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    8.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
    8.26 + * have any questions.
    8.27 + */
    8.28 +
    8.29 +package java.dyn;
    8.30 +
    8.31 +import java.util.WeakHashMap;
    8.32 +import sun.reflect.Reflection;
    8.33 +import static sun.dyn.util.VerifyAccess.checkBootstrapPrivilege;
    8.34 +
    8.35 +/**
    8.36 + * Static methods which control the linkage of invokedynamic call sites.
    8.37 + * @author John Rose, JSR 292 EG
    8.38 + */
    8.39 +public class Linkage {
    8.40 +    private Linkage() {}  // do not instantiate
    8.41 +
    8.42 +    /**
    8.43 +     * Register a bootstrap method for use for a given caller class.
    8.44 +     * The method handle must be of a type equivalent to {@link Linkage#makeCallSite}.
    8.45 +     * <p>
    8.46 +     * The operation will fail with an exception if any of the following conditions hold:
    8.47 +     * <ul>
    8.48 +     * <li>The caller of this method is in a different package than the {@code callerClass},
    8.49 +     *     and there is a security manager, and its {@code checkPermission} call throws
    8.50 +     *     when passed {@link LinkagePermission}("registerBootstrapMethod",callerClass).
    8.51 +     * <li>The given class already has a bootstrap method, either from an embedded
    8.52 +     *     {@code BootstrapInvokeDynamic} classfile attribute, or from a previous
    8.53 +     *     call to this method.
    8.54 +     * <li>The given class is already fully initialized.
    8.55 +     * <li>The given class is in the process of initialization, in another thread.
    8.56 +     * </ul>
    8.57 +     * Because of these rules, a class may install its own bootstrap method in
    8.58 +     * a static initializer.
    8.59 +     */
    8.60 +    public static
    8.61 +    void registerBootstrapMethod(Class callerClass, MethodHandle mh) {
    8.62 +        Class callc = Reflection.getCallerClass(2);
    8.63 +        checkBootstrapPrivilege(callc, callerClass, "registerBootstrapMethod");
    8.64 +        checkBSM(mh);
    8.65 +        synchronized (bootstrapMethods) {
    8.66 +            if (bootstrapMethods.containsKey(callerClass))
    8.67 +                throw new IllegalStateException("bootstrap method already declared in "+callerClass);
    8.68 +            bootstrapMethods.put(callerClass, mh);
    8.69 +        }
    8.70 +    }
    8.71 +
    8.72 +    static void checkBSM(MethodHandle mh) {
    8.73 +        if (mh == null)  throw new IllegalArgumentException("null bootstrap method");
    8.74 +        if (mh.type() == OLD_BOOTSTRAP_METHOD_TYPE) // FIXME: delete at EDR/PFD
    8.75 +            throw new WrongMethodTypeException("bootstrap method must be a CallSite factory");
    8.76 +        if (mh.type() != BOOTSTRAP_METHOD_TYPE)
    8.77 +            throw new WrongMethodTypeException(mh.toString());
    8.78 +    }
    8.79 +
    8.80 +    /**
    8.81 +     * Simplified version of registerBootstrapMethod for self-registration,
    8.82 +     * to be called from a static initializer.
    8.83 +     * Finds a static method of type (CallSite, Object[]) -> Object in the
    8.84 +     * given class, and installs it on the caller.
    8.85 +     * @throws IllegalArgumentException if there is no such method
    8.86 +     */
    8.87 +    public static
    8.88 +    void registerBootstrapMethod(Class<?> runtime, String name) {
    8.89 +        Class callc = Reflection.getCallerClass(2);
    8.90 +        MethodHandle bootstrapMethod =
    8.91 +            MethodHandles.findStaticFrom(callc, runtime, name, BOOTSTRAP_METHOD_TYPE);
    8.92 +        // FIXME: exception processing wrong here
    8.93 +        checkBSM(bootstrapMethod);
    8.94 +        Linkage.registerBootstrapMethod(callc, bootstrapMethod);
    8.95 +    }
    8.96 +
    8.97 +    /**
    8.98 +     * Simplified version of registerBootstrapMethod for self-registration,
    8.99 +     * to be called from a static initializer.
   8.100 +     * Finds a static method of type (CallSite, Object[]) -> Object in the
   8.101 +     * caller's class, and installs it on the caller.
   8.102 +     * @throws IllegalArgumentException if there is no such method
   8.103 +     */
   8.104 +    public static
   8.105 +    void registerBootstrapMethod(String name) {
   8.106 +        Class callc = Reflection.getCallerClass(2);
   8.107 +        MethodHandle bootstrapMethod =
   8.108 +            MethodHandles.findStaticFrom(callc, callc, name, BOOTSTRAP_METHOD_TYPE);
   8.109 +        // FIXME: exception processing wrong here
   8.110 +        checkBSM(bootstrapMethod);
   8.111 +        Linkage.registerBootstrapMethod(callc, bootstrapMethod);
   8.112 +    }
   8.113 +
   8.114 +    /**
   8.115 +     * Report the bootstrap method registered for a given class.
   8.116 +     * Returns null if the class has never yet registered a bootstrap method,
   8.117 +     * or if the class has explicitly registered a null bootstrap method.
   8.118 +     * Only callers privileged to set the bootstrap method may inquire
   8.119 +     * about it, because a bootstrap method is potentially a back-door entry
   8.120 +     * point into its class.
   8.121 +     */
   8.122 +    public static
   8.123 +    MethodHandle getBootstrapMethod(Class callerClass) {
   8.124 +        Class callc = Reflection.getCallerClass(2);
   8.125 +        checkBootstrapPrivilege(callc, callerClass, "registerBootstrapMethod");
   8.126 +        synchronized (bootstrapMethods) {
   8.127 +            return bootstrapMethods.get(callerClass);
   8.128 +        }
   8.129 +    }
   8.130 +
   8.131 +    /** The type of any bootstrap method is a three-argument method
   8.132 +     * {@code (Class<?>, String, MethodType)} returning a {@code CallSite}.
   8.133 +     */
   8.134 +    public static final MethodType BOOTSTRAP_METHOD_TYPE
   8.135 +            = MethodType.make(CallSite.class,
   8.136 +                              Class.class, String.class, MethodType.class);
   8.137 +
   8.138 +    private static final MethodType OLD_BOOTSTRAP_METHOD_TYPE
   8.139 +            = MethodType.make(Object.class,
   8.140 +                              CallSite.class, Object[].class);
   8.141 +
   8.142 +    private static final WeakHashMap<Class, MethodHandle> bootstrapMethods =
   8.143 +            new WeakHashMap<Class, MethodHandle>();
   8.144 +
   8.145 +    /**
   8.146 +     * Invalidate all <code>invokedynamic</code> call sites everywhere.
   8.147 +     * <p>
   8.148 +     * When this method returns, every <code>invokedynamic</code> instruction
   8.149 +     * will invoke its bootstrap method on next call.
   8.150 +     * <p>
   8.151 +     * It is unspecified whether call sites already known to the Java
   8.152 +     * code will continue to be associated with <code>invokedynamic</code>
   8.153 +     * instructions.  If any call site is still so associated, its
   8.154 +     * {@link CallSite#getTarget()} method is guaranteed to return null
   8.155 +     * the invalidation operation completes.
   8.156 +     * <p>
   8.157 +     * Invalidation operations are likely to be slow.  Use them sparingly.
   8.158 +     */
   8.159 +    public static
   8.160 +    Object invalidateAll() {
   8.161 +        SecurityManager security = System.getSecurityManager();
   8.162 +        if (security != null) {
   8.163 +            security.checkPermission(new LinkagePermission("invalidateAll"));
   8.164 +        }
   8.165 +        throw new UnsupportedOperationException("NYI");
   8.166 +    }
   8.167 +
   8.168 +    /**
   8.169 +     * Invalidate all <code>invokedynamic</code> call sites associated
   8.170 +     * with the given class.
   8.171 +     * (These are exactly those sites which report the given class
   8.172 +     * via the {@link CallSite#callerClass()} method.)
   8.173 +     * <p>
   8.174 +     * When this method returns, every matching <code>invokedynamic</code>
   8.175 +     * instruction will invoke its bootstrap method on next call.
   8.176 +     * <p>
   8.177 +     * For additional semantics of call site invalidation,
   8.178 +     * see {@link #invalidateAll()}.
   8.179 +     */
   8.180 +    public static
   8.181 +    Object invalidateCallerClass(Class<?> callerClass) {
   8.182 +        SecurityManager security = System.getSecurityManager();
   8.183 +        if (security != null) {
   8.184 +            security.checkPermission(new LinkagePermission("invalidateAll", callerClass));
   8.185 +        }
   8.186 +        throw new UnsupportedOperationException("NYI");
   8.187 +    }
   8.188 +
   8.189 +    private static Object doNotBootstrap(CallSite site, Object... arguments) {
   8.190 +        throw new UnsupportedOperationException("call site must not have null target: "+site);
   8.191 +    }
   8.192 +
   8.193 +    private static final MethodHandle DO_NOT_BOOTSTRAP =
   8.194 +            MethodHandles.Lookup.IMPL_LOOKUP.findStatic(Linkage.class, "doNotBootstrap",
   8.195 +                OLD_BOOTSTRAP_METHOD_TYPE);
   8.196 +
   8.197 +    // Up-call from the JVM.  Obsolete.  FIXME: Delete from VM then from here.
   8.198 +    static
   8.199 +    MethodHandle findBootstrapMethod(Class callerClass, Class searchBootstrapClass) {
   8.200 +        return DO_NOT_BOOTSTRAP;
   8.201 +    }
   8.202 +}
     9.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     9.2 +++ b/src/share/classes/java/dyn/LinkagePermission.java	Tue May 05 22:40:09 2009 -0700
     9.3 @@ -0,0 +1,111 @@
     9.4 +/*
     9.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
     9.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     9.7 + *
     9.8 + * This code is free software; you can redistribute it and/or modify it
     9.9 + * under the terms of the GNU General Public License version 2 only, as
    9.10 + * published by the Free Software Foundation.  Sun designates this
    9.11 + * particular file as subject to the "Classpath" exception as provided
    9.12 + * by Sun in the LICENSE file that accompanied this code.
    9.13 + *
    9.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    9.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    9.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    9.17 + * version 2 for more details (a copy is included in the LICENSE file that
    9.18 + * accompanied this code).
    9.19 + *
    9.20 + * You should have received a copy of the GNU General Public License version
    9.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    9.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    9.23 + *
    9.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    9.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
    9.26 + * have any questions.
    9.27 + */
    9.28 +
    9.29 +package java.dyn;
    9.30 +
    9.31 +import java.security.*;
    9.32 +import java.util.Enumeration;
    9.33 +import java.util.Hashtable;
    9.34 +import java.util.StringTokenizer;
    9.35 +
    9.36 +/**
    9.37 + * This class is for runtime permissions. A RuntimePermission
    9.38 + * contains a name (also referred to as a "target name") but
    9.39 + * no actions list; you either have the named permission
    9.40 + * or you don't.
    9.41 + *
    9.42 + * <P>
    9.43 + * The target name is the name of the runtime permission (see below). The
    9.44 + * naming convention follows the  hierarchical property naming convention.
    9.45 + * Also, an asterisk
    9.46 + * may appear at the end of the name, following a ".", or by itself, to
    9.47 + * signify a wildcard match. For example: "loadLibrary.*" or "*" is valid,
    9.48 + * "*loadLibrary" or "a*b" is not valid.
    9.49 + * <P>
    9.50 + * The following table lists all the possible RuntimePermission target names,
    9.51 + * and for each provides a description of what the permission allows
    9.52 + * and a discussion of the risks of granting code the permission.
    9.53 + * <P>
    9.54 + *
    9.55 + * <table border=1 cellpadding=5 summary="permission target name,
    9.56 + *  what the target allows,and associated risks">
    9.57 + * <tr>
    9.58 + * <th>Permission Target Name</th>
    9.59 + * <th>What the Permission Allows</th>
    9.60 + * <th>Risks of Allowing this Permission</th>
    9.61 + * </tr>
    9.62 + *
    9.63 + * <tr>
    9.64 + *   <td>registerBootstrapMethod.{class name}</td>
    9.65 + *   <td>Specifying a bootstrap method for invokedynamic, within a class of the given name</td>
    9.66 + *   <td>An attacker could attempt to attach a bootstrap method to a class which
    9.67 + *       has just been loaded, thus gaining control of its invokedynamic calls.</td>
    9.68 + * </tr>
    9.69 + *
    9.70 + * <tr>
    9.71 + *   <td>invalidateAll</td>
    9.72 + *   <td>Force the relinking of invokedynamic call sites everywhere.</td>
    9.73 + *   <td>This could allow an attacker to slow down the system, or perhaps surface timing bugs in a dynamic language implementations, by forcing redundant relinking operations.</td>
    9.74 + * </tr>
    9.75 + *
    9.76 + *
    9.77 + * <tr>
    9.78 + *   <td>invalidateCallerClass.{class name}</td>
    9.79 + *   <td>Force the relinking of invokedynamic call sites in the given class.</td>
    9.80 + *   <td>See {@code invalidateAll}.</td>
    9.81 + * </tr>
    9.82 + * </table>
    9.83 + *
    9.84 + * @see java.security.BasicPermission
    9.85 + * @see java.lang.SecurityManager
    9.86 + *
    9.87 + * @author John Rose, JSR 292 EG
    9.88 + */
    9.89 +
    9.90 +public final class LinkagePermission extends BasicPermission {
    9.91 +    /**
    9.92 +     * Create a new LinkagePermission with the given name.
    9.93 +     * The name is the symbolic name of the LinkagePermission, such as
    9.94 +     * "registerBootstrapMethod", "invalidateClass.*", etc. An asterisk
    9.95 +     * may appear at the end of the name, following a ".", or by itself, to
    9.96 +     * signify a wildcard match.
    9.97 +     *
    9.98 +     * @param name the name of the LinkagePermission
    9.99 +     */
   9.100 +    public LinkagePermission(String name) {
   9.101 +        super(name);
   9.102 +    }
   9.103 +
   9.104 +    /**
   9.105 +     * Create a new LinkagePermission with the given name on the given class.
   9.106 +     * Equivalent to {@code LinkagePermission(name+"."+clazz.getName())}.
   9.107 +     *
   9.108 +     * @param name the name of the LinkagePermission
   9.109 +     * @param clazz the class affected by the permission
   9.110 +     */
   9.111 +    public LinkagePermission(String name, Class<?> clazz) {
   9.112 +        super(name + "." + clazz.getName());
   9.113 +    }
   9.114 +}
    10.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    10.2 +++ b/src/share/classes/java/dyn/MethodHandle.java	Tue May 05 22:40:09 2009 -0700
    10.3 @@ -0,0 +1,135 @@
    10.4 +/*
    10.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    10.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    10.7 + *
    10.8 + * This code is free software; you can redistribute it and/or modify it
    10.9 + * under the terms of the GNU General Public License version 2 only, as
   10.10 + * published by the Free Software Foundation.  Sun designates this
   10.11 + * particular file as subject to the "Classpath" exception as provided
   10.12 + * by Sun in the LICENSE file that accompanied this code.
   10.13 + *
   10.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   10.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   10.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   10.17 + * version 2 for more details (a copy is included in the LICENSE file that
   10.18 + * accompanied this code).
   10.19 + *
   10.20 + * You should have received a copy of the GNU General Public License version
   10.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   10.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   10.23 + *
   10.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   10.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   10.26 + * have any questions.
   10.27 + */
   10.28 +
   10.29 +package java.dyn;
   10.30 +
   10.31 +//import sun.dyn.*;
   10.32 +
   10.33 +import sun.dyn.Access;
   10.34 +import sun.dyn.MethodHandleImpl;
   10.35 +
   10.36 +/**
   10.37 + * A method handle is a typed reference to the entry point of a method.
   10.38 + * <p>
   10.39 + * Method handles are strongly typed according to signature.
   10.40 + * They are not distinguished by method name or enclosing class.
   10.41 + * A method handle must be invoked under a signature which exactly matches
   10.42 + * the method handle's own type.
   10.43 + * <p>
   10.44 + * Every method handle confesses its type via the <code>type</code> accessor.
   10.45 + * The structure of this type is a series of classes, one of which is
   10.46 + * the return type of the method (or <code>void.class</code> if none).
   10.47 + * <p>
   10.48 + * Every method handle appears as an object containing a method named
   10.49 + * <code>invoke</code>, whose signature exactly matches
   10.50 + * the method handle's type.
   10.51 + * A normal Java method call (using the <code>invokevirtual</code> instruction)
   10.52 + * can invoke this method from Java source code (if language support is present).
   10.53 + * <p>
   10.54 + * Every call to a method handle specifies an intended method type,
   10.55 + * which must exactly match the type of the method handle.
   10.56 + * (The type is specified in the <code>invokevirtual</code> instruction,
   10.57 + * via a {@code CONSTANT_NameAndType} constant pool entry.)
   10.58 + * The call looks within the receiver object for a method
   10.59 + * named <code>invoke</code> of the intended method type.
   10.60 + * The call fails with a {@link WrongMethodTypeException}
   10.61 + * if the method does not exist, even if there is an <code>invoke</code>
   10.62 + * method of a closely similar signature.
   10.63 + * <p>
   10.64 + * A method handle is an unrestricted capability to call a method.
   10.65 + * A method handle can be formed on a non-public method by a class
   10.66 + * that has access to that method; the resulting handle can be used
   10.67 + * in any place by any caller who receives a reference to it.  Thus, access
   10.68 + * checking is performed when the method handle is created, not
   10.69 + * (as in reflection) every time it is called.  Handles to non-public
   10.70 + * methods, or in non-public classes, should generally be kept secret.
   10.71 + * They should not be passed to untrusted code.
   10.72 + * <p>
   10.73 + * Bytecode in an extended JVM can directly call a method handle's
   10.74 + * <code>invoke</code> from an <code>invokevirtual</code> instruction.
   10.75 + * The receiver class type must be <code>MethodHandle</code> and the method name
   10.76 + * must be <code>invoke</code>.  The signature of the invocation
   10.77 + * (after resolving symbolic type names) must exactly match the method type
   10.78 + * of the target method.
   10.79 + * <p>
   10.80 + * Bytecode in an extended JVM can directly obtain a method handle
   10.81 + * for any accessible method from a <code>ldc</code> instruction
   10.82 + * which refers to a <code>CONSTANT_Methodref</code> or
   10.83 + * <code>CONSTANT_InterfaceMethodref</code> constant pool entry.
   10.84 + * <p>
   10.85 + * All JVMs can also use a reflective API called <code>MethodHandles</code>
   10.86 + * for creating and calling method handles.
   10.87 + * <p>
   10.88 + * A method reference may refer either to a static or non-static method.
   10.89 + * In the non-static case, the method handle type includes an explicit
   10.90 + * receiver argument, prepended before any other arguments.
   10.91 + * In the method handle's type, the initial receiver argument is typed
   10.92 + * according to the class under which the method was initially requested.
   10.93 + * (E.g., if a non-static method handle is obtained via <code>ldc</code>,
   10.94 + * the type of the receiver is the class named in the constant pool entry.)
   10.95 + * <p>
   10.96 + * When a method handle to a virtual method is invoked, the method is
   10.97 + * always looked up in the receiver (that is, the first argument).
   10.98 + * <p>
   10.99 + * A non-virtual method handles to a specific virtual method implementation
  10.100 + * can also be created.  These do not perform virtual lookup based on
  10.101 + * receiver type.  Such a method handle simulates the effect of
  10.102 + * an <code>invokespecial</code> instruction to the same method.
  10.103 + *
  10.104 + * @see MethodType
  10.105 + * @see MethodHandles
  10.106 + * @author John Rose, JSR 292 EG
  10.107 + */
  10.108 +public abstract class MethodHandle
  10.109 +        // Note: This is an implementation inheritance hack, and will be removed
  10.110 +        // with a JVM change which moves the required hidden state onto this class.
  10.111 +        extends MethodHandleImpl
  10.112 +{
  10.113 +    // interface MethodHandle<T extends MethodType<R,A...>>
  10.114 +    // { T type(); <R,A...> public R invoke(A...); }
  10.115 +
  10.116 +    final private MethodType type;
  10.117 +
  10.118 +    /**
  10.119 +     * Report the type of this method handle.
  10.120 +     * Every invocation of this method handle must exactly match this type.
  10.121 +     * @return the method handle type
  10.122 +     */
  10.123 +    public MethodType type() {
  10.124 +        return type;
  10.125 +    }
  10.126 +
  10.127 +    /**
  10.128 +     * The constructor for MethodHandle may only be called by privileged code.
  10.129 +     * Subclasses may be in other packages, but must possess
  10.130 +     * a token which they obtained from MH with a security check.
  10.131 +     * @param token non-null object which proves access permission
  10.132 +     * @param type type (permanently assigned) of the new method handle
  10.133 +     */
  10.134 +    protected MethodHandle(Access token, MethodType type) {
  10.135 +        super(token);
  10.136 +        this.type = type;
  10.137 +    }
  10.138 +}
    11.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    11.2 +++ b/src/share/classes/java/dyn/MethodHandles.java	Tue May 05 22:40:09 2009 -0700
    11.3 @@ -0,0 +1,1092 @@
    11.4 +/*
    11.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    11.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    11.7 + *
    11.8 + * This code is free software; you can redistribute it and/or modify it
    11.9 + * under the terms of the GNU General Public License version 2 only, as
   11.10 + * published by the Free Software Foundation.  Sun designates this
   11.11 + * particular file as subject to the "Classpath" exception as provided
   11.12 + * by Sun in the LICENSE file that accompanied this code.
   11.13 + *
   11.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   11.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   11.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   11.17 + * version 2 for more details (a copy is included in the LICENSE file that
   11.18 + * accompanied this code).
   11.19 + *
   11.20 + * You should have received a copy of the GNU General Public License version
   11.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   11.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   11.23 + *
   11.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   11.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   11.26 + * have any questions.
   11.27 + */
   11.28 +
   11.29 +package java.dyn;
   11.30 +
   11.31 +import java.lang.reflect.Constructor;
   11.32 +import sun.dyn.Access;
   11.33 +import sun.dyn.MemberName;
   11.34 +import sun.dyn.MethodHandleImpl;
   11.35 +import sun.dyn.util.VerifyAccess;
   11.36 +import sun.dyn.util.Wrapper;
   11.37 +import java.lang.reflect.Field;
   11.38 +import java.lang.reflect.Method;
   11.39 +import java.lang.reflect.Modifier;
   11.40 +import java.util.ArrayList;
   11.41 +import java.util.Arrays;
   11.42 +import sun.dyn.Invokers;
   11.43 +import sun.dyn.MethodTypeImpl;
   11.44 +import sun.reflect.Reflection;
   11.45 +import static sun.dyn.MemberName.newIllegalArgumentException;
   11.46 +import static sun.dyn.MemberName.newNoAccessException;
   11.47 +
   11.48 +/**
   11.49 + * Fundamental operations and utilities for MethodHandle.
   11.50 + * <p>
   11.51 + * <em>API Note:</em>  The matching of method types in this API cannot
   11.52 + * be completely checked by Java's generic type system for three reasons:
   11.53 + * <ol>
   11.54 + * <li>Method types range over all possible arities,
   11.55 + * from no arguments to an arbitrary number of arguments.
   11.56 + * Generics are not variadic, and so cannot represent this.</li>
   11.57 + * <li>Method types can specify arguments of primitive types,
   11.58 + * which Java generic types cannot range over.</li>
   11.59 + * <li>Method types can optionally specify varargs (ellipsis).</li>
   11.60 + * </ol>
   11.61 + * @author John Rose, JSR 292 EG
   11.62 + */
   11.63 +public class MethodHandles {
   11.64 +
   11.65 +    private MethodHandles() { }  // do not instantiate
   11.66 +
   11.67 +    private static final Access IMPL_TOKEN = Access.getToken();
   11.68 +    private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(IMPL_TOKEN);
   11.69 +    static { MethodHandleImpl.initStatics(); }
   11.70 +    // See IMPL_LOOKUP below.
   11.71 +
   11.72 +    //// Method handle creation from ordinary methods.
   11.73 +
   11.74 +    public static Lookup lookup() {
   11.75 +        return new Lookup();
   11.76 +    }
   11.77 +
   11.78 +    /**
   11.79 +     * A factory object for creating method handles, when the creation
   11.80 +     * requires access checking.  Method handles do not perform
   11.81 +     * access checks when they are called; this is a major difference
   11.82 +     * from reflective {@link Method}, which performs access checking
   11.83 +     * against every caller, on every call.  Method handle access
   11.84 +     * restrictions are enforced when a method handle is created.
   11.85 +     * The caller class against which those restrictions are enforced
   11.86 +     * is known as the "lookup class".  {@link Lookup} embodies an
   11.87 +     * authenticated lookup class, and can be used to create any number
   11.88 +     * of access-checked method handles, all checked against a single
   11.89 +     * lookup class.
   11.90 +     * <p>
   11.91 +     * A class which needs to create method handles will call
   11.92 +     * {@code MethodHandles.lookup()} to create a factory for itself.
   11.93 +     * It may then use this factory to create method handles on
   11.94 +     * all of its methods, including private ones.
   11.95 +     * It may also delegate the lookup (e.g., to a metaobject protocol)
   11.96 +     * by passing the {@code Lookup} object to other code.
   11.97 +     * If this other code creates method handles, they will be access
   11.98 +     * checked against the original lookup class, and not with any higher
   11.99 +     * privileges.
  11.100 +     * <p>
  11.101 +     * Note that access checks only apply to named and reflected methods.
  11.102 +     * Other method handle creation methods, such as {@link #convertArguments},
  11.103 +     * do not require any access checks, and can be done independently
  11.104 +     * of any lookup class.
  11.105 +     * <p>
  11.106 +     * <em>A note about error conditions:<em>  A lookup can fail, because
  11.107 +     * the containing class is not accessible to the lookup class, or
  11.108 +     * because the desired class member is missing, or because the
  11.109 +     * desired class member is not accessible to the lookup class.
  11.110 +     * It can also fail if a security manager is installed and refuses
  11.111 +     * access.  In any of these cases, an exception will be
  11.112 +     * thrown from the attempted lookup.
  11.113 +     * In general, the conditions under which a method handle may be
  11.114 +     * created for a method M are exactly as restrictive as the conditions
  11.115 +     * under which the lookup class could have compiled a call to M.
  11.116 +     */
  11.117 +    public static final
  11.118 +    class Lookup {
  11.119 +        private final Class<?> lookupClass;
  11.120 +
  11.121 +        /** Which class is performing the lookup?  It is this class against
  11.122 +         *  which checks are performed for visibility and access permissions.
  11.123 +         *  <p>
  11.124 +         *  This value is null if and only if this lookup is {@link #PUBLIC_LOOKUP}.
  11.125 +         */
  11.126 +        public Class<?> lookupClass() {
  11.127 +            return lookupClass;
  11.128 +        }
  11.129 +
  11.130 +        /** Embody the current class (the lookupClass) as a lookup class
  11.131 +         * for method handle creation.
  11.132 +         * Must be called by from a method in this package,
  11.133 +         * which in turn is called by a method not in this package.
  11.134 +         * Also, don't make it private, lest javac interpose
  11.135 +         * an access$N method.
  11.136 +         */
  11.137 +        Lookup() {
  11.138 +            Class caller = getCallerClassAtEntryPoint();
  11.139 +            // make sure we haven't accidentally picked up this class:
  11.140 +            checkUnprivilegedlookupClass(caller);
  11.141 +            this.lookupClass = caller;
  11.142 +        }
  11.143 +
  11.144 +        private Lookup(Class<?> lookupClass) {
  11.145 +            this.lookupClass = lookupClass;
  11.146 +        }
  11.147 +
  11.148 +        /** Version of lookup which is trusted minimally.
  11.149 +         *  It can only be used to create method handles to
  11.150 +         *  publicly accessible members.
  11.151 +         */
  11.152 +        public static final Lookup PUBLIC_LOOKUP = new Lookup(null);
  11.153 +
  11.154 +        /** Package-private version of lookup which is trusted. */
  11.155 +        static final Lookup IMPL_LOOKUP = new Lookup(Access.class);
  11.156 +        static { MethodHandleImpl.initLookup(IMPL_TOKEN, IMPL_LOOKUP); }
  11.157 +
  11.158 +        private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
  11.159 +            if (lookupClass == null ||
  11.160 +                lookupClass == Access.class ||
  11.161 +                lookupClass.getName().startsWith("java.dyn."))
  11.162 +                throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
  11.163 +        }
  11.164 +
  11.165 +        @Override
  11.166 +        public String toString() {
  11.167 +            if (lookupClass == null)
  11.168 +                return "public";
  11.169 +            return lookupClass.getName();
  11.170 +        }
  11.171 +
  11.172 +        // call this from an entry point method in Lookup with extraFrames=0.
  11.173 +        private static Class<?> getCallerClassAtEntryPoint() {
  11.174 +            final int CALLER_DEPTH = 4;
  11.175 +            // 0: Reflection.getCC, 1: getCallerClassAtEntryPoint,
  11.176 +            // 2: Lookup.<init>, 3: MethodHandles.*, 4: caller
  11.177 +            // Note:  This should be the only use of getCallerClass in this file.
  11.178 +            return Reflection.getCallerClass(CALLER_DEPTH);
  11.179 +        }
  11.180 +
  11.181 +        /**
  11.182 +         * Produce a method handle for a static method.
  11.183 +         * The type of the method handle will be that of the method.
  11.184 +         * The method and all its argument types must be accessible to the lookup class.
  11.185 +         * If the method's class has not yet been initialized, that is done
  11.186 +         * immediately, before the method handle is returned.
  11.187 +         * @param defc the class from which the method is accessed
  11.188 +         * @param name the name of the method
  11.189 +         * @param type the type of the method
  11.190 +         * @return the desired method handle
  11.191 +         * @exception SecurityException <em>TBD</em>
  11.192 +         * @exception NoAccessException if the method does not exist or access checking fails
  11.193 +         */
  11.194 +        public
  11.195 +        MethodHandle findStatic(Class<?> defc, String name, MethodType type) throws NoAccessException {
  11.196 +            MemberName method = IMPL_NAMES.resolveOrFail(new MemberName(defc, name, type, Modifier.STATIC), true, lookupClass);
  11.197 +            checkStatic(true, method, lookupClass);
  11.198 +            //throw NoSuchMethodException
  11.199 +            return MethodHandleImpl.findMethod(IMPL_TOKEN, method, false, lookupClass);
  11.200 +        }
  11.201 +
  11.202 +        /**
  11.203 +         * Produce a method handle for a virtual method.
  11.204 +         * The type of the method handle will be that of the method,
  11.205 +         * with the receiver type ({@code defc}) prepended.
  11.206 +         * The method and all its argument types must be accessible to the lookup class.
  11.207 +         * <p>
  11.208 +         * When called, the handle will treat the first argument as a receiver
  11.209 +         * and dispatch on the receiver's type to determine which method
  11.210 +         * implementation to enter.
  11.211 +         * (The dispatching action is identical with that performed by an
  11.212 +         * {@code invokevirtual} or {@code invokeinterface} instruction.)
  11.213 +         * @param defc the class or interface from which the method is accessed
  11.214 +         * @param name the name of the method
  11.215 +         * @param type the type of the method, with the receiver argument omitted
  11.216 +         * @return the desired method handle
  11.217 +         * @exception SecurityException <em>TBD</em>
  11.218 +         * @exception NoAccessException if the method does not exist or access checking fails
  11.219 +         */
  11.220 +        public MethodHandle findVirtual(Class<?> defc, String name, MethodType type) throws NoAccessException {
  11.221 +            MemberName method = IMPL_NAMES.resolveOrFail(new MemberName(defc, name, type), true, lookupClass);
  11.222 +            checkStatic(false, method, lookupClass);
  11.223 +            return MethodHandleImpl.findMethod(IMPL_TOKEN, method, true, lookupClass);
  11.224 +        }
  11.225 +
  11.226 +        /**
  11.227 +         * Produce an early-bound method handle for a virtual method,
  11.228 +         * or a handle for a constructor, as if called from an {@code invokespecial}
  11.229 +         * instruction from {@code caller}.
  11.230 +         * The type of the method handle will be that of the method or constructor,
  11.231 +         * with a suitably restricted receiver type (such as {@code caller}) prepended.
  11.232 +         * The method or constructor and all its argument types must be accessible
  11.233 +         * to the caller.
  11.234 +         * <p>
  11.235 +         * When called, the handle will treat the first argument as a receiver,
  11.236 +         * but will not dispatch on the receiver's type.
  11.237 +         * (This direct invocation action is identical with that performed by an
  11.238 +         * {@code invokespecial} instruction.)
  11.239 +         * <p>
  11.240 +         * If the explicitly specified caller class is not identical with the
  11.241 +         * lookup class, a security check TBD is performed.
  11.242 +         * @param defc the class or interface from which the method is accessed
  11.243 +         * @param name the name of the method, or "<init>" for a constructor
  11.244 +         * @param type the type of the method, with the receiver argument omitted
  11.245 +         * @param specialCaller the proposed calling class to perform the {@code invokespecial}
  11.246 +         * @return the desired method handle
  11.247 +         * @exception SecurityException <em>TBD</em>
  11.248 +         * @exception NoAccessException if the method does not exist or access checking fails
  11.249 +         */
  11.250 +        public MethodHandle findSpecial(Class<?> defc, String name, MethodType type,
  11.251 +                                        Class<?> specialCaller) throws NoAccessException {
  11.252 +            checkSpecialCaller(specialCaller, lookupClass);
  11.253 +            MemberName method = IMPL_NAMES.resolveOrFail(new MemberName(defc, name, type), false, specialCaller);
  11.254 +            checkStatic(false, method, lookupClass);
  11.255 +            if (name.equals("<init>")) {
  11.256 +                if (defc != specialCaller)
  11.257 +                    throw newNoAccessException("constructor must be local to lookup class", method, lookupClass);
  11.258 +            } else if (defc.isInterface() || !defc.isAssignableFrom(specialCaller)) {
  11.259 +                throw newNoAccessException("method must be in a superclass of lookup class", method, lookupClass);
  11.260 +            }
  11.261 +            return MethodHandleImpl.findMethod(IMPL_TOKEN, method, false, specialCaller);
  11.262 +        }
  11.263 +
  11.264 +        /**
  11.265 +         * Produce an early-bound method handle for a non-static method.
  11.266 +         * The receiver must have a supertype {@code defc} in which a method
  11.267 +         * of the given name and type is accessible to the lookup class.
  11.268 +         * The method and all its argument types must be accessible to the lookup class.
  11.269 +         * The type of the method handle will be that of the method.
  11.270 +         * The given receiver will be bound into the method handle.
  11.271 +         * <p>
  11.272 +         * Equivalent to the following expression:
  11.273 +         * <code>
  11.274 +         * {@link #insertArgument}({@link #findVirtual}(defc, name, type), receiver)
  11.275 +         * </code>
  11.276 +         * @param receiver the object from which the method is accessed
  11.277 +         * @param name the name of the method
  11.278 +         * @param type the type of the method, with the receiver argument omitted
  11.279 +         * @return the desired method handle
  11.280 +         * @exception SecurityException <em>TBD</em>
  11.281 +         * @exception NoAccessException if the method does not exist or access checking fails
  11.282 +         */
  11.283 +        public MethodHandle bind(Object receiver, String name, MethodType type) throws NoAccessException {
  11.284 +            Class<? extends Object> rcvc = receiver.getClass(); // may get NPE
  11.285 +            MemberName reference = new MemberName(rcvc, name, type);
  11.286 +            MemberName method = IMPL_NAMES.resolveOrFail(reference, true, lookupClass);
  11.287 +            checkStatic(false, method, lookupClass);
  11.288 +            MethodHandle dmh = MethodHandleImpl.findMethod(IMPL_TOKEN, method, true, lookupClass);
  11.289 +            MethodHandle bmh = MethodHandleImpl.bindReceiver(IMPL_TOKEN, dmh, receiver);
  11.290 +            if (bmh == null)
  11.291 +                throw newNoAccessException(method, lookupClass);
  11.292 +            return bmh;
  11.293 +        }
  11.294 +
  11.295 +        /**
  11.296 +         * Make a direct method handle to <i>m</i>, if the lookup class has permission.
  11.297 +         * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
  11.298 +         * If <i>m</i> is virtual, overriding is respected on every call.
  11.299 +         * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
  11.300 +         * The type of the method handle will be that of the method,
  11.301 +         * with the receiver type prepended (but only if it is non-static).
  11.302 +         * If the method's {@code accessible} flag is not set,
  11.303 +         * access checking is performed immediately on behalf of the lookup class.
  11.304 +         * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
  11.305 +         * @param m the reflected method
  11.306 +         * @return a method handle which can invoke the reflected method
  11.307 +         * @exception NoAccessException if access checking fails
  11.308 +         */
  11.309 +        public MethodHandle unreflect(Method m) throws NoAccessException {
  11.310 +            return unreflectImpl(new MemberName(m), m.isAccessible(), true, lookupClass);
  11.311 +        }
  11.312 +
  11.313 +        /**
  11.314 +         * Produce a method handle for a reflected method.
  11.315 +         * It will bypass checks for overriding methods on the receiver,
  11.316 +         * as if by the {@code invokespecial} instruction.
  11.317 +         * The type of the method handle will be that of the method,
  11.318 +         * with the receiver type prepended.
  11.319 +         * If the method's {@code accessible} flag is not set,
  11.320 +         * access checking is performed immediately on behalf of the lookup class,
  11.321 +         * as if {@code invokespecial} instruction were being linked.
  11.322 +         * @param m the reflected method
  11.323 +         * @return a method handle which can invoke the reflected method
  11.324 +         * @exception NoAccessException if access checking fails
  11.325 +         */
  11.326 +        public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws NoAccessException {
  11.327 +            checkSpecialCaller(specialCaller, lookupClass);
  11.328 +            MemberName mname = new MemberName(m);
  11.329 +            checkStatic(false, mname, lookupClass);
  11.330 +            return unreflectImpl(mname, m.isAccessible(), false, specialCaller);
  11.331 +        }
  11.332 +
  11.333 +        /**
  11.334 +         * Produce a method handle for a reflected constructor.
  11.335 +         * The type of the method handle will be that of the constructor.
  11.336 +         * The method handle will perform a {@code newInstance} operation,
  11.337 +         * creating a new instance of the constructor's class on the
  11.338 +         * arguments passed to the method handle.
  11.339 +         * <p>
  11.340 +         * If the constructor's {@code accessible} flag is not set,
  11.341 +         * access checking is performed immediately on behalf of the lookup class,
  11.342 +         * as if {@code invokespecial} instruction were being linked.
  11.343 +         * @param ctor the reflected constructor
  11.344 +         * @return a method handle which can invoke the reflected constructor
  11.345 +         * @exception NoAccessException if access checking fails
  11.346 +         */
  11.347 +        public MethodHandle unreflectConstructor(Constructor ctor) throws NoAccessException {
  11.348 +            MemberName m = new MemberName(ctor);
  11.349 +            return unreflectImpl(m, ctor.isAccessible(), false, lookupClass);
  11.350 +        }
  11.351 +
  11.352 +        /**
  11.353 +         * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.354 +         * Produce a method handle giving read access to a reflected field.
  11.355 +         * The type of the method handle will have a return type of the field's
  11.356 +         * value type.  Its sole argument will be the field's containing class
  11.357 +         * (but only if it is non-static).
  11.358 +         * If the method's {@code accessible} flag is not set,
  11.359 +         * access checking is performed immediately on behalf of the lookup class.
  11.360 +         * @param f the reflected field
  11.361 +         * @return a method handle which can load values from the reflected field
  11.362 +         * @exception NoAccessException if access checking fails
  11.363 +         */
  11.364 +        public MethodHandle unreflectGetter(Field f) throws NoAccessException {
  11.365 +            return MethodHandleImpl.accessField(IMPL_TOKEN, new MemberName(f), false, lookupClass);
  11.366 +        }
  11.367 +
  11.368 +        /**
  11.369 +         * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.370 +         * Produce a method handle giving write access to a reflected field.
  11.371 +         * The type of the method handle will have a void return type.
  11.372 +         * Its last argument will be the field's value type.
  11.373 +         * Its other argument will be the field's containing class
  11.374 +         * (but only if it is non-static).
  11.375 +         * If the method's {@code accessible} flag is not set,
  11.376 +         * access checking is performed immediately on behalf of the lookup class.
  11.377 +         * @param f the reflected field
  11.378 +         * @return a method handle which can store values into the reflected field
  11.379 +         * @exception NoAccessException if access checking fails
  11.380 +         */
  11.381 +        public MethodHandle unreflectSetter(Field f) throws NoAccessException {
  11.382 +            return MethodHandleImpl.accessField(IMPL_TOKEN, new MemberName(f), true, lookupClass);
  11.383 +        }
  11.384 +
  11.385 +    }
  11.386 +
  11.387 +    static /*must not be public*/
  11.388 +    MethodHandle findStaticFrom(Class<?> lookupClass,
  11.389 +                                Class<?> defc, String name, MethodType type) throws NoAccessException {
  11.390 +        MemberName method = IMPL_NAMES.resolveOrFail(new MemberName(defc, name, type, Modifier.STATIC), true, lookupClass);
  11.391 +        checkStatic(true, method, lookupClass);
  11.392 +        return MethodHandleImpl.findMethod(IMPL_TOKEN, method, false, lookupClass);
  11.393 +    }
  11.394 +
  11.395 +    static void checkStatic(boolean wantStatic, MemberName m, Class<?> lookupClass) {
  11.396 +        if (wantStatic != m.isStatic()) {
  11.397 +            String message = wantStatic ? "expected a static method" : "expected a non-static method";
  11.398 +            throw newNoAccessException(message, m, lookupClass);
  11.399 +        }
  11.400 +    }
  11.401 +
  11.402 +    static void checkSpecialCaller(Class<?> specialCaller, Class<?> lookupClass) {
  11.403 +        if (lookupClass == Lookup.IMPL_LOOKUP.lookupClass())
  11.404 +            return;  // privileged action
  11.405 +        if (lookupClass == null ||  // public-only access
  11.406 +            !VerifyAccess.isSamePackageMember(specialCaller, lookupClass))
  11.407 +            throw newNoAccessException("no private access", new MemberName(specialCaller), lookupClass);
  11.408 +    }
  11.409 +
  11.410 +    // Helper for creating handles on reflected methods and constructors.
  11.411 +    static MethodHandle unreflectImpl(MemberName m, boolean isAccessible,
  11.412 +                                      boolean doDispatch, Class<?> lookupClass) {
  11.413 +        MethodType mtype = m.getInvocationType();
  11.414 +        Class<?> defc = m.getDeclaringClass();
  11.415 +        int mods = m.getModifiers();
  11.416 +        if (m.isStatic()) {
  11.417 +            if (!isAccessible &&
  11.418 +                    VerifyAccess.isAccessible(defc, mods, false, lookupClass) == null)
  11.419 +                throw newNoAccessException(m, lookupClass);
  11.420 +        } else {
  11.421 +            Class<?> constraint;
  11.422 +            if (isAccessible) {
  11.423 +                // abbreviated access check for "unlocked" method
  11.424 +                constraint = doDispatch ? defc : lookupClass;
  11.425 +            } else {
  11.426 +                constraint = VerifyAccess.isAccessible(defc, mods, doDispatch, lookupClass);
  11.427 +            }
  11.428 +            if (constraint != defc && !constraint.isAssignableFrom(defc)) {
  11.429 +                if (!defc.isAssignableFrom(constraint))
  11.430 +                    throw newNoAccessException("receiver must be in caller class", m, lookupClass);
  11.431 +                mtype = mtype.changeParameterType(0, constraint);
  11.432 +            }
  11.433 +        }
  11.434 +        return MethodHandleImpl.findMethod(IMPL_TOKEN, m, doDispatch, lookupClass);
  11.435 +    }
  11.436 +
  11.437 +    /**
  11.438 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.439 +     * Produce a method handle giving read access to elements of an array.
  11.440 +     * The type of the method handle will have a return type of the array's
  11.441 +     * element type.  Its first argument will be the array type,
  11.442 +     * and the second will be {@code int}.
  11.443 +     * @param arrayClass an array type
  11.444 +     * @return a method handle which can load values from the given array type
  11.445 +     * @throws  IllegalArgumentException if arrayClass is not an array type
  11.446 +     */
  11.447 +    public static
  11.448 +    MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
  11.449 +        return MethodHandleImpl.accessArrayElement(IMPL_TOKEN, arrayClass, false);
  11.450 +    }
  11.451 +
  11.452 +    /**
  11.453 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.454 +     * Produce a method handle giving write access to elements of an array.
  11.455 +     * The type of the method handle will have a void return type.
  11.456 +     * Its last argument will be the array's element type.
  11.457 +     * The first and second arguments will be the array type and int.
  11.458 +     * @return a method handle which can store values into the array type
  11.459 +     * @throws IllegalArgumentException if arrayClass is not an array type
  11.460 +     */
  11.461 +    public static
  11.462 +    MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
  11.463 +        return MethodHandleImpl.accessArrayElement(IMPL_TOKEN, arrayClass, true);
  11.464 +    }
  11.465 +
  11.466 +
  11.467 +    /// method handle invocation (reflective style)
  11.468 +
  11.469 +    /**
  11.470 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.471 +     * Call the {@code invoke} method of a given method handle,
  11.472 +     * with arguments that exactly match the parameter types of the method handle.
  11.473 +     * The length of the arguments array must equal the parameter count
  11.474 +     * of the target's type.
  11.475 +     * The arguments array is spread into separate arguments, and
  11.476 +     * basic reference and unboxing conversions are applied.
  11.477 +     * <p>
  11.478 +     * In order to match the type of the target, the following argument
  11.479 +     * conversions are applied as necessary:
  11.480 +     * <ul>
  11.481 +     * <li>reference casting
  11.482 +     * <li>unboxing
  11.483 +     * </ul>
  11.484 +     * The following conversions are not applied:
  11.485 +     * <ul>
  11.486 +     * <li>primitive conversions (e.g., {@code byte} to {@code int}
  11.487 +     * <li>varargs conversions other than the initial spread
  11.488 +     * <li>any application-specific conversions (e.g., string to number)
  11.489 +     * </ul>
  11.490 +     * The result returned by the call is boxed if it is a primitive,
  11.491 +     * or forced to null if the return type is void.
  11.492 +     * <p>
  11.493 +     * This call is a convenience method for the following code:
  11.494 +     * <pre>
  11.495 +     *   MethodHandle invoker = MethodHandles.genericInvoker(target.type(), 0, true);
  11.496 +     *   Object result = invoker.invoke(arguments);
  11.497 +     * </pre>
  11.498 +     * @param target the method handle to invoke
  11.499 +     * @param arguments the arguments to pass to the target
  11.500 +     * @return the result returned by the target
  11.501 +     */
  11.502 +    public static
  11.503 +    Object invoke(MethodHandle target, Object... arguments) {
  11.504 +        int argc = arguments == null ? 0 : arguments.length;
  11.505 +        MethodType type = target.type();
  11.506 +        if (argc <= 4) {
  11.507 +            MethodHandle invoker = invokers(type).genericInvoker();
  11.508 +            switch (argc) {
  11.509 +                case 0:  return invoker.<Object>invoke(target);
  11.510 +                case 1:  return invoker.<Object>invoke(target,
  11.511 +                                    arguments[0]);
  11.512 +                case 2:  return invoker.<Object>invoke(target,
  11.513 +                                    arguments[0], arguments[1]);
  11.514 +                case 3:  return invoker.<Object>invoke(target,
  11.515 +                                    arguments[0], arguments[1], arguments[2]);
  11.516 +                case 4:  return invoker.<Object>invoke(target,
  11.517 +                                    arguments[0], arguments[1], arguments[2], arguments[3]);
  11.518 +            }
  11.519 +        }
  11.520 +        MethodHandle invoker = invokers(type).varargsInvoker();
  11.521 +        return invoker.<Object>invoke(target, arguments);
  11.522 +    }
  11.523 +
  11.524 +    public static
  11.525 +    Object invoke_0(MethodHandle target) {
  11.526 +        MethodHandle invoker = invokers(target.type()).genericInvoker();
  11.527 +        return invoker.<Object>invoke(target);
  11.528 +    }
  11.529 +    public static
  11.530 +    Object invoke_1(MethodHandle target, Object a0) {
  11.531 +        MethodHandle invoker = invokers(target.type()).genericInvoker();
  11.532 +        return invoker.<Object>invoke(target, a0);
  11.533 +    }
  11.534 +    public static
  11.535 +    Object invoke_2(MethodHandle target, Object a0, Object a1) {
  11.536 +        MethodHandle invoker = invokers(target.type()).genericInvoker();
  11.537 +        return invoker.<Object>invoke(target, a0, a1);
  11.538 +    }
  11.539 +    public static
  11.540 +    Object invoke_3(MethodHandle target, Object a0, Object a1, Object a2) {
  11.541 +        MethodHandle invoker = invokers(target.type()).genericInvoker();
  11.542 +        return invoker.<Object>invoke(target, a0, a1, a2);
  11.543 +    }
  11.544 +    public static
  11.545 +    Object invoke_4(MethodHandle target, Object a0, Object a1, Object a2, Object a3) {
  11.546 +        MethodHandle invoker = invokers(target.type()).genericInvoker();
  11.547 +        return invoker.<Object>invoke(target, a0, a1, a2, a3);
  11.548 +    }
  11.549 +
  11.550 +    /**
  11.551 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.552 +     * Give a method handle which will invoke any method handle of the
  11.553 +     * given type on a standard set of {@code Object} type arguments.
  11.554 +     * The the resulting invoker will be a method handle with the following
  11.555 +     * arguments:
  11.556 +     * <ul>
  11.557 +     * <li>a single {@code MethodHandle} target
  11.558 +     * <li>zero or more {@code Object} values
  11.559 +     * <li>an optional {@code Object[]} array containing more arguments
  11.560 +     * </ul>
  11.561 +     * The invoker will spread the varargs array (if present), apply
  11.562 +     * reference casts as necessary, and unbox primitive arguments.
  11.563 +     * The return value of the invoker will be an {@code Object} reference,
  11.564 +     * boxing a primitive value if the original type returns a primitive,
  11.565 +     * and always null if the original type returns void.
  11.566 +     * <p>
  11.567 +     * This is a convenience method equivalent to the following code:
  11.568 +     * <pre>
  11.569 +     * MethodHandle invoker = exactInvoker(type);
  11.570 +     * MethodType genericType = MethodType.makeGeneric(objectArgCount, varargs);
  11.571 +     * genericType = genericType.insertParameterType(0, MethodHandle.class);
  11.572 +     * if (!varargs)
  11.573 +     *     return convertArguments(invoker, genericType);
  11.574 +     * else
  11.575 +     *     return spreadArguments(invoker, genericType);
  11.576 +     * </pre>
  11.577 +     * @param type the desired target type
  11.578 +     * @param objectArgCount number of fixed (non-varargs) {@code Object} arguments
  11.579 +     * @param varargs if true, the invoker will accept a final {@code Object[]} argument
  11.580 +     * @return a method handle suitable for invoking any method handle of the given type
  11.581 +     */
  11.582 +    static public
  11.583 +    MethodHandle genericInvoker(MethodType type, int objectArgCount, boolean varargs) {
  11.584 +        return invokers(type).genericInvoker();
  11.585 +    }
  11.586 +
  11.587 +    /**
  11.588 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.589 +     * Give a method handle which will take a invoke any method handle of the
  11.590 +     * given type.  The resulting invoker will have a type which is
  11.591 +     * exactly equal to the desired type, except that it will accept
  11.592 +     * an additional leading argument of type {@code MethodHandle}.
  11.593 +     * <p>
  11.594 +     * This is a convenience method equivalent to the following code:
  11.595 +     * <pre>
  11.596 +     *     MethodHandles.lookup().findVirtual(MethodHandle.class, "invoke", type);
  11.597 +     * </pre>
  11.598 +     * @param type the desired target type
  11.599 +     * @return a method handle suitable for invoking any method handle of the given type
  11.600 +     */
  11.601 +    static public
  11.602 +    MethodHandle exactInvoker(MethodType type) {
  11.603 +        return invokers(type).exactInvoker();
  11.604 +    }
  11.605 +
  11.606 +    static private Invokers invokers(MethodType type) {
  11.607 +        return MethodTypeImpl.invokers(IMPL_TOKEN, type);
  11.608 +    }
  11.609 +
  11.610 +    /**
  11.611 +     * <em>WORK IN PROGRESS:</em>
  11.612 +     * Perform value checking, exactly as if for an adapted method handle.
  11.613 +     * It is assumed that the given value is either null, of type T0,
  11.614 +     * or (if T0 is primitive) of the wrapper type corresponding to T0.
  11.615 +     * The following checks and conversions are made:
  11.616 +     * <ul>
  11.617 +     * <li>If T0 and T1 are references, then a cast to T1 is applied.
  11.618 +     *     (The types do not need to be related in any particular way.)
  11.619 +     * <li>If T0 and T1 are primitives, then a widening or narrowing
  11.620 +     *     conversion is applied, if one exists.
  11.621 +     * <li>If T0 is a primitive and T1 a reference, and
  11.622 +     *     T0 has a wrapper type TW, a boxing conversion to TW is applied,
  11.623 +     *     possibly followed by a reference conversion.
  11.624 +     *     T1 must be TW or a supertype.
  11.625 +     * <li>If T0 is a reference and T1 a primitive, and
  11.626 +     *     T1 has a wrapper type TW, an unboxing conversion is applied,
  11.627 +     *     possibly preceded by a reference conversion.
  11.628 +     *     T0 must be TW or a supertype.
  11.629 +     * <li>If T1 is void, the return value is discarded
  11.630 +     * <li>If T0 is void and T1 a reference, a null value is introduced.
  11.631 +     * <li>If T0 is void and T1 a primitive, a zero value is introduced.
  11.632 +     * </ul>
  11.633 +     * If the value is discarded, null will be returned.
  11.634 +     * @param valueType
  11.635 +     * @param value
  11.636 +     * @return the value, converted if necessary
  11.637 +     * @throws java.lang.ClassCastException if a cast fails
  11.638 +     */
  11.639 +    static
  11.640 +    <T0, T1> T1 checkValue(Class<T0> t0, Class<T1> t1, Object value)
  11.641 +       throws ClassCastException
  11.642 +    {
  11.643 +        if (t0 == t1) {
  11.644 +            // no conversion needed; just reassert the same type
  11.645 +            if (t0.isPrimitive())
  11.646 +                return Wrapper.asPrimitiveType(t1).cast(value);
  11.647 +            else
  11.648 +                return Wrapper.OBJECT.cast(value, t1);
  11.649 +        }
  11.650 +        boolean prim0 = t0.isPrimitive(), prim1 = t1.isPrimitive();
  11.651 +        if (!prim0) {
  11.652 +            // check contract with caller
  11.653 +            Wrapper.OBJECT.cast(value, t0);
  11.654 +            if (!prim1) {
  11.655 +                return Wrapper.OBJECT.cast(value, t1);
  11.656 +            }
  11.657 +            // convert reference to primitive by unboxing
  11.658 +            Wrapper w1 = Wrapper.forPrimitiveType(t1);
  11.659 +            return w1.cast(value, t1);
  11.660 +        }
  11.661 +        // check contract with caller:
  11.662 +        Wrapper.asWrapperType(t0).cast(value);
  11.663 +        Wrapper w1 = Wrapper.forPrimitiveType(t1);
  11.664 +        return w1.cast(value, t1);
  11.665 +    }
  11.666 +
  11.667 +    static
  11.668 +    Object checkValue(Class<?> T1, Object value)
  11.669 +       throws ClassCastException
  11.670 +    {
  11.671 +        Class<?> T0;
  11.672 +        if (value == null)
  11.673 +            T0 = Object.class;
  11.674 +        else
  11.675 +            T0 = value.getClass();
  11.676 +        return checkValue(T0, T1, value);
  11.677 +    }
  11.678 +
  11.679 +    /// method handle modification (creation from other method handles)
  11.680 +
  11.681 +    /**
  11.682 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.683 +     * Produce a method handle which adapts the type of the
  11.684 +     * given method handle to a new type, by pairwise argument conversion,
  11.685 +     * and/or varargs conversion.
  11.686 +     * The original type and new type must have the same number of
  11.687 +     * arguments, or else one or both them the must be varargs types.
  11.688 +     * The resulting method handle is guaranteed to confess a type
  11.689 +     * which is equal to the desired new type, with any varargs property erased.
  11.690 +     * <p>
  11.691 +     * If the original type and new type are equal, returns target.
  11.692 +     * <p>
  11.693 +     * The following conversions are applied as needed both to
  11.694 +     * arguments and return types.  Let T0 and T1 be the differing
  11.695 +     * new and old parameter types (or old and new return types)
  11.696 +     * for corresponding values passed by the new and old method types.
  11.697 +     * <p>
  11.698 +     * If an ordinary (non-varargs) parameter of the new type is
  11.699 +     * to be boxed in a varargs parameter of the old type of type T1[],
  11.700 +     * then T1 is the element type of the varargs array.
  11.701 +     * Otherwise, if a varargs parameter of the new type of type T0[]
  11.702 +     * is to be spread into one or more outgoing old type parameters,
  11.703 +     * then T0 is the element type of the
  11.704 +     * If the new type is varargs and the old type is not, the varargs
  11.705 +     * argument will be checked and must be a non-null array of exactly
  11.706 +     * the right length.  If there are no parameters in the old type
  11.707 +     * corresponding to the new varargs parameter, the varargs argument
  11.708 +     * is also allowed to be null.
  11.709 +     * <p>
  11.710 +     * Given those types T0, T1, one of the following conversions is applied
  11.711 +     * if possible:
  11.712 +     * <ul>
  11.713 +     * <li>If T0 and T1 are references, then a cast to T2 is applied,
  11.714 +     *     where T2 is Object if T1 is an interface, else T1.
  11.715 +     *     (The types do not need to be related in any particular way.
  11.716 +     *     The treatment of interfaces follows the usage of the bytecode verifier.)
  11.717 +     * <li>If T0 and T1 are primitives, then a Java casting
  11.718 +     *     conversion (JLS 5.5) is applied, if one exists.
  11.719 +     * <li>If T0 and T1 are primitives and one is boolean,
  11.720 +     *     the boolean is treated as a one-bit unsigned integer.
  11.721 +     *     (This treatment follows the usage of the bytecode verifier.)
  11.722 +     *     A conversion from another primitive type behaves as if
  11.723 +     *     it first converts to byte, and then masks all but the low bit.
  11.724 +     * <li>If T0 is a primitive and T1 a reference, a boxing
  11.725 +     *     conversion is applied if one exists, possibly followed by
  11.726 +     *     an reference conversion to a superclass.
  11.727 +     *     T1 must be a wrapper class or a supertype of one.
  11.728 +     *     If T1 is a wrapper class, T0 is converted if necessary
  11.729 +     *     to T1's primitive type by one of the preceding conversions.
  11.730 +     *     Otherwise, T0 is boxed, and its wrapper converted to T1.
  11.731 +     * <li>If T0 is a reference and T1 a primitive, an unboxing
  11.732 +     *     conversion is applied if one exists, possibly preceded by
  11.733 +     *     a reference conversion to a wrapper class.
  11.734 +     *     T0 must be a wrapper class or a supertype of one.
  11.735 +     *     If T0 is a wrapper class, its primitive value is converted
  11.736 +     *     if necessary to T1 by one of the preceding conversions.
  11.737 +     *     Otherwise, T0 is converted directly to the wrapper type for T1,
  11.738 +     *     which is then unboxed.
  11.739 +     * <li>If T1 is void, any returned value is discarded
  11.740 +     * <li>If T0 is void and T1 a reference, a null value is introduced.
  11.741 +     * <li>If T0 is void and T1 a primitive, a zero value is introduced.
  11.742 +     * </ul>
  11.743 +     * @param target the method handle to invoke after arguments are retyped
  11.744 +     * @param newType the expected type of the new method handle
  11.745 +     * @return a method handle which delegates to {@code target} after performing
  11.746 +     *           any necessary argument conversions, and arranges for any
  11.747 +     *           necessary return value conversions
  11.748 +     * @throws WrongMethodTypeException if the conversion cannot be made
  11.749 +     */
  11.750 +    public static
  11.751 +    MethodHandle convertArguments(MethodHandle target, MethodType newType) {
  11.752 +        MethodType oldType = target.type();
  11.753 +        if (oldType.equals(newType))
  11.754 +            return target;
  11.755 +        MethodHandle res = MethodHandleImpl.convertArguments(IMPL_TOKEN, target,
  11.756 +                                                 newType, oldType, null);
  11.757 +        if (res == null)
  11.758 +            throw newIllegalArgumentException("cannot convert to "+newType+": "+target);
  11.759 +        return res;
  11.760 +    }
  11.761 +
  11.762 +    /**
  11.763 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.764 +     * Produce a method handle which adapts the calling sequence of the
  11.765 +     * given method handle to a new type, by reordering the arguments.
  11.766 +     * The resulting method handle is guaranteed to confess a type
  11.767 +     * which is equal to the desired new type.
  11.768 +     * <p>
  11.769 +     * The given array controls the reordering.
  11.770 +     * Call {@code #I} the number of incoming parameters (the value
  11.771 +     * {@code newType.parameterCount()}, and call {@code #O} the number
  11.772 +     * of outgoing parameters (the value {@code target.type().parameterCount()}).
  11.773 +     * Then the length of the reordering array must be {@code #O},
  11.774 +     * and each element must be a non-negative number less than {@code #I}.
  11.775 +     * For every {@code N} less than {@code #O}, the {@code N}-th
  11.776 +     * outgoing argument will be taken from the {@code I}-th incoming
  11.777 +     * argument, where {@code I} is {@code reorder[N]}.
  11.778 +     * <p>
  11.779 +     * The reordering array need not specify an actual permutation.
  11.780 +     * An incoming argument will be duplicated if its index appears
  11.781 +     * more than once in the array, and an incoming argument will be dropped
  11.782 +     * if its index does not appear in the array.
  11.783 +     * <p>
  11.784 +     * Pairwise conversions are applied as needed to arguments and return
  11.785 +     * values, as with {@link #convertArguments}.
  11.786 +     * @param target the method handle to invoke after arguments are reordered
  11.787 +     * @param newType the expected type of the new method handle
  11.788 +     * @param reorder a string which controls the reordering
  11.789 +     * @return a method handle which delegates to {@code target} after performing
  11.790 +     *           any necessary argument motion and conversions, and arranges for any
  11.791 +     *           necessary return value conversions
  11.792 +     */
  11.793 +    public static
  11.794 +    MethodHandle permuteArguments(MethodHandle target, MethodType newType, int[] reorder) {
  11.795 +        MethodType oldType = target.type();
  11.796 +        checkReorder(reorder, newType, oldType);
  11.797 +        return MethodHandleImpl.convertArguments(IMPL_TOKEN, target,
  11.798 +                                                 newType, oldType,
  11.799 +                                                 reorder);
  11.800 +    }
  11.801 +
  11.802 +    private static void checkReorder(int[] reorder, MethodType newType, MethodType oldType) {
  11.803 +        if (reorder.length == oldType.parameterCount()) {
  11.804 +            int limit = newType.parameterCount();
  11.805 +            boolean bad = false;
  11.806 +            for (int i : reorder) {
  11.807 +                if (i < 0 || i >= limit) {
  11.808 +                    bad = true; break;
  11.809 +                }
  11.810 +            }
  11.811 +            if (!bad)  return;
  11.812 +        }
  11.813 +        throw newIllegalArgumentException("bad reorder array");
  11.814 +    }
  11.815 +
  11.816 +    /**
  11.817 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.818 +     * Produce a method handle which adapts the type of the
  11.819 +     * given method handle to a new type, by spreading the final argument.
  11.820 +     * The resulting method handle is guaranteed to confess a type
  11.821 +     * which is equal to the desired new type.
  11.822 +     * <p>
  11.823 +     * The final parameter type of the new type must be an array type T[].
  11.824 +     * This is the type of what is called the <i>spread</i> argument.
  11.825 +     * All other arguments of the new type are called <i>ordinary</i> arguments.
  11.826 +     * <p>
  11.827 +     * The ordinary arguments of the new type are pairwise converted
  11.828 +     * to the initial parameter types of the old type, according to the
  11.829 +     * rules in {@link #convertArguments}.
  11.830 +     * Any additional arguments in the old type
  11.831 +     * are converted from the array element type T,
  11.832 +     * again according to the rules in {@link #convertArguments}.
  11.833 +     * The return value is converted according likewise.
  11.834 +     * <p>
  11.835 +     * The call verifies that the spread argument is in fact an array
  11.836 +     * of exactly the type length, i.e., the excess number of
  11.837 +     * arguments in the old type over the ordinary arguments in the new type.
  11.838 +     * If there are no excess arguments, the spread argument is also
  11.839 +     * allowed to be null.
  11.840 +     * @param target the method handle to invoke after the argument is prepended
  11.841 +     * @param newType the expected type of the new method handle
  11.842 +     * @return a new method handle which spreads its final argument,
  11.843 +     *         before calling the original method handle
  11.844 +     */
  11.845 +    public static
  11.846 +    MethodHandle spreadArguments(MethodHandle target, MethodType newType) {
  11.847 +        MethodType oldType = target.type();
  11.848 +        int inargs  = newType.parameterCount();
  11.849 +        int outargs = oldType.parameterCount();
  11.850 +        int spreadPos = inargs - 1;
  11.851 +        int numSpread = (outargs - spreadPos);
  11.852 +        MethodHandle res = null;
  11.853 +        if (spreadPos >= 0 && numSpread >= 0) {
  11.854 +            res = MethodHandleImpl.spreadArguments(IMPL_TOKEN, target, newType, spreadPos);
  11.855 +        }
  11.856 +        if (res == null) {
  11.857 +            throw newIllegalArgumentException("cannot spread "+newType+" to " +oldType);
  11.858 +        }
  11.859 +        return res;
  11.860 +    }
  11.861 +
  11.862 +    /**
  11.863 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.864 +     * Produce a method handle which adapts the type of the
  11.865 +     * given method handle to a new type, by collecting a series of
  11.866 +     * trailing arguments into an array.
  11.867 +     * The resulting method handle is guaranteed to confess a type
  11.868 +     * which is equal to the desired new type.
  11.869 +     * <p>
  11.870 +     * This method is inverse to {@link #spreadArguments}.
  11.871 +     * The final parameter type of the old type must be an array type T[],
  11.872 +     * which is the type of what is called the <i>spread</i> argument.
  11.873 +     * The trailing arguments of the new type which correspond to
  11.874 +     * the spread argument are all converted to type T and collected
  11.875 +     * into an array before the original method is called.
  11.876 +     * <p>
  11.877 +     * ISSUE: Unify this with combineArguments.  CollectArguments
  11.878 +     * is combineArguments with (a) new Object[]{...} as a combiner,
  11.879 +     * and (b) the combined arguments dropped, in favor of the combined result.
  11.880 +     * @param target the method handle to invoke after the argument is prepended
  11.881 +     * @param newType the expected type of the new method handle
  11.882 +     * @return a new method handle which collects some trailings argument
  11.883 +     *         into an array, before calling the original method handle
  11.884 +     */
  11.885 +    public static
  11.886 +    MethodHandle collectArguments(MethodHandle target, MethodType newType) {
  11.887 +        MethodType oldType = target.type();
  11.888 +        int inargs  = newType.parameterCount();
  11.889 +        int outargs = oldType.parameterCount();
  11.890 +        int collectPos = outargs - 1;
  11.891 +        int numCollect = (inargs - collectPos);
  11.892 +        if (collectPos < 0 || numCollect < 0)
  11.893 +            throw newIllegalArgumentException("wrong number of arguments");
  11.894 +        return MethodHandleImpl.collectArguments(IMPL_TOKEN, target, newType, collectPos);
  11.895 +    }
  11.896 +
  11.897 +    /**
  11.898 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.899 +     * Produce a method handle which calls the original method handle,
  11.900 +     * after inserting the given argument at the given position.
  11.901 +     * The type of the new method handle will drop the corresponding argument
  11.902 +     * type from the original handle's type.
  11.903 +     * <p>
  11.904 +     * The given argument object must match the dropped argument type.
  11.905 +     * If the dropped argument type is a primitive, the argument object
  11.906 +     * must be a wrapper, and is unboxed to produce the primitive.
  11.907 +     * <p>
  11.908 +     * The  <i>pos</i> may range between zero and <i>N</i> (inclusively),
  11.909 +     * where <i>N</i> is the number of argument types in <i>target</i>,
  11.910 +     * meaning to insert the new argument as the first or last (respectively),
  11.911 +     * or somewhere in between.
  11.912 +     * @param target the method handle to invoke after the argument is inserted
  11.913 +     * @param pos where to insert the argument (zero for the first)
  11.914 +     * @param value the argument to insert
  11.915 +     * @return a new method handle which inserts an additional argument,
  11.916 +     *         before calling the original method handle
  11.917 +     */
  11.918 +    public static
  11.919 +    MethodHandle insertArgument(MethodHandle target, int pos, Object value) {
  11.920 +        MethodType oldType = target.type();
  11.921 +        ArrayList<Class<?>> ptypes =
  11.922 +                new ArrayList<Class<?>>(oldType.parameterList());
  11.923 +        int outargs = oldType.parameterCount();
  11.924 +        int inargs  = outargs - 1;
  11.925 +        if (pos < 0 || pos >= outargs)
  11.926 +            throw newIllegalArgumentException("no argument type to append");
  11.927 +        Class<?> valueType = ptypes.remove(pos);
  11.928 +        value = checkValue(valueType, value);
  11.929 +        if (pos == 0 && !valueType.isPrimitive()) {
  11.930 +            // At least for now, make bound method handles a special case.
  11.931 +            // This lets us get by with minimal JVM support, at the expense
  11.932 +            // of generating signature-specific adapters as Java bytecodes.
  11.933 +            MethodHandle bmh = MethodHandleImpl.bindReceiver(IMPL_TOKEN, target, value);
  11.934 +            if (bmh != null)  return bmh;
  11.935 +            // else fall through to general adapter machinery
  11.936 +        }
  11.937 +        return MethodHandleImpl.bindArgument(IMPL_TOKEN, target, pos, value);
  11.938 +    }
  11.939 +
  11.940 +    /**
  11.941 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.942 +     * Produce a method handle which calls the original method handle,
  11.943 +     * after dropping the given argument(s) at the given position.
  11.944 +     * The type of the new method handle will insert the given argument
  11.945 +     * type(s), at that position, into the original handle's type.
  11.946 +     * <p>
  11.947 +     * The <i>pos</i> may range between zero and <i>N-1</i>,
  11.948 +     * where <i>N</i> is the number of argument types in <i>target</i>,
  11.949 +     * meaning to drop the first or last argument (respectively),
  11.950 +     * or an argument somewhere in between.
  11.951 +     * @param target the method handle to invoke after the argument is dropped
  11.952 +     * @param valueTypes the type(s) of the argument to drop
  11.953 +     * @param pos which argument to drop (zero for the first)
  11.954 +     * @return a new method handle which drops an argument of the given type,
  11.955 +     *         before calling the original method handle
  11.956 +     */
  11.957 +    public static
  11.958 +    MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
  11.959 +        if (valueTypes.length == 0)  return target;
  11.960 +        MethodType oldType = target.type();
  11.961 +        int outargs = oldType.parameterCount();
  11.962 +        int inargs  = outargs + valueTypes.length;
  11.963 +        if (pos < 0 || pos >= inargs)
  11.964 +            throw newIllegalArgumentException("no argument type to remove");
  11.965 +        ArrayList<Class<?>> ptypes =
  11.966 +                new ArrayList<Class<?>>(oldType.parameterList());
  11.967 +        ptypes.addAll(pos, Arrays.asList(valueTypes));
  11.968 +        MethodType newType = MethodType.make(oldType.returnType(), ptypes);
  11.969 +        return MethodHandleImpl.dropArguments(IMPL_TOKEN, target, newType, pos);
  11.970 +    }
  11.971 +
  11.972 +    /**
  11.973 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
  11.974 +     * Make a method handle which adapts a target method handle,
  11.975 +     * by guarding it with a test, a boolean-valued method handle.
  11.976 +     * If the guard fails, a fallback handle is called instead.
  11.977 +     * All three method handles must have the same corresponding
  11.978 +     * argument and return types, except that the return type
  11.979 +     * of the test must be boolean.
  11.980 +     * <p> Here is pseudocode for the resulting adapter:
  11.981 +     * <blockquote><pre>
  11.982 +     * signature T(A...);
  11.983 +     * boolean test(A...);
  11.984 +     * T target(A...);
  11.985 +     * T fallback(A...);
  11.986 +     * T adapter(A... a) {
  11.987 +     *   if (test(a...))
  11.988 +     *     return target(a...);
  11.989 +     *   else
  11.990 +     *     return fallback(a...);
  11.991 +     * }
  11.992 +     * </pre></blockquote>
  11.993 +     * @param test method handle used for test, must return boolean
  11.994 +     * @param target method handle to call if test passes
  11.995 +     * @param fallback method handle to call if test fails
  11.996 +     * @return method handle which incorporates the specified if/then/else logic
  11.997 +     * @throws IllegalArgumentException if {@code test} does not return boolean,
  11.998 +     *          or if all three method types do not match (with the return
  11.999 +     *          type of {@code test} changed to match that of {@code target}).
 11.1000 +     */
 11.1001 +    public static
 11.1002 +    MethodHandle guardWithTest(MethodHandle test,
 11.1003 +                               MethodHandle target,
 11.1004 +                               MethodHandle fallback) {
 11.1005 +        if (target.type() != fallback.type())
 11.1006 +            throw newIllegalArgumentException("target and fallback types do not match");
 11.1007 +        if (target.type().changeReturnType(boolean.class) != test.type())
 11.1008 +            throw newIllegalArgumentException("target and test types do not match");
 11.1009 +        /* {
 11.1010 +            MethodHandle invoke = findVirtual(MethodHandle.class, "invoke", target.type());
 11.1011 +            static MethodHandle choose(boolean z, MethodHandle t, MethodHandle f) {
 11.1012 +                return z ? t : f;
 11.1013 +            }
 11.1014 +            static MethodHandle compose(MethodHandle f, MethodHandle g) {
 11.1015 +                Class<?> initargs = g.type().parameterArray();
 11.1016 +                f = dropArguments(f, 1, initargs);  // ignore 2nd copy of args
 11.1017 +                return combineArguments(f, g);
 11.1018 +            }
 11.1019 +            // choose = \z.(z ? target : fallback)
 11.1020 +            MethodHandle choose = findVirtual(MethodHandles.class, "choose",
 11.1021 +                    MethodType.make(boolean.class, MethodHandle.class, MethodHandle.class));
 11.1022 +            choose = appendArgument(choose, target);
 11.1023 +            choose = appendArgument(choose, fallback);
 11.1024 +            MethodHandle dispatch = compose(choose, test);
 11.1025 +            // dispatch = \(a...).(test(a...) ? target : fallback)
 11.1026 +            return combineArguments(invoke, dispatch, 0);
 11.1027 +            // return \(a...).((test(a...) ? target : fallback).invoke(a...))
 11.1028 +        } */
 11.1029 +        return MethodHandleImpl.makeGuardWithTest(IMPL_TOKEN, test, target, fallback);
 11.1030 +    }
 11.1031 +
 11.1032 +    /**
 11.1033 +     * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
 11.1034 +     * Adapt a target method handle {@code target} by first processing
 11.1035 +     * its arguments, and then calling the target.
 11.1036 +     * The initial processing is performed by a second method handle, the {@code combiner}.
 11.1037 +     * After this, control passes to the {@code target}, with the same arguments.
 11.1038 +     * <p>
 11.1039 +     * The return value of the {@code combiner} is inserted into the argument list
 11.1040 +     * for the {@code target} at the indicated position {@code pos}, if it is non-negative.
 11.1041 +     * Except for this inserted argument (if any), the argument types of
 11.1042 +     * the target {@code target} and the {@code combiner} must be identical.
 11.1043 +     * <p>
 11.1044 +     * (Note that {@link #dropArguments} can be used to remove any arguments
 11.1045 +     * that either the {@code combiner} or {@code target} does not wish to receive.)
 11.1046 +     * <p>
 11.1047 +     * The combiner handle must have the same argument types as the
 11.1048 +     * target handle, but must return {@link MethodHandle} instead of
 11.1049 +     * the ultimate return type.  The returned method handle, in turn,
 11.1050 +     * is required to have exactly the given final method type.
 11.1051 +     * <p> Here is pseudocode for the resulting adapter:
 11.1052 +     * <blockquote><pre>
 11.1053 +     * signature V(A[pos]..., B...);
 11.1054 +     * signature T(A[pos]..., V, B...);
 11.1055 +     * T target(A... a, V v, B... b);
 11.1056 +     * V combiner(A..., B...);
 11.1057 +     * T adapter(A... a, B... b) {
 11.1058 +     *   V v = combiner(a..., b...);
 11.1059 +     *   return target(a..., v, b...);
 11.1060 +     * }
 11.1061 +     * </pre></blockquote>
 11.1062 +     * @param target the method handle to invoke after arguments are combined
 11.1063 +     * @param pos where the return value of {@code combiner} is to
 11.1064 +     *          be inserted as an argument to {@code target}
 11.1065 +     * @param combiner method handle to call initially on the incoming arguments
 11.1066 +     * @return method handle which incorporates the specified dispatch logic
 11.1067 +     * @throws IllegalArgumentException if {@code combiner} does not itself
 11.1068 +     *          return either void or the {@code pos}-th argument of {@code target},
 11.1069 +     *          or does not have the same argument types as {@code target}
 11.1070 +     *          (minus the inserted argument)
 11.1071 +     */
 11.1072 +    public static
 11.1073 +    MethodHandle combineArguments(MethodHandle target, int pos, MethodHandle combiner) {
 11.1074 +        MethodType mhType = target.type();
 11.1075 +        Class<?> combineType = combiner.type().returnType();
 11.1076 +        MethodType incomingArgs;
 11.1077 +        if (pos < 0) {
 11.1078 +            // No inserted argument; target & combiner must have same argument types.
 11.1079 +            incomingArgs = mhType;
 11.1080 +            if (!incomingArgs.changeReturnType(combineType).equals(combiner.type()))
 11.1081 +                throw newIllegalArgumentException("target and combiner types do not match");
 11.1082 +        } else {
 11.1083 +            // Inserted argument.
 11.1084 +            if (pos >= mhType.parameterCount()
 11.1085 +                || mhType.parameterType(pos) != combineType)
 11.1086 +                throw newIllegalArgumentException("inserted combiner argument does not match target");
 11.1087 +            incomingArgs = mhType.dropParameterType(pos);
 11.1088 +        }
 11.1089 +        if (!incomingArgs.changeReturnType(combineType).equals(combiner.type())) {
 11.1090 +            throw newIllegalArgumentException("target and combiner types do not match");
 11.1091 +        }
 11.1092 +        return MethodHandleImpl.combineArguments(IMPL_TOKEN, target, combiner, pos);
 11.1093 +    }
 11.1094 +
 11.1095 +}
    12.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    12.2 +++ b/src/share/classes/java/dyn/MethodType.java	Tue May 05 22:40:09 2009 -0700
    12.3 @@ -0,0 +1,575 @@
    12.4 +/*
    12.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    12.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    12.7 + *
    12.8 + * This code is free software; you can redistribute it and/or modify it
    12.9 + * under the terms of the GNU General Public License version 2 only, as
   12.10 + * published by the Free Software Foundation.  Sun designates this
   12.11 + * particular file as subject to the "Classpath" exception as provided
   12.12 + * by Sun in the LICENSE file that accompanied this code.
   12.13 + *
   12.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   12.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   12.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   12.17 + * version 2 for more details (a copy is included in the LICENSE file that
   12.18 + * accompanied this code).
   12.19 + *
   12.20 + * You should have received a copy of the GNU General Public License version
   12.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   12.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   12.23 + *
   12.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   12.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   12.26 + * have any questions.
   12.27 + */
   12.28 +
   12.29 +package java.dyn;
   12.30 +
   12.31 +import java.util.Arrays;
   12.32 +import java.util.Collections;
   12.33 +import java.util.HashMap;
   12.34 +import java.util.List;
   12.35 +import sun.dyn.Access;
   12.36 +import sun.dyn.Invokers;
   12.37 +import sun.dyn.MethodTypeImpl;
   12.38 +import sun.dyn.util.BytecodeSignature;
   12.39 +import static sun.dyn.MemberName.newIllegalArgumentException;
   12.40 +
   12.41 +/**
   12.42 + * Run-time token used to match call sites with method handles.
   12.43 + * The structure is a return type accompanied by any number of parameter types.
   12.44 + * The types (primitive, void, and reference) are represented by Class objects.
   12.45 + * All instances of <code>MethodType</code> are immutable.
   12.46 + * Two instances are completely interchangeable if they compare equal.
   12.47 + * Equality depends exactly on the return and parameter types.
   12.48 + * <p>
   12.49 + * This type can be created only by factory methods, which manage interning.
   12.50 + *
   12.51 + * @author John Rose, JSR 292 EG
   12.52 + */
   12.53 +public final
   12.54 +class MethodType {
   12.55 +    private final Class<?>   rtype;
   12.56 +    private final Class<?>[] ptypes;
   12.57 +    private MethodTypeForm form; // erased form, plus cached data about primitives
   12.58 +    private MethodType wrapAlt;  // alternative wrapped/unwrapped version
   12.59 +    private Invokers invokers;   // cache of handy higher-order adapters
   12.60 +
   12.61 +    private static final Access IMPL_TOKEN = Access.getToken();
   12.62 +
   12.63 +    // share a cache with a friend in this package
   12.64 +    Invokers getInvokers() { return invokers; }
   12.65 +    void setInvokers(Invokers inv) { invokers = inv; }
   12.66 +
   12.67 +    static {
   12.68 +        // This hack allows the implementation package special access to
   12.69 +        // the internals of MethodType.  In particular, the Form has all sorts
   12.70 +        // of cached information useful to the implementation code.
   12.71 +        MethodTypeImpl.setMethodTypeFriend(IMPL_TOKEN, new MethodTypeImpl.MethodTypeFriend() {
   12.72 +            public Class<?>[] ptypes(MethodType mt)        { return mt.ptypes; }
   12.73 +            public MethodTypeImpl form(MethodType mt)      { return mt.form; }
   12.74 +            public void setForm(MethodType mt, MethodTypeImpl form) {
   12.75 +                assert(mt.form == null);
   12.76 +                mt.form = (MethodTypeForm) form;
   12.77 +            }
   12.78 +            public MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
   12.79 +                return MethodType.makeImpl(rtype, ptypes, trusted);
   12.80 +            }
   12.81 +            public MethodTypeImpl newMethodTypeForm(MethodType mt) {
   12.82 +                return new MethodTypeForm(mt);
   12.83 +            }
   12.84 +            public Invokers getInvokers(MethodType mt)    { return mt.invokers; }
   12.85 +            public void setInvokers(MethodType mt, Invokers inv) { mt.invokers = inv; }
   12.86 +        });
   12.87 +    }
   12.88 +
   12.89 +    private MethodType(Class<?> rtype, Class<?>[] ptypes) {
   12.90 +        checkRtype(rtype);
   12.91 +        checkPtypes(ptypes);
   12.92 +        this.rtype = rtype;
   12.93 +        this.ptypes = ptypes;
   12.94 +    }
   12.95 +
   12.96 +    private void checkRtype(Class<?> rtype) {
   12.97 +        rtype.equals(rtype);  // null check
   12.98 +    }
   12.99 +    private void checkPtypes(Class<?>[] ptypes) {
  12.100 +        for (Class<?> ptype : ptypes) {
  12.101 +            ptype.equals(ptype);  // null check
  12.102 +            if (ptype == void.class)
  12.103 +                throw newIllegalArgumentException("void parameter: "+this);
  12.104 +        }
  12.105 +    }
  12.106 +
  12.107 +    static final HashMap<MethodType,MethodType> internTable
  12.108 +            = new HashMap<MethodType, MethodType>();
  12.109 +
  12.110 +    static final Class<?>[] NO_PTYPES = {};
  12.111 +
  12.112 +    /** Find or create an instance of the given method type.
  12.113 +     * @param rtype  the return type
  12.114 +     * @param ptypes the parameter types
  12.115 +     * @return the interned method type with the given parts
  12.116 +     * @throws NullPointerException if rtype or any ptype is null
  12.117 +     * @throws IllegalArgumentException if any of the ptypes is void
  12.118 +     */
  12.119 +    public static
  12.120 +    MethodType make(Class<?> rtype, Class<?>[] ptypes) {
  12.121 +        return makeImpl(rtype, ptypes, false);
  12.122 +    }
  12.123 +
  12.124 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[])}. */
  12.125 +    public static
  12.126 +    MethodType make(Class<?> rtype, List<? extends Class<?>> ptypes) {
  12.127 +        return makeImpl(rtype, ptypes.toArray(NO_PTYPES), true);
  12.128 +    }
  12.129 +
  12.130 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[])}.
  12.131 +     *  The leading parameter type is prepended to the remaining array.
  12.132 +     */
  12.133 +    public static
  12.134 +    MethodType make(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes) {
  12.135 +        Class<?>[] ptypes1 = new Class<?>[1+ptypes.length];
  12.136 +        ptypes1[0] = ptype0;
  12.137 +        System.arraycopy(ptypes, 0, ptypes1, 1, ptypes.length);
  12.138 +        return makeImpl(rtype, ptypes1, true);
  12.139 +    }
  12.140 +
  12.141 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[])}.
  12.142 +     *  The resulting method has no parameter types.
  12.143 +     */
  12.144 +    public static
  12.145 +    MethodType make(Class<?> rtype) {
  12.146 +        return makeImpl(rtype, NO_PTYPES, true);
  12.147 +    }
  12.148 +
  12.149 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[])}.
  12.150 +     *  The resulting method has the single given parameter type.
  12.151 +     */
  12.152 +    public static
  12.153 +    MethodType make(Class<?> rtype, Class<?> ptype0) {
  12.154 +        return makeImpl(rtype, new Class<?>[]{ ptype0 }, true);
  12.155 +    }
  12.156 +
  12.157 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[])}.
  12.158 +     *  The resulting method has the same parameter types as {@code ptypes},
  12.159 +     *  and the specified return type.
  12.160 +     */
  12.161 +    public static
  12.162 +    MethodType make(Class<?> rtype, MethodType ptypes) {
  12.163 +        return makeImpl(rtype, ptypes.ptypes, true);
  12.164 +    }
  12.165 +
  12.166 +    /**
  12.167 +     * Sole factory method to find or create an interned method type.
  12.168 +     * @param rtype desired return type
  12.169 +     * @param ptypes desired parameter types
  12.170 +     * @param trusted whether the ptypes can be used without cloning
  12.171 +     * @return the unique method type of the desired structure
  12.172 +     */
  12.173 +    private static
  12.174 +    MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
  12.175 +        if (ptypes == null || ptypes.length == 0) {
  12.176 +            ptypes = NO_PTYPES; trusted = true;
  12.177 +        }
  12.178 +        MethodType mt1 = new MethodType(rtype, ptypes);
  12.179 +        MethodType mt0;
  12.180 +        synchronized (internTable) {
  12.181 +            mt0 = internTable.get(mt1);
  12.182 +            if (mt0 != null)
  12.183 +                return mt0;
  12.184 +        }
  12.185 +        if (!trusted)
  12.186 +            // defensively copy the array passed in by the user
  12.187 +            mt1 = new MethodType(rtype, ptypes.clone());
  12.188 +        // promote the object to the Real Thing, and reprobe
  12.189 +        MethodTypeImpl.initForm(IMPL_TOKEN, mt1);
  12.190 +        synchronized (internTable) {
  12.191 +            mt0 = internTable.get(mt1);
  12.192 +            if (mt0 != null)
  12.193 +                return mt0;
  12.194 +            internTable.put(mt1, mt1);
  12.195 +        }
  12.196 +        return mt1;
  12.197 +    }
  12.198 +
  12.199 +    // Entry point from JVM.  TODO: Change the name & signature.
  12.200 +    private static MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes,
  12.201 +            boolean ignore1, boolean ignore2) {
  12.202 +        return makeImpl(rtype, ptypes, true);
  12.203 +    }
  12.204 +
  12.205 +    private static final MethodType[] objectOnlyTypes = new MethodType[20];
  12.206 +
  12.207 +    /**
  12.208 +     * Convenience method for {@link #make(java.lang.Class, java.lang.Class[], boolean)}.
  12.209 +     * All parameters and the return type will be Object, except the final varargs parameter if any.
  12.210 +     * @param objectArgCount number of parameters (excluding the varargs parameter if any)
  12.211 +     * @param varargs whether there will be a varargs parameter, of type Object[]
  12.212 +     * @return a totally generic method type, given only its count of parameters and varargs
  12.213 +     * @see #makeGeneric(int)
  12.214 +     */
  12.215 +    public static
  12.216 +    MethodType makeGeneric(int objectArgCount, boolean varargs) {
  12.217 +        MethodType mt;
  12.218 +        int ivarargs = (!varargs ? 0 : 1);
  12.219 +        int ootIndex = objectArgCount*2 + ivarargs;
  12.220 +        if (ootIndex < objectOnlyTypes.length) {
  12.221 +            mt = objectOnlyTypes[ootIndex];
  12.222 +            if (mt != null)  return mt;
  12.223 +        }
  12.224 +        Class<?>[] ptypes = new Class<?>[objectArgCount + ivarargs];
  12.225 +        Arrays.fill(ptypes, Object.class);
  12.226 +        if (ivarargs != 0)  ptypes[objectArgCount] = Object[].class;
  12.227 +        mt = makeImpl(Object.class, ptypes, true);
  12.228 +        if (ootIndex < objectOnlyTypes.length) {
  12.229 +            objectOnlyTypes[ootIndex] = mt;     // cache it here also!
  12.230 +        }
  12.231 +        return mt;
  12.232 +    }
  12.233 +
  12.234 +    /**
  12.235 +     * All parameters and the return type will be Object.
  12.236 +     * @param objectArgCount number of parameters
  12.237 +     * @return a totally generic method type, given only its count of parameters
  12.238 +     * @see #makeGeneric(int, boolean)
  12.239 +     */
  12.240 +    public static
  12.241 +    MethodType makeGeneric(int objectArgCount) {
  12.242 +        return makeGeneric(objectArgCount, false);
  12.243 +    }
  12.244 +
  12.245 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[], boolean)}.
  12.246 +     * @param num    the index (zero-based) of the parameter type to change
  12.247 +     * @param nptype a new parameter type to replace the old one with
  12.248 +     * @return the same type, except with the selected parameter changed
  12.249 +     */
  12.250 +    public MethodType changeParameterType(int num, Class<?> nptype) {
  12.251 +        if (parameterType(num) == nptype)  return this;
  12.252 +        Class<?>[] nptypes = ptypes.clone();
  12.253 +        nptypes[num] = nptype;
  12.254 +        return makeImpl(rtype, nptypes, true);
  12.255 +    }
  12.256 +
  12.257 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[], boolean)}.
  12.258 +     * @param num    the position (zero-based) of the inserted parameter type
  12.259 +     * @param nptype a new parameter type to insert into the parameter list
  12.260 +     * @return the same type, except with the selected parameter inserted
  12.261 +     */
  12.262 +    public MethodType insertParameterType(int num, Class<?> nptype) {
  12.263 +        int len = ptypes.length;
  12.264 +        Class<?>[] nptypes = Arrays.copyOfRange(ptypes, 0, len+1);
  12.265 +        System.arraycopy(nptypes, num, nptypes, num+1, len-num);
  12.266 +        nptypes[num] = nptype;
  12.267 +        return makeImpl(rtype, nptypes, true);
  12.268 +    }
  12.269 +
  12.270 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[], boolean)}.
  12.271 +     * @param num    the index (zero-based) of the parameter type to remove
  12.272 +     * @return the same type, except with the selected parameter removed
  12.273 +     */
  12.274 +    public MethodType dropParameterType(int num) {
  12.275 +        int len = ptypes.length;
  12.276 +        Class<?>[] nptypes;
  12.277 +        if (num == 0) {
  12.278 +            nptypes = Arrays.copyOfRange(ptypes, 1, len);
  12.279 +        } else {
  12.280 +            nptypes = Arrays.copyOfRange(ptypes, 0, len-1);
  12.281 +            System.arraycopy(ptypes, num+1, nptypes, num, (len-1)-num);
  12.282 +        }
  12.283 +        return makeImpl(rtype, nptypes, true);
  12.284 +    }
  12.285 +
  12.286 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[], boolean)}.
  12.287 +     * @param nrtype a return parameter type to replace the old one with
  12.288 +     * @return the same type, except with the return type change
  12.289 +     */
  12.290 +    public MethodType changeReturnType(Class<?> nrtype) {
  12.291 +        if (returnType() == nrtype)  return this;
  12.292 +        return makeImpl(nrtype, ptypes, true);
  12.293 +    }
  12.294 +
  12.295 +    /** Convenience method.
  12.296 +     * Report if this type contains a primitive argument or return value.
  12.297 +     * @return true if any of the types are primitives
  12.298 +     */
  12.299 +    public boolean hasPrimitives() {
  12.300 +        return form.hasPrimitives();
  12.301 +    }
  12.302 +
  12.303 +    /** Convenience method.
  12.304 +     * Report if this type contains a wrapper argument or return value.
  12.305 +     * Wrappers are types which box primitive values, such as {@link Integer}.
  12.306 +     * @return true if any of the types are wrappers
  12.307 +     */
  12.308 +    public boolean hasWrappers() {
  12.309 +        return unwrap() != this;
  12.310 +    }
  12.311 +
  12.312 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[])}.
  12.313 +     * Erase all reference types to Object.
  12.314 +     * @return a version of the original type with all reference types replaced
  12.315 +     */
  12.316 +    public MethodType erase() {
  12.317 +        return form.erasedType();
  12.318 +    }
  12.319 +
  12.320 +    /** Convenience method for {@link #makeGeneric(int)}.
  12.321 +     * Convert all types, both reference and primitive, to Object.
  12.322 +     * @return a version of the original type with all types replaced
  12.323 +     */
  12.324 +    public MethodType generic() {
  12.325 +        return makeGeneric(parameterCount());
  12.326 +    }
  12.327 +
  12.328 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[])}.
  12.329 +     * Convert all primitive types to their corresponding wrapper types.
  12.330 +     * A {@code void} return type is changed to the type {@code java.lang.Void}.
  12.331 +     * @return a version of the original type with all primitive types replaced
  12.332 +     */
  12.333 +    public MethodType wrap() {
  12.334 +        return hasPrimitives() ? wrapWithPrims(this) : this;
  12.335 +    }
  12.336 +
  12.337 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[])}.
  12.338 +     * Convert all wrapper types to their corresponding primitive types.
  12.339 +     * A return type of {@java.lang.Void} is changed to {@code void}.
  12.340 +     * @return a version of the original type with all wrapper types replaced
  12.341 +     */
  12.342 +    public MethodType unwrap() {
  12.343 +        MethodType noprims = !hasPrimitives() ? this : wrapWithPrims(this);
  12.344 +        return unwrapWithNoPrims(noprims);
  12.345 +    }
  12.346 +
  12.347 +    private static MethodType wrapWithPrims(MethodType pt) {
  12.348 +        assert(pt.hasPrimitives());
  12.349 +        MethodType wt = pt.wrapAlt;
  12.350 +        if (wt == null) {
  12.351 +            // fill in lazily
  12.352 +            wt = MethodTypeImpl.canonicalize(pt, MethodTypeImpl.WRAP, MethodTypeImpl.WRAP);
  12.353 +            assert(wt != null);
  12.354 +            pt.wrapAlt = wt;
  12.355 +        }
  12.356 +        return wt;
  12.357 +    }
  12.358 +
  12.359 +    private static MethodType unwrapWithNoPrims(MethodType wt) {
  12.360 +        assert(!wt.hasPrimitives());
  12.361 +        MethodType uwt = wt.wrapAlt;
  12.362 +        if (uwt == null) {
  12.363 +            // fill in lazily
  12.364 +            uwt = MethodTypeImpl.canonicalize(wt, MethodTypeImpl.UNWRAP, MethodTypeImpl.UNWRAP);
  12.365 +            if (uwt == null)
  12.366 +                uwt = wt;    // type has no wrappers or prims at all
  12.367 +            wt.wrapAlt = uwt;
  12.368 +        }
  12.369 +        return uwt;
  12.370 +    }
  12.371 +
  12.372 +    /** @param num the index (zero-based) of the desired parameter type
  12.373 +     *  @return the selected parameter type
  12.374 +     */
  12.375 +    public Class<?> parameterType(int num) {
  12.376 +        return ptypes[num];
  12.377 +    }
  12.378 +    /** @return the number of parameter types */
  12.379 +    public int parameterCount() {
  12.380 +        return ptypes.length;
  12.381 +    }
  12.382 +    /** @return the return type */
  12.383 +    public Class<?> returnType() {
  12.384 +        return rtype;
  12.385 +    }
  12.386 +
  12.387 +    /**
  12.388 +     * Convenience method to present the arguments as a list.
  12.389 +     * @return the parameter types (as an immutable list)
  12.390 +     */
  12.391 +    public List<Class<?>> parameterList() {
  12.392 +        return Collections.unmodifiableList(Arrays.asList(ptypes));
  12.393 +    }
  12.394 +
  12.395 +    /**
  12.396 +     * Convenience method to present the arguments as an array.
  12.397 +     * @return the parameter types (as a fresh copy if necessary)
  12.398 +     */
  12.399 +    public Class<?>[] parameterArray() {
  12.400 +        return ptypes.clone();
  12.401 +    }
  12.402 +
  12.403 +    /**
  12.404 +     * Compares the specified object with this type for equality.
  12.405 +     * That is, it returns <tt>true</tt> if and only if the specified object
  12.406 +     * is also a method type with exactly the same parameters and return type.
  12.407 +     * @param x object to compare
  12.408 +     * @see Object#equals(Object)
  12.409 +     */
  12.410 +    @Override
  12.411 +    public boolean equals(Object x) {
  12.412 +        return this == x || x instanceof MethodType && equals((MethodType)x);
  12.413 +    }
  12.414 +
  12.415 +    private boolean equals(MethodType that) {
  12.416 +        return this.rtype == that.rtype
  12.417 +            && Arrays.equals(this.ptypes, that.ptypes);
  12.418 +    }
  12.419 +
  12.420 +    /**
  12.421 +     * Returns the hash code value for this method type.
  12.422 +     * It is defined to be the same as the hashcode of a List
  12.423 +     * whose elements are the return type followed by the
  12.424 +     * parameter types.
  12.425 +     * @return the hash code value for this method type
  12.426 +     * @see Object#hashCode()
  12.427 +     * @see #equals(Object)
  12.428 +     * @see List#hashCode()
  12.429 +     */
  12.430 +    @Override
  12.431 +    public int hashCode() {
  12.432 +      int hashCode = 31 + rtype.hashCode();
  12.433 +      for (Class<?> ptype : ptypes)
  12.434 +          hashCode = 31*hashCode + ptype.hashCode();
  12.435 +      return hashCode;
  12.436 +    }
  12.437 +
  12.438 +    /**
  12.439 +     * The string representation of a method type is a
  12.440 +     * parenthesis enclosed, comma separated list of type names,
  12.441 +     * followed immediately by the return type.
  12.442 +     * <p>
  12.443 +     * If a type name is array, it the base type followed
  12.444 +     * by [], rather than the Class.getName of the array type.
  12.445 +     */
  12.446 +    @Override
  12.447 +    public String toString() {
  12.448 +        StringBuilder sb = new StringBuilder();
  12.449 +        sb.append("(");
  12.450 +        for (int i = 0; i < ptypes.length; i++) {
  12.451 +            if (i > 0)  sb.append(",");
  12.452 +            putName(sb, ptypes[i]);
  12.453 +        }
  12.454 +        sb.append(")");
  12.455 +        putName(sb, rtype);
  12.456 +        return sb.toString();
  12.457 +    }
  12.458 +
  12.459 +    static void putName(StringBuilder sb, Class<?> cls) {
  12.460 +        int brackets = 0;
  12.461 +        while (cls.isArray()) {
  12.462 +            cls = cls.getComponentType();
  12.463 +            brackets++;
  12.464 +        }
  12.465 +        String n = cls.getName();
  12.466 +        /*
  12.467 +        if (n.startsWith("java.lang.")) {
  12.468 +            String nb = n.substring("java.lang.".length());
  12.469 +            if (nb.indexOf('.') < 0)  n = nb;
  12.470 +        } else if (n.indexOf('.') < 0) {
  12.471 +            n = "."+n;          // anonymous package
  12.472 +        }
  12.473 +        */
  12.474 +        sb.append(n);
  12.475 +        while (brackets > 0) {
  12.476 +            sb.append("[]");
  12.477 +            brackets--;
  12.478 +        }
  12.479 +    }
  12.480 +
  12.481 +    /// Queries which have to do with the bytecode architecture
  12.482 +
  12.483 +    /** The number of JVM stack slots required to invoke a method
  12.484 +     * of this type.  Note that (for historic reasons) the JVM requires
  12.485 +     * a second stack slot to pass long and double arguments.
  12.486 +     * So this method returns {@link #parameterCount()} plus the
  12.487 +     * number of long and double parameters (if any).
  12.488 +     * <p>
  12.489 +     * This method is included for the benfit of applications that must
  12.490 +     * generate bytecodes that process method handles and invokedynamic.
  12.491 +     * @return the number of JVM stack slots for this type's parameters
  12.492 +     */
  12.493 +    public int parameterSlotCount() {
  12.494 +        return form.parameterSlotCount();
  12.495 +    }
  12.496 +
  12.497 +    /** Number of JVM stack slots which carry all parameters after
  12.498 +     * the given position, which must be in the range of 0 to
  12.499 +     * {@code parameterCount} inclusive.  Successive parameters are
  12.500 +     * more shallowly stacked, and parameters are indexed in the bytecodes
  12.501 +     * according to their trailing edge.  Thus, to obtain the depth
  12.502 +     * in the outgoing call stack of parameter {@code N}, obtain
  12.503 +     * the {@code parameterSlotDepth} of its trailing edge
  12.504 +     * at position {@code N+1}.
  12.505 +     * <p>
  12.506 +     * Parameters of type {@code long} and {@code double} occupy
  12.507 +     * two stack slots (for historical reasons) and all others occupy one.
  12.508 +     * Therefore, the number returned is the number of arguments
  12.509 +     * <em>including</em> and <em>after</em> the given parameter,
  12.510 +     * <em>plus</em> the number of long or double arguments
  12.511 +     * at or after after the argument for the given parameter.
  12.512 +     * <p>
  12.513 +     * This method is included for the benfit of applications that must
  12.514 +     * generate bytecodes that process method handles and invokedynamic.
  12.515 +     * @param num an index (zero-based, inclusive) within the parameter types
  12.516 +     * @return the index of the (shallowest) JVM stack slot transmitting the
  12.517 +     *         given parameter
  12.518 +     */
  12.519 +    public int parameterSlotDepth(int num) {
  12.520 +        if (num < 0 || num > ptypes.length)
  12.521 +            parameterType(num);  // force a range check
  12.522 +        return form.parameterToArgSlot(num-1);
  12.523 +    }
  12.524 +
  12.525 +    /** The number of JVM stack slots required to receive a return value
  12.526 +     * from a method of this type.
  12.527 +     * If the {@link #returnType() return type} is void, it will be zero,
  12.528 +     * else if the return type is long or double, it will be two, else one.
  12.529 +     * <p>
  12.530 +     * This method is included for the benfit of applications that must
  12.531 +     * generate bytecodes that process method handles and invokedynamic.
  12.532 +     * @return the number of JVM stack slots (0, 1, or 2) for this type's return value
  12.533 +     */
  12.534 +    public int returnSlotCount() {
  12.535 +        return form.returnSlotCount();
  12.536 +    }
  12.537 +
  12.538 +    /** Convenience method for {@link #make(java.lang.Class, java.lang.Class[])}.
  12.539 +     * Find or create an instance (interned) of the given method type.
  12.540 +     * Any class or interface name embedded in the signature string
  12.541 +     * will be resolved by calling {@link ClassLoader#loadClass(java.lang.String)}
  12.542 +     * on the given loader (or if it is null, on the system class loader).
  12.543 +     * <p>
  12.544 +     * Note that it is possible to build method types which cannot be
  12.545 +     * constructed by this method, because their component types are
  12.546 +     * not all reachable from a common class loader.
  12.547 +     * <p>
  12.548 +     * This method is included for the benfit of applications that must
  12.549 +     * generate bytecodes that process method handles and invokedynamic.
  12.550 +     * @param bytecodeSignature a bytecode-level signature string "(T...)T"
  12.551 +     * @param loader the class loader in which to look up the types
  12.552 +     * @return a method type matching the bytecode-level signature
  12.553 +     * @throws IllegalArgumentException if the string is not well-formed
  12.554 +     * @throws TypeNotPresentException if a named type cannot be found
  12.555 +     */
  12.556 +    public static MethodType fromBytecodeString(String bytecodeSignature, ClassLoader loader)
  12.557 +        throws IllegalArgumentException, TypeNotPresentException
  12.558 +    {
  12.559 +        List<Class<?>> types = BytecodeSignature.parseMethod(bytecodeSignature, loader);
  12.560 +        Class<?> rtype = types.remove(types.size() - 1);
  12.561 +        Class<?>[] ptypes = types.toArray(NO_PTYPES);
  12.562 +        return makeImpl(rtype, ptypes, true);
  12.563 +    }
  12.564 +
  12.565 +    /**
  12.566 +     * Create a bytecode signature representation of the type.
  12.567 +     * Note that this is not a strict inverse of
  12.568 +     * <p>
  12.569 +     * This method is included for the benfit of applications that must
  12.570 +     * generate bytecodes that process method handles and invokedynamic.
  12.571 +     * {@link #fromBytecodeString(java.lang.String, java.lang.ClassLoader)},
  12.572 +     * because the latter requires a suitable class loader argument.
  12.573 +     * @return the bytecode signature representation
  12.574 +     */
  12.575 +    public String toBytecodeString() {
  12.576 +        return BytecodeSignature.unparse(this);
  12.577 +    }
  12.578 +}
    13.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    13.2 +++ b/src/share/classes/java/dyn/MethodTypeForm.java	Tue May 05 22:40:09 2009 -0700
    13.3 @@ -0,0 +1,39 @@
    13.4 +/*
    13.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    13.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    13.7 + *
    13.8 + * This code is free software; you can redistribute it and/or modify it
    13.9 + * under the terms of the GNU General Public License version 2 only, as
   13.10 + * published by the Free Software Foundation.  Sun designates this
   13.11 + * particular file as subject to the "Classpath" exception as provided
   13.12 + * by Sun in the LICENSE file that accompanied this code.
   13.13 + *
   13.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   13.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   13.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   13.17 + * version 2 for more details (a copy is included in the LICENSE file that
   13.18 + * accompanied this code).
   13.19 + *
   13.20 + * You should have received a copy of the GNU General Public License version
   13.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   13.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   13.23 + *
   13.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   13.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   13.26 + * have any questions.
   13.27 + */
   13.28 +
   13.29 +package java.dyn;
   13.30 +
   13.31 +/**
   13.32 + * TO DO:  Temporary shim; remove after refactoring effects are complete in JVM.
   13.33 + * @author John Rose
   13.34 + */
   13.35 +import sun.dyn.MethodTypeImpl;
   13.36 +
   13.37 +class MethodTypeForm extends MethodTypeImpl {
   13.38 +
   13.39 +    MethodTypeForm(MethodType erasedType) {
   13.40 +        super(erasedType);
   13.41 +    }
   13.42 +}
    14.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    14.2 +++ b/src/share/classes/java/dyn/NoAccessException.java	Tue May 05 22:40:09 2009 -0700
    14.3 @@ -0,0 +1,75 @@
    14.4 +/*
    14.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    14.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    14.7 + *
    14.8 + * This code is free software; you can redistribute it and/or modify it
    14.9 + * under the terms of the GNU General Public License version 2 only, as
   14.10 + * published by the Free Software Foundation.  Sun designates this
   14.11 + * particular file as subject to the "Classpath" exception as provided
   14.12 + * by Sun in the LICENSE file that accompanied this code.
   14.13 + *
   14.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   14.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   14.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   14.17 + * version 2 for more details (a copy is included in the LICENSE file that
   14.18 + * accompanied this code).
   14.19 + *
   14.20 + * You should have received a copy of the GNU General Public License version
   14.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   14.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   14.23 + *
   14.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   14.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   14.26 + * have any questions.
   14.27 + */
   14.28 +
   14.29 +package java.dyn;
   14.30 +
   14.31 +/**
   14.32 + * Thrown to indicate that a caller has attempted to create a method handle
   14.33 + * which calls a method to which the caller does not have access.
   14.34 + * This unchecked exception is analogous to {@link IllegalAccessException},
   14.35 + * which is a checked exception thrown when reflective invocation fails
   14.36 + * because of an access check.  With method handles, this same access
   14.37 + * checking is performed on behalf of the method handle creator,
   14.38 + * at the time of creation.
   14.39 + * @author John Rose, JSR 292 EG
   14.40 + */
   14.41 +public class NoAccessException extends RuntimeException {
   14.42 +    /**
   14.43 +     * Constructs a {@code NoAccessException} with no detail message.
   14.44 +     */
   14.45 +    public NoAccessException() {
   14.46 +        super();
   14.47 +    }
   14.48 +
   14.49 +    /**
   14.50 +     * Constructs a {@code NoAccessException} with the specified
   14.51 +     * detail message.
   14.52 +     *
   14.53 +     * @param s the detail message
   14.54 +     */
   14.55 +    public NoAccessException(String s) {
   14.56 +        super(s);
   14.57 +    }
   14.58 +
   14.59 +    /**
   14.60 +     * Constructs a {@code NoAccessException} with the specified cause.
   14.61 +     *
   14.62 +     * @param cause the underlying cause of the exception
   14.63 +     */
   14.64 +    public NoAccessException(Throwable cause) {
   14.65 +        super(cause);
   14.66 +    }
   14.67 +
   14.68 +    /**
   14.69 +     * Constructs a {@code NoAccessException} with the specified
   14.70 +     * detail message and cause.
   14.71 +     *
   14.72 +     * @param s the detail message
   14.73 +     * @param cause the underlying cause of the exception
   14.74 +     */
   14.75 +    public NoAccessException(String s, Throwable cause) {
   14.76 +        super(s, cause);
   14.77 +    }
   14.78 +}
    15.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    15.2 +++ b/src/share/classes/java/dyn/WrongMethodTypeException.java	Tue May 05 22:40:09 2009 -0700
    15.3 @@ -0,0 +1,59 @@
    15.4 +/*
    15.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    15.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    15.7 + *
    15.8 + * This code is free software; you can redistribute it and/or modify it
    15.9 + * under the terms of the GNU General Public License version 2 only, as
   15.10 + * published by the Free Software Foundation.  Sun designates this
   15.11 + * particular file as subject to the "Classpath" exception as provided
   15.12 + * by Sun in the LICENSE file that accompanied this code.
   15.13 + *
   15.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   15.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   15.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   15.17 + * version 2 for more details (a copy is included in the LICENSE file that
   15.18 + * accompanied this code).
   15.19 + *
   15.20 + * You should have received a copy of the GNU General Public License version
   15.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   15.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   15.23 + *
   15.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   15.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   15.26 + * have any questions.
   15.27 + */
   15.28 +
   15.29 +package java.dyn;
   15.30 +
   15.31 +/**
   15.32 + * Thrown to indicate that code has attempted to call a method handle
   15.33 + * via the wrong method type.  As with the bytecode representation of
   15.34 + * normal Java method calls, method handle calls are strongly typed
   15.35 + * to a specific signature associated with a call site.
   15.36 + * <p>
   15.37 + * This exception may also be thrown when two method handles are
   15.38 + * composed, and the system detects that their types cannot be
   15.39 + * matched up correctly.  This amounts to an early evaluation
   15.40 + * of the type mismatch, at method handle construction time,
   15.41 + * instead of when the mismatched method handle is called.
   15.42 + *
   15.43 + * @author John Rose, JSR 292 EG
   15.44 + */
   15.45 +public class WrongMethodTypeException extends RuntimeException {
   15.46 +    /**
   15.47 +     * Constructs a {@code WrongMethodTypeException} with no detail message.
   15.48 +     */
   15.49 +    public WrongMethodTypeException() {
   15.50 +        super();
   15.51 +    }
   15.52 +
   15.53 +    /**
   15.54 +     * Constructs a {@code WrongMethodTypeException} with the specified
   15.55 +     * detail message.
   15.56 +     *
   15.57 +     * @param s the detail message.
   15.58 +     */
   15.59 +    public WrongMethodTypeException(String s) {
   15.60 +        super(s);
   15.61 +    }
   15.62 +}
    16.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    16.2 +++ b/src/share/classes/java/dyn/package-info.java	Tue May 05 22:40:09 2009 -0700
    16.3 @@ -0,0 +1,32 @@
    16.4 +/*
    16.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    16.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    16.7 + *
    16.8 + * This code is free software; you can redistribute it and/or modify it
    16.9 + * under the terms of the GNU General Public License version 2 only, as
   16.10 + * published by the Free Software Foundation.  Sun designates this
   16.11 + * particular file as subject to the "Classpath" exception as provided
   16.12 + * by Sun in the LICENSE file that accompanied this code.
   16.13 + *
   16.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   16.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   16.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   16.17 + * version 2 for more details (a copy is included in the LICENSE file that
   16.18 + * accompanied this code).
   16.19 + *
   16.20 + * You should have received a copy of the GNU General Public License version
   16.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   16.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   16.23 + *
   16.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   16.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   16.26 + * have any questions.
   16.27 + */
   16.28 +
   16.29 +/**
   16.30 + * This package contains dynamic language support provided directly by
   16.31 + * the Java core class libraries and virtual machine.
   16.32 + * @author John Rose, JSR 292 EG
   16.33 + */
   16.34 +
   16.35 +package java.dyn;
    17.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    17.2 +++ b/src/share/classes/sun/dyn/Access.java	Tue May 05 22:40:09 2009 -0700
    17.3 @@ -0,0 +1,109 @@
    17.4 +/*
    17.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    17.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    17.7 + *
    17.8 + * This code is free software; you can redistribute it and/or modify it
    17.9 + * under the terms of the GNU General Public License version 2 only, as
   17.10 + * published by the Free Software Foundation.  Sun designates this
   17.11 + * particular file as subject to the "Classpath" exception as provided
   17.12 + * by Sun in the LICENSE file that accompanied this code.
   17.13 + *
   17.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   17.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   17.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   17.17 + * version 2 for more details (a copy is included in the LICENSE file that
   17.18 + * accompanied this code).
   17.19 + *
   17.20 + * You should have received a copy of the GNU General Public License version
   17.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   17.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   17.23 + *
   17.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   17.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   17.26 + * have any questions.
   17.27 + */
   17.28 +
   17.29 +package sun.dyn;
   17.30 +
   17.31 +import sun.reflect.Reflection;
   17.32 +
   17.33 +/**
   17.34 + * Access control to this package.
   17.35 + * Classes in other packages can attempt to acquire the access token,
   17.36 + * but will fail if they are not recognized as friends.
   17.37 + * Certain methods in this package, although public, require a non-null
   17.38 + * access token in order to proceed; they act like package-private methods.
   17.39 + * @author jrose
   17.40 + */
   17.41 +
   17.42 +public class Access {
   17.43 +
   17.44 +    private Access() { }
   17.45 +
   17.46 +    /**
   17.47 +     * The heart of this pattern:  The list of classes which are
   17.48 +     * permitted to acquire the access token, and become honorary
   17.49 +     * members of this package.
   17.50 +     */
   17.51 +    private static final String[] FRIENDS = {
   17.52 +        "java.dyn.", "sun.dyn."
   17.53 +    };
   17.54 +
   17.55 +    /**
   17.56 +     * The following object is NOT public.  That's the point of the pattern.
   17.57 +     * It is package-private, so that any member of this package
   17.58 +     * can acquire the access token, and give it away to trusted friends.
   17.59 +     */
   17.60 +    static final Access TOKEN = new Access();
   17.61 +
   17.62 +    /**
   17.63 +     * @return Access.TOKEN, if the caller is a friend of this package
   17.64 +     */
   17.65 +    public static Access getToken() {
   17.66 +        Class<?> callc = Reflection.getCallerClass(2);
   17.67 +        if (isFriend(callc))
   17.68 +            return TOKEN;
   17.69 +        else
   17.70 +            throw new IllegalAccessError("bad caller: " + callc);
   17.71 +    }
   17.72 +
   17.73 +    /** Is the given name the name of a class which could be our friend? */
   17.74 +    public static boolean isFriendName(String name) {
   17.75 +        for (String friend : FRIENDS) {
   17.76 +            if (name.startsWith(friend))
   17.77 +                return true;
   17.78 +        }
   17.79 +        return false;
   17.80 +    }
   17.81 +
   17.82 +    /** Is the given class a friend?  True if {@link #isFriendName},
   17.83 +     *  and the given class also shares a class loader with us.
   17.84 +     */
   17.85 +    public static boolean isFriend(Class<?> c) {
   17.86 +        return isFriendName(c.getName()) && c.getClassLoader() == CLASS_LOADER;
   17.87 +    }
   17.88 +
   17.89 +    private static final ClassLoader CLASS_LOADER = Access.class.getClassLoader();
   17.90 +
   17.91 +    /**
   17.92 +     * Throw an IllegalAccessError if the caller does not possess
   17.93 +     * the Access.TOKEN.
   17.94 +     * @param must be Access.TOKEN
   17.95 +     */
   17.96 +    public static void check(Access token) {
   17.97 +        if (token == null)
   17.98 +            fail();
   17.99 +        // else it must be the unique Access.TOKEN
  17.100 +        assert(token == Access.TOKEN);
  17.101 +    }
  17.102 +    private static void fail() {
  17.103 +        final int CALLER_DEPTH = 3;
  17.104 +        // 0: Reflection.getCC, 1: this.fail, 2: Access.*, 3: caller
  17.105 +        Class<?> callc = Reflection.getCallerClass(CALLER_DEPTH);
  17.106 +        throw new IllegalAccessError("bad caller: " + callc);
  17.107 +    }
  17.108 +
  17.109 +    static {
  17.110 +        //sun.reflect.Reflection.registerMethodsToFilter(MH.class, "getToken");
  17.111 +    }
  17.112 +}
    18.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    18.2 +++ b/src/share/classes/sun/dyn/AdapterMethodHandle.java	Tue May 05 22:40:09 2009 -0700
    18.3 @@ -0,0 +1,728 @@
    18.4 +/*
    18.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    18.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    18.7 + *
    18.8 + * This code is free software; you can redistribute it and/or modify it
    18.9 + * under the terms of the GNU General Public License version 2 only, as
   18.10 + * published by the Free Software Foundation.  Sun designates this
   18.11 + * particular file as subject to the "Classpath" exception as provided
   18.12 + * by Sun in the LICENSE file that accompanied this code.
   18.13 + *
   18.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   18.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   18.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   18.17 + * version 2 for more details (a copy is included in the LICENSE file that
   18.18 + * accompanied this code).
   18.19 + *
   18.20 + * You should have received a copy of the GNU General Public License version
   18.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   18.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   18.23 + *
   18.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   18.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   18.26 + * have any questions.
   18.27 + */
   18.28 +
   18.29 +package sun.dyn;
   18.30 +
   18.31 +import sun.dyn.util.VerifyType;
   18.32 +import sun.dyn.util.Wrapper;
   18.33 +import java.dyn.*;
   18.34 +import java.util.Arrays;
   18.35 +import static sun.dyn.MethodHandleNatives.Constants.*;
   18.36 +import static sun.dyn.MethodHandleImpl.newIllegalArgumentException;
   18.37 +
   18.38 +/**
   18.39 + * This method handle performs simple conversion or checking of a single argument.
   18.40 + * @author jrose
   18.41 + */
   18.42 +public class AdapterMethodHandle extends BoundMethodHandle {
   18.43 +
   18.44 +    //MethodHandle vmtarget;   // next AMH or BMH in chain or final DMH
   18.45 +    //Object       argument;   // parameter to the conversion if needed
   18.46 +    //int          vmargslot;  // which argument slot is affected
   18.47 +    private final int conversion;  // the type of conversion: RETYPE_ONLY, etc.
   18.48 +
   18.49 +    // Constructors in this class *must* be package scoped or private.
   18.50 +    private AdapterMethodHandle(MethodHandle target, MethodType newType,
   18.51 +                long conv, Object convArg) {
   18.52 +        super(newType, convArg, newType.parameterSlotDepth(1+convArgPos(conv)));
   18.53 +        this.conversion = convCode(conv);
   18.54 +        if (MethodHandleNatives.JVM_SUPPORT) {
   18.55 +            // JVM might update VM-specific bits of conversion (ignore)
   18.56 +            MethodHandleNatives.init(this, target, convArgPos(conv));
   18.57 +        }
   18.58 +    }
   18.59 +    private AdapterMethodHandle(MethodHandle target, MethodType newType,
   18.60 +                long conv) {
   18.61 +        this(target, newType, conv, null);
   18.62 +    }
   18.63 +
   18.64 +    private static final Access IMPL_TOKEN = Access.getToken();
   18.65 +
   18.66 +    // TO DO:  When adapting another MH with a null conversion, clone
   18.67 +    // the target and change its type, instead of adding another layer.
   18.68 +
   18.69 +    /** Can a JVM-level adapter directly implement the proposed
   18.70 +     *  argument conversions, as if by MethodHandles.convertArguments?
   18.71 +     */
   18.72 +    public static boolean canPairwiseConvert(MethodType newType, MethodType oldType) {
   18.73 +        // same number of args, of course
   18.74 +        int len = newType.parameterCount();
   18.75 +        if (len != oldType.parameterCount())
   18.76 +            return false;
   18.77 +
   18.78 +        // Check return type.  (Not much can be done with it.)
   18.79 +        Class<?> exp = newType.returnType();
   18.80 +        Class<?> ret = oldType.returnType();
   18.81 +        if (!VerifyType.isNullConversion(ret, exp))
   18.82 +            return false;
   18.83 +
   18.84 +        // Check args pairwise.
   18.85 +        for (int i = 0; i < len; i++) {
   18.86 +            Class<?> src = newType.parameterType(i); // source type
   18.87 +            Class<?> dst = oldType.parameterType(i); // destination type
   18.88 +            if (!canConvertArgument(src, dst))
   18.89 +                return false;
   18.90 +        }
   18.91 +
   18.92 +        return true;
   18.93 +    }
   18.94 +
   18.95 +    /** Can a JVM-level adapter directly implement the proposed
   18.96 +     *  argument conversion, as if by MethodHandles.convertArguments?
   18.97 +     */
   18.98 +    public static boolean canConvertArgument(Class<?> src, Class<?> dst) {
   18.99 +        // ? Retool this logic to use RETYPE_ONLY, CHECK_CAST, etc., as opcodes,
  18.100 +        // so we don't need to repeat so much decision making.
  18.101 +        if (VerifyType.isNullConversion(src, dst)) {
  18.102 +            return true;
  18.103 +        } else if (src.isPrimitive()) {
  18.104 +            if (dst.isPrimitive())
  18.105 +                return canPrimCast(src, dst);
  18.106 +            else
  18.107 +                return canBoxArgument(src, dst);
  18.108 +        } else {
  18.109 +            if (dst.isPrimitive())
  18.110 +                return canUnboxArgument(src, dst);
  18.111 +            else
  18.112 +                return true;  // any two refs can be interconverted
  18.113 +        }
  18.114 +    }
  18.115 +
  18.116 +    /**
  18.117 +     * Create a JVM-level adapter method handle to conform the given method
  18.118 +     * handle to the similar newType, using only pairwise argument conversions.
  18.119 +     * For each argument, convert incoming argument to the exact type needed.
  18.120 +     * Only null conversions are allowed on the return value (until
  18.121 +     * the JVM supports ricochet adapters).
  18.122 +     * The argument conversions allowed are casting, unboxing,
  18.123 +     * integral widening or narrowing, and floating point widening or narrowing.
  18.124 +     * @param token access check
  18.125 +     * @param newType required call type
  18.126 +     * @param target original method handle
  18.127 +     * @return an adapter to the original handle with the desired new type,
  18.128 +     *          or the original target if the types are already identical
  18.129 +     *          or null if the adaptation cannot be made
  18.130 +     */
  18.131 +    public static MethodHandle makePairwiseConvert(Access token,
  18.132 +                MethodType newType, MethodHandle target) {
  18.133 +        Access.check(token);
  18.134 +        MethodType oldType = target.type();
  18.135 +        if (newType == oldType)  return target;
  18.136 +
  18.137 +        if (!canPairwiseConvert(newType, oldType))
  18.138 +            return null;
  18.139 +        // (after this point, it is an assertion error to fail to convert)
  18.140 +
  18.141 +        // Find last non-trivial conversion (if any).
  18.142 +        int lastConv = newType.parameterCount()-1;
  18.143 +        while (lastConv >= 0) {
  18.144 +            Class<?> src = newType.parameterType(lastConv); // source type
  18.145 +            Class<?> dst = oldType.parameterType(lastConv); // destination type
  18.146 +            if (VerifyType.isNullConversion(src, dst)) {
  18.147 +                --lastConv;
  18.148 +            } else {
  18.149 +                break;
  18.150 +            }
  18.151 +        }
  18.152 +        // Now build a chain of one or more adapters.
  18.153 +        MethodHandle adapter = target;
  18.154 +        MethodType midType = oldType.changeReturnType(newType.returnType());
  18.155 +        for (int i = 0; i <= lastConv; i++) {
  18.156 +            Class<?> src = newType.parameterType(i); // source type
  18.157 +            Class<?> dst = midType.parameterType(i); // destination type
  18.158 +            if (VerifyType.isNullConversion(src, dst)) {
  18.159 +                // do nothing: difference is trivial
  18.160 +                continue;
  18.161 +            }
  18.162 +            // Work the current type backward toward the desired caller type:
  18.163 +            if (i != lastConv) {
  18.164 +                midType = midType.changeParameterType(i, src);
  18.165 +            } else {
  18.166 +                // When doing the last (or only) real conversion,
  18.167 +                // force all remaining null conversions to happen also.
  18.168 +                assert(VerifyType.isNullConversion(newType, midType.changeParameterType(i, src)));
  18.169 +                midType = newType;
  18.170 +            }
  18.171 +
  18.172 +            // Tricky case analysis follows.
  18.173 +            // It parallels canConvertArgument() above.
  18.174 +            if (src.isPrimitive()) {
  18.175 +                if (dst.isPrimitive()) {
  18.176 +                    adapter = makePrimCast(token, midType, adapter, i, dst);
  18.177 +                } else {
  18.178 +                    adapter = makeBoxArgument(token, midType, adapter, i, dst);
  18.179 +                }
  18.180 +            } else {
  18.181 +                if (dst.isPrimitive()) {
  18.182 +                    // Caller has boxed a primitive.  Unbox it for the target.
  18.183 +                    // The box type must correspond exactly to the primitive type.
  18.184 +                    // This is simpler than the powerful set of widening
  18.185 +                    // conversions supported by reflect.Method.invoke.
  18.186 +                    // Those conversions require a big nest of if/then/else logic,
  18.187 +                    // which we prefer to make a user responsibility.
  18.188 +                    adapter = makeUnboxArgument(token, midType, adapter, i, dst);
  18.189 +                } else {
  18.190 +                    // Simple reference conversion.
  18.191 +                    // Note:  Do not check for a class hierarchy relation
  18.192 +                    // between src and dst.  In all cases a 'null' argument
  18.193 +                    // will pass the cast conversion.
  18.194 +                    adapter = makeCheckCast(token, midType, adapter, i, dst);
  18.195 +                }
  18.196 +            }
  18.197 +            assert(adapter != null);
  18.198 +            assert(adapter.type() == midType);
  18.199 +        }
  18.200 +        if (adapter.type() != newType) {
  18.201 +            // Only trivial conversions remain.
  18.202 +            adapter = makeRetypeOnly(IMPL_TOKEN, newType, adapter);
  18.203 +            assert(adapter != null);
  18.204 +            // Actually, that's because there were no non-trivial ones:
  18.205 +            assert(lastConv == -1);
  18.206 +        }
  18.207 +        assert(adapter.type() == newType);
  18.208 +        return adapter;
  18.209 +    }
  18.210 +
  18.211 +    /**
  18.212 +     * Create a JVM-level adapter method handle to permute the arguments
  18.213 +     * of the given method.
  18.214 +     * @param token access check
  18.215 +     * @param newType required call type
  18.216 +     * @param target original method handle
  18.217 +     * @param argumentMap for each target argument, position of its source in newType
  18.218 +     * @return an adapter to the original handle with the desired new type,
  18.219 +     *          or the original target if the types are already identical
  18.220 +     *          and the permutation is null
  18.221 +     * @throws IllegalArgumentException if the adaptation cannot be made
  18.222 +     *          directly by a JVM-level adapter, without help from Java code
  18.223 +     */
  18.224 +    public static MethodHandle makePermutation(Access token,
  18.225 +                MethodType newType, MethodHandle target,
  18.226 +                int[] argumentMap) {
  18.227 +        MethodType oldType = target.type();
  18.228 +        boolean nullPermutation = true;
  18.229 +        for (int i = 0; i < argumentMap.length; i++) {
  18.230 +            int pos = argumentMap[i];
  18.231 +            if (pos != i)
  18.232 +                nullPermutation = false;
  18.233 +            if (pos < 0 || pos >= newType.parameterCount()) {
  18.234 +                argumentMap = new int[0]; break;
  18.235 +            }
  18.236 +        }
  18.237 +        if (argumentMap.length != oldType.parameterCount())
  18.238 +            throw newIllegalArgumentException("bad permutation: "+Arrays.toString(argumentMap));
  18.239 +        if (nullPermutation) {
  18.240 +            MethodHandle res = makePairwiseConvert(token, newType, target);
  18.241 +            // well, that was easy
  18.242 +            if (res == null)
  18.243 +                throw newIllegalArgumentException("cannot convert pairwise: "+newType);
  18.244 +            return res;
  18.245 +        }
  18.246 +
  18.247 +        // Check return type.  (Not much can be done with it.)
  18.248 +        Class<?> exp = newType.returnType();
  18.249 +        Class<?> ret = oldType.returnType();
  18.250 +        if (!VerifyType.isNullConversion(ret, exp))
  18.251 +            throw newIllegalArgumentException("bad return conversion for "+newType);
  18.252 +
  18.253 +        // See if the argument types match up.
  18.254 +        for (int i = 0; i < argumentMap.length; i++) {
  18.255 +            int j = argumentMap[i];
  18.256 +            Class<?> src = newType.parameterType(j);
  18.257 +            Class<?> dst = oldType.parameterType(i);
  18.258 +            if (!VerifyType.isNullConversion(src, dst))
  18.259 +                throw newIllegalArgumentException("bad argument #"+j+" conversion for "+newType);
  18.260 +        }
  18.261 +
  18.262 +        // Now figure out a nice mix of SWAP, ROT, DUP, and DROP adapters.
  18.263 +        // A workable greedy algorithm is as follows:
  18.264 +        // Drop unused outgoing arguments (right to left: shallowest first).
  18.265 +        // Duplicate doubly-used outgoing arguments (left to right: deepest first).
  18.266 +        // Then the remaining problem is a true argument permutation.
  18.267 +        // Marshal the outgoing arguments as required from left to right.
  18.268 +        // That is, find the deepest outgoing stack position that does not yet
  18.269 +        // have the correct argument value, and correct at least that position
  18.270 +        // by swapping or rotating in the misplaced value (from a shallower place).
  18.271 +        // If the misplaced value is followed by one or more consecutive values
  18.272 +        // (also misplaced)  issue a rotation which brings as many as possible
  18.273 +        // into position.  Otherwise make progress with either a swap or a
  18.274 +        // rotation.  Prefer the swap as cheaper, but do not use it if it
  18.275 +        // breaks a slot pair.  Prefer the rotation over the swap if it would
  18.276 +        // preserve more consecutive values shallower than the target position.
  18.277 +        // When more than one rotation will work (because the required value
  18.278 +        // is already adjacent to the target position), then use a rotation
  18.279 +        // which moves the old value in the target position adjacent to
  18.280 +        // one of its consecutive values.  Also, prefer shorter rotation
  18.281 +        // spans, since they use fewer memory cycles for shuffling.
  18.282 +
  18.283 +        throw new UnsupportedOperationException("NYI");
  18.284 +    }
  18.285 +
  18.286 +    private static byte basicType(Class<?> type) {
  18.287 +        if (type == null)  return T_VOID;
  18.288 +        switch (Wrapper.forBasicType(type)) {
  18.289 +            case BOOLEAN:  return T_BOOLEAN;
  18.290 +            case CHAR:     return T_CHAR;
  18.291 +            case FLOAT:    return T_FLOAT;
  18.292 +            case DOUBLE:   return T_DOUBLE;
  18.293 +            case BYTE:     return T_BYTE;
  18.294 +            case SHORT:    return T_SHORT;
  18.295 +            case INT:      return T_INT;
  18.296 +            case LONG:     return T_LONG;
  18.297 +            case OBJECT:   return T_OBJECT;
  18.298 +            case VOID:     return T_VOID;
  18.299 +        }
  18.300 +        return 99; // T_ILLEGAL or some such
  18.301 +    }
  18.302 +
  18.303 +    /** Number of stack slots for the given type.
  18.304 +     *  Two for T_DOUBLE and T_FLOAT, one for the rest.
  18.305 +     */
  18.306 +    private static int type2size(int type) {
  18.307 +        assert(type >= T_BOOLEAN && type <= T_OBJECT);
  18.308 +        return (type == T_FLOAT || type == T_DOUBLE) ? 2 : 1;
  18.309 +    }
  18.310 +
  18.311 +    /** Construct an adapter conversion descriptor for a single-argument conversion. */
  18.312 +    private static long makeConv(int convOp, int argnum, int src, int dest) {
  18.313 +        assert(src  == (src  & 0xF));
  18.314 +        assert(dest == (dest & 0xF));
  18.315 +        assert(convOp >= OP_CHECK_CAST && convOp <= OP_PRIM_TO_REF);
  18.316 +        long stackMove = type2size(dest) - type2size(src);
  18.317 +        return ((long) argnum << 32 |
  18.318 +                (long) convOp << CONV_OP_SHIFT |
  18.319 +                (int)  src    << CONV_SRC_TYPE_SHIFT |
  18.320 +                (int)  dest   << CONV_DEST_TYPE_SHIFT |
  18.321 +                stackMove     << CONV_STACK_MOVE_SHIFT
  18.322 +                );
  18.323 +    }
  18.324 +    private static long makeConv(int convOp, int argnum, int stackMove) {
  18.325 +        assert(convOp >= OP_SWAP_ARGS && convOp <= OP_SPREAD_ARGS);
  18.326 +        byte src = 0, dest = 0;
  18.327 +        if (convOp >= OP_COLLECT_ARGS && convOp <= OP_SPREAD_ARGS)
  18.328 +            src = dest = T_OBJECT;
  18.329 +        return ((long) argnum << 32 |
  18.330 +                (long) convOp << CONV_OP_SHIFT |
  18.331 +                (int)  src    << CONV_SRC_TYPE_SHIFT |
  18.332 +                (int)  dest   << CONV_DEST_TYPE_SHIFT |
  18.333 +                stackMove     << CONV_STACK_MOVE_SHIFT
  18.334 +                );
  18.335 +    }
  18.336 +    private static long makeConv(int convOp) {
  18.337 +        assert(convOp == OP_RETYPE_ONLY);
  18.338 +        return (long) convOp << CONV_OP_SHIFT;   // stackMove, src, dst, argnum all zero
  18.339 +    }
  18.340 +    private static int convCode(long conv) {
  18.341 +        return (int)conv;
  18.342 +    }
  18.343 +    private static int convArgPos(long conv) {
  18.344 +        return (int)(conv >>> 32);
  18.345 +    }
  18.346 +    private static boolean convOpSupported(int convOp) {
  18.347 +        assert(convOp >= 0 && convOp <= CONV_OP_LIMIT);
  18.348 +        return ((1<<convOp) & CONV_OP_IMPLEMENTED_MASK) != 0;
  18.349 +    }
  18.350 +
  18.351 +    /** One of OP_RETYPE_ONLY, etc. */
  18.352 +    int conversionOp() { return (conversion & CONV_OP_MASK) >> CONV_OP_SHIFT; }
  18.353 +
  18.354 +    @Override
  18.355 +    public String toString() {
  18.356 +        return addTypeString(this, "Adapted[" + basicToString(nonAdapter((MethodHandle)vmtarget)) + "]");
  18.357 +    }
  18.358 +
  18.359 +    private static MethodHandle nonAdapter(MethodHandle mh) {
  18.360 +        return (MethodHandle)
  18.361 +            MethodHandleNatives.getTarget(mh, ETF_DIRECT_HANDLE);
  18.362 +    }
  18.363 +
  18.364 +    /* Return one plus the position of the first non-trivial difference
  18.365 +     * between the given types.  This is not a symmetric operation;
  18.366 +     * we are considering adapting the targetType to adapterType.
  18.367 +     * Trivial differences are those which could be ignored by the JVM
  18.368 +     * without subverting the verifier.  Otherwise, adaptable differences
  18.369 +     * are ones for which we could create an adapter to make the type change.
  18.370 +     * Return zero if there are no differences (other than trivial ones).
  18.371 +     * Return 1+N if N is the only adaptable argument difference.
  18.372 +     * Return the -2-N where N is the first of several adaptable
  18.373 +     * argument differences.
  18.374 +     * Return -1 if there there are differences which are not adaptable.
  18.375 +     */
  18.376 +    private static int diffTypes(MethodType adapterType,
  18.377 +                                 MethodType targetType,
  18.378 +                                 boolean raw) {
  18.379 +        int diff;
  18.380 +        diff = diffReturnTypes(adapterType, targetType, raw);
  18.381 +        if (diff != 0)  return diff;
  18.382 +        int nargs = adapterType.parameterCount();
  18.383 +        if (nargs != targetType.parameterCount())
  18.384 +            return -1;
  18.385 +        diff = diffParamTypes(adapterType, 0, targetType, 0, nargs, raw);
  18.386 +        //System.out.println("diff "+adapterType);
  18.387 +        //System.out.println("  "+diff+" "+targetType);
  18.388 +        return diff;
  18.389 +    }
  18.390 +    private static int diffReturnTypes(MethodType adapterType,
  18.391 +                                       MethodType targetType,
  18.392 +                                       boolean raw) {
  18.393 +        Class<?> src = targetType.returnType();
  18.394 +        Class<?> dst = adapterType.returnType();
  18.395 +        if ((!raw
  18.396 +             ? VerifyType.canPassUnchecked(src, dst)
  18.397 +             : VerifyType.canPassRaw(src, dst)
  18.398 +             ) > 0)
  18.399 +            return 0;  // no significant difference
  18.400 +        if (raw && !src.isPrimitive() && !dst.isPrimitive())
  18.401 +            return 0;  // can force a reference return (very carefully!)
  18.402 +        //if (false)  return 1;  // never adaptable!
  18.403 +        return -1;  // some significant difference
  18.404 +    }
  18.405 +    private static int diffParamTypes(MethodType adapterType, int tstart,
  18.406 +                                      MethodType targetType, int astart,
  18.407 +                                      int nargs, boolean raw) {
  18.408 +        assert(nargs >= 0);
  18.409 +        int res = 0;
  18.410 +        for (int i = 0; i < nargs; i++) {
  18.411 +            Class<?> src  = adapterType.parameterType(tstart+i);
  18.412 +            Class<?> dest = targetType.parameterType(astart+i);
  18.413 +            if ((!raw
  18.414 +                 ? VerifyType.canPassUnchecked(src, dest)
  18.415 +                 : VerifyType.canPassRaw(src, dest)
  18.416 +                ) <= 0) {
  18.417 +                // found a difference; is it the only one so far?
  18.418 +                if (res != 0)
  18.419 +                    return -1-res; // return -2-i for prev. i
  18.420 +                res = 1+i;
  18.421 +            }
  18.422 +        }
  18.423 +        return res;
  18.424 +    }
  18.425 +
  18.426 +    /** Can a retyping adapter (alone) validly convert the target to newType? */
  18.427 +    public static boolean canRetypeOnly(MethodType newType, MethodType targetType) {
  18.428 +        return canRetypeOnly(newType, targetType, false);
  18.429 +    }
  18.430 +    /** Can a retyping adapter (alone) convert the target to newType?
  18.431 +     *  It is allowed to widen subword types and void to int, to make bitwise
  18.432 +     *  conversions between float/int and double/long, and to perform unchecked
  18.433 +     *  reference conversions on return.  This last feature requires that the
  18.434 +     *  caller be trusted, and perform explicit cast conversions on return values.
  18.435 +     */
  18.436 +    static boolean canRawRetypeOnly(MethodType newType, MethodType targetType) {
  18.437 +        return canRetypeOnly(newType, targetType, true);
  18.438 +    }
  18.439 +    static boolean canRetypeOnly(MethodType newType, MethodType targetType, boolean raw) {
  18.440 +        if (!convOpSupported(OP_RETYPE_ONLY))  return false;
  18.441 +        int diff = diffTypes(newType, targetType, raw);
  18.442 +        // %%% This assert is too strong.  Factor diff into VerifyType and reconcile.
  18.443 +        assert((diff == 0) == VerifyType.isNullConversion(newType, targetType));
  18.444 +        return diff == 0;
  18.445 +    }
  18.446 +
  18.447 +    /** Factory method:  Performs no conversions; simply retypes the adapter.
  18.448 +     *  Allows unchecked argument conversions pairwise, if they are safe.
  18.449 +     *  Returns null if not possible.
  18.450 +     */
  18.451 +    public static MethodHandle makeRetypeOnly(Access token,
  18.452 +                MethodType newType, MethodHandle target) {
  18.453 +        return makeRetypeOnly(token, newType, target, false);
  18.454 +    }
  18.455 +    public static MethodHandle makeRawRetypeOnly(Access token,
  18.456 +                MethodType newType, MethodHandle target) {
  18.457 +        return makeRetypeOnly(token, newType, target, true);
  18.458 +    }
  18.459 +    static MethodHandle makeRetypeOnly(Access token,
  18.460 +                MethodType newType, MethodHandle target, boolean raw) {
  18.461 +        Access.check(token);
  18.462 +        if (!canRetypeOnly(newType, target.type(), raw))
  18.463 +            return null;
  18.464 +        // TO DO:  clone the target guy, whatever he is, with new type.
  18.465 +        return new AdapterMethodHandle(target, newType, makeConv(OP_RETYPE_ONLY));
  18.466 +    }
  18.467 +
  18.468 +    /** Can a checkcast adapter validly convert the target to newType?
  18.469 +     *  The JVM supports all kind of reference casts, even silly ones.
  18.470 +     */
  18.471 +    public static boolean canCheckCast(MethodType newType, MethodType targetType,
  18.472 +                int arg, Class<?> castType) {
  18.473 +        if (!convOpSupported(OP_CHECK_CAST))  return false;
  18.474 +        Class<?> src = newType.parameterType(arg);
  18.475 +        Class<?> dst = targetType.parameterType(arg);
  18.476 +        if (!canCheckCast(src, castType)
  18.477 +                || !VerifyType.isNullConversion(castType, dst))
  18.478 +            return false;
  18.479 +        int diff = diffTypes(newType, targetType, false);
  18.480 +        return (diff == arg+1);  // arg is sole non-trivial diff
  18.481 +    }
  18.482 +    /** Can an primitive conversion adapter validly convert src to dst? */
  18.483 +    public static boolean canCheckCast(Class<?> src, Class<?> dst) {
  18.484 +        return (!src.isPrimitive() && !dst.isPrimitive());
  18.485 +    }
  18.486 +
  18.487 +    /** Factory method:  Forces a cast at the given argument.
  18.488 +     *  The castType is the target of the cast, and can be any type
  18.489 +     *  with a null conversion to the corresponding target parameter.
  18.490 +     *  Return null if this cannot be done.
  18.491 +     */
  18.492 +    public static MethodHandle makeCheckCast(Access token,
  18.493 +                MethodType newType, MethodHandle target,
  18.494 +                int arg, Class<?> castType) {
  18.495 +        Access.check(token);
  18.496 +        if (!canCheckCast(newType, target.type(), arg, castType))
  18.497 +            return null;
  18.498 +        long conv = makeConv(OP_CHECK_CAST, arg, 0);
  18.499 +        return new AdapterMethodHandle(target, newType, conv, castType);
  18.500 +    }
  18.501 +
  18.502 +    /** Can an primitive conversion adapter validly convert the target to newType?
  18.503 +     *  The JVM currently supports all conversions except those between
  18.504 +     *  floating and integral types.
  18.505 +     */
  18.506 +    public static boolean canPrimCast(MethodType newType, MethodType targetType,
  18.507 +                int arg, Class<?> convType) {
  18.508 +        if (!convOpSupported(OP_PRIM_TO_PRIM))  return false;
  18.509 +        Class<?> src = newType.parameterType(arg);
  18.510 +        Class<?> dst = targetType.parameterType(arg);
  18.511 +        if (!canPrimCast(src, convType)
  18.512 +                || !VerifyType.isNullConversion(convType, dst))
  18.513 +            return false;
  18.514 +        int diff = diffTypes(newType, targetType, false);
  18.515 +        return (diff == arg+1);  // arg is sole non-trivial diff
  18.516 +    }
  18.517 +    /** Can an primitive conversion adapter validly convert src to dst? */
  18.518 +    public static boolean canPrimCast(Class<?> src, Class<?> dst) {
  18.519 +        if (src == dst || !src.isPrimitive() || !dst.isPrimitive()) {
  18.520 +            return false;
  18.521 +        } else if (Wrapper.forPrimitiveType(dst).isFloating()) {
  18.522 +            // both must be floating types
  18.523 +            return Wrapper.forPrimitiveType(src).isFloating();
  18.524 +        } else {
  18.525 +            // both are integral, and all combinations work fine
  18.526 +            assert(Wrapper.forPrimitiveType(src).isIntegral() &&
  18.527 +                   Wrapper.forPrimitiveType(dst).isIntegral());
  18.528 +            return true;
  18.529 +        }
  18.530 +    }
  18.531 +
  18.532 +    /** Factory method:  Truncate the given argument with zero or sign extension,
  18.533 +     *  and/or convert between single and doubleword versions of integer or float.
  18.534 +     *  The convType is the target of the conversion, and can be any type
  18.535 +     *  with a null conversion to the corresponding target parameter.
  18.536 +     *  Return null if this cannot be done.
  18.537 +     */
  18.538 +    public static MethodHandle makePrimCast(Access token,
  18.539 +                MethodType newType, MethodHandle target,
  18.540 +                int arg, Class<?> convType) {
  18.541 +        Access.check(token);
  18.542 +        MethodType oldType = target.type();
  18.543 +        Class<?> src = newType.parameterType(arg);
  18.544 +        Class<?> dst = oldType.parameterType(arg);
  18.545 +        if (!canPrimCast(newType, oldType, arg, convType))
  18.546 +            return null;
  18.547 +        long conv = makeConv(OP_PRIM_TO_PRIM, arg, basicType(src), basicType(convType));
  18.548 +        return new AdapterMethodHandle(target, newType, conv);
  18.549 +    }
  18.550 +
  18.551 +    /** Can an unboxing conversion validly convert src to dst?
  18.552 +     *  The JVM currently supports all kinds of casting and unboxing.
  18.553 +     *  The convType is the unboxed type; it can be either a primitive or wrapper.
  18.554 +     */
  18.555 +    public static boolean canUnboxArgument(MethodType newType, MethodType targetType,
  18.556 +                int arg, Class<?> convType) {
  18.557 +        if (!convOpSupported(OP_REF_TO_PRIM))  return false;
  18.558 +        Class<?> src = newType.parameterType(arg);
  18.559 +        Class<?> dst = targetType.parameterType(arg);
  18.560 +        Class<?> boxType = Wrapper.asWrapperType(convType);
  18.561 +        convType = Wrapper.asPrimitiveType(convType);
  18.562 +        if (!canCheckCast(src, boxType)
  18.563 +                || boxType == convType
  18.564 +                || !VerifyType.isNullConversion(convType, dst))
  18.565 +            return false;
  18.566 +        int diff = diffTypes(newType, targetType, false);
  18.567 +        return (diff == arg+1);  // arg is sole non-trivial diff
  18.568 +    }
  18.569 +    /** Can an primitive unboxing adapter validly convert src to dst? */
  18.570 +    public static boolean canUnboxArgument(Class<?> src, Class<?> dst) {
  18.571 +        return (!src.isPrimitive() && Wrapper.asPrimitiveType(dst).isPrimitive());
  18.572 +    }
  18.573 +
  18.574 +    /** Factory method:  Unbox the given argument.
  18.575 +     *  Return null if this cannot be done.
  18.576 +     */
  18.577 +    public static MethodHandle makeUnboxArgument(Access token,
  18.578 +                MethodType newType, MethodHandle target,
  18.579 +                int arg, Class<?> convType) {
  18.580 +        MethodType oldType = target.type();
  18.581 +        Class<?> src = newType.parameterType(arg);
  18.582 +        Class<?> dst = oldType.parameterType(arg);
  18.583 +        Class<?> boxType = Wrapper.asWrapperType(convType);
  18.584 +        Class<?> primType = Wrapper.asPrimitiveType(convType);
  18.585 +        if (!canUnboxArgument(newType, oldType, arg, convType))
  18.586 +            return null;
  18.587 +        MethodType castDone = newType;
  18.588 +        if (!VerifyType.isNullConversion(src, boxType))
  18.589 +            castDone = newType.changeParameterType(arg, boxType);
  18.590 +        long conv = makeConv(OP_REF_TO_PRIM, arg, T_OBJECT, basicType(primType));
  18.591 +        MethodHandle adapter = new AdapterMethodHandle(target, castDone, conv, boxType);
  18.592 +        if (castDone == newType)
  18.593 +            return adapter;
  18.594 +        return makeCheckCast(token, newType, adapter, arg, boxType);
  18.595 +    }
  18.596 +
  18.597 +    /** Can an primitive boxing adapter validly convert src to dst? */
  18.598 +    public static boolean canBoxArgument(Class<?> src, Class<?> dst) {
  18.599 +        if (!convOpSupported(OP_PRIM_TO_REF))  return false;
  18.600 +        throw new UnsupportedOperationException("NYI");
  18.601 +    }
  18.602 +
  18.603 +    /** Factory method:  Unbox the given argument.
  18.604 +     *  Return null if this cannot be done.
  18.605 +     */
  18.606 +    public static MethodHandle makeBoxArgument(Access token,
  18.607 +                MethodType newType, MethodHandle target,
  18.608 +                int arg, Class<?> convType) {
  18.609 +        // this is difficult to do in the JVM because it must GC
  18.610 +        return null;
  18.611 +    }
  18.612 +
  18.613 +    // TO DO: makeSwapArguments, makeRotateArguments, makeDuplicateArguments
  18.614 +
  18.615 +    /** Can an adapter simply drop arguments to convert the target to newType? */
  18.616 +    public static boolean canDropArguments(MethodType newType, MethodType targetType,
  18.617 +                int dropArgPos, int dropArgCount) {
  18.618 +        if (dropArgCount == 0)
  18.619 +            return canRetypeOnly(newType, targetType);
  18.620 +        if (!convOpSupported(OP_DROP_ARGS))  return false;
  18.621 +        if (diffReturnTypes(newType, targetType, false) != 0)
  18.622 +            return false;
  18.623 +        int nptypes = newType.parameterCount();
  18.624 +        // parameter types must be the same up to the drop point
  18.625 +        if (dropArgPos != 0 && diffParamTypes(newType, 0, targetType, 0, dropArgPos, false) != 0)
  18.626 +            return false;
  18.627 +        int afterPos = dropArgPos + dropArgCount;
  18.628 +        int afterCount = nptypes - afterPos;
  18.629 +        if (dropArgPos < 0 || dropArgPos >= nptypes ||
  18.630 +            dropArgCount < 1 || afterPos > nptypes ||
  18.631 +            targetType.parameterCount() != nptypes - dropArgCount)
  18.632 +            return false;
  18.633 +        // parameter types after the drop point must also be the same
  18.634 +        if (afterCount != 0 && diffParamTypes(newType, afterPos, targetType, dropArgPos, afterCount, false) != 0)
  18.635 +            return false;
  18.636 +        return true;
  18.637 +    }
  18.638 +
  18.639 +    /** Factory method:  Drop selected arguments.
  18.640 +     *  Allow unchecked retyping of remaining arguments, pairwise.
  18.641 +     *  Return null if this is not possible.
  18.642 +     */
  18.643 +    public static MethodHandle makeDropArguments(Access token,
  18.644 +                MethodType newType, MethodHandle target,
  18.645 +                int dropArgPos, int dropArgCount) {
  18.646 +        Access.check(token);
  18.647 +        if (dropArgCount == 0)
  18.648 +            return makeRetypeOnly(IMPL_TOKEN, newType, target);
  18.649 +        MethodType mt = target.type();
  18.650 +        int argCount  = mt.parameterCount();
  18.651 +        if (!canDropArguments(newType, mt, dropArgPos, dropArgCount))
  18.652 +            return null;
  18.653 +        int dropSlotCount, dropSlotPos;
  18.654 +        if (dropArgCount >= argCount) {
  18.655 +            assert(dropArgPos == argCount-1);
  18.656 +            dropSlotPos = 0;
  18.657 +            dropSlotCount = mt.parameterSlotCount();
  18.658 +        } else {
  18.659 +            // arglist: [0: keep... | dpos: drop... | dpos+dcount: keep... ]
  18.660 +            int lastDroppedArg = dropArgPos + dropArgCount - 1;
  18.661 +            int lastKeptArg    = dropArgPos - 1;  // might be -1, which is OK
  18.662 +            dropSlotPos      = mt.parameterSlotDepth(1+lastDroppedArg);
  18.663 +            int lastKeptSlot = mt.parameterSlotDepth(1+lastKeptArg);
  18.664 +            dropSlotCount = lastKeptSlot - dropSlotPos;
  18.665 +            assert(dropSlotCount >= dropArgCount);
  18.666 +        }
  18.667 +        long conv = makeConv(OP_DROP_ARGS, dropArgPos, +dropSlotCount);
  18.668 +        return new AdapterMethodHandle(target, newType, dropSlotCount, conv);
  18.669 +    }
  18.670 +
  18.671 +    /** Can an adapter spread an argument to convert the target to newType? */
  18.672 +    public static boolean canSpreadArguments(MethodType newType, MethodType targetType,
  18.673 +                Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) {
  18.674 +        if (!convOpSupported(OP_SPREAD_ARGS))  return false;
  18.675 +        if (diffReturnTypes(newType, targetType, false) != 0)
  18.676 +            return false;
  18.677 +        int nptypes = newType.parameterCount();
  18.678 +        // parameter types must be the same up to the spread point
  18.679 +        if (spreadArgPos != 0 && diffParamTypes(newType, 0, targetType, 0, spreadArgPos, false) != 0)
  18.680 +            return false;
  18.681 +        int afterPos = spreadArgPos + spreadArgCount;
  18.682 +        int afterCount = nptypes - afterPos;
  18.683 +        if (spreadArgPos < 0 || spreadArgPos >= nptypes ||
  18.684 +            spreadArgCount < 0 ||
  18.685 +            targetType.parameterCount() != nptypes - 1 + spreadArgCount)
  18.686 +            return false;
  18.687 +        // parameter types after the spread point must also be the same
  18.688 +        if (afterCount != 0 && diffParamTypes(newType, spreadArgPos+1, targetType, afterPos, afterCount, false) != 0)
  18.689 +            return false;
  18.690 +        // match the array element type to the spread arg types
  18.691 +        Class<?> rawSpreadArgType = newType.parameterType(spreadArgPos);
  18.692 +        if (rawSpreadArgType != spreadArgType && !canCheckCast(rawSpreadArgType, spreadArgType))
  18.693 +            return false;
  18.694 +        for (int i = 0; i < spreadArgCount; i++) {
  18.695 +            Class<?> src = VerifyType.spreadArgElementType(spreadArgType, i);
  18.696 +            Class<?> dst = targetType.parameterType(spreadArgPos + i);
  18.697 +            if (src == null || !VerifyType.isNullConversion(src, dst))
  18.698 +                return false;
  18.699 +        }
  18.700 +        return true;
  18.701 +    }
  18.702 +
  18.703 +    /** Factory method:  Spread selected argument. */
  18.704 +    public static MethodHandle makeSpreadArguments(Access token,
  18.705 +                MethodType newType, MethodHandle target,
  18.706 +                Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) {
  18.707 +        Access.check(token);
  18.708 +        MethodType mt = target.type();
  18.709 +        int argCount  = mt.parameterCount();
  18.710 +        if (!canSpreadArguments(newType, mt, spreadArgType, spreadArgPos, spreadArgCount))
  18.711 +            return null;
  18.712 +        int spreadSlotCount, spreadSlotPos;
  18.713 +        if (spreadArgCount >= argCount) {
  18.714 +            assert(spreadArgPos == argCount-1);
  18.715 +            spreadSlotPos = 0;
  18.716 +            spreadSlotCount = mt.parameterSlotCount();
  18.717 +        } else {
  18.718 +            // arglist: [0: keep... | dpos: spread... | dpos+dcount: keep... ]
  18.719 +            int lastSpreadArg = spreadArgPos + spreadArgCount - 1;
  18.720 +            int lastKeptArg   = spreadArgPos - 1;  // might be -1, which is OK
  18.721 +            spreadSlotPos     = mt.parameterSlotDepth(1+lastSpreadArg);
  18.722 +            int lastKeptSlot  = mt.parameterSlotDepth(1+lastKeptArg);
  18.723 +            spreadSlotCount = lastKeptSlot - spreadSlotPos;
  18.724 +            assert(spreadSlotCount >= spreadArgCount);
  18.725 +        }
  18.726 +        long conv = makeConv(OP_SPREAD_ARGS, spreadArgPos, spreadSlotCount);
  18.727 +        return new AdapterMethodHandle(target, newType, conv, spreadArgType);
  18.728 +    }
  18.729 +
  18.730 +    // TO DO: makeCollectArguments, makeFlyby, makeRicochet
  18.731 +}
    19.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    19.2 +++ b/src/share/classes/sun/dyn/BoundMethodHandle.java	Tue May 05 22:40:09 2009 -0700
    19.3 @@ -0,0 +1,180 @@
    19.4 +/*
    19.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    19.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    19.7 + *
    19.8 + * This code is free software; you can redistribute it and/or modify it
    19.9 + * under the terms of the GNU General Public License version 2 only, as
   19.10 + * published by the Free Software Foundation.  Sun designates this
   19.11 + * particular file as subject to the "Classpath" exception as provided
   19.12 + * by Sun in the LICENSE file that accompanied this code.
   19.13 + *
   19.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   19.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   19.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   19.17 + * version 2 for more details (a copy is included in the LICENSE file that
   19.18 + * accompanied this code).
   19.19 + *
   19.20 + * You should have received a copy of the GNU General Public License version
   19.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   19.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   19.23 + *
   19.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   19.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   19.26 + * have any questions.
   19.27 + */
   19.28 +
   19.29 +package sun.dyn;
   19.30 +
   19.31 +import sun.dyn.util.VerifyType;
   19.32 +import sun.dyn.util.Wrapper;
   19.33 +import java.dyn.*;
   19.34 +
   19.35 +/**
   19.36 + * The flavor of method handle which emulates an invoke instruction
   19.37 + * on a predetermined argument.  The JVM dispatches to the correct method
   19.38 + * when the handle is created, not when it is invoked.
   19.39 + * @author jrose
   19.40 + */
   19.41 +public class BoundMethodHandle extends MethodHandle  {
   19.42 +    //MethodHandle vmtarget;           // next BMH or final DMH or methodOop
   19.43 +    private final Object argument;     // argument to insert
   19.44 +    private final int    vmargslot;    // position at which it is inserted
   19.45 +
   19.46 +    // Constructors in this class *must* be package scoped or private.
   19.47 +
   19.48 +    /** Bind a direct MH to its receiver (or first ref. argument).
   19.49 +     *  The JVM will pre-dispatch the MH if it is not already static.
   19.50 +     */
   19.51 +    BoundMethodHandle(DirectMethodHandle mh, Object argument) {
   19.52 +        super(Access.TOKEN, mh.type().dropParameterType(0));
   19.53 +        // check the type now, once for all:
   19.54 +        this.argument = checkReferenceArgument(argument, mh, 0);
   19.55 +        this.vmargslot = this.type().parameterSlotCount();
   19.56 +        if (MethodHandleNatives.JVM_SUPPORT) {
   19.57 +            this.vmtarget = null;  // maybe updated by JVM
   19.58 +            MethodHandleNatives.init(this, mh, 0);
   19.59 +        } else {
   19.60 +            this.vmtarget = mh;
   19.61 +        }
   19.62 +     }
   19.63 +
   19.64 +    private static final int REF_ARG = 0, PRIM_ARG = 1, SELF_ARG = 2;
   19.65 +
   19.66 +    /** Insert an argument into an arbitrary method handle.
   19.67 +     *  If argnum is zero, inserts the first argument, etc.
   19.68 +     *  The argument type must be a reference.
   19.69 +     */
   19.70 +    BoundMethodHandle(MethodHandle mh, Object argument, int argnum) {
   19.71 +        this(mh, argument, argnum, mh.type().parameterType(argnum).isPrimitive() ? PRIM_ARG : REF_ARG);
   19.72 +    }
   19.73 +
   19.74 +    /** Insert an argument into an arbitrary method handle.
   19.75 +     *  If argnum is zero, inserts the first argument, etc.
   19.76 +     */
   19.77 +    BoundMethodHandle(MethodHandle mh, Object argument, int argnum, int whichArg) {
   19.78 +        super(Access.TOKEN, mh.type().dropParameterType(argnum));
   19.79 +        if (whichArg == PRIM_ARG)
   19.80 +            this.argument = bindPrimitiveArgument(argument, mh, argnum);
   19.81 +        else {
   19.82 +            if (whichArg == SELF_ARG)  argument = this;
   19.83 +            this.argument = checkReferenceArgument(argument, mh, argnum);
   19.84 +        }
   19.85 +        this.vmargslot = this.type().parameterSlotDepth(argnum);
   19.86 +        if (MethodHandleNatives.JVM_SUPPORT) {
   19.87 +            this.vmtarget = null;  // maybe updated by JVM
   19.88 +            MethodHandleNatives.init(this, mh, argnum);
   19.89 +        } else {
   19.90 +            this.vmtarget = mh;
   19.91 +        }
   19.92 +    }
   19.93 +
   19.94 +    /** For the AdapterMethodHandle subclass.
   19.95 +     */
   19.96 +    BoundMethodHandle(MethodType type, Object argument, int vmargslot) {
   19.97 +        super(Access.TOKEN, type);
   19.98 +        this.argument = argument;
   19.99 +        this.vmargslot = vmargslot;
  19.100 +        assert(this.getClass() == AdapterMethodHandle.class);
  19.101 +    }
  19.102 +
  19.103 +    /** Initialize the current object as a method handle, binding it
  19.104 +     *  as the {@code argnum}th argument of the method handle {@code entryPoint}.
  19.105 +     *  The invocation type of the resulting method handle will be the
  19.106 +     *  same as {@code entryPoint},  except that the {@code argnum}th argument
  19.107 +     *  type will be dropped.
  19.108 +     */
  19.109 +    public BoundMethodHandle(MethodHandle entryPoint, int argnum) {
  19.110 +        this(entryPoint, null, argnum, SELF_ARG);
  19.111 +
  19.112 +        // Note:  If the conversion fails, perhaps because of a bad entryPoint,
  19.113 +        // the MethodHandle.type field will not be filled in, and therefore
  19.114 +        // no MH.invoke call will ever succeed.  The caller may retain a pointer
  19.115 +        // to the broken method handle, but no harm can be done with it.
  19.116 +    }
  19.117 +
  19.118 +    /** Initialize the current object as a method handle, binding it
  19.119 +     *  as the first argument of the method handle {@code entryPoint}.
  19.120 +     *  The invocation type of the resulting method handle will be the
  19.121 +     *  same as {@code entryPoint},  except that the first argument
  19.122 +     *  type will be dropped.
  19.123 +     */
  19.124 +    public BoundMethodHandle(MethodHandle entryPoint) {
  19.125 +        this(entryPoint, null, 0, SELF_ARG);
  19.126 +    }
  19.127 +
  19.128 +    /** Make sure the given {@code argument} can be used as {@code argnum}-th
  19.129 +     *  parameter of the given method handle {@code mh}, which must be a reference.
  19.130 +     *  <p>
  19.131 +     *  If this fails, throw a suitable {@code WrongMethodTypeException},
  19.132 +     *  which will prevent the creation of an illegally typed bound
  19.133 +     *  method handle.
  19.134 +     */
  19.135 +    final static Object checkReferenceArgument(Object argument, MethodHandle mh, int argnum) {
  19.136 +        Class<?> ptype = mh.type().parameterType(argnum);
  19.137 +        if (ptype.isPrimitive()) {
  19.138 +            // fail
  19.139 +        } else if (argument == null) {
  19.140 +            return null;
  19.141 +        } else if (VerifyType.isNullReferenceConversion(argument.getClass(), ptype)) {
  19.142 +            return argument;
  19.143 +        }
  19.144 +        throw badBoundArgumentException(argument, mh, argnum);
  19.145 +    }
  19.146 +
  19.147 +    /** Make sure the given {@code argument} can be used as {@code argnum}-th
  19.148 +     *  parameter of the given method handle {@code mh}, which must be a primitive.
  19.149 +     *  <p>
  19.150 +     *  If this fails, throw a suitable {@code WrongMethodTypeException},
  19.151 +     *  which will prevent the creation of an illegally typed bound
  19.152 +     *  method handle.
  19.153 +     */
  19.154 +    final static Object bindPrimitiveArgument(Object argument, MethodHandle mh, int argnum) {
  19.155 +        Class<?> ptype = mh.type().parameterType(argnum);
  19.156 +        Wrapper  wrap = Wrapper.forPrimitiveType(ptype);
  19.157 +        Object   zero  = wrap.zero();
  19.158 +        if (zero == null) {
  19.159 +            // fail
  19.160 +        } else if (argument == null) {
  19.161 +            if (ptype != int.class && wrap.isSubwordOrInt())
  19.162 +                return Integer.valueOf(0);
  19.163 +            else
  19.164 +                return zero;
  19.165 +        } else if (VerifyType.isNullReferenceConversion(argument.getClass(), zero.getClass())) {
  19.166 +            if (ptype != int.class && wrap.isSubwordOrInt())
  19.167 +                return Wrapper.INT.wrap(argument);
  19.168 +            else
  19.169 +                return argument;
  19.170 +        }
  19.171 +        throw badBoundArgumentException(argument, mh, argnum);
  19.172 +    }
  19.173 +
  19.174 +    final static RuntimeException badBoundArgumentException(Object argument, MethodHandle mh, int argnum) {
  19.175 +        String atype = (argument == null) ? "null" : argument.getClass().toString();
  19.176 +        return new WrongMethodTypeException("cannot bind "+atype+" argument to parameter #"+argnum+" of "+mh.type());
  19.177 +    }
  19.178 +
  19.179 +    @Override
  19.180 +    public String toString() {
  19.181 +        return "Bound[" + super.toString() + "]";
  19.182 +    }
  19.183 +}
    20.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    20.2 +++ b/src/share/classes/sun/dyn/CallSiteImpl.java	Tue May 05 22:40:09 2009 -0700
    20.3 @@ -0,0 +1,70 @@
    20.4 +/*
    20.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    20.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    20.7 + *
    20.8 + * This code is free software; you can redistribute it and/or modify it
    20.9 + * under the terms of the GNU General Public License version 2 only, as
   20.10 + * published by the Free Software Foundation.  Sun designates this
   20.11 + * particular file as subject to the "Classpath" exception as provided
   20.12 + * by Sun in the LICENSE file that accompanied this code.
   20.13 + *
   20.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   20.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   20.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   20.17 + * version 2 for more details (a copy is included in the LICENSE file that
   20.18 + * accompanied this code).
   20.19 + *
   20.20 + * You should have received a copy of the GNU General Public License version
   20.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   20.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   20.23 + *
   20.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   20.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   20.26 + * have any questions.
   20.27 + */
   20.28 +
   20.29 +package sun.dyn;
   20.30 +
   20.31 +import java.dyn.*;
   20.32 +
   20.33 +/**
   20.34 + * The CallSite privately created by the JVM at every invokedynamic instruction.
   20.35 + * @author jrose
   20.36 + */
   20.37 +class CallSiteImpl extends CallSite {
   20.38 +    // Fields used only by the JVM.  Do not use or change.
   20.39 +    private Object vmmethod;
   20.40 +
   20.41 +    // Values supplied by the JVM:
   20.42 +    int callerMID, callerBCI;
   20.43 +
   20.44 +    private CallSiteImpl(Class<?> caller, String name, MethodType type) {
   20.45 +        super(caller, name, type);
   20.46 +    }
   20.47 +
   20.48 +    @Override
   20.49 +    public void setTarget(MethodHandle mh) {
   20.50 +        checkTarget(mh);
   20.51 +        if (MethodHandleNatives.JVM_SUPPORT)
   20.52 +            MethodHandleNatives.linkCallSite(this, (MethodHandle) mh);
   20.53 +        else
   20.54 +            super.setTarget(mh);
   20.55 +    }
   20.56 +
   20.57 +    private static final MethodHandle PRIVATE_INITIALIZE_CALL_SITE =
   20.58 +            MethodHandleImpl.IMPL_LOOKUP.findStatic(CallSite.class, "privateInitializeCallSite",
   20.59 +                MethodType.make(void.class, CallSite.class, int.class, int.class));
   20.60 +
   20.61 +    // this is the up-call from the JVM:
   20.62 +    static CallSite makeSite(Class<?> caller, String name, MethodType type,
   20.63 +                             int callerMID, int callerBCI) {
   20.64 +        MethodHandle bsm = Linkage.getBootstrapMethod(caller);
   20.65 +        if (bsm == null)
   20.66 +            throw new InvokeDynamicBootstrapError("class has no bootstrap method: "+caller);
   20.67 +        CallSite site = bsm.<CallSite>invoke(caller, name, type);
   20.68 +        if (site == null)
   20.69 +            throw new InvokeDynamicBootstrapError("class bootstrap method failed to create a call site: "+caller);
   20.70 +        PRIVATE_INITIALIZE_CALL_SITE.<void>invoke(site, callerMID, callerBCI);
   20.71 +        return site;
   20.72 +    }
   20.73 +}
    21.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    21.2 +++ b/src/share/classes/sun/dyn/DirectMethodHandle.java	Tue May 05 22:40:09 2009 -0700
    21.3 @@ -0,0 +1,56 @@
    21.4 +/*
    21.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    21.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    21.7 + *
    21.8 + * This code is free software; you can redistribute it and/or modify it
    21.9 + * under the terms of the GNU General Public License version 2 only, as
   21.10 + * published by the Free Software Foundation.  Sun designates this
   21.11 + * particular file as subject to the "Classpath" exception as provided
   21.12 + * by Sun in the LICENSE file that accompanied this code.
   21.13 + *
   21.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   21.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   21.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   21.17 + * version 2 for more details (a copy is included in the LICENSE file that
   21.18 + * accompanied this code).
   21.19 + *
   21.20 + * You should have received a copy of the GNU General Public License version
   21.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   21.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   21.23 + *
   21.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   21.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   21.26 + * have any questions.
   21.27 + */
   21.28 +
   21.29 +package sun.dyn;
   21.30 +
   21.31 +import java.dyn.*;
   21.32 +import static sun.dyn.MethodHandleNatives.Constants.*;
   21.33 +
   21.34 +/**
   21.35 + * The flavor of method handle which emulates invokespecial or invokestatic.
   21.36 + * @author jrose
   21.37 + */
   21.38 +class DirectMethodHandle extends MethodHandle {
   21.39 +    //inherited oop    vmtarget;    // methodOop or virtual class/interface oop
   21.40 +    private final int  vmindex;     // method index within class or interface
   21.41 +    { vmindex = VM_INDEX_UNINITIALIZED; }  // JVM may change this
   21.42 +
   21.43 +    // Constructors in this class *must* be package scoped or private.
   21.44 +    DirectMethodHandle(MethodType mtype, MemberName m, boolean doDispatch, Class<?> lookupClass) {
   21.45 +        super(Access.TOKEN, mtype);
   21.46 +
   21.47 +        assert(m.isMethod() || !doDispatch && m.isConstructor());
   21.48 +        if (!m.isResolved())
   21.49 +            throw new InternalError();
   21.50 +
   21.51 +        // Null check and replace privilege token (as passed to JVM) with null.
   21.52 +        if (lookupClass.equals(Access.class))  lookupClass = null;
   21.53 +        MethodHandleNatives.init(this, (Object) m, doDispatch, lookupClass);
   21.54 +    }
   21.55 +
   21.56 +    boolean isValid() {
   21.57 +        return (vmindex != VM_INDEX_UNINITIALIZED);
   21.58 +    }
   21.59 +}
    22.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    22.2 +++ b/src/share/classes/sun/dyn/FilterGeneric.java	Tue May 05 22:40:09 2009 -0700
    22.3 @@ -0,0 +1,338 @@
    22.4 +/*
    22.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    22.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    22.7 + *
    22.8 + * This code is free software; you can redistribute it and/or modify it
    22.9 + * under the terms of the GNU General Public License version 2 only, as
   22.10 + * published by the Free Software Foundation.  Sun designates this
   22.11 + * particular file as subject to the "Classpath" exception as provided
   22.12 + * by Sun in the LICENSE file that accompanied this code.
   22.13 + *
   22.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   22.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   22.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   22.17 + * version 2 for more details (a copy is included in the LICENSE file that
   22.18 + * accompanied this code).
   22.19 + *
   22.20 + * You should have received a copy of the GNU General Public License version
   22.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   22.22 + * Inc., 51 Franklin Sf, tifth Floor, Boston, MA 02110-1301 USA.
   22.23 + *
   22.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   22.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   22.26 + * have any questions.
   22.27 + */
   22.28 +
   22.29 +package sun.dyn;
   22.30 +
   22.31 +import java.dyn.JavaMethodHandle;
   22.32 +import java.dyn.MethodHandle;
   22.33 +import java.dyn.MethodType;
   22.34 +import java.dyn.NoAccessException;
   22.35 +import java.lang.reflect.Constructor;
   22.36 +import java.lang.reflect.InvocationTargetException;
   22.37 +
   22.38 +/**
   22.39 + * "Flyby adapters" which apply arbitrary conversions to arguments
   22.40 + * on the way to a ultimate target.
   22.41 + * For simplicity, these are all generically typed.
   22.42 + * @author jrose
   22.43 + */
   22.44 +class FilterGeneric {
   22.45 +    // type for the outgoing call (will be generic)
   22.46 +    private final MethodType targetType;
   22.47 +    // position of (first) argument to participate in filtering
   22.48 +    private final short argumentPosition;
   22.49 +    // number of arguments to participate in filtering
   22.50 +    private final short argumentCount;
   22.51 +    // how the result interacts with the filtered arguments: Prepend, Append, Replace, Discard
   22.52 +    private final char replaceMode;
   22.53 +    // prototype adapter (clone and customize for each new target & conversion!)
   22.54 +    private final Adapter adapter;
   22.55 +    // entry point for adapter (Adapter mh, a...) => ...
   22.56 +    private final MethodHandle entryPoint;
   22.57 +    // more of them (loosely cached)
   22.58 +    private FilterGeneric variations;
   22.59 +
   22.60 +    /** Compute and cache information common to all unboxing adapters
   22.61 +     *  that can call out to targets of the erasure-family of the given erased type.
   22.62 +     */
   22.63 +    // TO DO: Make this private.
   22.64 +    FilterGeneric(MethodType targetType, short argumentPosition, short argumentCount, char replaceMode) {
   22.65 +        if (argumentCount == 0) {
   22.66 +            if (replaceMode == 'P' || replaceMode == 'A')  replaceMode = 'R';
   22.67 +            if (replaceMode == 'I')  argumentPosition = 0;
   22.68 +        }
   22.69 +        this.targetType = targetType;
   22.70 +        this.argumentPosition = argumentPosition;
   22.71 +        this.argumentCount = argumentCount;
   22.72 +        this.replaceMode = replaceMode;
   22.73 +        validate(targetType, argumentPosition, argumentCount, replaceMode);
   22.74 +        Adapter ad = findAdapter(targetType, argumentPosition, argumentCount, replaceMode, filterType());
   22.75 +        if (ad == null)
   22.76 +            ad = buildAdapterFromBytecodes(targetType, argumentPosition, argumentCount, replaceMode, filterType());
   22.77 +        this.adapter = ad;
   22.78 +        this.entryPoint = ad.prototypeEntryPoint();
   22.79 +    }
   22.80 +
   22.81 +    Adapter makeInstance(MethodHandle filter, MethodHandle target) {
   22.82 +        return adapter.makeInstance(entryPoint, filter, target);
   22.83 +    }
   22.84 +
   22.85 +    /** Build an adapter of the given generic type, which invokes typedTarget
   22.86 +     *  on the incoming arguments, after unboxing as necessary.
   22.87 +     *  The return value is boxed if necessary.
   22.88 +     * @param genericType  the required type of the result
   22.89 +     * @param typedTarget the target
   22.90 +     * @return an adapter method handle
   22.91 +     */
   22.92 +    public static MethodHandle make(MethodHandle target, int pos, MethodHandle filter) {
   22.93 +        return FilterGeneric.of(target.type(), (short)pos, (short)1, 'R').makeInstance(filter, target);
   22.94 +    }
   22.95 +
   22.96 +    /** Return the adapter information for this type's erasure. */
   22.97 +    static FilterGeneric of(MethodType type, short ap, short ac, char mode) {
   22.98 +        if (type.generic() != type)
   22.99 +            throw new IllegalArgumentException("must be generic: "+type);
  22.100 +        validate(type, ap, ac, mode);
  22.101 +        MethodTypeImpl form = MethodTypeImpl.of(type);
  22.102 +        FilterGeneric filterGen = form.filterGeneric;
  22.103 +        if (filterGen == null)
  22.104 +            form.filterGeneric = filterGen = new FilterGeneric(type, (short)0, (short)1, 'R');
  22.105 +        return find(filterGen, ap, ac, mode);
  22.106 +    }
  22.107 +
  22.108 +    static FilterGeneric find(FilterGeneric gen, short ap, short ac, char mode) {
  22.109 +        for (;;) {
  22.110 +            if (gen.argumentPosition == ap &&
  22.111 +                gen.argumentCount == ac &&
  22.112 +                gen.replaceMode == mode) {
  22.113 +                return gen;
  22.114 +            }
  22.115 +            FilterGeneric gen2 = gen.variations;
  22.116 +            if (gen2 == null)  break;
  22.117 +            gen = gen2;
  22.118 +        }
  22.119 +        FilterGeneric gen2 = new FilterGeneric(gen.targetType, ap, ac, mode);
  22.120 +        gen.variations = gen2;  // OK if this smashes another cached chain
  22.121 +        return gen2;
  22.122 +    }
  22.123 +
  22.124 +    private static void validate(MethodType type, short ap, short ac, char mode) {
  22.125 +        int endpos = ap + ac;
  22.126 +        switch (mode) {
  22.127 +            case 'P': case 'A': case 'R': case 'D':
  22.128 +                if (ap >= 0 && ac >= 0 &&
  22.129 +                        endpos >= 0 && endpos <= type.parameterCount())
  22.130 +                    return;
  22.131 +            default:
  22.132 +                throw new InternalError("configuration "+patternName(ap, ac, mode));
  22.133 +        }
  22.134 +    }
  22.135 +
  22.136 +    public String toString() {
  22.137 +        return "FilterGeneric/"+patternName()+targetType;
  22.138 +    }
  22.139 +
  22.140 +    String patternName() {
  22.141 +        return patternName(argumentPosition, argumentCount, replaceMode);
  22.142 +    }
  22.143 +
  22.144 +    static String patternName(short ap, short ac, char mode) {
  22.145 +        return ""+mode+ap+(ac>1?"_"+ac:"");
  22.146 +    }
  22.147 +
  22.148 +    Class<?> filterType() {
  22.149 +        return Object.class;  // result of filter operation; an uninteresting type
  22.150 +    }
  22.151 +
  22.152 +    static MethodType targetType(MethodType entryType, short ap, short ac, char mode,
  22.153 +                                 Class<?> arg) {
  22.154 +        MethodType type = entryType;
  22.155 +        int pos = ap;
  22.156 +        switch (mode) {
  22.157 +            case 'A':
  22.158 +                pos += ac;
  22.159 +            case 'P':
  22.160 +                type = type.insertParameterType(pos, arg);
  22.161 +                break;
  22.162 +            case 'I':
  22.163 +                for (int i = 1; i < ac; i++)
  22.164 +                    type = type.dropParameterType(pos);
  22.165 +                assert(type.parameterType(pos) == arg);
  22.166 +                break;
  22.167 +            case 'D':
  22.168 +                break;
  22.169 +        }
  22.170 +        return type;
  22.171 +    }
  22.172 +
  22.173 +    static MethodType entryType(MethodType targetType, short ap, short ac, char mode,
  22.174 +                                Class<?> arg) {
  22.175 +        MethodType type = targetType;
  22.176 +        int pos = ap;
  22.177 +        switch (mode) {
  22.178 +            case 'A':
  22.179 +                pos += ac;
  22.180 +            case 'P':
  22.181 +                type = type.dropParameterType(pos);
  22.182 +                break;
  22.183 +            case 'I':
  22.184 +                for (int i = 1; i < ac; i++)
  22.185 +                    type = type.insertParameterType(pos, arg);
  22.186 +                assert(type.parameterType(pos) == arg);
  22.187 +                break;
  22.188 +            case 'D':
  22.189 +                break;
  22.190 +        }
  22.191 +        return type;
  22.192 +    }
  22.193 +
  22.194 +    /* Create an adapter that handles spreading calls for the given type. */
  22.195 +    static Adapter findAdapter(MethodType targetType, short ap, short ac, char mode, Class<?> arg) {
  22.196 +        MethodType entryType = entryType(targetType, ap, ac, mode, arg);
  22.197 +        int argc = targetType.parameterCount();
  22.198 +        String pname = patternName(ap, ac, mode);
  22.199 +        String cname0 = "F"+argc;
  22.200 +        String cname1 = "F"+argc+mode;
  22.201 +        String cname2 = "F"+argc+pname;
  22.202 +        String[] cnames = { cname0, cname1, cname1+"X", cname2 };
  22.203 +        String iname = "invoke_"+pname;
  22.204 +        // e.g., F5R; invoke_R3
  22.205 +        for (String cname : cnames) {
  22.206 +            Class<? extends Adapter> acls = Adapter.findSubClass(cname);
  22.207 +            if (acls == null)  continue;
  22.208 +            // see if it has the required invoke method
  22.209 +            MethodHandle entryPoint = null;
  22.210 +            try {
  22.211 +                entryPoint = MethodHandleImpl.IMPL_LOOKUP.findSpecial(acls, iname, entryType, acls);
  22.212 +            } catch (NoAccessException ex) {
  22.213 +            }
  22.214 +            if (entryPoint == null)  continue;
  22.215 +            Constructor<? extends Adapter> ctor = null;
  22.216 +            try {
  22.217 +                ctor = acls.getDeclaredConstructor(MethodHandle.class);
  22.218 +            } catch (NoSuchMethodException ex) {
  22.219 +            } catch (SecurityException ex) {
  22.220 +            }
  22.221 +            if (ctor == null)  continue;
  22.222 +            try {
  22.223 +                // Produce an instance configured as a prototype.
  22.224 +                return ctor.newInstance(entryPoint);
  22.225 +            } catch (IllegalArgumentException ex) {
  22.226 +            } catch (InvocationTargetException ex) {
  22.227 +            } catch (InstantiationException ex) {
  22.228 +            } catch (IllegalAccessException ex) {
  22.229 +            }
  22.230 +        }
  22.231 +        return null;
  22.232 +    }
  22.233 +
  22.234 +    static Adapter buildAdapterFromBytecodes(MethodType targetType, short ap, short ac, char mode, Class<?> arg) {
  22.235 +        throw new UnsupportedOperationException("NYI");
  22.236 +    }
  22.237 +
  22.238 +    /**
  22.239 +     * This adapter takes some untyped arguments, and returns an untyped result.
  22.240 +     * Internally, it applies the invoker to the target, which causes the
  22.241 +     * objects to be unboxed; the result is a raw type in L/I/J/F/D.
  22.242 +     * This result is passed to convert, which is responsible for
  22.243 +     * converting the raw result into a boxed object.
  22.244 +     * The invoker is kept separate from the target because it can be
  22.245 +     * generated once per type erasure family, and reused across adapters.
  22.246 +     */
  22.247 +    static abstract class Adapter extends JavaMethodHandle {
  22.248 +        protected final MethodHandle filter;
  22.249 +        protected final MethodHandle target;
  22.250 +
  22.251 +        protected boolean isPrototype() { return target == null; }
  22.252 +        protected Adapter(MethodHandle entryPoint) {
  22.253 +            this(entryPoint, entryPoint, null);
  22.254 +            assert(isPrototype());
  22.255 +        }
  22.256 +        protected MethodHandle prototypeEntryPoint() {
  22.257 +            if (!isPrototype())  throw new InternalError();
  22.258 +            return filter;
  22.259 +        }
  22.260 +
  22.261 +        protected Adapter(MethodHandle entryPoint,
  22.262 +                          MethodHandle filter, MethodHandle target) {
  22.263 +            super(entryPoint);
  22.264 +            this.filter = filter;
  22.265 +            this.target = target;
  22.266 +        }
  22.267 +
  22.268 +        /** Make a copy of self, with new fields. */
  22.269 +        protected abstract Adapter makeInstance(MethodHandle entryPoint,
  22.270 +                MethodHandle filter, MethodHandle target);
  22.271 +        // { return new ThisType(entryPoint, filter, target); }
  22.272 +
  22.273 +        static private final String CLASS_PREFIX; // "sun.dyn.FilterGeneric$"
  22.274 +        static {
  22.275 +            String aname = Adapter.class.getName();
  22.276 +            String sname = Adapter.class.getSimpleName();
  22.277 +            if (!aname.endsWith(sname))  throw new InternalError();
  22.278 +            CLASS_PREFIX = aname.substring(0, aname.length() - sname.length());
  22.279 +        }
  22.280 +        /** Find a sibing class of Adapter. */
  22.281 +        static Class<? extends Adapter> findSubClass(String name) {
  22.282 +            String cname = Adapter.CLASS_PREFIX + name;
  22.283 +            try {
  22.284 +                return Class.forName(cname).asSubclass(Adapter.class);
  22.285 +            } catch (ClassNotFoundException ex) {
  22.286 +                return null;
  22.287 +            } catch (ClassCastException ex) {
  22.288 +                return null;
  22.289 +            }
  22.290 +        }
  22.291 +    }
  22.292 +
  22.293 +    //* generated classes follow this pattern:
  22.294 +    static class F1RX extends Adapter {
  22.295 +        protected F1RX(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  22.296 +        protected F1RX(MethodHandle e, MethodHandle f, MethodHandle t)
  22.297 +                        { super(e, f, t); }
  22.298 +        protected F1RX makeInstance(MethodHandle e, MethodHandle f, MethodHandle t)
  22.299 +                        { return new F1RX(e, f, t); }
  22.300 +        protected Object filter(Object a0) { return filter.<Object>invoke(a0); }
  22.301 +        protected Object target(Object a0) { return target.<Object>invoke(a0); }
  22.302 +        protected Object invoke_R0(Object a0) { return target(filter(a0)); }
  22.303 +    }
  22.304 +    static class F2RX extends Adapter {
  22.305 +        protected F2RX(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  22.306 +        protected F2RX(MethodHandle e, MethodHandle f, MethodHandle t)
  22.307 +                        { super(e, f, t); }
  22.308 +        protected F2RX makeInstance(MethodHandle e, MethodHandle f, MethodHandle t)
  22.309 +                        { return new F2RX(e, f, t); }
  22.310 +        protected Object filter(Object a0) { return filter.<Object>invoke(a0); }
  22.311 +        protected Object target(Object a0, Object a1) { return target.<Object>invoke(a0, a1); }
  22.312 +        protected Object invoke_R0(Object a0, Object a1) { return target(filter(a0), a1); }
  22.313 +        protected Object invoke_R1(Object a0, Object a1) { return target(a0, filter(a1)); }
  22.314 +    }
  22.315 +    static class F3RX extends Adapter {
  22.316 +        protected F3RX(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  22.317 +        protected F3RX(MethodHandle e, MethodHandle f, MethodHandle t)
  22.318 +                        { super(e, f, t); }
  22.319 +        protected F3RX makeInstance(MethodHandle e, MethodHandle f, MethodHandle t)
  22.320 +                        { return new F3RX(e, f, t); }
  22.321 +        protected Object filter(Object a0) { return filter.<Object>invoke(a0); }
  22.322 +        protected Object target(Object a0, Object a1, Object a2) { return target.<Object>invoke(a0, a1, a2); }
  22.323 +        protected Object invoke_R0(Object a0, Object a1, Object a2) { return target(filter(a0), a1, a2); }
  22.324 +        protected Object invoke_R1(Object a0, Object a1, Object a2) { return target(a0, filter(a1), a2); }
  22.325 +        protected Object invoke_R2(Object a0, Object a1, Object a2) { return target(a0, a1, filter(a2)); }
  22.326 +    }
  22.327 +    static class F4RX extends Adapter {
  22.328 +        protected F4RX(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  22.329 +        protected F4RX(MethodHandle e, MethodHandle f, MethodHandle t)
  22.330 +                        { super(e, f, t); }
  22.331 +        protected F4RX makeInstance(MethodHandle e, MethodHandle f, MethodHandle t)
  22.332 +                        { return new F4RX(e, f, t); }
  22.333 +        protected Object filter(Object a0) { return filter.<Object>invoke(a0); }
  22.334 +        protected Object target(Object a0, Object a1, Object a2, Object a3) { return target.<Object>invoke(a0, a1, a2, a3); }
  22.335 +        protected Object invoke_R0(Object a0, Object a1, Object a2, Object a3) { return target(filter(a0), a1, a2, a3); }
  22.336 +        protected Object invoke_R1(Object a0, Object a1, Object a2, Object a3) { return target(a0, filter(a1), a2, a3); }
  22.337 +        protected Object invoke_R2(Object a0, Object a1, Object a2, Object a3) { return target(a0, a1, filter(a2), a3); }
  22.338 +        protected Object invoke_R3(Object a0, Object a1, Object a2, Object a3) { return target(a0, a1, a2, filter(a3)); }
  22.339 +    }
  22.340 +    // */
  22.341 +}
    23.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    23.2 +++ b/src/share/classes/sun/dyn/FilterOneArgument.java	Tue May 05 22:40:09 2009 -0700
    23.3 @@ -0,0 +1,73 @@
    23.4 +/*
    23.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    23.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    23.7 + *
    23.8 + * This code is free software; you can redistribute it and/or modify it
    23.9 + * under the terms of the GNU General Public License version 2 only, as
   23.10 + * published by the Free Software Foundation.  Sun designates this
   23.11 + * particular file as subject to the "Classpath" exception as provided
   23.12 + * by Sun in the LICENSE file that accompanied this code.
   23.13 + *
   23.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   23.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   23.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   23.17 + * version 2 for more details (a copy is included in the LICENSE file that
   23.18 + * accompanied this code).
   23.19 + *
   23.20 + * You should have received a copy of the GNU General Public License version
   23.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   23.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   23.23 + *
   23.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   23.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   23.26 + * have any questions.
   23.27 + */
   23.28 +
   23.29 +package sun.dyn;
   23.30 +
   23.31 +import java.dyn.JavaMethodHandle;
   23.32 +import java.dyn.MethodHandle;
   23.33 +import java.dyn.MethodHandles;
   23.34 +import java.dyn.MethodType;
   23.35 +
   23.36 +/**
   23.37 + * Unary function composition, useful for many small plumbing jobs.
   23.38 + * The invoke method takes a single reference argument, and returns a reference
   23.39 + * Internally, it first calls the {@code filter} method on the argument,
   23.40 + * Making up the difference between the raw method type and the
   23.41 + * final method type is the responsibility of a JVM-level adapter.
   23.42 + * @author jrose
   23.43 + */
   23.44 +public class FilterOneArgument extends JavaMethodHandle {
   23.45 +    protected final MethodHandle filter;  // Object -> Object
   23.46 +    protected final MethodHandle target;  // Object -> Object
   23.47 +
   23.48 +    protected Object entryPoint(Object argument) {
   23.49 +        Object filteredArgument = filter.<Object>invoke(argument);
   23.50 +        return target.<Object>invoke(filteredArgument);
   23.51 +    }
   23.52 +
   23.53 +    private static final MethodHandle entryPoint =
   23.54 +        MethodHandleImpl.IMPL_LOOKUP.findVirtual(FilterOneArgument.class, "entryPoint", MethodType.makeGeneric(1));
   23.55 +
   23.56 +    protected FilterOneArgument(MethodHandle filter, MethodHandle target) {
   23.57 +        super(entryPoint);
   23.58 +        this.filter = filter;
   23.59 +        this.target = target;
   23.60 +    }
   23.61 +
   23.62 +    public static MethodHandle make(MethodHandle filter, MethodHandle target) {
   23.63 +        if (filter == null)  return target;
   23.64 +        if (target == null)  return filter;
   23.65 +        return new FilterOneArgument(filter, target);
   23.66 +    }
   23.67 +
   23.68 +    public String toString() {
   23.69 +        return filter + "|>" + target;
   23.70 +    }
   23.71 +
   23.72 +//    MethodHandle make(MethodHandle filter1, MethodHandle filter2, MethodHandle target) {
   23.73 +//        MethodHandle filter = make(filter1, filter2);
   23.74 +//        return make(filter, target);
   23.75 +//    }
   23.76 +}
    24.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    24.2 +++ b/src/share/classes/sun/dyn/FromGeneric.java	Tue May 05 22:40:09 2009 -0700
    24.3 @@ -0,0 +1,627 @@
    24.4 +/*
    24.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    24.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    24.7 + *
    24.8 + * This code is free software; you can redistribute it and/or modify it
    24.9 + * under the terms of the GNU General Public License version 2 only, as
   24.10 + * published by the Free Software Foundation.  Sun designates this
   24.11 + * particular file as subject to the "Classpath" exception as provided
   24.12 + * by Sun in the LICENSE file that accompanied this code.
   24.13 + *
   24.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   24.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   24.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   24.17 + * version 2 for more details (a copy is included in the LICENSE file that
   24.18 + * accompanied this code).
   24.19 + *
   24.20 + * You should have received a copy of the GNU General Public License version
   24.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   24.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   24.23 + *
   24.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   24.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   24.26 + * have any questions.
   24.27 + */
   24.28 +
   24.29 +package sun.dyn;
   24.30 +
   24.31 +import java.dyn.JavaMethodHandle;
   24.32 +import java.dyn.MethodHandle;
   24.33 +import java.dyn.MethodHandles;
   24.34 +import java.dyn.MethodType;
   24.35 +import java.dyn.NoAccessException;
   24.36 +import java.lang.reflect.Constructor;
   24.37 +import java.lang.reflect.InvocationTargetException;
   24.38 +import sun.dyn.util.ValueConversions;
   24.39 +import sun.dyn.util.Wrapper;
   24.40 +
   24.41 +/**
   24.42 + * Adapters which mediate between incoming calls which are not generic
   24.43 + * and outgoing calls which are.  Any call can be represented generically
   24.44 + * boxing up its arguments, and (on return) unboxing the return value.
   24.45 + * <p>
   24.46 + * A call is "generic" (in MethodHandle terms) if its MethodType features
   24.47 + * only Object arguments.  A non-generic call therefore features
   24.48 + * primitives and/or reference types other than Object.
   24.49 + * An adapter has types for its incoming and outgoing calls.
   24.50 + * The incoming call type is simply determined by the adapter's type
   24.51 + * (the MethodType it presents to callers).  The outgoing call type
   24.52 + * is determined by the adapter's target (a MethodHandle that the adapter
   24.53 + * either binds internally or else takes as a leading argument).
   24.54 + * (To stretch the term, adapter-like method handles may have multiple
   24.55 + * targets or be polymorphic across multiple call types.)
   24.56 + * <p>
   24.57 + * This adapter can sometimes be more directly implemented
   24.58 + * by the JVM's built-in OP_SPREAD_ARGS adapter.
   24.59 + * @author jrose
   24.60 + */
   24.61 +class FromGeneric {
   24.62 +    // type for the outgoing call (may have primitives, etc.)
   24.63 +    private final MethodType targetType;
   24.64 +    // type of the outgoing call internal to the adapter
   24.65 +    private final MethodType internalType;
   24.66 +    // prototype adapter (clone and customize for each new target!)
   24.67 +    private final Adapter adapter;
   24.68 +    // entry point for adapter (Adapter mh, a...) => ...
   24.69 +    private final MethodHandle entryPoint;
   24.70 +    // unboxing invoker of type (MH, Object**N) => raw return value
   24.71 +    // it makes up the difference of internalType => targetType
   24.72 +    private final MethodHandle unboxingInvoker;
   24.73 +    // conversion which boxes a the target's raw return value
   24.74 +    private final MethodHandle returnConversion;
   24.75 +
   24.76 +    /** Compute and cache information common to all unboxing adapters
   24.77 +     *  that can call out to targets of the erasure-family of the given erased type.
   24.78 +     */
   24.79 +    private FromGeneric(MethodType targetType) {
   24.80 +        this.targetType = targetType;
   24.81 +        MethodType internalType0;
   24.82 +        // the target invoker will generally need casts on reference arguments
   24.83 +        Adapter ad = findAdapter(internalType0 = targetType.erase());
   24.84 +        if (ad != null) {
   24.85 +            // Immediate hit to exactly the adapter we want,
   24.86 +            // with no monkeying around with primitive types.
   24.87 +            this.internalType = internalType0;
   24.88 +            this.adapter = ad;
   24.89 +            this.entryPoint = ad.prototypeEntryPoint();
   24.90 +            this.returnConversion = computeReturnConversion(targetType, internalType0);
   24.91 +            this.unboxingInvoker = computeUnboxingInvoker(targetType, internalType0);
   24.92 +            return;
   24.93 +        }
   24.94 +
   24.95 +        // outgoing primitive arguments will be wrapped; unwrap them
   24.96 +        MethodType primsAsObj = MethodTypeImpl.of(targetType).primArgsAsBoxes();
   24.97 +        MethodType objArgsRawRet = MethodTypeImpl.of(primsAsObj).primsAsInts();
   24.98 +        if (objArgsRawRet != targetType)
   24.99 +            ad = findAdapter(internalType0 = objArgsRawRet);
  24.100 +        if (ad == null) {
  24.101 +            ad = buildAdapterFromBytecodes(internalType0 = targetType);
  24.102 +        }
  24.103 +        this.internalType = internalType0;
  24.104 +        this.adapter = ad;
  24.105 +        MethodType tepType = targetType.insertParameterType(0, adapter.getClass());
  24.106 +        this.entryPoint = ad.prototypeEntryPoint();
  24.107 +        this.returnConversion = computeReturnConversion(targetType, internalType0);
  24.108 +        this.unboxingInvoker = computeUnboxingInvoker(targetType, internalType0);
  24.109 +    }
  24.110 +
  24.111 +    /**
  24.112 +     * The typed target will be called according to targetType.
  24.113 +     * The adapter code will in fact see the raw result from internalType,
  24.114 +     * and must box it into an object.  Produce a converter for this.
  24.115 +     */
  24.116 +    private static MethodHandle computeReturnConversion(
  24.117 +            MethodType targetType, MethodType internalType) {
  24.118 +        Class<?> tret = targetType.returnType();
  24.119 +        Class<?> iret = internalType.returnType();
  24.120 +        Wrapper wrap = Wrapper.forBasicType(tret);
  24.121 +        if (!iret.isPrimitive()) {
  24.122 +            assert(iret == Object.class);
  24.123 +            return ValueConversions.identity();
  24.124 +        } else if (wrap.primitiveType() == iret) {
  24.125 +            return ValueConversions.box(wrap, false);
  24.126 +        } else {
  24.127 +            assert(tret == double.class ? iret == long.class : iret == int.class);
  24.128 +            return ValueConversions.boxRaw(wrap, false);
  24.129 +        }
  24.130 +    }
  24.131 +
  24.132 +    /**
  24.133 +     * The typed target will need an exact invocation point; provide it here.
  24.134 +     * The adapter will possibly need to make a slightly different call,
  24.135 +     * so adapt the invoker.  This way, the logic for making up the
  24.136 +     * difference between what the adapter can call and what the target
  24.137 +     * needs can be cached once per type.
  24.138 +     */
  24.139 +    private static MethodHandle computeUnboxingInvoker(
  24.140 +            MethodType targetType, MethodType internalType) {
  24.141 +        // All the adapters we have here have reference-untyped internal calls.
  24.142 +        assert(internalType == internalType.erase());
  24.143 +        MethodHandle invoker = MethodHandles.exactInvoker(targetType);
  24.144 +        // cast all narrow reference types, unbox all primitive arguments:
  24.145 +        MethodType fixArgsType = internalType.changeReturnType(targetType.returnType());
  24.146 +        MethodHandle fixArgs = AdapterMethodHandle.convertArguments(Access.TOKEN,
  24.147 +                                 invoker, Invokers.invokerType(fixArgsType),
  24.148 +                                 invoker.type(), null);
  24.149 +        if (fixArgs == null)
  24.150 +            throw new InternalError("bad fixArgs");
  24.151 +        // reinterpret the calling sequence as raw:
  24.152 +        MethodHandle retyper = AdapterMethodHandle.makeRawRetypeOnly(Access.TOKEN,
  24.153 +                                        Invokers.invokerType(internalType), fixArgs);
  24.154 +        if (retyper == null)
  24.155 +            throw new InternalError("bad retyper");
  24.156 +        return retyper;
  24.157 +    }
  24.158 +
  24.159 +    Adapter makeInstance(MethodHandle typedTarget) {
  24.160 +        MethodType type = typedTarget.type();
  24.161 +        if (type == targetType) {
  24.162 +            return adapter.makeInstance(entryPoint, unboxingInvoker, returnConversion, typedTarget);
  24.163 +        }
  24.164 +        // my erased-type is not exactly the same as the desired type
  24.165 +        assert(type.erase() == targetType);  // else we are busted
  24.166 +        MethodHandle invoker = computeUnboxingInvoker(type, internalType);
  24.167 +        return adapter.makeInstance(entryPoint, invoker, returnConversion, typedTarget);
  24.168 +    }
  24.169 +
  24.170 +    /** Build an adapter of the given generic type, which invokes typedTarget
  24.171 +     *  on the incoming arguments, after unboxing as necessary.
  24.172 +     *  The return value is boxed if necessary.
  24.173 +     * @param genericType  the required type of the result
  24.174 +     * @param typedTarget the target
  24.175 +     * @return an adapter method handle
  24.176 +     */
  24.177 +    public static MethodHandle make(MethodHandle typedTarget) {
  24.178 +        MethodType type = typedTarget.type();
  24.179 +        if (type == type.generic())  return typedTarget;
  24.180 +        return FromGeneric.of(type).makeInstance(typedTarget);
  24.181 +    }
  24.182 +
  24.183 +    /** Return the adapter information for this type's erasure. */
  24.184 +    static FromGeneric of(MethodType type) {
  24.185 +        MethodTypeImpl form = MethodTypeImpl.of(type);
  24.186 +        FromGeneric fromGen = form.fromGeneric;
  24.187 +        if (fromGen == null)
  24.188 +            form.fromGeneric = fromGen = new FromGeneric(form.erasedType());
  24.189 +        return fromGen;
  24.190 +    }
  24.191 +
  24.192 +    public String toString() {
  24.193 +        return "FromGeneric"+targetType;
  24.194 +    }
  24.195 +
  24.196 +    /* Create an adapter that handles spreading calls for the given type. */
  24.197 +    static Adapter findAdapter(MethodType internalType) {
  24.198 +        MethodType entryType = internalType.generic();
  24.199 +        MethodTypeImpl form = MethodTypeImpl.of(internalType);
  24.200 +        Class<?> rtype = internalType.returnType();
  24.201 +        int argc = form.parameterCount();
  24.202 +        int lac = form.longPrimitiveParameterCount();
  24.203 +        int iac = form.primitiveParameterCount() - lac;
  24.204 +        String intsAndLongs = (iac > 0 ? "I"+iac : "")+(lac > 0 ? "J"+lac : "");
  24.205 +        String rawReturn = String.valueOf(Wrapper.forPrimitiveType(rtype).basicTypeChar());
  24.206 +        String cname0 = rawReturn + argc;
  24.207 +        String cname1 = "A"       + argc;
  24.208 +        String[] cnames = { cname0+intsAndLongs, cname0, cname1+intsAndLongs, cname1 };
  24.209 +        String iname = "invoke_"+cname0+intsAndLongs;
  24.210 +        // e.g., D5I2, D5, L5I2, L5; invoke_D5
  24.211 +        for (String cname : cnames) {
  24.212 +            Class<? extends Adapter> acls = Adapter.findSubClass(cname);
  24.213 +            if (acls == null)  continue;
  24.214 +            // see if it has the required invoke method
  24.215 +            MethodHandle entryPoint = null;
  24.216 +            try {
  24.217 +                entryPoint = MethodHandleImpl.IMPL_LOOKUP.findSpecial(acls, iname, entryType, acls);
  24.218 +            } catch (NoAccessException ex) {
  24.219 +            }
  24.220 +            if (entryPoint == null)  continue;
  24.221 +            Constructor<? extends Adapter> ctor = null;
  24.222 +            try {
  24.223 +                ctor = acls.getDeclaredConstructor(MethodHandle.class);
  24.224 +            } catch (NoSuchMethodException ex) {
  24.225 +            } catch (SecurityException ex) {
  24.226 +            }
  24.227 +            if (ctor == null)  continue;
  24.228 +            try {
  24.229 +                // Produce an instance configured as a prototype.
  24.230 +                return ctor.newInstance(entryPoint);
  24.231 +            } catch (IllegalArgumentException ex) {
  24.232 +            } catch (InvocationTargetException ex) {
  24.233 +            } catch (InstantiationException ex) {
  24.234 +            } catch (IllegalAccessException ex) {
  24.235 +            }
  24.236 +        }
  24.237 +        return null;
  24.238 +    }
  24.239 +
  24.240 +    static Adapter buildAdapterFromBytecodes(MethodType internalType) {
  24.241 +        throw new UnsupportedOperationException("NYI");
  24.242 +    }
  24.243 +
  24.244 +    /**
  24.245 +     * This adapter takes some untyped arguments, and returns an untyped result.
  24.246 +     * Internally, it applies the invoker to the target, which causes the
  24.247 +     * objects to be unboxed; the result is a raw type in L/I/J/F/D.
  24.248 +     * This result is passed to convert, which is responsible for
  24.249 +     * converting the raw result into a boxed object.
  24.250 +     * The invoker is kept separate from the target because it can be
  24.251 +     * generated once per type erasure family, and reused across adapters.
  24.252 +     */
  24.253 +    static abstract class Adapter extends JavaMethodHandle {
  24.254 +        /*
  24.255 +         * class X<<R,int N>> extends Adapter {
  24.256 +         *   (MH, Object**N)=>raw(R) invoker;
  24.257 +         *   (any**N)=>R target;
  24.258 +         *   raw(R)=>Object convert;
  24.259 +         *   Object invoke(Object**N a) = convert(invoker(target, a...))
  24.260 +         * }
  24.261 +         */
  24.262 +        protected final MethodHandle invoker;  // (MH, Object**N) => raw(R)
  24.263 +        protected final MethodHandle convert;  // raw(R) => Object
  24.264 +        protected final MethodHandle target;   // (any**N) => R
  24.265 +
  24.266 +        protected boolean isPrototype() { return target == null; }
  24.267 +        protected Adapter(MethodHandle entryPoint) {
  24.268 +            this(entryPoint, null, entryPoint, null);
  24.269 +            assert(isPrototype());
  24.270 +        }
  24.271 +        protected MethodHandle prototypeEntryPoint() {
  24.272 +            if (!isPrototype())  throw new InternalError();
  24.273 +            return convert;
  24.274 +        }
  24.275 +
  24.276 +        protected Adapter(MethodHandle entryPoint,
  24.277 +                          MethodHandle invoker, MethodHandle convert, MethodHandle target) {
  24.278 +            super(entryPoint);
  24.279 +            this.invoker = invoker;
  24.280 +            this.convert = convert;
  24.281 +            this.target  = target;
  24.282 +        }
  24.283 +
  24.284 +        /** Make a copy of self, with new fields. */
  24.285 +        protected abstract Adapter makeInstance(MethodHandle entryPoint,
  24.286 +                MethodHandle invoker, MethodHandle convert, MethodHandle target);
  24.287 +        // { return new ThisType(entryPoint, convert, target); }
  24.288 +
  24.289 +        /// Conversions on the value returned from the target.
  24.290 +        protected Object convert_L(Object result) { return convert.<Object>invoke(result); }
  24.291 +        protected Object convert_I(int    result) { return convert.<Object>invoke(result); }
  24.292 +        protected Object convert_J(long   result) { return convert.<Object>invoke(result); }
  24.293 +        protected Object convert_F(float  result) { return convert.<Object>invoke(result); }
  24.294 +        protected Object convert_D(double result) { return convert.<Object>invoke(result); }
  24.295 +
  24.296 +        static private final String CLASS_PREFIX; // "sun.dyn.FromGeneric$"
  24.297 +        static {
  24.298 +            String aname = Adapter.class.getName();
  24.299 +            String sname = Adapter.class.getSimpleName();
  24.300 +            if (!aname.endsWith(sname))  throw new InternalError();
  24.301 +            CLASS_PREFIX = aname.substring(0, aname.length() - sname.length());
  24.302 +        }
  24.303 +        /** Find a sibing class of Adapter. */
  24.304 +        static Class<? extends Adapter> findSubClass(String name) {
  24.305 +            String cname = Adapter.CLASS_PREFIX + name;
  24.306 +            try {
  24.307 +                return Class.forName(cname).asSubclass(Adapter.class);
  24.308 +            } catch (ClassNotFoundException ex) {
  24.309 +                return null;
  24.310 +            } catch (ClassCastException ex) {
  24.311 +                return null;
  24.312 +            }
  24.313 +        }
  24.314 +    }
  24.315 +
  24.316 +    /* generated classes follow this pattern:
  24.317 +    static class xA2 extends Adapter {
  24.318 +        protected xA2(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.319 +        protected xA2(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.320 +                        { super(e, i, c, t); }
  24.321 +        protected xA2 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.322 +                        { return new xA2(e, i, c, t); }
  24.323 +        protected Object invoke_L2(Object a0, Object a1) { return convert_L(invoker.<Object>invoke(target, a0, a1)); }
  24.324 +        protected Object invoke_I2(Object a0, Object a1) { return convert_I(invoker.<int   >invoke(target, a0, a1)); }
  24.325 +        protected Object invoke_J2(Object a0, Object a1) { return convert_J(invoker.<long  >invoke(target, a0, a1)); }
  24.326 +        protected Object invoke_F2(Object a0, Object a1) { return convert_F(invoker.<float >invoke(target, a0, a1)); }
  24.327 +        protected Object invoke_D2(Object a0, Object a1) { return convert_D(invoker.<double>invoke(target, a0, a1)); }
  24.328 +    }
  24.329 +    // */
  24.330 +
  24.331 +/*
  24.332 +: SHELL; n=FromGeneric; cp -p $n.java $n.java-; sed < $n.java- > $n.java+ -e '/{{*{{/,/}}*}}/w /tmp/genclasses.java' -e '/}}*}}/q'; (cd /tmp; javac -d . genclasses.java; java -cp . genclasses) >> $n.java+; echo '}' >> $n.java+; mv $n.java+ $n.java; mv $n.java- $n.java~
  24.333 +//{{{
  24.334 +import java.util.*;
  24.335 +class genclasses {
  24.336 +    static String[] TYPES = { "Object", "int   ", "long  ", "float ", "double" };
  24.337 +    static String[] TCHARS = { "L",     "I",      "J",      "F",      "D",     "A" };
  24.338 +    static String[][] TEMPLATES = { {
  24.339 +        "@for@ arity=0..10  rcat<=4 nrefs<=99 nints=0   nlongs=0",
  24.340 +        "    //@each-cat@",
  24.341 +        "    static class @cat@ extends Adapter {",
  24.342 +        "        protected @cat@(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype",
  24.343 +        "        protected @cat@(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)",
  24.344 +        "                        { super(e, i, c, t); }",
  24.345 +        "        protected @cat@ makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)",
  24.346 +        "                        { return new @cat@(e, i, c, t); }",
  24.347 +        "        //@each-R@",
  24.348 +        "        protected Object invoke_@catN@(@Tvav@) { return convert_@Rc@(invoker.<@R@>invoke(target@av@)); }",
  24.349 +        "        //@end-R@",
  24.350 +        "    }",
  24.351 +    } };
  24.352 +    static final String NEWLINE_INDENT = "\n                ";
  24.353 +    enum VAR {
  24.354 +        cat, catN, R, Rc, av, Tvav, Ovav;
  24.355 +        public final String pattern = "@"+toString().replace('_','.')+"@";
  24.356 +        public String binding;
  24.357 +        static void makeBindings(boolean topLevel, int rcat, int nrefs, int nints, int nlongs) {
  24.358 +            int nargs = nrefs + nints + nlongs;
  24.359 +            if (topLevel)
  24.360 +                VAR.cat.binding = catstr(ALL_RETURN_TYPES ? TYPES.length : rcat, nrefs, nints, nlongs);
  24.361 +            VAR.catN.binding = catstr(rcat, nrefs, nints, nlongs);
  24.362 +            VAR.R.binding = TYPES[rcat];
  24.363 +            VAR.Rc.binding = TCHARS[rcat];
  24.364 +            String[] Tv = new String[nargs];
  24.365 +            String[] av = new String[nargs];
  24.366 +            String[] Tvav = new String[nargs];
  24.367 +            String[] Ovav = new String[nargs];
  24.368 +            for (int i = 0; i < nargs; i++) {
  24.369 +                int tcat = (i < nrefs) ? 0 : (i < nrefs + nints) ? 1 : 2;
  24.370 +                Tv[i] = TYPES[tcat];
  24.371 +                av[i] = arg(i);
  24.372 +                Tvav[i] = param(Tv[i], av[i]);
  24.373 +                Ovav[i] = param("Object", av[i]);
  24.374 +            }
  24.375 +            VAR.av.binding = comma(", ", av);
  24.376 +            VAR.Tvav.binding = comma(Tvav);
  24.377 +            VAR.Ovav.binding = comma(Ovav);
  24.378 +        }
  24.379 +        static String arg(int i) { return "a"+i; }
  24.380 +        static String param(String t, String a) { return t+" "+a; }
  24.381 +        static String comma(String[] v) { return comma("", v); }
  24.382 +        static String comma(String sep, String[] v) {
  24.383 +            if (v.length == 0)  return "";
  24.384 +            String res = sep+v[0];
  24.385 +            for (int i = 1; i < v.length; i++)  res += ", "+v[i];
  24.386 +            return res;
  24.387 +        }
  24.388 +        static String transform(String string) {
  24.389 +            for (VAR var : values())
  24.390 +                string = string.replaceAll(var.pattern, var.binding);
  24.391 +            return string;
  24.392 +        }
  24.393 +    }
  24.394 +    static String[] stringsIn(String[] strings, int beg, int end) {
  24.395 +        return Arrays.copyOfRange(strings, beg, Math.min(end, strings.length));
  24.396 +    }
  24.397 +    static String[] stringsBefore(String[] strings, int pos) {
  24.398 +        return stringsIn(strings, 0, pos);
  24.399 +    }
  24.400 +    static String[] stringsAfter(String[] strings, int pos) {
  24.401 +        return stringsIn(strings, pos, strings.length);
  24.402 +    }
  24.403 +    static int indexAfter(String[] strings, int pos, String tag) {
  24.404 +        return Math.min(indexBefore(strings, pos, tag) + 1, strings.length);
  24.405 +    }
  24.406 +    static int indexBefore(String[] strings, int pos, String tag) {
  24.407 +        for (int i = pos, end = strings.length; ; i++) {
  24.408 +            if (i == end || strings[i].endsWith(tag))  return i;
  24.409 +        }
  24.410 +    }
  24.411 +    static int MIN_ARITY, MAX_ARITY, MAX_RCAT, MAX_REFS, MAX_INTS, MAX_LONGS;
  24.412 +    static boolean ALL_ARG_TYPES, ALL_RETURN_TYPES;
  24.413 +    static HashSet<String> done = new HashSet<String>();
  24.414 +    public static void main(String... av) {
  24.415 +        for (String[] template : TEMPLATES) {
  24.416 +            int forLinesLimit = indexBefore(template, 0, "@each-cat@");
  24.417 +            String[] forLines = stringsBefore(template, forLinesLimit);
  24.418 +            template = stringsAfter(template, forLinesLimit);
  24.419 +            for (String forLine : forLines)
  24.420 +                expandTemplate(forLine, template);
  24.421 +        }
  24.422 +    }
  24.423 +    static void expandTemplate(String forLine, String[] template) {
  24.424 +        String[] params = forLine.split("[^0-9]+");
  24.425 +        if (params[0].length() == 0)  params = stringsAfter(params, 1);
  24.426 +        System.out.println("//params="+Arrays.asList(params));
  24.427 +        int pcur = 0;
  24.428 +        MIN_ARITY = Integer.valueOf(params[pcur++]);
  24.429 +        MAX_ARITY = Integer.valueOf(params[pcur++]);
  24.430 +        MAX_RCAT  = Integer.valueOf(params[pcur++]);
  24.431 +        MAX_REFS  = Integer.valueOf(params[pcur++]);
  24.432 +        MAX_INTS  = Integer.valueOf(params[pcur++]);
  24.433 +        MAX_LONGS = Integer.valueOf(params[pcur++]);
  24.434 +        if (pcur != params.length)  throw new RuntimeException("bad extra param: "+forLine);
  24.435 +        if (MAX_RCAT >= TYPES.length)  MAX_RCAT = TYPES.length - 1;
  24.436 +        ALL_ARG_TYPES = (indexBefore(template, 0, "@each-Tv@") < template.length);
  24.437 +        ALL_RETURN_TYPES = (indexBefore(template, 0, "@each-R@") < template.length);
  24.438 +        for (int nargs = MIN_ARITY; nargs <= MAX_ARITY; nargs++) {
  24.439 +            for (int rcat = 0; rcat <= MAX_RCAT; rcat++) {
  24.440 +                expandTemplate(template, true, rcat, nargs, 0, 0);
  24.441 +                if (ALL_ARG_TYPES)  break;
  24.442 +                expandTemplateForPrims(template, true, rcat, nargs, 1, 1);
  24.443 +                if (ALL_RETURN_TYPES)  break;
  24.444 +            }
  24.445 +        }
  24.446 +    }
  24.447 +    static String catstr(int rcat, int nrefs, int nints, int nlongs) {
  24.448 +        int nargs = nrefs + nints + nlongs;
  24.449 +        String cat = TCHARS[rcat] + nargs;
  24.450 +        if (!ALL_ARG_TYPES)  cat += (nints==0?"":"I"+nints)+(nlongs==0?"":"J"+nlongs);
  24.451 +        return cat;
  24.452 +    }
  24.453 +    static void expandTemplateForPrims(String[] template, boolean topLevel, int rcat, int nargs, int minints, int minlongs) {
  24.454 +        for (int isLong = 0; isLong <= 1; isLong++) {
  24.455 +            for (int nprims = 1; nprims <= nargs; nprims++) {
  24.456 +                int nrefs = nargs - nprims;
  24.457 +                int nints = ((1-isLong) * nprims);
  24.458 +                int nlongs = (isLong * nprims);
  24.459 +                expandTemplate(template, topLevel, rcat, nrefs, nints, nlongs);
  24.460 +            }
  24.461 +        }
  24.462 +    }
  24.463 +    static void expandTemplate(String[] template, boolean topLevel,
  24.464 +                               int rcat, int nrefs, int nints, int nlongs) {
  24.465 +        int nargs = nrefs + nints + nlongs;
  24.466 +        if (nrefs > MAX_REFS || nints > MAX_INTS || nlongs > MAX_LONGS)  return;
  24.467 +        VAR.makeBindings(topLevel, rcat, nrefs, nints, nlongs);
  24.468 +        if (topLevel && !done.add(VAR.cat.binding)) {
  24.469 +            System.out.println("    //repeat "+VAR.cat.binding);
  24.470 +            return;
  24.471 +        }
  24.472 +        for (int i = 0; i < template.length; i++) {
  24.473 +            String line = template[i];
  24.474 +            if (line.endsWith("@each-cat@")) {
  24.475 +                // ignore
  24.476 +            } else if (line.endsWith("@each-R@")) {
  24.477 +                int blockEnd = indexAfter(template, i, "@end-R@");
  24.478 +                String[] block = stringsIn(template, i+1, blockEnd-1);
  24.479 +                for (int rcat1 = rcat; rcat1 <= MAX_RCAT; rcat1++)
  24.480 +                    expandTemplate(block, false, rcat1, nrefs, nints, nlongs);
  24.481 +                VAR.makeBindings(topLevel, rcat, nrefs, nints, nlongs);
  24.482 +                i = blockEnd-1; continue;
  24.483 +            } else if (line.endsWith("@each-Tv@")) {
  24.484 +                int blockEnd = indexAfter(template, i, "@end-Tv@");
  24.485 +                String[] block = stringsIn(template, i+1, blockEnd-1);
  24.486 +                expandTemplate(block, false, rcat, nrefs, nints, nlongs);
  24.487 +                expandTemplateForPrims(block, false, rcat, nargs, nints+1, nlongs+1);
  24.488 +                VAR.makeBindings(topLevel, rcat, nrefs, nints, nlongs);
  24.489 +                i = blockEnd-1; continue;
  24.490 +            } else {
  24.491 +                System.out.println(VAR.transform(line));
  24.492 +            }
  24.493 +        }
  24.494 +    }
  24.495 +}
  24.496 +//}}} */
  24.497 +//params=[0, 10, 4, 99, 0, 0]
  24.498 +    static class A0 extends Adapter {
  24.499 +        protected A0(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.500 +        protected A0(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.501 +                        { super(e, i, c, t); }
  24.502 +        protected A0 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.503 +                        { return new A0(e, i, c, t); }
  24.504 +        protected Object invoke_L0() { return convert_L(invoker.<Object>invoke(target)); }
  24.505 +        protected Object invoke_I0() { return convert_I(invoker.<int   >invoke(target)); }
  24.506 +        protected Object invoke_J0() { return convert_J(invoker.<long  >invoke(target)); }
  24.507 +        protected Object invoke_F0() { return convert_F(invoker.<float >invoke(target)); }
  24.508 +        protected Object invoke_D0() { return convert_D(invoker.<double>invoke(target)); }
  24.509 +    }
  24.510 +    static class A1 extends Adapter {
  24.511 +        protected A1(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.512 +        protected A1(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.513 +                        { super(e, i, c, t); }
  24.514 +        protected A1 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.515 +                        { return new A1(e, i, c, t); }
  24.516 +        protected Object invoke_L1(Object a0) { return convert_L(invoker.<Object>invoke(target, a0)); }
  24.517 +        protected Object invoke_I1(Object a0) { return convert_I(invoker.<int   >invoke(target, a0)); }
  24.518 +        protected Object invoke_J1(Object a0) { return convert_J(invoker.<long  >invoke(target, a0)); }
  24.519 +        protected Object invoke_F1(Object a0) { return convert_F(invoker.<float >invoke(target, a0)); }
  24.520 +        protected Object invoke_D1(Object a0) { return convert_D(invoker.<double>invoke(target, a0)); }
  24.521 +    }
  24.522 +    static class A2 extends Adapter {
  24.523 +        protected A2(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.524 +        protected A2(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.525 +                        { super(e, i, c, t); }
  24.526 +        protected A2 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.527 +                        { return new A2(e, i, c, t); }
  24.528 +        protected Object invoke_L2(Object a0, Object a1) { return convert_L(invoker.<Object>invoke(target, a0, a1)); }
  24.529 +        protected Object invoke_I2(Object a0, Object a1) { return convert_I(invoker.<int   >invoke(target, a0, a1)); }
  24.530 +        protected Object invoke_J2(Object a0, Object a1) { return convert_J(invoker.<long  >invoke(target, a0, a1)); }
  24.531 +        protected Object invoke_F2(Object a0, Object a1) { return convert_F(invoker.<float >invoke(target, a0, a1)); }
  24.532 +        protected Object invoke_D2(Object a0, Object a1) { return convert_D(invoker.<double>invoke(target, a0, a1)); }
  24.533 +    }
  24.534 +    static class A3 extends Adapter {
  24.535 +        protected A3(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.536 +        protected A3(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.537 +                        { super(e, i, c, t); }
  24.538 +        protected A3 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.539 +                        { return new A3(e, i, c, t); }
  24.540 +        protected Object invoke_L3(Object a0, Object a1, Object a2) { return convert_L(invoker.<Object>invoke(target, a0, a1, a2)); }
  24.541 +        protected Object invoke_I3(Object a0, Object a1, Object a2) { return convert_I(invoker.<int   >invoke(target, a0, a1, a2)); }
  24.542 +        protected Object invoke_J3(Object a0, Object a1, Object a2) { return convert_J(invoker.<long  >invoke(target, a0, a1, a2)); }
  24.543 +        protected Object invoke_F3(Object a0, Object a1, Object a2) { return convert_F(invoker.<float >invoke(target, a0, a1, a2)); }
  24.544 +        protected Object invoke_D3(Object a0, Object a1, Object a2) { return convert_D(invoker.<double>invoke(target, a0, a1, a2)); }
  24.545 +    }
  24.546 +    static class A4 extends Adapter {
  24.547 +        protected A4(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.548 +        protected A4(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.549 +                        { super(e, i, c, t); }
  24.550 +        protected A4 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.551 +                        { return new A4(e, i, c, t); }
  24.552 +        protected Object invoke_L4(Object a0, Object a1, Object a2, Object a3) { return convert_L(invoker.<Object>invoke(target, a0, a1, a2, a3)); }
  24.553 +        protected Object invoke_I4(Object a0, Object a1, Object a2, Object a3) { return convert_I(invoker.<int   >invoke(target, a0, a1, a2, a3)); }
  24.554 +        protected Object invoke_J4(Object a0, Object a1, Object a2, Object a3) { return convert_J(invoker.<long  >invoke(target, a0, a1, a2, a3)); }
  24.555 +        protected Object invoke_F4(Object a0, Object a1, Object a2, Object a3) { return convert_F(invoker.<float >invoke(target, a0, a1, a2, a3)); }
  24.556 +        protected Object invoke_D4(Object a0, Object a1, Object a2, Object a3) { return convert_D(invoker.<double>invoke(target, a0, a1, a2, a3)); }
  24.557 +    }
  24.558 +    static class A5 extends Adapter {
  24.559 +        protected A5(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.560 +        protected A5(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.561 +                        { super(e, i, c, t); }
  24.562 +        protected A5 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.563 +                        { return new A5(e, i, c, t); }
  24.564 +        protected Object invoke_L5(Object a0, Object a1, Object a2, Object a3, Object a4) { return convert_L(invoker.<Object>invoke(target, a0, a1, a2, a3, a4)); }
  24.565 +        protected Object invoke_I5(Object a0, Object a1, Object a2, Object a3, Object a4) { return convert_I(invoker.<int   >invoke(target, a0, a1, a2, a3, a4)); }
  24.566 +        protected Object invoke_J5(Object a0, Object a1, Object a2, Object a3, Object a4) { return convert_J(invoker.<long  >invoke(target, a0, a1, a2, a3, a4)); }
  24.567 +        protected Object invoke_F5(Object a0, Object a1, Object a2, Object a3, Object a4) { return convert_F(invoker.<float >invoke(target, a0, a1, a2, a3, a4)); }
  24.568 +        protected Object invoke_D5(Object a0, Object a1, Object a2, Object a3, Object a4) { return convert_D(invoker.<double>invoke(target, a0, a1, a2, a3, a4)); }
  24.569 +    }
  24.570 +    static class A6 extends Adapter {
  24.571 +        protected A6(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.572 +        protected A6(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.573 +                        { super(e, i, c, t); }
  24.574 +        protected A6 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.575 +                        { return new A6(e, i, c, t); }
  24.576 +        protected Object invoke_L6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return convert_L(invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5)); }
  24.577 +        protected Object invoke_I6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return convert_I(invoker.<int   >invoke(target, a0, a1, a2, a3, a4, a5)); }
  24.578 +        protected Object invoke_J6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return convert_J(invoker.<long  >invoke(target, a0, a1, a2, a3, a4, a5)); }
  24.579 +        protected Object invoke_F6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return convert_F(invoker.<float >invoke(target, a0, a1, a2, a3, a4, a5)); }
  24.580 +        protected Object invoke_D6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return convert_D(invoker.<double>invoke(target, a0, a1, a2, a3, a4, a5)); }
  24.581 +    }
  24.582 +    static class A7 extends Adapter {
  24.583 +        protected A7(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.584 +        protected A7(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.585 +                        { super(e, i, c, t); }
  24.586 +        protected A7 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.587 +                        { return new A7(e, i, c, t); }
  24.588 +        protected Object invoke_L7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return convert_L(invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5, a6)); }
  24.589 +        protected Object invoke_I7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return convert_I(invoker.<int   >invoke(target, a0, a1, a2, a3, a4, a5, a6)); }
  24.590 +        protected Object invoke_J7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return convert_J(invoker.<long  >invoke(target, a0, a1, a2, a3, a4, a5, a6)); }
  24.591 +        protected Object invoke_F7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return convert_F(invoker.<float >invoke(target, a0, a1, a2, a3, a4, a5, a6)); }
  24.592 +        protected Object invoke_D7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return convert_D(invoker.<double>invoke(target, a0, a1, a2, a3, a4, a5, a6)); }
  24.593 +    }
  24.594 +    static class A8 extends Adapter {
  24.595 +        protected A8(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.596 +        protected A8(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.597 +                        { super(e, i, c, t); }
  24.598 +        protected A8 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.599 +                        { return new A8(e, i, c, t); }
  24.600 +        protected Object invoke_L8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return convert_L(invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5, a6, a7)); }
  24.601 +        protected Object invoke_I8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return convert_I(invoker.<int   >invoke(target, a0, a1, a2, a3, a4, a5, a6, a7)); }
  24.602 +        protected Object invoke_J8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return convert_J(invoker.<long  >invoke(target, a0, a1, a2, a3, a4, a5, a6, a7)); }
  24.603 +        protected Object invoke_F8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return convert_F(invoker.<float >invoke(target, a0, a1, a2, a3, a4, a5, a6, a7)); }
  24.604 +        protected Object invoke_D8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return convert_D(invoker.<double>invoke(target, a0, a1, a2, a3, a4, a5, a6, a7)); }
  24.605 +    }
  24.606 +    static class A9 extends Adapter {
  24.607 +        protected A9(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.608 +        protected A9(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.609 +                        { super(e, i, c, t); }
  24.610 +        protected A9 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.611 +                        { return new A9(e, i, c, t); }
  24.612 +        protected Object invoke_L9(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return convert_L(invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  24.613 +        protected Object invoke_I9(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return convert_I(invoker.<int   >invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  24.614 +        protected Object invoke_J9(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return convert_J(invoker.<long  >invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  24.615 +        protected Object invoke_F9(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return convert_F(invoker.<float >invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  24.616 +        protected Object invoke_D9(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return convert_D(invoker.<double>invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  24.617 +    }
  24.618 +    static class A10 extends Adapter {
  24.619 +        protected A10(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  24.620 +        protected A10(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.621 +                        { super(e, i, c, t); }
  24.622 +        protected A10 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t)
  24.623 +                        { return new A10(e, i, c, t); }
  24.624 +        protected Object invoke_L10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return convert_L(invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  24.625 +        protected Object invoke_I10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return convert_I(invoker.<int   >invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  24.626 +        protected Object invoke_J10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return convert_J(invoker.<long  >invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  24.627 +        protected Object invoke_F10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return convert_F(invoker.<float >invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  24.628 +        protected Object invoke_D10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return convert_D(invoker.<double>invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  24.629 +    }
  24.630 +}
    25.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    25.2 +++ b/src/share/classes/sun/dyn/Invokers.java	Tue May 05 22:40:09 2009 -0700
    25.3 @@ -0,0 +1,86 @@
    25.4 +/*
    25.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    25.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    25.7 + *
    25.8 + * This code is free software; you can redistribute it and/or modify it
    25.9 + * under the terms of the GNU General Public License version 2 only, as
   25.10 + * published by the Free Software Foundation.  Sun designates this
   25.11 + * particular file as subject to the "Classpath" exception as provided
   25.12 + * by Sun in the LICENSE file that accompanied this code.
   25.13 + *
   25.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   25.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   25.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   25.17 + * version 2 for more details (a copy is included in the LICENSE file that
   25.18 + * accompanied this code).
   25.19 + *
   25.20 + * You should have received a copy of the GNU General Public License version
   25.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   25.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   25.23 + *
   25.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   25.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   25.26 + * have any questions.
   25.27 + */
   25.28 +
   25.29 +package sun.dyn;
   25.30 +
   25.31 +import java.dyn.MethodHandle;
   25.32 +import java.dyn.MethodHandles;
   25.33 +import java.dyn.MethodType;
   25.34 +
   25.35 +
   25.36 +/**
   25.37 + * Construction and caching of often-used invokers.
   25.38 + * @author jrose
   25.39 + */
   25.40 +public class Invokers {
   25.41 +    // exact type (sans leading taget MH) for the outgoing call
   25.42 +    private final MethodType targetType;
   25.43 +
   25.44 +    // exact invoker for the outgoing call
   25.45 +    private /*lazy*/ MethodHandle exactInvoker;
   25.46 +
   25.47 +    // generic (untyped) invoker for the outgoing call
   25.48 +    private /*lazy*/ MethodHandle genericInvoker;
   25.49 +
   25.50 +    /** Compute and cache information common to all collecting adapters
   25.51 +     *  that implement members of the erasure-family of the given erased type.
   25.52 +     */
   25.53 +    public Invokers(Access token, MethodType targetType) {
   25.54 +        Access.check(token);
   25.55 +        this.targetType = targetType;
   25.56 +    }
   25.57 +
   25.58 +    public static MethodType invokerType(MethodType targetType) {
   25.59 +        return targetType.insertParameterType(0, MethodHandle.class);
   25.60 +    }
   25.61 +
   25.62 +    public MethodHandle exactInvoker() {
   25.63 +        MethodHandle invoker = exactInvoker;
   25.64 +        if (invoker != null)  return invoker;
   25.65 +        invoker = MethodHandleImpl.IMPL_LOOKUP.findVirtual(MethodHandle.class, "invoke", targetType);
   25.66 +        if (invoker == null)  throw new InternalError("JVM cannot find invoker for "+targetType);
   25.67 +        assert(invokerType(targetType) == invoker.type());
   25.68 +        exactInvoker = invoker;
   25.69 +        return invoker;
   25.70 +    }
   25.71 +
   25.72 +    public MethodHandle genericInvoker() {
   25.73 +        MethodHandle invoker1 = exactInvoker();
   25.74 +        MethodHandle invoker = genericInvoker;
   25.75 +        if (invoker != null)  return invoker;
   25.76 +        MethodType genericType = targetType.generic();
   25.77 +        invoker = MethodHandles.convertArguments(invoker1, invokerType(genericType));
   25.78 +        genericInvoker = invoker;
   25.79 +        return invoker;
   25.80 +    }
   25.81 +
   25.82 +    public MethodHandle varargsInvoker() {
   25.83 +        throw new UnsupportedOperationException("NYI");
   25.84 +    }
   25.85 +
   25.86 +    public String toString() {
   25.87 +        return "Invokers"+targetType;
   25.88 +    }
   25.89 +}
    26.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    26.2 +++ b/src/share/classes/sun/dyn/MemberName.java	Tue May 05 22:40:09 2009 -0700
    26.3 @@ -0,0 +1,552 @@
    26.4 +/*
    26.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    26.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    26.7 + *
    26.8 + * This code is free software; you can redistribute it and/or modify it
    26.9 + * under the terms of the GNU General Public License version 2 only, as
   26.10 + * published by the Free Software Foundation.  Sun designates this
   26.11 + * particular file as subject to the "Classpath" exception as provided
   26.12 + * by Sun in the LICENSE file that accompanied this code.
   26.13 + *
   26.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   26.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   26.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   26.17 + * version 2 for more details (a copy is included in the LICENSE file that
   26.18 + * accompanied this code).
   26.19 + *
   26.20 + * You should have received a copy of the GNU General Public License version
   26.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   26.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   26.23 + *
   26.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   26.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   26.26 + * have any questions.
   26.27 + */
   26.28 +
   26.29 +package sun.dyn;
   26.30 +
   26.31 +import sun.dyn.util.BytecodeSignature;
   26.32 +import java.dyn.*;
   26.33 +import java.lang.reflect.Constructor;
   26.34 +import java.lang.reflect.Field;
   26.35 +import java.lang.reflect.Method;
   26.36 +import java.lang.reflect.Member;
   26.37 +import java.lang.reflect.Modifier;
   26.38 +import java.util.ArrayList;
   26.39 +import java.util.Collections;
   26.40 +import java.util.Iterator;
   26.41 +import java.util.List;
   26.42 +import static sun.dyn.MethodHandleNatives.Constants.*;
   26.43 +
   26.44 +/**
   26.45 + * Compact information which fully characterizes a method or field reference.
   26.46 + * When resolved, it includes a direct pointer to JVM metadata.
   26.47 + * This representation is stateless and only decriptive.
   26.48 + * It provides no private information and no capability to use the member.
   26.49 + * <p>
   26.50 + * By contrast, a java.lang.reflect.Method contains fuller information
   26.51 + * about the internals of a method (except its bytecodes) and also
   26.52 + * allows invocation.  A MemberName is much lighter than a reflect.Method,
   26.53 + * since it contains about 7 fields to Method's 16 (plus its sub-arrays),
   26.54 + * and those seven fields omit much of the information in Method.
   26.55 + * @author jrose
   26.56 + */
   26.57 +public final class MemberName implements Member, Cloneable {
   26.58 +    private Class<?>   clazz;       // class in which the method is defined
   26.59 +    private String     name;        // may be null if not yet materialized
   26.60 +    private Object     type;        // may be null if not yet materialized
   26.61 +    private int        flags;       // modifier bits; see reflect.Modifier
   26.62 +
   26.63 +    private Object     vmtarget;    // VM-specific target value
   26.64 +    private int        vmindex;     // method index within class or interface
   26.65 +
   26.66 +    { vmindex = VM_INDEX_UNINITIALIZED; }
   26.67 +
   26.68 +    public Class<?> getDeclaringClass() {
   26.69 +        if (clazz == null && isResolved()) {
   26.70 +            expandFromVM();
   26.71 +        }
   26.72 +        return clazz;
   26.73 +    }
   26.74 +
   26.75 +    public ClassLoader getClassLoader() {
   26.76 +        return clazz.getClassLoader();
   26.77 +    }
   26.78 +
   26.79 +    public String getName() {
   26.80 +        if (name == null) {
   26.81 +            expandFromVM();
   26.82 +            if (name == null)  return null;
   26.83 +        }
   26.84 +        return name;
   26.85 +    }
   26.86 +
   26.87 +    public MethodType getMethodType() {
   26.88 +        if (type == null) {
   26.89 +            expandFromVM();
   26.90 +            if (type == null)  return null;
   26.91 +        }
   26.92 +        if (!isInvocable())
   26.93 +            throw newIllegalArgumentException("not invocable, no method type");
   26.94 +        if (type instanceof MethodType) {
   26.95 +            return (MethodType) type;
   26.96 +        }
   26.97 +        if (type instanceof String) {
   26.98 +            String sig = (String) type;
   26.99 +            MethodType res = MethodType.fromBytecodeString(sig, getClassLoader());
  26.100 +            this.type = res;
  26.101 +            return res;
  26.102 +        }
  26.103 +        if (type instanceof Object[]) {
  26.104 +            Object[] typeInfo = (Object[]) type;
  26.105 +            Class<?>[] ptypes = (Class<?>[]) typeInfo[1];
  26.106 +            Class<?> rtype = (Class<?>) typeInfo[0];
  26.107 +            MethodType res = MethodType.make(rtype, ptypes);
  26.108 +            this.type = res;
  26.109 +            return res;
  26.110 +        }
  26.111 +        throw new InternalError("bad method type "+type);
  26.112 +    }
  26.113 +
  26.114 +    public MethodType getInvocationType() {
  26.115 +        MethodType itype = getMethodType();
  26.116 +        if (!isStatic())
  26.117 +            itype = itype.insertParameterType(0, clazz);
  26.118 +        return itype;
  26.119 +    }
  26.120 +
  26.121 +    public Class<?>[] getParameterTypes() {
  26.122 +        return getMethodType().parameterArray();
  26.123 +    }
  26.124 +
  26.125 +    public Class<?> getReturnType() {
  26.126 +        return getMethodType().returnType();
  26.127 +    }
  26.128 +
  26.129 +    public Class<?> getFieldType() {
  26.130 +        if (type == null) {
  26.131 +            expandFromVM();
  26.132 +            if (type == null)  return null;
  26.133 +        }
  26.134 +        if (isInvocable())
  26.135 +            throw newIllegalArgumentException("not a field or nested class, no simple type");
  26.136 +        if (type instanceof Class<?>) {
  26.137 +            return (Class<?>) type;
  26.138 +        }
  26.139 +        if (type instanceof String) {
  26.140 +            String sig = (String) type;
  26.141 +            MethodType mtype = MethodType.fromBytecodeString("()"+sig, getClassLoader());
  26.142 +            Class<?> res = mtype.returnType();
  26.143 +            this.type = res;
  26.144 +            return res;
  26.145 +        }
  26.146 +        throw new InternalError("bad field type "+type);
  26.147 +    }
  26.148 +
  26.149 +    public Object getType() {
  26.150 +        return (isInvocable() ? getMethodType() : getFieldType());
  26.151 +    }
  26.152 +
  26.153 +    public String getSignature() {
  26.154 +        if (type == null) {
  26.155 +            expandFromVM();
  26.156 +            if (type == null)  return null;
  26.157 +        }
  26.158 +        if (type instanceof String)
  26.159 +            return (String) type;
  26.160 +        if (isInvocable())
  26.161 +            return BytecodeSignature.unparse(getMethodType());
  26.162 +        else
  26.163 +            return BytecodeSignature.unparse(getFieldType());
  26.164 +    }
  26.165 +
  26.166 +    public int getModifiers() {
  26.167 +        return (flags & RECOGNIZED_MODIFIERS);
  26.168 +    }
  26.169 +
  26.170 +    private void setFlags(int flags) {
  26.171 +        this.flags = flags;
  26.172 +        assert(testAnyFlags(ALL_KINDS));
  26.173 +    }
  26.174 +
  26.175 +    private boolean testFlags(int mask, int value) {
  26.176 +        return (flags & mask) == value;
  26.177 +    }
  26.178 +    private boolean testAllFlags(int mask) {
  26.179 +        return testFlags(mask, mask);
  26.180 +    }
  26.181 +    private boolean testAnyFlags(int mask) {
  26.182 +        return !testFlags(mask, 0);
  26.183 +    }
  26.184 +
  26.185 +    public boolean isStatic() {
  26.186 +        return Modifier.isStatic(flags);
  26.187 +    }
  26.188 +    public boolean isPublic() {
  26.189 +        return Modifier.isPublic(flags);
  26.190 +    }
  26.191 +    public boolean isPrivate() {
  26.192 +        return Modifier.isPrivate(flags);
  26.193 +    }
  26.194 +    public boolean isProtected() {
  26.195 +        return Modifier.isProtected(flags);
  26.196 +    }
  26.197 +    public boolean isFinal() {
  26.198 +        return Modifier.isFinal(flags);
  26.199 +    }
  26.200 +    public boolean isAbstract() {
  26.201 +        return Modifier.isAbstract(flags);
  26.202 +    }
  26.203 +    // let the rest (native, volatile, transient, etc.) be tested via Modifier.isFoo
  26.204 +
  26.205 +    // unofficial modifier flags, used by HotSpot:
  26.206 +    static final int BRIDGE    = 0x00000040;
  26.207 +    static final int VARARGS   = 0x00000080;
  26.208 +    static final int SYNTHETIC = 0x00001000;
  26.209 +    static final int ANNOTATION= 0x00002000;
  26.210 +    static final int ENUM      = 0x00004000;
  26.211 +    public boolean isBridge() {
  26.212 +        return testAllFlags(IS_METHOD | BRIDGE);
  26.213 +    }
  26.214 +    public boolean isVarargs() {
  26.215 +        return testAllFlags(VARARGS) && isInvocable();
  26.216 +    }
  26.217 +    public boolean isSynthetic() {
  26.218 +        return testAllFlags(SYNTHETIC);
  26.219 +    }
  26.220 +
  26.221 +    static final String CONSTRUCTOR_NAME = "<init>";  // the ever-popular
  26.222 +
  26.223 +    // modifiers exported by the JVM:
  26.224 +    static final int RECOGNIZED_MODIFIERS = 0xFFFF;
  26.225 +
  26.226 +    // private flags, not part of RECOGNIZED_MODIFIERS:
  26.227 +    static final int
  26.228 +            IS_METHOD      = MN_IS_METHOD,      // method (not constructor)
  26.229 +            IS_CONSTRUCTOR = MN_IS_CONSTRUCTOR, // constructor
  26.230 +            IS_FIELD       = MN_IS_FIELD,       // field
  26.231 +            IS_TYPE        = MN_IS_TYPE;        // nested type
  26.232 +    static final int  // for MethodHandleNatives.getMembers
  26.233 +            SEARCH_SUPERCLASSES = MN_SEARCH_SUPERCLASSES,
  26.234 +            SEARCH_INTERFACES   = MN_SEARCH_INTERFACES;
  26.235 +
  26.236 +    static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
  26.237 +    static final int ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE;
  26.238 +    static final int IS_INVOCABLE = IS_METHOD | IS_CONSTRUCTOR;
  26.239 +    static final int IS_FIELD_OR_METHOD = IS_METHOD | IS_FIELD;
  26.240 +    static final int SEARCH_ALL_SUPERS = SEARCH_SUPERCLASSES | SEARCH_INTERFACES;
  26.241 +
  26.242 +    public boolean isInvocable() {
  26.243 +        return testAnyFlags(IS_INVOCABLE);
  26.244 +    }
  26.245 +    public boolean isFieldOrMethod() {
  26.246 +        return testAnyFlags(IS_FIELD_OR_METHOD);
  26.247 +    }
  26.248 +    public boolean isMethod() {
  26.249 +        return testAllFlags(IS_METHOD);
  26.250 +    }
  26.251 +    public boolean isConstructor() {
  26.252 +        return testAllFlags(IS_CONSTRUCTOR);
  26.253 +    }
  26.254 +    public boolean isField() {
  26.255 +        return testAllFlags(IS_FIELD);
  26.256 +    }
  26.257 +    public boolean isType() {
  26.258 +        return testAllFlags(IS_TYPE);
  26.259 +    }
  26.260 +    public boolean isPackage() {
  26.261 +        return !testAnyFlags(ALL_ACCESS);
  26.262 +    }
  26.263 +
  26.264 +    /** Initialize a query.   It is not resolved. */
  26.265 +    private void init(Class<?> defClass, String name, Object type, int flags) {
  26.266 +        // defining class is allowed to be null (for a naked name/type pair)
  26.267 +        name.toString();  // null check
  26.268 +        type.equals(type);  // null check
  26.269 +        // fill in fields:
  26.270 +        this.clazz = defClass;
  26.271 +        this.name = name;
  26.272 +        this.type = type;
  26.273 +        setFlags(flags);
  26.274 +        assert(!isResolved());
  26.275 +    }
  26.276 +
  26.277 +    private void expandFromVM() {
  26.278 +        if (!isResolved())  return;
  26.279 +        if (type instanceof Object[])
  26.280 +            type = null;  // don't saddle JVM w/ typeInfo
  26.281 +        MethodHandleNatives.expand(this);
  26.282 +    }
  26.283 +
  26.284 +    // Capturing information from the Core Reflection API:
  26.285 +    private static int flagsMods(int flags, int mods) {
  26.286 +        assert((flags & RECOGNIZED_MODIFIERS) == 0);
  26.287 +        assert((mods & ~RECOGNIZED_MODIFIERS) == 0);
  26.288 +        return flags | mods;
  26.289 +    }
  26.290 +    public MemberName(Method m) {
  26.291 +        Object[] typeInfo = { m.getReturnType(), m.getParameterTypes() };
  26.292 +        init(m.getDeclaringClass(), m.getName(), typeInfo, flagsMods(IS_METHOD, m.getModifiers()));
  26.293 +        // fill in vmtarget, vmindex while we have m in hand:
  26.294 +        MethodHandleNatives.init(this, m);
  26.295 +        assert(isResolved());
  26.296 +    }
  26.297 +    public MemberName(Constructor ctor) {
  26.298 +        Object[] typeInfo = { void.class, ctor.getParameterTypes() };
  26.299 +        init(ctor.getDeclaringClass(), CONSTRUCTOR_NAME, typeInfo, flagsMods(IS_CONSTRUCTOR, ctor.getModifiers()));
  26.300 +        // fill in vmtarget, vmindex while we have ctor in hand:
  26.301 +        MethodHandleNatives.init(this, ctor);
  26.302 +        assert(isResolved());
  26.303 +    }
  26.304 +    public MemberName(Field fld) {
  26.305 +        init(fld.getDeclaringClass(), fld.getName(), fld.getType(), flagsMods(IS_FIELD, fld.getModifiers()));
  26.306 +        // fill in vmtarget, vmindex while we have fld in hand:
  26.307 +        MethodHandleNatives.init(this, fld);
  26.308 +        assert(isResolved());
  26.309 +    }
  26.310 +    public MemberName(Class<?> type) {
  26.311 +        init(type.getDeclaringClass(), type.getSimpleName(), type, flagsMods(IS_TYPE, type.getModifiers()));
  26.312 +        vmindex = 0;  // isResolved
  26.313 +        assert(isResolved());
  26.314 +    }
  26.315 +
  26.316 +    // bare-bones constructor; the JVM will fill it in
  26.317 +    MemberName() { }
  26.318 +
  26.319 +    // locally useful cloner
  26.320 +    @Override protected MemberName clone() {
  26.321 +        try {
  26.322 +            return (MemberName) super.clone();
  26.323 +        } catch (CloneNotSupportedException ex) {
  26.324 +            throw new InternalError();
  26.325 +        }
  26.326 +     }
  26.327 +
  26.328 +    // %%% define equals/hashcode?
  26.329 +
  26.330 +    // Construction from symbolic parts, for queries:
  26.331 +    public MemberName(Class<?> defClass, String name, Class<?> type, int modifiers) {
  26.332 +        init(defClass, name, type, IS_FIELD | (modifiers & RECOGNIZED_MODIFIERS));
  26.333 +    }
  26.334 +    public MemberName(Class<?> defClass, String name, Class<?> type) {
  26.335 +        this(defClass, name, type, 0);
  26.336 +    }
  26.337 +    public MemberName(Class<?> defClass, String name, MethodType type, int modifiers) {
  26.338 +        int flagBit = (name.equals(CONSTRUCTOR_NAME) ? IS_CONSTRUCTOR : IS_METHOD);
  26.339 +        init(defClass, name, type, flagBit | (modifiers & RECOGNIZED_MODIFIERS));
  26.340 +    }
  26.341 +    public MemberName(Class<?> defClass, String name, MethodType type) {
  26.342 +        this(defClass, name, type, 0);
  26.343 +    }
  26.344 +
  26.345 +    boolean isResolved() {
  26.346 +        return (vmindex != VM_INDEX_UNINITIALIZED);
  26.347 +    }
  26.348 +
  26.349 +    public boolean hasReceiverTypeDispatch() {
  26.350 +        return (isMethod() && getVMIndex(Access.TOKEN) >= 0);
  26.351 +    }
  26.352 +
  26.353 +    @Override
  26.354 +    public String toString() {
  26.355 +        if (isType())
  26.356 +            return type.toString();  // class java.lang.String
  26.357 +        // else it is a field, method, or constructor
  26.358 +        StringBuilder buf = new StringBuilder();
  26.359 +        if (getDeclaringClass() != null) {
  26.360 +            buf.append(getName(clazz));
  26.361 +            buf.append('.');
  26.362 +        }
  26.363 +        buf.append(getName());
  26.364 +        if (!isInvocable())  buf.append('/');
  26.365 +        buf.append(getName(getType()));
  26.366 +        /*
  26.367 +        buf.append('/');
  26.368 +        // key: Public, private, pRotected, sTatic, Final, sYnchronized,
  26.369 +        // transient/Varargs, native, (interface), abstract, sTrict, sYnthetic,
  26.370 +        // (annotation), Enum, (unused)
  26.371 +        final String FIELD_MOD_CHARS  = "PprTF?vt????Y?E?";
  26.372 +        final String METHOD_MOD_CHARS = "PprTFybVn?atY???";
  26.373 +        String modChars = (isInvocable() ? METHOD_MOD_CHARS : FIELD_MOD_CHARS);
  26.374 +        for (int i = 0; i < modChars.length(); i++) {
  26.375 +            if ((flags & (1 << i)) != 0) {
  26.376 +                char mc = modChars.charAt(i);
  26.377 +                if (mc != '.')
  26.378 +                    buf.append(mc);
  26.379 +            }
  26.380 +        }
  26.381 +         */
  26.382 +        return buf.toString();
  26.383 +    }
  26.384 +    private static String getName(Object obj) {
  26.385 +        if (obj instanceof Class<?>)
  26.386 +            return ((Class<?>)obj).getName();
  26.387 +        return obj.toString();
  26.388 +    }
  26.389 +
  26.390 +    // Queries to the JVM:
  26.391 +    public int getVMIndex(Access token) {
  26.392 +        Access.check(token);
  26.393 +        if (!isResolved())
  26.394 +            throw newIllegalStateException("not resolved");
  26.395 +        return vmindex;
  26.396 +    }
  26.397 +//    public Object getVMTarget(Access token) {
  26.398 +//        Access.check(token);
  26.399 +//        if (!isResolved())
  26.400 +//            throw newIllegalStateException("not resolved");
  26.401 +//        return vmtarget;
  26.402 +//    }
  26.403 +    private RuntimeException newIllegalStateException(String message) {
  26.404 +        return new IllegalStateException(message+": "+this);
  26.405 +    }
  26.406 +
  26.407 +    // handy shared exception makers (they simplify the common case code)
  26.408 +    public static RuntimeException newIllegalArgumentException(String message) {
  26.409 +        return new IllegalArgumentException(message);
  26.410 +    }
  26.411 +    public static NoAccessException newNoAccessException(MemberName name, Class<?> lookupClass) {
  26.412 +        return newNoAccessException("cannot access", name, lookupClass);
  26.413 +    }
  26.414 +    public static NoAccessException newNoAccessException(String message,
  26.415 +            MemberName name, Class<?> lookupClass) {
  26.416 +        message += ": " + name;
  26.417 +        if (lookupClass != null)  message += ", from " + lookupClass.getName();
  26.418 +        return new NoAccessException(message);
  26.419 +    }
  26.420 +
  26.421 +    /** Actually making a query requires an access check. */
  26.422 +    public static Factory getFactory(Access token) {
  26.423 +        Access.check(token);
  26.424 +        return Factory.INSTANCE;
  26.425 +    }
  26.426 +    public static Factory getFactory() {
  26.427 +        return getFactory(Access.getToken());
  26.428 +    }
  26.429 +    public static class Factory {
  26.430 +        private Factory() { } // singleton pattern
  26.431 +        static Factory INSTANCE = new Factory();
  26.432 +
  26.433 +        private static int ALLOWED_FLAGS = SEARCH_ALL_SUPERS | ALL_KINDS;
  26.434 +
  26.435 +        /// Queries
  26.436 +        List<MemberName> getMembers(Class<?> defc,
  26.437 +                String matchName, Object matchType,
  26.438 +                int matchFlags, Class<?> lookupClass) {
  26.439 +            matchFlags &= ALLOWED_FLAGS;
  26.440 +            String matchSig = null;
  26.441 +            if (matchType != null) {
  26.442 +                matchSig = BytecodeSignature.unparse(matchType);
  26.443 +                if (matchSig.startsWith("("))
  26.444 +                    matchFlags &= ~(ALL_KINDS & ~IS_INVOCABLE);
  26.445 +                else
  26.446 +                    matchFlags &= ~(ALL_KINDS & ~IS_FIELD);
  26.447 +            }
  26.448 +            final int BUF_MAX = 0x2000;
  26.449 +            int len1 = matchName == null ? 10 : matchType == null ? 4 : 1;
  26.450 +            MemberName[] buf = newMemberBuffer(len1);
  26.451 +            int totalCount = 0;
  26.452 +            ArrayList<MemberName[]> bufs = null;
  26.453 +            for (;;) {
  26.454 +                int bufCount = MethodHandleNatives.getMembers(defc,
  26.455 +                        matchName, matchSig, matchFlags,
  26.456 +                        MethodHandleNatives.asNativeCaller(lookupClass),
  26.457 +                        totalCount, buf);
  26.458 +                if (bufCount <= buf.length) {
  26.459 +                    if (bufCount >= 0)
  26.460 +                        totalCount += bufCount;
  26.461 +                    break;
  26.462 +                }
  26.463 +                // JVM returned tp us with an intentional overflow!
  26.464 +                totalCount += buf.length;
  26.465 +                int excess = bufCount - buf.length;
  26.466 +                if (bufs == null)  bufs = new ArrayList<MemberName[]>(1);
  26.467 +                bufs.add(buf);
  26.468 +                int len2 = buf.length;
  26.469 +                len2 = Math.max(len2, excess);
  26.470 +                len2 = Math.max(len2, totalCount / 4);
  26.471 +                buf = newMemberBuffer(Math.min(BUF_MAX, len2));
  26.472 +            }
  26.473 +            ArrayList<MemberName> result = new ArrayList<MemberName>(totalCount);
  26.474 +            if (bufs != null) {
  26.475 +                for (MemberName[] buf0 : bufs) {
  26.476 +                    Collections.addAll(result, buf0);
  26.477 +                }
  26.478 +            }
  26.479 +            Collections.addAll(result, buf);
  26.480 +            // Signature matching is not the same as type matching, since
  26.481 +            // one signature might correspond to several types.
  26.482 +            // So if matchType is a Class or MethodType, refilter the results.
  26.483 +            if (matchType != null && matchType != matchSig) {
  26.484 +                for (Iterator<MemberName> it = result.iterator(); it.hasNext();) {
  26.485 +                    MemberName m = it.next();
  26.486 +                    if (!matchType.equals(m.getType()))
  26.487 +                        it.remove();
  26.488 +                }
  26.489 +            }
  26.490 +            return result;
  26.491 +        }
  26.492 +        boolean resolveInPlace(MemberName m, boolean searchSupers, Class<?> lookupClass) {
  26.493 +            Class<?> caller = MethodHandleNatives.asNativeCaller(lookupClass);
  26.494 +            MethodHandleNatives.resolve(m, caller);
  26.495 +            if (m.isResolved())  return true;
  26.496 +            int matchFlags = m.flags | (searchSupers ? SEARCH_ALL_SUPERS : 0);
  26.497 +            String matchSig = m.getSignature();
  26.498 +            MemberName[] buf = { m };
  26.499 +            int n = MethodHandleNatives.getMembers(m.getDeclaringClass(),
  26.500 +                    m.getName(), matchSig, matchFlags, caller, 0, buf);
  26.501 +            if (n != 1)  return false;
  26.502 +            return m.isResolved();
  26.503 +        }
  26.504 +        public MemberName resolveOrNull(MemberName m, boolean searchSupers, Class<?> lookupClass) {
  26.505 +            MemberName result = m.clone();
  26.506 +            if (resolveInPlace(result, searchSupers, lookupClass))
  26.507 +                return result;
  26.508 +            return null;
  26.509 +        }
  26.510 +        public MemberName resolveOrFail(MemberName m, boolean searchSupers, Class<?> lookupClass) {
  26.511 +            MemberName result = resolveOrNull(m, searchSupers, lookupClass);
  26.512 +            if (result != null)
  26.513 +                return result;
  26.514 +            throw newNoAccessException(m, lookupClass);
  26.515 +        }
  26.516 +        public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
  26.517 +                Class<?> lookupClass) {
  26.518 +            return getMethods(defc, searchSupers, null, null, lookupClass);
  26.519 +        }
  26.520 +        public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
  26.521 +                String name, MethodType type, Class<?> lookupClass) {
  26.522 +            int matchFlags = IS_METHOD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
  26.523 +            return getMembers(defc, name, type, matchFlags, lookupClass);
  26.524 +        }
  26.525 +        public List<MemberName> getConstructors(Class<?> defc, Class<?> lookupClass) {
  26.526 +            return getMembers(defc, null, null, IS_CONSTRUCTOR, lookupClass);
  26.527 +        }
  26.528 +        public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
  26.529 +                Class<?> lookupClass) {
  26.530 +            return getFields(defc, searchSupers, null, null, lookupClass);
  26.531 +        }
  26.532 +        public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
  26.533 +                String name, Class<?> type, Class<?> lookupClass) {
  26.534 +            int matchFlags = IS_FIELD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
  26.535 +            return getMembers(defc, name, type, matchFlags, lookupClass);
  26.536 +        }
  26.537 +        public List<MemberName> getNestedTypes(Class<?> defc, boolean searchSupers,
  26.538 +                Class<?> lookupClass) {
  26.539 +            int matchFlags = IS_TYPE | (searchSupers ? SEARCH_ALL_SUPERS : 0);
  26.540 +            return getMembers(defc, null, null, matchFlags, lookupClass);
  26.541 +        }
  26.542 +        private static MemberName[] newMemberBuffer(int length) {
  26.543 +            MemberName[] buf = new MemberName[length];
  26.544 +            // fill the buffer with dummy structs for the JVM to fill in
  26.545 +            for (int i = 0; i < length; i++)
  26.546 +                buf[i] = new MemberName();
  26.547 +            return buf;
  26.548 +        }
  26.549 +    }
  26.550 +
  26.551 +//    static {
  26.552 +//        System.out.println("Hello world!  My methods are:");
  26.553 +//        System.out.println(Factory.INSTANCE.getMethods(MemberName.class, true, null));
  26.554 +//    }
  26.555 +}
    27.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    27.2 +++ b/src/share/classes/sun/dyn/MethodHandleImpl.java	Tue May 05 22:40:09 2009 -0700
    27.3 @@ -0,0 +1,355 @@
    27.4 +/*
    27.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    27.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    27.7 + *
    27.8 + * This code is free software; you can redistribute it and/or modify it
    27.9 + * under the terms of the GNU General Public License version 2 only, as
   27.10 + * published by the Free Software Foundation.  Sun designates this
   27.11 + * particular file as subject to the "Classpath" exception as provided
   27.12 + * by Sun in the LICENSE file that accompanied this code.
   27.13 + *
   27.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   27.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   27.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   27.17 + * version 2 for more details (a copy is included in the LICENSE file that
   27.18 + * accompanied this code).
   27.19 + *
   27.20 + * You should have received a copy of the GNU General Public License version
   27.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   27.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   27.23 + *
   27.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   27.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   27.26 + * have any questions.
   27.27 + */
   27.28 +
   27.29 +package sun.dyn;
   27.30 +
   27.31 +import java.dyn.MethodHandle;
   27.32 +import java.dyn.MethodHandles;
   27.33 +import java.dyn.MethodHandles.Lookup;
   27.34 +import java.dyn.MethodType;
   27.35 +import sun.dyn.util.VerifyType;
   27.36 +import java.dyn.NoAccessException;
   27.37 +import static sun.dyn.MemberName.newIllegalArgumentException;
   27.38 +import static sun.dyn.MemberName.newNoAccessException;
   27.39 +
   27.40 +/**
   27.41 + * Base class for method handles, containing JVM-specific fields and logic.
   27.42 + * TO DO:  It should not be a base class.
   27.43 + * @author jrose
   27.44 + */
   27.45 +public abstract class MethodHandleImpl {
   27.46 +
   27.47 +    // Fields which really belong in MethodHandle:
   27.48 +    private byte       vmentry;    // adapter stub or method entry point
   27.49 +    //private int      vmslots;    // optionally, hoist type.form.vmslots
   27.50 +    protected Object   vmtarget;   // VM-specific, class-specific target value
   27.51 +    //MethodType       type;       // defined in MethodHandle
   27.52 +
   27.53 +    // TO DO:  vmtarget should be invisible to Java, since the JVM puts internal
   27.54 +    // managed pointers into it.  Making it visible exposes it to debuggers,
   27.55 +    // which can cause errors when they treat the pointer as an Object.
   27.56 +
   27.57 +    // These two dummy fields are present to force 'I' and 'J' signatures
   27.58 +    // into this class's constant pool, so they can be transferred
   27.59 +    // to vmentry when this class is loaded.
   27.60 +    static final int  INT_FIELD = 0;
   27.61 +    static final long LONG_FIELD = 0;
   27.62 +
   27.63 +    // type is defined in java.dyn.MethodHandle, which is platform-independent
   27.64 +
   27.65 +    // vmentry (a void* field) is used *only* by by the JVM.
   27.66 +    // The JVM adjusts its type to int or long depending on system wordsize.
   27.67 +    // Since it is statically typed as neither int nor long, it is impossible
   27.68 +    // to use this field from Java bytecode.  (Please don't try to, either.)
   27.69 +
   27.70 +    // The vmentry is an assembly-language stub which is jumped to
   27.71 +    // immediately after the method type is verified.
   27.72 +    // For a direct MH, this stub loads the vmtarget's entry point
   27.73 +    // and jumps to it.
   27.74 +
   27.75 +    /**
   27.76 +     * VM-based method handles must have a security token.
   27.77 +     * This security token can only be obtained by trusted code.
   27.78 +     * Do not create method handles directly; use factory methods.
   27.79 +     */
   27.80 +    public MethodHandleImpl(Access token) {
   27.81 +        Access.check(token);
   27.82 +    }
   27.83 +
   27.84 +    /** Initialize the method type form to participate in JVM calls.
   27.85 +     *  This is done once for each erased type.
   27.86 +     */
   27.87 +    public static void init(Access token, MethodType self) {
   27.88 +        Access.check(token);
   27.89 +        if (MethodHandleNatives.JVM_SUPPORT)
   27.90 +            MethodHandleNatives.init(self);
   27.91 +    }
   27.92 +
   27.93 +    /// Factory methods to create method handles:
   27.94 +
   27.95 +    private static final MemberName.Factory LOOKUP = MemberName.Factory.INSTANCE;
   27.96 +
   27.97 +    static private Lookup IMPL_LOOKUP_INIT;
   27.98 +
   27.99 +    public static void initLookup(Access token, Lookup lookup) {
  27.100 +        Access.check(token);
  27.101 +        if (IMPL_LOOKUP_INIT != null || lookup.lookupClass() != Access.class)
  27.102 +            throw new InternalError();
  27.103 +        IMPL_LOOKUP_INIT = lookup;
  27.104 +    }
  27.105 +
  27.106 +    public static Lookup getLookup(Access token) {
  27.107 +        Access.check(token);
  27.108 +        return IMPL_LOOKUP;
  27.109 +    }
  27.110 +
  27.111 +    static {
  27.112 +        // Force initialization:
  27.113 +        Lookup.PUBLIC_LOOKUP.lookupClass();
  27.114 +        if (IMPL_LOOKUP_INIT == null)
  27.115 +            throw new InternalError();
  27.116 +    }
  27.117 +
  27.118 +    public static void initStatics() {
  27.119 +        // Trigger preceding sequence.
  27.120 +    }
  27.121 +
  27.122 +    /** Shared secret with MethodHandles.Lookup, a copy of Lookup.IMPL_LOOKUP. */
  27.123 +    static final Lookup IMPL_LOOKUP = IMPL_LOOKUP_INIT;
  27.124 +
  27.125 +
  27.126 +    /** Look up a given method.
  27.127 +     * Callable only from java.dyn and related packages.
  27.128 +     * <p>
  27.129 +     * The resulting method handle type will be of the given type,
  27.130 +     * with a receiver type {@code rcvc} prepended if the member is not static.
  27.131 +     * <p>
  27.132 +     * Access checks are made as of the given lookup class.
  27.133 +     * In particular, if the method is protected and {@code defc} is in a
  27.134 +     * different package from the lookup class, then {@code rcvc} must be
  27.135 +     * the lookup class or a subclass.
  27.136 +     * @param token Proof that the lookup class has access to this package.
  27.137 +     * @param member Resolved method or constructor to call.
  27.138 +     * @param name Name of the desired method.
  27.139 +     * @param rcvc Receiver type of desired non-static method (else null)
  27.140 +     * @param doDispatch whether the method handle will test the receiver type
  27.141 +     * @param lookupClass access-check relative to this class
  27.142 +     * @return a direct handle to the matching method
  27.143 +     * @throws NoAccessException if the given method cannot be accessed by the lookup class
  27.144 +     */
  27.145 +    public static
  27.146 +    MethodHandle findMethod(Access token, MemberName method,
  27.147 +            boolean doDispatch, Class<?> lookupClass) {
  27.148 +        Access.check(token);  // only trusted calls
  27.149 +        MethodType mtype = method.getMethodType();
  27.150 +        if (method.isStatic()) {
  27.151 +            doDispatch = false;
  27.152 +        } else {
  27.153 +            // adjust the advertised receiver type to be exactly the one requested
  27.154 +            // (in the case of invokespecial, this will be the calling class)
  27.155 +            mtype = mtype.insertParameterType(0, method.getDeclaringClass());
  27.156 +            if (method.isConstructor())
  27.157 +                doDispatch = true;
  27.158 +        }
  27.159 +        DirectMethodHandle mh = new DirectMethodHandle(mtype, method, doDispatch, lookupClass);
  27.160 +        if (!mh.isValid())
  27.161 +            throw newNoAccessException(method, lookupClass);
  27.162 +        return mh;
  27.163 +    }
  27.164 +
  27.165 +    public static
  27.166 +    MethodHandle accessField(Access token,
  27.167 +                           MemberName member, boolean isSetter,
  27.168 +                           Class<?> lookupClass) {
  27.169 +        Access.check(token);
  27.170 +        // FIXME: Use sun.misc.Unsafe to dig up the dirt on the field.
  27.171 +        throw new UnsupportedOperationException("Not yet implemented");
  27.172 +    }
  27.173 +
  27.174 +    public static
  27.175 +    MethodHandle accessArrayElement(Access token,
  27.176 +                           Class<?> arrayClass, boolean isSetter) {
  27.177 +        Access.check(token);
  27.178 +        if (!arrayClass.isArray())
  27.179 +            throw newIllegalArgumentException("not an array: "+arrayClass);
  27.180 +        // FIXME: Use sun.misc.Unsafe to dig up the dirt on the array.
  27.181 +        throw new UnsupportedOperationException("Not yet implemented");
  27.182 +    }
  27.183 +
  27.184 +    /** Bind a predetermined first argument to the given direct method handle.
  27.185 +     * Callable only from MethodHandles.
  27.186 +     * @param token Proof that the caller has access to this package.
  27.187 +     * @param target Any direct method handle.
  27.188 +     * @param receiver Receiver (or first static method argument) to pre-bind.
  27.189 +     * @return a BoundMethodHandle for the given DirectMethodHandle, or null if it does not exist
  27.190 +     */
  27.191 +    public static
  27.192 +    MethodHandle bindReceiver(Access token,
  27.193 +                              MethodHandle target, Object receiver) {
  27.194 +        Access.check(token);
  27.195 +        if (target instanceof DirectMethodHandle)
  27.196 +            return new BoundMethodHandle((DirectMethodHandle)target, receiver, 0);
  27.197 +        return null;   // let caller try something else
  27.198 +    }
  27.199 +
  27.200 +    /** Bind a predetermined argument to the given arbitrary method handle.
  27.201 +     * Callable only from MethodHandles.
  27.202 +     * @param token Proof that the caller has access to this package.
  27.203 +     * @param target Any method handle.
  27.204 +     * @param receiver Argument (which can be a boxed primitive) to pre-bind.
  27.205 +     * @return a suitable BoundMethodHandle
  27.206 +     */
  27.207 +    public static
  27.208 +    MethodHandle bindArgument(Access token,
  27.209 +                              MethodHandle target, int argnum, Object receiver) {
  27.210 +        Access.check(token);
  27.211 +        throw new UnsupportedOperationException("NYI");
  27.212 +    }
  27.213 +
  27.214 +    public static MethodHandle convertArguments(Access token,
  27.215 +                                                MethodHandle target,
  27.216 +                                                MethodType newType,
  27.217 +                                                MethodType oldType,
  27.218 +                                                int[] permutationOrNull) {
  27.219 +        Access.check(token);
  27.220 +        MethodHandle res = AdapterMethodHandle.makePairwiseConvert(token, newType, target);
  27.221 +        if (res != null)
  27.222 +            return res;
  27.223 +        int argc = oldType.parameterCount();
  27.224 +        // The JVM can't do it directly, so fill in the gap with a Java adapter.
  27.225 +        // TO DO: figure out what to put here from case-by-case experience
  27.226 +        // Use a heavier method:  Convert all the arguments to Object,
  27.227 +        // then back to the desired types.  We might have to use Java-based
  27.228 +        // method handles to do this.
  27.229 +        MethodType objType = MethodType.makeGeneric(argc);
  27.230 +        MethodHandle objTarget = AdapterMethodHandle.makePairwiseConvert(token, objType, target);
  27.231 +        if (objTarget == null)
  27.232 +            objTarget = FromGeneric.make(target);
  27.233 +        res = AdapterMethodHandle.makePairwiseConvert(token, newType, objTarget);
  27.234 +        if (res != null)
  27.235 +            return res;
  27.236 +        return ToGeneric.make(newType, objTarget);
  27.237 +    }
  27.238 +
  27.239 +    public static MethodHandle spreadArguments(Access token,
  27.240 +                                               MethodHandle target,
  27.241 +                                               MethodType newType,
  27.242 +                                               int spreadArg) {
  27.243 +        Access.check(token);
  27.244 +        // TO DO: maybe allow the restarg to be Object and implicitly cast to Object[]
  27.245 +        MethodType oldType = target.type();
  27.246 +        // spread the last argument of newType to oldType
  27.247 +        int spreadCount = oldType.parameterCount() - spreadArg;
  27.248 +        Class<Object[]> spreadArgType = Object[].class;
  27.249 +        MethodHandle res = AdapterMethodHandle.makeSpreadArguments(token, newType, target, spreadArgType, spreadArg, spreadCount);
  27.250 +        if (res != null)
  27.251 +            return res;
  27.252 +        // try an intermediate adapter
  27.253 +        Class<?> spreadType = null;
  27.254 +        if (spreadArg < 0 || spreadArg >= newType.parameterCount()
  27.255 +            || !VerifyType.isSpreadArgType(spreadType = newType.parameterType(spreadArg)))
  27.256 +            throw newIllegalArgumentException("no restarg in "+newType);
  27.257 +        Class<?>[] ptypes = oldType.parameterArray();
  27.258 +        for (int i = 0; i < spreadCount; i++)
  27.259 +            ptypes[spreadArg + i] = VerifyType.spreadArgElementType(spreadType, i);
  27.260 +        MethodType midType = MethodType.make(newType.returnType(), ptypes);
  27.261 +        // after spreading, some arguments may need further conversion
  27.262 +        target = convertArguments(token, target, midType, oldType, null);
  27.263 +        if (target == null)
  27.264 +            throw new UnsupportedOperationException("NYI: convert "+midType+" =calls=> "+oldType);
  27.265 +        res = AdapterMethodHandle.makeSpreadArguments(token, newType, target, spreadArgType, spreadArg, spreadCount);
  27.266 +        return res;
  27.267 +    }
  27.268 +
  27.269 +    public static MethodHandle collectArguments(Access token,
  27.270 +                                                MethodHandle target,
  27.271 +                                                MethodType newType,
  27.272 +                                                int collectArg) {
  27.273 +        if (collectArg > 0)
  27.274 +            throw new UnsupportedOperationException("NYI");
  27.275 +        throw new UnsupportedOperationException("NYI");
  27.276 +    }
  27.277 +    public static
  27.278 +    MethodHandle dropArguments(Access token, MethodHandle target,
  27.279 +                               MethodType newType, int argnum) {
  27.280 +        Access.check(token);
  27.281 +        throw new UnsupportedOperationException("NYI");
  27.282 +    }
  27.283 +
  27.284 +    public static
  27.285 +    MethodHandle makeGuardWithTest(Access token,
  27.286 +                                   final MethodHandle test,
  27.287 +                                   final MethodHandle target,
  27.288 +                                   final MethodHandle fallback) {
  27.289 +        Access.check(token);
  27.290 +        // %%% This is just a sketch.  It needs to be de-boxed.
  27.291 +        // Adjust the handles to accept varargs lists.
  27.292 +        MethodType type = target.type();
  27.293 +        Class<?>  rtype = type.returnType();
  27.294 +        if (type.parameterCount() != 1 || type.parameterType(0).isPrimitive()) {
  27.295 +            MethodType vatestType   = MethodType.make(boolean.class, Object[].class);
  27.296 +            MethodType vatargetType = MethodType.make(rtype, Object[].class);
  27.297 +            MethodHandle vaguard = makeGuardWithTest(token,
  27.298 +                    MethodHandles.spreadArguments(test, vatestType),
  27.299 +                    MethodHandles.spreadArguments(target, vatargetType),
  27.300 +                    MethodHandles.spreadArguments(fallback, vatargetType));
  27.301 +            return MethodHandles.collectArguments(vaguard, type);
  27.302 +        }
  27.303 +        if (rtype.isPrimitive()) {
  27.304 +            MethodType boxtype = type.changeReturnType(Object.class);
  27.305 +            MethodHandle boxguard = makeGuardWithTest(token,
  27.306 +                    test,
  27.307 +                    MethodHandles.convertArguments(target, boxtype),
  27.308 +                    MethodHandles.convertArguments(fallback, boxtype));
  27.309 +            return MethodHandles.convertArguments(boxguard, type);
  27.310 +        }
  27.311 +        // Got here?  Reduced calling sequence to Object(Object).
  27.312 +        class Guarder {
  27.313 +            Object invoke(Object x) {
  27.314 +                // If javac supports MethodHandle.invoke directly:
  27.315 +                //z = vatest.invoke<boolean>(arguments);
  27.316 +                // If javac does not support direct MH.invoke calls:
  27.317 +                boolean z = (Boolean) MethodHandles.invoke_1(test, x);
  27.318 +                MethodHandle mh = (z ? target : fallback);
  27.319 +                return MethodHandles.invoke_1(mh, x);
  27.320 +            }
  27.321 +            MethodHandle handle() {
  27.322 +                MethodType invokeType = MethodType.makeGeneric(0, true);
  27.323 +                MethodHandle vh = IMPL_LOOKUP.bind(this, "invoke", invokeType);
  27.324 +                return MethodHandles.collectArguments(vh, target.type());
  27.325 +            }
  27.326 +        }
  27.327 +        return new Guarder().handle();
  27.328 +    }
  27.329 +
  27.330 +    public static
  27.331 +    MethodHandle combineArguments(Access token, MethodHandle target, MethodHandle checker, int pos) {
  27.332 +        Access.check(token);
  27.333 +        throw new UnsupportedOperationException("Not yet implemented");
  27.334 +    }
  27.335 +
  27.336 +    protected static String basicToString(MethodHandle target) {
  27.337 +        MemberName name = null;
  27.338 +        if (target != null)
  27.339 +            name = MethodHandleNatives.getMethodName(target);
  27.340 +        if (name == null)
  27.341 +            return "<unknown>";
  27.342 +        return name.getName();
  27.343 +    }
  27.344 +
  27.345 +    protected static String addTypeString(MethodHandle target, String name) {
  27.346 +        if (target == null)  return name;
  27.347 +        return name+target.type();
  27.348 +    }
  27.349 +    static RuntimeException newIllegalArgumentException(String string) {
  27.350 +        return new IllegalArgumentException(string);
  27.351 +    }
  27.352 +
  27.353 +    @Override
  27.354 +    public String toString() {
  27.355 +        MethodHandle self = (MethodHandle) this;
  27.356 +        return addTypeString(self, basicToString(self));
  27.357 +    }
  27.358 +}
    28.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    28.2 +++ b/src/share/classes/sun/dyn/MethodHandleNatives.java	Tue May 05 22:40:09 2009 -0700
    28.3 @@ -0,0 +1,271 @@
    28.4 +/*
    28.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    28.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    28.7 + *
    28.8 + * This code is free software; you can redistribute it and/or modify it
    28.9 + * under the terms of the GNU General Public License version 2 only, as
   28.10 + * published by the Free Software Foundation.  Sun designates this
   28.11 + * particular file as subject to the "Classpath" exception as provided
   28.12 + * by Sun in the LICENSE file that accompanied this code.
   28.13 + *
   28.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   28.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   28.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   28.17 + * version 2 for more details (a copy is included in the LICENSE file that
   28.18 + * accompanied this code).
   28.19 + *
   28.20 + * You should have received a copy of the GNU General Public License version
   28.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   28.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   28.23 + *
   28.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   28.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   28.26 + * have any questions.
   28.27 + */
   28.28 +
   28.29 +package sun.dyn;
   28.30 +
   28.31 +import java.dyn.MethodHandle;
   28.32 +import java.dyn.MethodType;
   28.33 +import java.lang.reflect.AccessibleObject;
   28.34 +import java.lang.reflect.Field;
   28.35 +import static sun.dyn.MethodHandleNatives.Constants.*;
   28.36 +
   28.37 +/**
   28.38 + * The JVM interface for the method handles package is all here.
   28.39 + * @author jrose
   28.40 + */
   28.41 +class MethodHandleNatives {
   28.42 +
   28.43 +    private MethodHandleNatives() { } // static only
   28.44 +
   28.45 +    /// MethodName support
   28.46 +
   28.47 +    static native void init(MemberName self, Object ref);
   28.48 +    static native void expand(MemberName self);
   28.49 +    static native void resolve(MemberName self, Class<?> caller);
   28.50 +    static native int getMembers(Class<?> defc, String matchName, String matchSig,
   28.51 +            int matchFlags, Class<?> caller, int skip, MemberName[] results);
   28.52 +
   28.53 +    static Class<?> asNativeCaller(Class<?> lookupClass) {
   28.54 +        if (lookupClass == null)  // means "public only, non-privileged"
   28.55 +            return sun.dyn.empty.Empty.class;
   28.56 +        if (lookupClass == Access.class)  // means "internal, privileged"
   28.57 +            return null;    // to the JVM, null means completely privileged
   28.58 +        return lookupClass;
   28.59 +    }
   28.60 +
   28.61 +    /// MethodHandle support
   28.62 +
   28.63 +    /** Initialize the method handle to adapt the call. */
   28.64 +    static native void init(AdapterMethodHandle self, MethodHandle target, int argnum);
   28.65 +    /** Initialize the method handle to call the correct method, directly. */
   28.66 +    static native void init(BoundMethodHandle self, Object target, int argnum);
   28.67 +    /** Initialize the method handle to call as if by an invoke* instruction. */
   28.68 +    static native void init(DirectMethodHandle self, Object ref, boolean doDispatch, Class<?> caller);
   28.69 +
   28.70 +    /** Initialize a method type, once per form. */
   28.71 +    static native void init(MethodType self);
   28.72 +
   28.73 +    /** Tell the JVM that we need to change the target of an invokedynamic. */
   28.74 +    static native void linkCallSite(CallSiteImpl site, MethodHandle target);
   28.75 +
   28.76 +    /** Fetch the vmtarget field.
   28.77 +     *  It will be sanitized as necessary to avoid exposing non-Java references.
   28.78 +     *  This routine is for debugging and reflection.
   28.79 +     */
   28.80 +    static native Object getTarget(MethodHandle self, int format);
   28.81 +
   28.82 +    /** Fetch the name of the handled method, if available.
   28.83 +     *  This routine is for debugging and reflection.
   28.84 +     */
   28.85 +    static MemberName getMethodName(MethodHandle self) {
   28.86 +        if (!JVM_SUPPORT)  return null;
   28.87 +        return (MemberName) getTarget(self, ETF_METHOD_NAME);
   28.88 +    }
   28.89 +
   28.90 +    /** Fetch the reflective version of the handled method, if available.
   28.91 +     */
   28.92 +    static AccessibleObject getTargetMethod(MethodHandle self) {
   28.93 +        if (!JVM_SUPPORT)  return null;
   28.94 +        return (AccessibleObject) getTarget(self, ETF_REFLECT_METHOD);
   28.95 +    }
   28.96 +
   28.97 +    /** Fetch the target of this method handle.
   28.98 +     *  If it directly targets a method, return a tuple of method info.
   28.99 +     *  The info is of the form new Object[]{defclass, name, sig, refclass}.
  28.100 +     *  If it is chained to another method handle, return that handle.
  28.101 +     */
  28.102 +    static Object getTargetInfo(MethodHandle self) {
  28.103 +        if (!JVM_SUPPORT)  return null;
  28.104 +        return getTarget(self, ETF_HANDLE_OR_METHOD_NAME);
  28.105 +    }
  28.106 +
  28.107 +    static Object[] makeTarget(Class<?> defc, String name, String sig, int mods, Class<?> refc) {
  28.108 +        return new Object[] { defc, name, sig, mods, refc };
  28.109 +    }
  28.110 +
  28.111 +    /** Fetch MH-related JVM parameter.
  28.112 +     *  which=0 retrieves MethodHandlePushLimit
  28.113 +     *  which=1 retrieves stack slot push size (in address units)
  28.114 +     */
  28.115 +    static native int getConstant(int which);
  28.116 +
  28.117 +    /** True iff this HotSpot JVM has built-in support for method handles.
  28.118 +     * If false, some test cases might run, but functionality will be missing.
  28.119 +     */
  28.120 +    public static final boolean JVM_SUPPORT;
  28.121 +
  28.122 +    /** Java copy of MethodHandlePushLimit in range 2..255. */
  28.123 +    static final int JVM_PUSH_LIMIT;
  28.124 +    /** JVM stack motion (in words) after one slot is pushed, usually -1.
  28.125 +     */
  28.126 +    static final int JVM_STACK_MOVE_UNIT;
  28.127 +
  28.128 +    private static native void registerNatives();
  28.129 +    static {
  28.130 +        boolean JVM_SUPPORT_;
  28.131 +        int     JVM_PUSH_LIMIT_;
  28.132 +        int     JVM_STACK_MOVE_UNIT_;
  28.133 +        try {
  28.134 +            registerNatives();
  28.135 +            JVM_SUPPORT_ = true;
  28.136 +            JVM_PUSH_LIMIT_ = getConstant(Constants.GC_JVM_PUSH_LIMIT);
  28.137 +            JVM_STACK_MOVE_UNIT_ = getConstant(Constants.GC_JVM_STACK_MOVE_LIMIT);
  28.138 +            //sun.reflect.Reflection.registerMethodsToFilter(MethodHandleImpl.class, "init");
  28.139 +        } catch (UnsatisfiedLinkError ee) {
  28.140 +            // ignore; if we use init() methods later we'll see linkage errors
  28.141 +            JVM_SUPPORT_ = false;
  28.142 +            JVM_PUSH_LIMIT_ = 3;  // arbitrary
  28.143 +            JVM_STACK_MOVE_UNIT_ = -1;  // arbitrary
  28.144 +            //System.out.println("Warning: Running with JVM_SUPPORT=false");
  28.145 +            //System.out.println(ee);
  28.146 +            JVM_SUPPORT = JVM_SUPPORT_;
  28.147 +            JVM_PUSH_LIMIT = JVM_PUSH_LIMIT_;
  28.148 +            JVM_STACK_MOVE_UNIT = JVM_STACK_MOVE_UNIT_;
  28.149 +            throw ee;  // just die; hopeless to try to run with an older JVM
  28.150 +        }
  28.151 +        JVM_SUPPORT = JVM_SUPPORT_;
  28.152 +        JVM_PUSH_LIMIT = JVM_PUSH_LIMIT_;
  28.153 +        JVM_STACK_MOVE_UNIT = JVM_STACK_MOVE_UNIT_;
  28.154 +    }
  28.155 +
  28.156 +    // All compile-time constants go here.
  28.157 +    // There is an opportunity to check them against the JVM's idea of them.
  28.158 +    static class Constants {
  28.159 +        Constants() { } // static only
  28.160 +        // MethodHandleImpl
  28.161 +        static final int // for getConstant
  28.162 +                GC_JVM_PUSH_LIMIT = 0,
  28.163 +                GC_JVM_STACK_MOVE_LIMIT = 1;
  28.164 +        static final int
  28.165 +                ETF_HANDLE_OR_METHOD_NAME = 0, // all available data (immediate MH or method)
  28.166 +                ETF_DIRECT_HANDLE         = 1, // ultimate method handle (will be a DMH, may be self)
  28.167 +                ETF_METHOD_NAME           = 2, // ultimate method as MemberName
  28.168 +                ETF_REFLECT_METHOD        = 3; // ultimate method as java.lang.reflect object (sans refClass)
  28.169 +
  28.170 +        // MemberName
  28.171 +        // The JVM uses values of -2 and above for vtable indexes.
  28.172 +        // Field values are simple positive offsets.
  28.173 +        // Ref: src/share/vm/oops/methodOop.hpp
  28.174 +        // This value is negative enough to avoid such numbers,
  28.175 +        // but not too negative.
  28.176 +        static final int
  28.177 +                MN_IS_METHOD           = 0x00010000, // method (not constructor)
  28.178 +                MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
  28.179 +                MN_IS_FIELD            = 0x00040000, // field
  28.180 +                MN_IS_TYPE             = 0x00080000, // nested type
  28.181 +                MN_SEARCH_SUPERCLASSES = 0x00100000, // for MHN.getMembers
  28.182 +                MN_SEARCH_INTERFACES   = 0x00200000, // for MHN.getMembers
  28.183 +                VM_INDEX_UNINITIALIZED = -99;
  28.184 +
  28.185 +        // AdapterMethodHandle
  28.186 +        /** Conversions recognized by the JVM.
  28.187 +         *  They must align with the constants in sun.dyn_AdapterMethodHandle,
  28.188 +         *  in the JVM file hotspot/src/share/vm/classfile/javaClasses.hpp.
  28.189 +         */
  28.190 +        static final int
  28.191 +            OP_RETYPE_ONLY   = 0x0, // no argument changes; straight retype
  28.192 +            OP_CHECK_CAST    = 0x1, // ref-to-ref conversion; requires a Class argument
  28.193 +            OP_PRIM_TO_PRIM  = 0x2, // converts from one primitive to another
  28.194 +            OP_REF_TO_PRIM   = 0x3, // unboxes a wrapper to produce a primitive
  28.195 +            OP_PRIM_TO_REF   = 0x4, // boxes a primitive into a wrapper (NYI)
  28.196 +            OP_SWAP_ARGS     = 0x5, // swap arguments (vminfo is 2nd arg)
  28.197 +            OP_ROT_ARGS      = 0x6, // rotate arguments (vminfo is displaced arg)
  28.198 +            OP_DUP_ARGS      = 0x7, // duplicates one or more arguments (at TOS)
  28.199 +            OP_DROP_ARGS     = 0x8, // remove one or more argument slots
  28.200 +            OP_COLLECT_ARGS  = 0x9, // combine one or more arguments into a varargs (NYI)
  28.201 +            OP_SPREAD_ARGS   = 0xA, // expand in place a varargs array (of known size)
  28.202 +            OP_FLYBY         = 0xB, // operate first on reified argument list (NYI)
  28.203 +            OP_RICOCHET      = 0xC, // run an adapter chain on the return value (NYI)
  28.204 +            CONV_OP_LIMIT    = 0xD; // limit of CONV_OP enumeration
  28.205 +        /** Shift and mask values for decoding the AMH.conversion field.
  28.206 +         *  These numbers are shared with the JVM for creating AMHs.
  28.207 +         */
  28.208 +        static final int
  28.209 +            CONV_OP_MASK     = 0xF00, // this nybble contains the conversion op field
  28.210 +            CONV_VMINFO_MASK = 0x0FF, // LSB is reserved for JVM use
  28.211 +            CONV_VMINFO_SHIFT     =  0, // position of bits in CONV_VMINFO_MASK
  28.212 +            CONV_OP_SHIFT         =  8, // position of bits in CONV_OP_MASK
  28.213 +            CONV_DEST_TYPE_SHIFT  = 12, // byte 2 has the adapter BasicType (if needed)
  28.214 +            CONV_SRC_TYPE_SHIFT   = 16, // byte 2 has the source BasicType (if needed)
  28.215 +            CONV_STACK_MOVE_SHIFT = 20, // high 12 bits give signed SP change
  28.216 +            CONV_STACK_MOVE_MASK  = (1 << (32 - CONV_STACK_MOVE_SHIFT)) - 1;
  28.217 +
  28.218 +        /** Which conv-ops are implemented by the JVM? */
  28.219 +        static final int CONV_OP_IMPLEMENTED_MASK =
  28.220 +                // TODO: The following expression should be replaced by
  28.221 +                // a JVM query.
  28.222 +                ((1<<OP_RETYPE_ONLY)
  28.223 +                |(1<<OP_CHECK_CAST)
  28.224 +                |(1<<OP_PRIM_TO_PRIM)
  28.225 +                |(1<<OP_REF_TO_PRIM)
  28.226 +                |(1<<OP_SWAP_ARGS)
  28.227 +                |(1<<OP_ROT_ARGS)
  28.228 +                |(1<<OP_DUP_ARGS)
  28.229 +                |(1<<OP_DROP_ARGS)
  28.230 +                );
  28.231 +
  28.232 +        /**
  28.233 +         * Basic types as encoded in the JVM.  These code values are not
  28.234 +         * intended for use outside this class.  They are used as part of
  28.235 +         * a private interface between the JVM and this class.
  28.236 +         */
  28.237 +        static final int
  28.238 +            T_BOOLEAN  =  4,
  28.239 +            T_CHAR     =  5,
  28.240 +            T_FLOAT    =  6,
  28.241 +            T_DOUBLE   =  7,
  28.242 +            T_BYTE     =  8,
  28.243 +            T_SHORT    =  9,
  28.244 +            T_INT      = 10,
  28.245 +            T_LONG     = 11,
  28.246 +            T_OBJECT   = 12,
  28.247 +            //T_ARRAY    = 13
  28.248 +            T_VOID     = 14;
  28.249 +            //T_ADDRESS  = 15
  28.250 +    }
  28.251 +
  28.252 +    private static native int getNamedCon(int which, Object[] name);
  28.253 +    static boolean verifyConstants() {
  28.254 +        Object[] box = { null };
  28.255 +        for (int i = 0; ; i++) {
  28.256 +            box[0] = null;
  28.257 +            int vmval = getNamedCon(i, box);
  28.258 +            if (box[0] == null)  break;
  28.259 +            String name = (String) box[0];
  28.260 +            try {
  28.261 +                Field con = Constants.class.getDeclaredField(name);
  28.262 +                int jval = con.getInt(null);
  28.263 +                if (jval != vmval)
  28.264 +                    throw new InternalError(name+": JVM has "+vmval+" while Java has "+jval);
  28.265 +            } catch (Exception ex) {
  28.266 +                throw new InternalError(name+": access failed, got "+ex);
  28.267 +            }
  28.268 +        }
  28.269 +        return true;
  28.270 +    }
  28.271 +    static {
  28.272 +        if (JVM_SUPPORT)  verifyConstants();
  28.273 +    }
  28.274 +}
    29.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    29.2 +++ b/src/share/classes/sun/dyn/MethodTypeImpl.java	Tue May 05 22:40:09 2009 -0700
    29.3 @@ -0,0 +1,502 @@
    29.4 +/*
    29.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    29.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    29.7 + *
    29.8 + * This code is free software; you can redistribute it and/or modify it
    29.9 + * under the terms of the GNU General Public License version 2 only, as
   29.10 + * published by the Free Software Foundation.  Sun designates this
   29.11 + * particular file as subject to the "Classpath" exception as provided
   29.12 + * by Sun in the LICENSE file that accompanied this code.
   29.13 + *
   29.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   29.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   29.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   29.17 + * version 2 for more details (a copy is included in the LICENSE file that
   29.18 + * accompanied this code).
   29.19 + *
   29.20 + * You should have received a copy of the GNU General Public License version
   29.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   29.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   29.23 + *
   29.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   29.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   29.26 + * have any questions.
   29.27 + */
   29.28 +
   29.29 +package sun.dyn;
   29.30 +
   29.31 +import java.dyn.*;
   29.32 +import sun.dyn.util.Wrapper;
   29.33 +
   29.34 +/**
   29.35 + * Shared information for a group of method types, which differ
   29.36 + * only by reference types, and therefore share a common erasure
   29.37 + * and wrapping.
   29.38 + * <p>
   29.39 + * For an empirical discussion of the structure of method types,
   29.40 + * see <a href="http://groups.google.com/group/jvm-languages/browse_thread/thread/ac9308ae74da9b7e/">
   29.41 + * the thread "Avoiding Boxing" on jvm-languages</a>.
   29.42 + * There are approximately 2000 distinct erased method types in the JDK.
   29.43 + * There are a little over 10 times that number of unerased types.
   29.44 + * No more than half of these are likely to be loaded at once.
   29.45 + * @author John Rose
   29.46 + */
   29.47 +public class MethodTypeImpl {
   29.48 +    final int[] argToSlotTable, slotToArgTable;
   29.49 +    final long argCounts;               // packed slot & value counts
   29.50 +    final long primCounts;              // packed prim & double counts
   29.51 +    final int vmslots;                  // total number of parameter slots
   29.52 +    final MethodType erasedType;        // the canonical erasure
   29.53 +    /*lazy*/ MethodType primsAsBoxes;   // replace prims by wrappers
   29.54 +    /*lazy*/ MethodType primArgsAsBoxes; // wrap args only; make raw return
   29.55 +    /*lazy*/ MethodType primsAsInts;    // replace prims by int/long
   29.56 +    /*lazy*/ MethodType primsAsLongs;   // replace prims by long
   29.57 +    /*lazy*/ MethodType primsAtEnd;     // reorder primitives to the end
   29.58 +
   29.59 +    // Cached adapter information:
   29.60 +    /*lazy*/ ToGeneric   toGeneric;     // convert cs. with prims to w/o
   29.61 +    /*lazy*/ FromGeneric fromGeneric;   // convert cs. w/o prims to with
   29.62 +    /*lazy*/ FilterGeneric filterGeneric; // convert argument(s) on the fly
   29.63 +    ///*lazy*/ Invokers    invokers;    // cache of handy higher-order adapters
   29.64 +
   29.65 +    public MethodType erasedType() {
   29.66 +        return erasedType;
   29.67 +    }
   29.68 +
   29.69 +    public static MethodTypeImpl of(MethodType type) {
   29.70 +        return METHOD_TYPE_FRIEND.form(type);
   29.71 +    }
   29.72 +
   29.73 +    /** Access methods for the internals of MethodType, supplied to
   29.74 +     *  MethodTypeForm as a trusted agent.
   29.75 +     */
   29.76 +    static public interface MethodTypeFriend {
   29.77 +        Class<?>[]     ptypes(MethodType mt);
   29.78 +        MethodTypeImpl form(MethodType mt);
   29.79 +        void           setForm(MethodType mt, MethodTypeImpl form);
   29.80 +        MethodType     makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted);
   29.81 +        MethodTypeImpl newMethodTypeForm(MethodType mt);
   29.82 +        Invokers       getInvokers(MethodType mt);
   29.83 +        void           setInvokers(MethodType mt, Invokers inv);
   29.84 +    }
   29.85 +    public static void setMethodTypeFriend(Access token, MethodTypeFriend am) {
   29.86 +        Access.check(token);
   29.87 +        if (METHOD_TYPE_FRIEND != null)
   29.88 +            throw new InternalError();  // just once
   29.89 +        METHOD_TYPE_FRIEND = am;
   29.90 +    }
   29.91 +    static private MethodTypeFriend METHOD_TYPE_FRIEND;
   29.92 +
   29.93 +    protected MethodTypeImpl(MethodType erasedType) {
   29.94 +        this.erasedType = erasedType;
   29.95 +
   29.96 +        Class<?>[] ptypes = METHOD_TYPE_FRIEND.ptypes(erasedType);
   29.97 +        int ptypeCount = ptypes.length;
   29.98 +        int pslotCount = ptypeCount;            // temp. estimate
   29.99 +        int rtypeCount = 1;                     // temp. estimate
  29.100 +        int rslotCount = 1;                     // temp. estimate
  29.101 +
  29.102 +        int[] argToSlotTab = null, slotToArgTab = null;
  29.103 +
  29.104 +        // Walk the argument types, looking for primitives.
  29.105 +        int pac = 0, lac = 0, prc = 0, lrc = 0;
  29.106 +        Class<?> epts[] = ptypes;
  29.107 +        for (int i = 0; i < epts.length; i++) {
  29.108 +            Class<?> pt = epts[i];
  29.109 +            if (pt != Object.class) {
  29.110 +                assert(pt.isPrimitive());
  29.111 +                ++pac;
  29.112 +                if (hasTwoArgSlots(pt))  ++lac;
  29.113 +            }
  29.114 +        }
  29.115 +        pslotCount += lac;                  // #slots = #args + #longs
  29.116 +        Class<?> rt = erasedType.returnType();
  29.117 +        if (rt != Object.class) {
  29.118 +            ++prc;          // even void.class counts as a prim here
  29.119 +            if (hasTwoArgSlots(rt))  ++lrc;
  29.120 +            // adjust #slots, #args
  29.121 +            if (rt == void.class)
  29.122 +                rtypeCount = rslotCount = 0;
  29.123 +            else
  29.124 +                rslotCount += lrc;
  29.125 +        }
  29.126 +        if (lac != 0) {
  29.127 +            int slot = ptypeCount + lac;
  29.128 +            slotToArgTab = new int[slot+1];
  29.129 +            argToSlotTab = new int[1+ptypeCount];
  29.130 +            argToSlotTab[0] = slot;  // argument "-1" is past end of slots
  29.131 +            for (int i = 0; i < epts.length; i++) {
  29.132 +                Class<?> pt = epts[i];
  29.133 +                if (hasTwoArgSlots(pt))  --slot;
  29.134 +                --slot;
  29.135 +                slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
  29.136 +                argToSlotTab[1+i]  = slot;
  29.137 +            }
  29.138 +            assert(slot == 0);  // filled the table
  29.139 +        }
  29.140 +        this.primCounts = pack(lrc, prc, lac, pac);
  29.141 +        this.argCounts = pack(rslotCount, rtypeCount, pslotCount, ptypeCount);
  29.142 +        if (slotToArgTab == null) {
  29.143 +            int slot = ptypeCount; // first arg is deepest in stack
  29.144 +            slotToArgTab = new int[slot+1];
  29.145 +            argToSlotTab = new int[1+ptypeCount];
  29.146 +            argToSlotTab[0] = slot;  // argument "-1" is past end of slots
  29.147 +            for (int i = 0; i < ptypeCount; i++) {
  29.148 +                --slot;
  29.149 +                slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
  29.150 +                argToSlotTab[1+i]  = slot;
  29.151 +            }
  29.152 +        }
  29.153 +        this.argToSlotTable = argToSlotTab;
  29.154 +        this.slotToArgTable = slotToArgTab;
  29.155 +
  29.156 +        if (pslotCount >= 256)  throw new IllegalArgumentException("too many arguments");
  29.157 +
  29.158 +        // send a few bits down to the JVM:
  29.159 +        this.vmslots = parameterSlotCount();
  29.160 +
  29.161 +        // short circuit some no-op canonicalizations:
  29.162 +        if (!hasPrimitives()) {
  29.163 +            primsAsBoxes = erasedType;
  29.164 +            primArgsAsBoxes = erasedType;
  29.165 +            primsAsInts  = erasedType;
  29.166 +            primsAsLongs = erasedType;
  29.167 +            primsAtEnd   = erasedType;
  29.168 +        }
  29.169 +    }
  29.170 +
  29.171 +    /** Turn all primitive types to corresponding wrapper types.
  29.172 +     */
  29.173 +    public MethodType primsAsBoxes() {
  29.174 +        MethodType ct = primsAsBoxes;
  29.175 +        if (ct != null)  return ct;
  29.176 +        MethodType t = erasedType;
  29.177 +        ct = canonicalize(erasedType, WRAP, WRAP);
  29.178 +        if (ct == null)  ct = t;  // no prims to box
  29.179 +        return primsAsBoxes = ct;
  29.180 +    }
  29.181 +
  29.182 +    /** Turn all primitive argument types to corresponding wrapper types.
  29.183 +     *  Subword and void return types are promoted to int.
  29.184 +     */
  29.185 +    public MethodType primArgsAsBoxes() {
  29.186 +        MethodType ct = primArgsAsBoxes;
  29.187 +        if (ct != null)  return ct;
  29.188 +        MethodType t = erasedType;
  29.189 +        ct = canonicalize(erasedType, RAW_RETURN, WRAP);
  29.190 +        if (ct == null)  ct = t;  // no prims to box
  29.191 +        return primArgsAsBoxes = ct;
  29.192 +    }
  29.193 +
  29.194 +    /** Turn all primitive types to either int or long.
  29.195 +     *  Floating point return types are not changed, because
  29.196 +     *  they may require special calling sequences.
  29.197 +     *  A void return value is turned to int.
  29.198 +     */
  29.199 +    public MethodType primsAsInts() {
  29.200 +        MethodType ct = primsAsInts;
  29.201 +        if (ct != null)  return ct;
  29.202 +        MethodType t = erasedType;
  29.203 +        ct = canonicalize(t, RAW_RETURN, INTS);
  29.204 +        if (ct == null)  ct = t;  // no prims to int-ify
  29.205 +        return primsAsInts = ct;
  29.206 +    }
  29.207 +
  29.208 +    /** Turn all primitive types to either int or long.
  29.209 +     *  Floating point return types are not changed, because
  29.210 +     *  they may require special calling sequences.
  29.211 +     *  A void return value is turned to int.
  29.212 +     */
  29.213 +    public MethodType primsAsLongs() {
  29.214 +        MethodType ct = primsAsLongs;
  29.215 +        if (ct != null)  return ct;
  29.216 +        MethodType t = erasedType;
  29.217 +        ct = canonicalize(t, RAW_RETURN, LONGS);
  29.218 +        if (ct == null)  ct = t;  // no prims to int-ify
  29.219 +        return primsAsLongs = ct;
  29.220 +    }
  29.221 +
  29.222 +    /** Stably sort parameters into 3 buckets: ref, int, long. */
  29.223 +    public MethodType primsAtEnd() {
  29.224 +        MethodType ct = primsAtEnd;
  29.225 +        if (ct != null)  return ct;
  29.226 +        MethodType t = erasedType;
  29.227 +
  29.228 +        int pac = primitiveParameterCount();
  29.229 +        if (pac == 0)
  29.230 +            return primsAtEnd = t;
  29.231 +
  29.232 +        int argc = parameterCount();
  29.233 +        int lac = longPrimitiveParameterCount();
  29.234 +        if (pac == argc && (lac == 0 || lac == argc))
  29.235 +            return primsAtEnd = t;
  29.236 +
  29.237 +        // known to have a mix of 2 or 3 of ref, int, long
  29.238 +        return primsAtEnd = reorderParameters(t, primsAtEndOrder(t), null);
  29.239 +
  29.240 +    }
  29.241 +
  29.242 +    /** Compute a new ordering of parameters so that all references
  29.243 +     *  are before all ints or longs, and all ints are before all longs.
  29.244 +     *  For this ordering, doubles count as longs, and all other primitive
  29.245 +     *  values count as ints.
  29.246 +     *  As a special case, if the parameters are already in the specified
  29.247 +     *  order, this method returns a null reference, rather than an array
  29.248 +     *  specifying a null permutation.
  29.249 +     *  <p>
  29.250 +     *  For example, the type {@code (int,boolean,int,Object,String)void}
  29.251 +     *  produces the order {@code {3,4,0,1,2}}, the type
  29.252 +     *  {@code (long,int,String)void} produces {@code {2,1,2}}, and
  29.253 +     *  the type {@code (Object,int)Object} produces {@code null}.
  29.254 +     */
  29.255 +    public static int[] primsAtEndOrder(MethodType mt) {
  29.256 +        MethodTypeImpl form = METHOD_TYPE_FRIEND.form(mt);
  29.257 +        if (form.primsAtEnd == form.erasedType)
  29.258 +            // quick check shows no reordering is necessary
  29.259 +            return null;
  29.260 +
  29.261 +        int argc = form.parameterCount();
  29.262 +        int[] paramOrder = new int[argc];
  29.263 +
  29.264 +        // 3-way bucket sort:
  29.265 +        int pac = form.primitiveParameterCount();
  29.266 +        int lac = form.longPrimitiveParameterCount();
  29.267 +        int rfill = 0, ifill = argc - pac, lfill = argc - lac;
  29.268 +
  29.269 +        Class<?>[] ptypes = METHOD_TYPE_FRIEND.ptypes(mt);
  29.270 +        boolean changed = false;
  29.271 +        for (int i = 0; i < ptypes.length; i++) {
  29.272 +            Class<?> pt = ptypes[i];
  29.273 +            int ord;
  29.274 +            if (!pt.isPrimitive())             ord = rfill++;
  29.275 +            else if (!hasTwoArgSlots(pt))      ord = ifill++;
  29.276 +            else                               ord = lfill++;
  29.277 +            if (ord != i)  changed = true;
  29.278 +            paramOrder[i] = ord;
  29.279 +        }
  29.280 +        assert(rfill == argc - pac && ifill == argc - lac && lfill == argc);
  29.281 +        if (!changed) {
  29.282 +            form.primsAtEnd = form.erasedType;
  29.283 +            return null;
  29.284 +        }
  29.285 +        return paramOrder;
  29.286 +    }
  29.287 +
  29.288 +    /** Put the existing parameters of mt into a new order, given by newParamOrder.
  29.289 +     *  The third argument is logically appended to mt.parameterArray,
  29.290 +     *  so that elements of newParamOrder can index either pre-existing or
  29.291 +     *  new parameter types.
  29.292 +     */
  29.293 +    public static MethodType reorderParameters(MethodType mt, int[] newParamOrder, Class<?>[] moreParams) {
  29.294 +        if (newParamOrder == null)  return mt;  // no-op reordering
  29.295 +        Class<?>[] ptypes = METHOD_TYPE_FRIEND.ptypes(mt);
  29.296 +        Class<?>[] ntypes = new Class<?>[newParamOrder.length];
  29.297 +        int ordMax = ptypes.length + (moreParams == null ? 0 : moreParams.length);
  29.298 +        boolean changed = (ntypes.length != ptypes.length);
  29.299 +        for (int i = 0; i < newParamOrder.length; i++) {
  29.300 +            int ord = newParamOrder[i];
  29.301 +            if (ord != i)  changed = true;
  29.302 +            Class<?> nt;
  29.303 +            if (ord < ptypes.length)   nt = ptypes[ord];
  29.304 +            else if (ord == ordMax)    nt = mt.returnType();
  29.305 +            else                       nt = moreParams[ord - ptypes.length];
  29.306 +            ntypes[i] = nt;
  29.307 +        }
  29.308 +        if (!changed)  return mt;
  29.309 +        return METHOD_TYPE_FRIEND.makeImpl(mt.returnType(), ntypes, true);
  29.310 +    }
  29.311 +
  29.312 +    private static boolean hasTwoArgSlots(Class<?> type) {
  29.313 +        return type == long.class || type == double.class;
  29.314 +    }
  29.315 +
  29.316 +    private static long pack(int a, int b, int c, int d) {
  29.317 +        assert(((a|b|c|d) & ~0xFFFF) == 0);
  29.318 +        long hw = ((a << 16) | b), lw = ((c << 16) | d);
  29.319 +        return (hw << 32) | lw;
  29.320 +    }
  29.321 +    private static char unpack(long packed, int word) { // word==0 => return a, ==3 => return d
  29.322 +        assert(word <= 3);
  29.323 +        return (char)(packed >> ((3-word) * 16));
  29.324 +    }
  29.325 +
  29.326 +    public int parameterCount() {                      // # outgoing values
  29.327 +        return unpack(argCounts, 3);
  29.328 +    }
  29.329 +    public int parameterSlotCount() {                  // # outgoing interpreter slots
  29.330 +        return unpack(argCounts, 2);
  29.331 +    }
  29.332 +    public int returnCount() {                         // = 0 (V), or 1
  29.333 +        return unpack(argCounts, 1);
  29.334 +    }
  29.335 +    public int returnSlotCount() {                     // = 0 (V), 2 (J/D), or 1
  29.336 +        return unpack(argCounts, 0);
  29.337 +    }
  29.338 +    public int primitiveParameterCount() {
  29.339 +        return unpack(primCounts, 3);
  29.340 +    }
  29.341 +    public int longPrimitiveParameterCount() {
  29.342 +        return unpack(primCounts, 2);
  29.343 +    }
  29.344 +    public int primitiveReturnCount() {                // = 0 (obj), or 1
  29.345 +        return unpack(primCounts, 1);
  29.346 +    }
  29.347 +    public int longPrimitiveReturnCount() {            // = 1 (J/D), or 0
  29.348 +        return unpack(primCounts, 0);
  29.349 +    }
  29.350 +    public boolean hasPrimitives() {
  29.351 +        return primCounts != 0;
  29.352 +    }
  29.353 +//    public boolean hasNonVoidPrimitives() {
  29.354 +//        if (primCounts == 0)  return false;
  29.355 +//        if (primitiveParameterCount() != 0)  return true;
  29.356 +//        return (primitiveReturnCount() != 0 && returnCount() != 0);
  29.357 +//    }
  29.358 +    public boolean hasLongPrimitives() {
  29.359 +        return (longPrimitiveParameterCount() | longPrimitiveReturnCount()) != 0;
  29.360 +    }
  29.361 +    public int parameterToArgSlot(int i) {
  29.362 +        return argToSlotTable[1+i];
  29.363 +    }
  29.364 +    public int argSlotToParameter(int argSlot) {
  29.365 +        // Note:  Empty slots are represented by zero in this table.
  29.366 +        // Valid arguments slots contain incremented entries, so as to be non-zero.
  29.367 +        // We return -1 the caller to mean an empty slot.
  29.368 +        return slotToArgTable[argSlot] - 1;
  29.369 +    }
  29.370 +
  29.371 +    public static void initForm(Access token, MethodType mt) {
  29.372 +        Access.check(token);
  29.373 +        MethodTypeImpl form = findForm(mt);
  29.374 +        METHOD_TYPE_FRIEND.setForm(mt, form);
  29.375 +        if (form.erasedType == mt) {
  29.376 +            // This is a principal (erased) type; show it to the JVM.
  29.377 +            MethodHandleImpl.init(token, mt);
  29.378 +        }
  29.379 +    }
  29.380 +
  29.381 +    static MethodTypeImpl findForm(MethodType mt) {
  29.382 +        MethodType erased = canonicalize(mt, ERASE, ERASE);
  29.383 +        if (erased == null) {
  29.384 +            // It is already erased.  Make a new MethodTypeForm.
  29.385 +            return METHOD_TYPE_FRIEND.newMethodTypeForm(mt);
  29.386 +        } else {
  29.387 +            // Share the MethodTypeForm with the erased version.
  29.388 +            return METHOD_TYPE_FRIEND.form(erased);
  29.389 +        }
  29.390 +    }
  29.391 +
  29.392 +    /** Codes for {@link #canonicalize(java.lang.Class, int).
  29.393 +     * ERASE means change every reference to {@code Object}.
  29.394 +     * WRAP means convert primitives (including {@code void} to their
  29.395 +     * corresponding wrapper types.  UNWRAP means the reverse of WRAP.
  29.396 +     * INTS means convert all non-void primitive types to int or long,
  29.397 +     * according to size.  LONGS means convert all non-void primitives
  29.398 +     * to long, regardless of size.  RAW_RETURN means convert a type
  29.399 +     * (assumed to be a return type) to int if it is smaller than an int,
  29.400 +     * or if it is void.
  29.401 +     */
  29.402 +    public static final int NO_CHANGE = 0, ERASE = 1, WRAP = 2, UNWRAP = 3, INTS = 4, LONGS = 5, RAW_RETURN = 6;
  29.403 +
  29.404 +    /** Canonicalize the types in the given method type.
  29.405 +     * If any types change, intern the new type, and return it.
  29.406 +     * Otherwise return null.
  29.407 +     */
  29.408 +    public static MethodType canonicalize(MethodType mt, int howRet, int howArgs) {
  29.409 +        Class<?>[] ptypes = METHOD_TYPE_FRIEND.ptypes(mt);
  29.410 +        Class<?>[] ptc = MethodTypeImpl.canonicalizes(ptypes, howArgs);
  29.411 +        Class<?> rtype = mt.returnType();
  29.412 +        Class<?> rtc = MethodTypeImpl.canonicalize(rtype, howRet);
  29.413 +        if (ptc == null && rtc == null) {
  29.414 +            // It is already canonical.
  29.415 +            return null;
  29.416 +        }
  29.417 +        // Find the erased version of the method type:
  29.418 +        if (rtc == null)  rtc = rtype;
  29.419 +        if (ptc == null)  ptc = ptypes;
  29.420 +        return METHOD_TYPE_FRIEND.makeImpl(rtc, ptc, true);
  29.421 +    }
  29.422 +
  29.423 +    /** Canonicalize the given return or param type.
  29.424 +     *  Return null if the type is already canonicalized.
  29.425 +     */
  29.426 +    static Class<?> canonicalize(Class<?> t, int how) {
  29.427 +        Class<?> ct;
  29.428 +        if (t == Object.class) {
  29.429 +            // no change, ever
  29.430 +        } else if (!t.isPrimitive()) {
  29.431 +            switch (how) {
  29.432 +                case UNWRAP:
  29.433 +                    ct = Wrapper.asPrimitiveType(t);
  29.434 +                    if (ct != t)  return ct;
  29.435 +                    break;
  29.436 +                case RAW_RETURN:
  29.437 +                case ERASE:
  29.438 +                    return Object.class;
  29.439 +            }
  29.440 +        } else if (t == void.class) {
  29.441 +            // no change, usually
  29.442 +            switch (how) {
  29.443 +                case RAW_RETURN:
  29.444 +                    return int.class;
  29.445 +                case WRAP:
  29.446 +                    return Void.class;
  29.447 +            }
  29.448 +        } else {
  29.449 +            // non-void primitive
  29.450 +            switch (how) {
  29.451 +                case WRAP:
  29.452 +                    return Wrapper.asWrapperType(t);
  29.453 +                case INTS:
  29.454 +                    if (t == int.class || t == long.class)
  29.455 +                        return null;  // no change
  29.456 +                    if (t == double.class)
  29.457 +                        return long.class;
  29.458 +                    return int.class;
  29.459 +                case LONGS:
  29.460 +                    if (t == long.class)
  29.461 +                        return null;  // no change
  29.462 +                    return long.class;
  29.463 +                case RAW_RETURN:
  29.464 +                    if (t == int.class || t == long.class ||
  29.465 +                        t == float.class || t == double.class)
  29.466 +                        return null;  // no change
  29.467 +                    // everything else returns as an int
  29.468 +                    return int.class;
  29.469 +            }
  29.470 +        }
  29.471 +        // no change; return null to signify
  29.472 +        return null;
  29.473 +    }
  29.474 +
  29.475 +    /** Canonicalize each param type in the given array.
  29.476 +     *  Return null if all types are already canonicalized.
  29.477 +     */
  29.478 +    static Class<?>[] canonicalizes(Class<?>[] ts, int how) {
  29.479 +        Class<?>[] cs = null;
  29.480 +        for (int imax = ts.length, i = 0; i < imax; i++) {
  29.481 +            Class<?> c = canonicalize(ts[i], how);
  29.482 +            if (c != null) {
  29.483 +                if (cs == null)
  29.484 +                    cs = ts.clone();
  29.485 +                cs[i] = c;
  29.486 +            }
  29.487 +        }
  29.488 +        return cs;
  29.489 +    }
  29.490 +
  29.491 +    public static Invokers invokers(Access token, MethodType type) {
  29.492 +        Access.check(token);
  29.493 +        Invokers inv = METHOD_TYPE_FRIEND.getInvokers(type);
  29.494 +        if (inv != null)  return inv;
  29.495 +        inv = new Invokers(token, type);
  29.496 +        METHOD_TYPE_FRIEND.setInvokers(type, inv);
  29.497 +        return inv;
  29.498 +    }
  29.499 +
  29.500 +    @Override
  29.501 +    public String toString() {
  29.502 +        return "Form"+erasedType;
  29.503 +    }
  29.504 +
  29.505 +}
    30.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    30.2 +++ b/src/share/classes/sun/dyn/ToGeneric.java	Tue May 05 22:40:09 2009 -0700
    30.3 @@ -0,0 +1,1018 @@
    30.4 +/*
    30.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    30.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    30.7 + *
    30.8 + * This code is free software; you can redistribute it and/or modify it
    30.9 + * under the terms of the GNU General Public License version 2 only, as
   30.10 + * published by the Free Software Foundation.  Sun designates this
   30.11 + * particular file as subject to the "Classpath" exception as provided
   30.12 + * by Sun in the LICENSE file that accompanied this code.
   30.13 + *
   30.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   30.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   30.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   30.17 + * version 2 for more details (a copy is included in the LICENSE file that
   30.18 + * accompanied this code).
   30.19 + *
   30.20 + * You should have received a copy of the GNU General Public License version
   30.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   30.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   30.23 + *
   30.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   30.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   30.26 + * have any questions.
   30.27 + */
   30.28 +
   30.29 +package sun.dyn;
   30.30 +
   30.31 +import java.dyn.JavaMethodHandle;
   30.32 +import java.dyn.MethodHandle;
   30.33 +import java.dyn.MethodHandles;
   30.34 +import java.dyn.MethodType;
   30.35 +import java.dyn.NoAccessException;
   30.36 +import java.lang.reflect.Constructor;
   30.37 +import java.lang.reflect.InvocationTargetException;
   30.38 +import sun.dyn.util.ValueConversions;
   30.39 +import sun.dyn.util.Wrapper;
   30.40 +
   30.41 +/**
   30.42 + * Adapters which mediate between incoming calls which are not generic
   30.43 + * and outgoing calls which are.  Any call can be represented generically
   30.44 + * boxing up its arguments, and (on return) unboxing the return value.
   30.45 + * <p>
   30.46 + * A call is "generic" (in MethodHandle terms) if its MethodType features
   30.47 + * only Object arguments.  A non-generic call therefore features
   30.48 + * primitives and/or reference types other than Object.
   30.49 + * An adapter has types for its incoming and outgoing calls.
   30.50 + * The incoming call type is simply determined by the adapter's type
   30.51 + * (the MethodType it presents to callers).  The outgoing call type
   30.52 + * is determined by the adapter's target (a MethodHandle that the adapter
   30.53 + * either binds internally or else takes as a leading argument).
   30.54 + * (To stretch the term, adapter-like method handles may have multiple
   30.55 + * targets or be polymorphic across multiple call types.)
   30.56 + * @author jrose
   30.57 + */
   30.58 +class ToGeneric {
   30.59 +    // type for the incoming call (may be erased)
   30.60 +    private final MethodType entryType;
   30.61 +    // incoming type with primitives moved to the end and turned to int/long
   30.62 +    private final MethodType rawEntryType;
   30.63 +    // adapter for the erased type
   30.64 +    private final Adapter adapter;
   30.65 +    // entry point for adapter (Adapter mh, a...) => ...
   30.66 +    private final MethodHandle entryPoint;
   30.67 +    // permutation of arguments for primsAtEndType
   30.68 +    private final int[] primsAtEndOrder;
   30.69 +    // optional final argument list conversions (at least, invokes the target)
   30.70 +    private final MethodHandle invoker;
   30.71 +    // conversion which unboxes a primitive return value
   30.72 +    private final MethodHandle returnConversion;
   30.73 +
   30.74 +    /** Compute and cache information common to all collecting adapters
   30.75 +     *  that implement members of the erasure-family of the given erased type.
   30.76 +     */
   30.77 +    private ToGeneric(MethodType entryType) {
   30.78 +        assert(entryType.erase() == entryType); // for now
   30.79 +        // incoming call will first "forget" all reference types except Object
   30.80 +        this.entryType = entryType;
   30.81 +        MethodHandle invoker0 = MethodHandles.exactInvoker(entryType.generic());
   30.82 +        MethodType rawEntryTypeInit;
   30.83 +        Adapter ad = findAdapter(rawEntryTypeInit = entryType);
   30.84 +        if (ad != null) {
   30.85 +            // Immediate hit to exactly the adapter we want,
   30.86 +            // with no monkeying around with primitive types.
   30.87 +            this.returnConversion = computeReturnConversion(entryType, rawEntryTypeInit, false);
   30.88 +            this.rawEntryType = rawEntryTypeInit;
   30.89 +            this.adapter = ad;
   30.90 +            this.entryPoint = ad.prototypeEntryPoint();
   30.91 +            this.primsAtEndOrder = null;
   30.92 +            this.invoker = invoker0;
   30.93 +            return;
   30.94 +        }
   30.95 +
   30.96 +        // next, it will reorder primitives after references
   30.97 +        MethodType primsAtEnd = MethodTypeImpl.of(entryType).primsAtEnd();
   30.98 +        // at the same time, it will "forget" all primitive types except int/long
   30.99 +        this.primsAtEndOrder = MethodTypeImpl.primsAtEndOrder(entryType);
  30.100 +        if (primsAtEndOrder != null) {
  30.101 +            // reordering is required; build on top of a simpler ToGeneric
  30.102 +            ToGeneric va2 = ToGeneric.of(primsAtEnd);
  30.103 +            this.adapter = va2.adapter;
  30.104 +            this.entryPoint = MethodHandleImpl.convertArguments(Access.TOKEN,
  30.105 +                    va2.entryPoint, primsAtEnd, entryType, primsAtEndOrder);
  30.106 +            // example: for entryType of (int,Object,Object), the reordered
  30.107 +            // type is (Object,Object,int) and the order is {1,2,0},
  30.108 +            // and putPAE is (mh,int0,obj1,obj2) => mh.invoke(obj1,obj2,int0)
  30.109 +            if (true) throw new UnsupportedOperationException("NYI");
  30.110 +            return;
  30.111 +        }
  30.112 +
  30.113 +        // after any needed argument reordering, it will reinterpret
  30.114 +        // primitive arguments according to their "raw" types int/long
  30.115 +        MethodType intsAtEnd = MethodTypeImpl.of(primsAtEnd).primsAsInts();
  30.116 +        ad = findAdapter(rawEntryTypeInit = intsAtEnd);
  30.117 +        if (ad == null) {
  30.118 +            // Perhaps the adapter is available only for longs.
  30.119 +            // If so, we can use it, but there will have to be a little
  30.120 +            // more stack motion on each call.
  30.121 +            MethodType longsAtEnd = MethodTypeImpl.of(primsAtEnd).primsAsLongs();
  30.122 +            ad = findAdapter(rawEntryTypeInit = longsAtEnd);
  30.123 +            if (ad == null) {
  30.124 +                // If there is no statically compiled adapter,
  30.125 +                // build one by means of dynamic bytecode generation.
  30.126 +                ad = buildAdapterFromBytecodes(rawEntryTypeInit = intsAtEnd);
  30.127 +            }
  30.128 +        }
  30.129 +        MethodHandle rawEntryPoint = ad.prototypeEntryPoint();
  30.130 +        MethodType tepType = entryType.insertParameterType(0, ad.getClass());
  30.131 +        this.entryPoint =
  30.132 +            AdapterMethodHandle.makeRawRetypeOnly(Access.TOKEN, tepType, rawEntryPoint);
  30.133 +        if (this.entryPoint == null)
  30.134 +            throw new UnsupportedOperationException("cannot retype to "+entryType
  30.135 +                    +" from "+rawEntryPoint.type().dropParameterType(0));
  30.136 +        this.returnConversion = computeReturnConversion(entryType, rawEntryTypeInit, false);
  30.137 +        this.rawEntryType = rawEntryTypeInit;
  30.138 +        this.adapter = ad;
  30.139 +        this.invoker = makeRawArgumentFilter(invoker0,
  30.140 +                rawEntryPoint.type().dropParameterType(0), entryType);
  30.141 +    }
  30.142 +
  30.143 +    /** A generic argument list will be created by a call of type 'raw'.
  30.144 +     *  The values need to be reboxed for to match 'cooked'.
  30.145 +     *  Do this on the fly.
  30.146 +     */
  30.147 +    // TO DO: Use a generic argument converter in a different file
  30.148 +    static MethodHandle makeRawArgumentFilter(MethodHandle invoker,
  30.149 +            MethodType raw, MethodType cooked) {
  30.150 +        MethodHandle filteredInvoker = null;
  30.151 +        for (int i = 0, nargs = raw.parameterCount(); i < nargs; i++) {
  30.152 +            Class<?> src = raw.parameterType(i);
  30.153 +            Class<?> dst = cooked.parameterType(i);
  30.154 +            if (src == dst)  continue;
  30.155 +            assert(src.isPrimitive() && dst.isPrimitive());
  30.156 +            if (filteredInvoker == null) {
  30.157 +                filteredInvoker =
  30.158 +                        AdapterMethodHandle.makeCheckCast(Access.TOKEN,
  30.159 +                            invoker.type().generic(), invoker, 0, MethodHandle.class);
  30.160 +                if (filteredInvoker == null)  throw new UnsupportedOperationException("NYI");
  30.161 +            }
  30.162 +            MethodHandle reboxer = ValueConversions.rebox(dst, false);
  30.163 +            FilterGeneric gen = new FilterGeneric(filteredInvoker.type(), (short)(1+i), (short)1, 'R');
  30.164 +            filteredInvoker = gen.makeInstance(reboxer, filteredInvoker);
  30.165 +        }
  30.166 +        if (filteredInvoker == null)  return invoker;
  30.167 +        return AdapterMethodHandle.makeRetypeOnly(Access.TOKEN, invoker.type(), filteredInvoker);
  30.168 +    }
  30.169 +
  30.170 +    /**
  30.171 +     * Caller will be expecting a result from a call to {@code type},
  30.172 +     * while the internal adapter entry point is rawEntryType.
  30.173 +     * Also, the internal target method will be returning a boxed value,
  30.174 +     * as an untyped object.
  30.175 +     * <p>
  30.176 +     * Produce a value converter which will be typed to convert from
  30.177 +     * {@code Object} to the return value of {@code rawEntryType}, and will
  30.178 +     * in fact ensure that the value is compatible with the return type of
  30.179 +     * {@code type}.
  30.180 +     */
  30.181 +    private static MethodHandle computeReturnConversion(
  30.182 +            MethodType type, MethodType rawEntryType, boolean mustCast) {
  30.183 +        Class<?> tret = type.returnType();
  30.184 +        Class<?> rret = rawEntryType.returnType();
  30.185 +        if (mustCast || !tret.isPrimitive()) {
  30.186 +            assert(!tret.isPrimitive());
  30.187 +            assert(!rret.isPrimitive());
  30.188 +            if (rret == Object.class && !mustCast)
  30.189 +                return null;
  30.190 +            return ValueConversions.cast(tret, false);
  30.191 +        } else if (tret == rret) {
  30.192 +            return ValueConversions.unbox(tret, false);
  30.193 +        } else {
  30.194 +            assert(rret.isPrimitive());
  30.195 +            assert(tret == double.class ? rret == long.class : rret == int.class);
  30.196 +            return ValueConversions.unboxRaw(tret, false);
  30.197 +        }
  30.198 +    }
  30.199 +
  30.200 +    Adapter makeInstance(MethodType type, MethodHandle genericTarget) {
  30.201 +        genericTarget.getClass();  // check for NPE
  30.202 +        MethodHandle convert = returnConversion;
  30.203 +        if (primsAtEndOrder != null)
  30.204 +            // reorder arguments passed to genericTarget, if primsAtEndOrder
  30.205 +            throw new UnsupportedOperationException("NYI");
  30.206 +        if (type == entryType) {
  30.207 +            if (convert == null)  convert = ValueConversions.identity();
  30.208 +            return adapter.makeInstance(entryPoint, invoker, convert, genericTarget);
  30.209 +        }
  30.210 +        // my erased-type is not exactly the same as the desired type
  30.211 +        assert(type.erase() == entryType);  // else we are busted
  30.212 +        if (convert == null)
  30.213 +            convert = computeReturnConversion(type, rawEntryType, true);
  30.214 +        // retype erased reference arguments (the cast makes it safe to do this)
  30.215 +        MethodType tepType = type.insertParameterType(0, adapter.getClass());
  30.216 +        MethodHandle typedEntryPoint =
  30.217 +            AdapterMethodHandle.makeRawRetypeOnly(Access.TOKEN, tepType, entryPoint);
  30.218 +        return adapter.makeInstance(typedEntryPoint, invoker, convert, genericTarget);
  30.219 +    }
  30.220 +
  30.221 +    /** Build an adapter of the given type, which invokes genericTarget
  30.222 +     *  on the incoming arguments, after boxing as necessary.
  30.223 +     *  The return value is unboxed if necessary.
  30.224 +     * @param type  the required type of the
  30.225 +     * @param genericTarget the target, which must accept and return only Object values
  30.226 +     * @return an adapter method handle
  30.227 +     */
  30.228 +    public static MethodHandle make(MethodType type, MethodHandle genericTarget) {
  30.229 +        MethodType gtype = genericTarget.type();
  30.230 +        if (type.generic() != gtype)
  30.231 +            throw new IllegalArgumentException();
  30.232 +        if (type == gtype)  return genericTarget;
  30.233 +        return ToGeneric.of(type).makeInstance(type, genericTarget);
  30.234 +    }
  30.235 +
  30.236 +    /** Return the adapter information for this type's erasure. */
  30.237 +    static ToGeneric of(MethodType type) {
  30.238 +        MethodTypeImpl form = MethodTypeImpl.of(type);
  30.239 +        ToGeneric toGen = form.toGeneric;
  30.240 +        if (toGen == null)
  30.241 +            form.toGeneric = toGen = new ToGeneric(form.erasedType());
  30.242 +        return toGen;
  30.243 +    }
  30.244 +
  30.245 +    public String toString() {
  30.246 +        return "ToGeneric"+entryType
  30.247 +                +(primsAtEndOrder!=null?"[reorder]":"");
  30.248 +    }
  30.249 +
  30.250 +    /* Create an adapter for the given incoming call type. */
  30.251 +    static Adapter findAdapter(MethodType entryPointType) {
  30.252 +        MethodTypeImpl form = MethodTypeImpl.of(entryPointType);
  30.253 +        Class<?> rtype = entryPointType.returnType();
  30.254 +        int argc = form.parameterCount();
  30.255 +        int lac = form.longPrimitiveParameterCount();
  30.256 +        int iac = form.primitiveParameterCount() - lac;
  30.257 +        String intsAndLongs = (iac > 0 ? "I"+iac : "")+(lac > 0 ? "J"+lac : "");
  30.258 +        String rawReturn = String.valueOf(Wrapper.forPrimitiveType(rtype).basicTypeChar());
  30.259 +        String iname0 = "invoke_"+rawReturn;
  30.260 +        String iname1 = "invoke";
  30.261 +        String[] inames = { iname0, iname1 };
  30.262 +        String cname0 = rawReturn + argc;
  30.263 +        String cname1 = "A"       + argc;
  30.264 +        String[] cnames = { cname1, cname1+intsAndLongs, cname0, cname0+intsAndLongs };
  30.265 +        // e.g., D5I2, D5, L5I2, L5
  30.266 +        for (String cname : cnames) {
  30.267 +            Class<? extends Adapter> acls = Adapter.findSubClass(cname);
  30.268 +            if (acls == null)  continue;
  30.269 +            // see if it has the required invoke method
  30.270 +            for (String iname : inames) {
  30.271 +                MethodHandle entryPoint = null;
  30.272 +                try {
  30.273 +                    entryPoint = MethodHandleImpl.IMPL_LOOKUP.
  30.274 +                                    findSpecial(acls, iname, entryPointType, acls);
  30.275 +                } catch (NoAccessException ex) {
  30.276 +                }
  30.277 +                if (entryPoint == null)  continue;
  30.278 +                Constructor<? extends Adapter> ctor = null;
  30.279 +                try {
  30.280 +                    // Prototype builder:
  30.281 +                    ctor = acls.getDeclaredConstructor(MethodHandle.class);
  30.282 +                } catch (NoSuchMethodException ex) {
  30.283 +                } catch (SecurityException ex) {
  30.284 +                }
  30.285 +                if (ctor == null)  continue;
  30.286 +                try {
  30.287 +                    return ctor.newInstance(entryPoint);
  30.288 +                } catch (IllegalArgumentException ex) {
  30.289 +                } catch (InvocationTargetException ex) {
  30.290 +                } catch (InstantiationException ex) {
  30.291 +                } catch (IllegalAccessException ex) {
  30.292 +                }
  30.293 +            }
  30.294 +        }
  30.295 +        return null;
  30.296 +    }
  30.297 +
  30.298 +    static Adapter buildAdapterFromBytecodes(MethodType entryPointType) {
  30.299 +        throw new UnsupportedOperationException("NYI");
  30.300 +    }
  30.301 +
  30.302 +    /**
  30.303 +     * The invoke method takes some particular but unconstrained spread
  30.304 +     * of raw argument types, and returns a raw return type (in L/I/J/F/D).
  30.305 +     * Internally, it converts the incoming arguments uniformly into objects.
  30.306 +     * This series of objects is then passed to the {@code target} method,
  30.307 +     * which returns a result object.  This result is finally converted,
  30.308 +     * via another method handle {@code convert}, which is responsible for
  30.309 +     * converting the object result into the raw return value.
  30.310 +     */
  30.311 +    static abstract class Adapter extends JavaMethodHandle {
  30.312 +        /*
  30.313 +         * class X<<R,A...>> extends Adapter {
  30.314 +         *   Object...=>Object target;
  30.315 +         *   Object=>R convert;
  30.316 +         *   R invoke(A... a...) = convert(invoker(target, a...)))
  30.317 +         * }
  30.318 +         */
  30.319 +        protected final MethodHandle invoker;  // (MH, Object...) -> Object
  30.320 +        protected final MethodHandle target;   // Object... -> Object
  30.321 +        protected final MethodHandle convert;  // Object -> R
  30.322 +
  30.323 +        protected boolean isPrototype() { return target == null; }
  30.324 +        /* Prototype constructor. */
  30.325 +        protected Adapter(MethodHandle entryPoint) {
  30.326 +            super(entryPoint);
  30.327 +            this.invoker = null;
  30.328 +            this.convert = entryPoint;
  30.329 +            this.target = null;
  30.330 +            assert(isPrototype());
  30.331 +        }
  30.332 +        protected MethodHandle prototypeEntryPoint() {
  30.333 +            if (!isPrototype())  throw new InternalError();
  30.334 +            return convert;
  30.335 +        }
  30.336 +
  30.337 +        protected Adapter(MethodHandle entryPoint, MethodHandle invoker, MethodHandle convert, MethodHandle target) {
  30.338 +            super(entryPoint);
  30.339 +            this.invoker = invoker;
  30.340 +            this.convert = convert;
  30.341 +            this.target = target;
  30.342 +        }
  30.343 +
  30.344 +        /** Make a copy of self, with new fields. */
  30.345 +        protected abstract Adapter makeInstance(MethodHandle entryPoint,
  30.346 +                MethodHandle invoker, MethodHandle convert, MethodHandle target);
  30.347 +        // { return new ThisType(entryPoint, convert, target); }
  30.348 +
  30.349 +        // Code to run when the arguments (<= 4) have all been boxed.
  30.350 +        protected Object target()               { return invoker.<Object>invoke(target); }
  30.351 +        protected Object target(Object a0)      { return invoker.<Object>invoke(target, a0); }
  30.352 +        protected Object target(Object a0, Object a1)
  30.353 +                                                { return invoker.<Object>invoke(target, a0, a1); }
  30.354 +        protected Object target(Object a0, Object a1, Object a2)
  30.355 +                                                { return invoker.<Object>invoke(target, a0, a1, a2); }
  30.356 +        protected Object target(Object a0, Object a1, Object a2, Object a3)
  30.357 +                                                { return invoker.<Object>invoke(target, a0, a1, a2, a3); }
  30.358 +        /*
  30.359 +        protected Object target_0(Object... av) { return invoker.<Object>invoke(target, av); }
  30.360 +        protected Object target_1(Object a0, Object... av)
  30.361 +                                                { return invoker.<Object>invoke(target, a0, (Object)av); }
  30.362 +        protected Object target_2(Object a0, Object a1, Object... av)
  30.363 +                                                { return invoker.<Object>invoke(target, a0, a1, (Object)av); }
  30.364 +        protected Object target_3(Object a0, Object a1, Object a2, Object... av)
  30.365 +                                                { return invoker.<Object>invoke(target, a0, a1, a2, (Object)av); }
  30.366 +        protected Object target_4(Object a0, Object a1, Object a2, Object a3, Object... av)
  30.367 +                                                { return invoker.<Object>invoke(target, a0, a1, a2, a3, (Object)av); }
  30.368 +        // */
  30.369 +        // (For more than 4 arguments, generate the code in the adapter itself.)
  30.370 +
  30.371 +        // Code to run when the generic target has finished and produced a value.
  30.372 +        protected Object return_L(Object res) { return convert.<Object>invoke(res); }
  30.373 +        protected int    return_I(Object res) { return convert.<int   >invoke(res); }
  30.374 +        protected long   return_J(Object res) { return convert.<long  >invoke(res); }
  30.375 +        protected float  return_F(Object res) { return convert.<float >invoke(res); }
  30.376 +        protected double return_D(Object res) { return convert.<double>invoke(res); }
  30.377 +
  30.378 +        static private final String CLASS_PREFIX; // "sun.dyn.ToGeneric$"
  30.379 +        static {
  30.380 +            String aname = Adapter.class.getName();
  30.381 +            String sname = Adapter.class.getSimpleName();
  30.382 +            if (!aname.endsWith(sname))  throw new InternalError();
  30.383 +            CLASS_PREFIX = aname.substring(0, aname.length() - sname.length());
  30.384 +        }
  30.385 +        /** Find a sibing class of Adapter. */
  30.386 +        static Class<? extends Adapter> findSubClass(String name) {
  30.387 +            String cname = Adapter.CLASS_PREFIX + name;
  30.388 +            try {
  30.389 +                return Class.forName(cname).asSubclass(Adapter.class);
  30.390 +            } catch (ClassNotFoundException ex) {
  30.391 +                return null;
  30.392 +            } catch (ClassCastException ex) {
  30.393 +                return null;
  30.394 +            }
  30.395 +        }
  30.396 +    }
  30.397 +
  30.398 +    /* generated classes follow this pattern:
  30.399 +    static class A1 extends Adapter {
  30.400 +        protected A1(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.401 +        protected A1(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.402 +        protected A1 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A1(e, i, c, t); }
  30.403 +        protected Object target(Object a0)    { return invoker.<Object>invoke(target, a0); }
  30.404 +        protected Object targetA1(Object a0) { return target(a0); }
  30.405 +        protected Object targetA1(int    a0) { return target(a0); }
  30.406 +        protected Object targetA1(long   a0) { return target(a0); }
  30.407 +        protected Object invoke_L(Object a0) { return return_L(targetA1(a0)); }
  30.408 +        protected int    invoke_I(Object a0) { return return_I(targetA1(a0)); }
  30.409 +        protected long   invoke_J(Object a0) { return return_J(targetA1(a0)); }
  30.410 +        protected float  invoke_F(Object a0) { return return_F(targetA1(a0)); }
  30.411 +        protected double invoke_D(Object a0) { return return_D(targetA1(a0)); }
  30.412 +        protected Object invoke_L(int    a0) { return return_L(targetA1(a0)); }
  30.413 +        protected int    invoke_I(int    a0) { return return_I(targetA1(a0)); }
  30.414 +        protected long   invoke_J(int    a0) { return return_J(targetA1(a0)); }
  30.415 +        protected float  invoke_F(int    a0) { return return_F(targetA1(a0)); }
  30.416 +        protected double invoke_D(int    a0) { return return_D(targetA1(a0)); }
  30.417 +        protected Object invoke_L(long   a0) { return return_L(targetA1(a0)); }
  30.418 +        protected int    invoke_I(long   a0) { return return_I(targetA1(a0)); }
  30.419 +        protected long   invoke_J(long   a0) { return return_J(targetA1(a0)); }
  30.420 +        protected float  invoke_F(long   a0) { return return_F(targetA1(a0)); }
  30.421 +        protected double invoke_D(long   a0) { return return_D(targetA1(a0)); }
  30.422 +    }
  30.423 +    // */
  30.424 +
  30.425 +/*
  30.426 +: SHELL; n=ToGeneric; cp -p $n.java $n.java-; sed < $n.java- > $n.java+ -e '/{{*{{/,/}}*}}/w /tmp/genclasses.java' -e '/}}*}}/q'; (cd /tmp; javac -d . genclasses.java; java -cp . genclasses) >> $n.java+; echo '}' >> $n.java+; mv $n.java+ $n.java; mv $n.java- $n.java~
  30.427 +//{{{
  30.428 +import java.util.*;
  30.429 +class genclasses {
  30.430 +    static String[] TYPES = { "Object", "int   ", "long  ", "float ", "double" };
  30.431 +    static String[] TCHARS = { "L",     "I",      "J",      "F",      "D",     "A" };
  30.432 +    static String[][] TEMPLATES = { {
  30.433 +        "@for@ arity=0..3   rcat<=4 nrefs<=99 nints<=99 nlongs<=99",
  30.434 +        "@for@ arity=4..5   rcat<=2 nrefs<=99 nints<=99 nlongs<=99",
  30.435 +        "@for@ arity=6..10  rcat<=2 nrefs<=99 nints=0   nlongs<=99",
  30.436 +        "    //@each-cat@",
  30.437 +        "    static class @cat@ extends Adapter {",
  30.438 +        "        protected @cat@(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype",
  30.439 +        "        protected @cat@(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }",
  30.440 +        "        protected @cat@ makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new @cat@(e, i, c, t); }",
  30.441 +        "        protected Object target(@Ovav@)   { return invoker.<Object>invoke(target, @av@); }",
  30.442 +        "        //@each-Tv@",
  30.443 +        "        protected Object target@cat@(@Tvav@) { return target(@av@); }",
  30.444 +        "        //@end-Tv@",
  30.445 +        "        //@each-Tv@",
  30.446 +        "        //@each-R@",
  30.447 +        "        protected @R@ invoke_@Rc@(@Tvav@) { return return_@Rc@(target@cat@(@av@)); }",
  30.448 +        "        //@end-R@",
  30.449 +        "        //@end-Tv@",
  30.450 +        "    }",
  30.451 +    } };
  30.452 +    enum VAR {
  30.453 +        cat, R, Rc, Tv, av, Tvav, Ovav;
  30.454 +        public final String pattern = "@"+toString().replace('_','.')+"@";
  30.455 +        public String binding;
  30.456 +        static void makeBindings(boolean topLevel, int rcat, int nrefs, int nints, int nlongs) {
  30.457 +            int nargs = nrefs + nints + nlongs;
  30.458 +            if (topLevel)
  30.459 +                VAR.cat.binding = catstr(ALL_RETURN_TYPES ? TYPES.length : rcat, nrefs, nints, nlongs);
  30.460 +            VAR.R.binding = TYPES[rcat];
  30.461 +            VAR.Rc.binding = TCHARS[rcat];
  30.462 +            String[] Tv = new String[nargs];
  30.463 +            String[] av = new String[nargs];
  30.464 +            String[] Tvav = new String[nargs];
  30.465 +            String[] Ovav = new String[nargs];
  30.466 +            for (int i = 0; i < nargs; i++) {
  30.467 +                int tcat = (i < nrefs) ? 0 : (i < nrefs + nints) ? 1 : 2;
  30.468 +                Tv[i] = TYPES[tcat];
  30.469 +                av[i] = arg(i);
  30.470 +                Tvav[i] = param(Tv[i], av[i]);
  30.471 +                Ovav[i] = param("Object", av[i]);
  30.472 +            }
  30.473 +            VAR.Tv.binding = comma(Tv);
  30.474 +            VAR.av.binding = comma(av);
  30.475 +            VAR.Tvav.binding = comma(Tvav);
  30.476 +            VAR.Ovav.binding = comma(Ovav);
  30.477 +        }
  30.478 +        static String arg(int i) { return "a"+i; }
  30.479 +        static String param(String t, String a) { return t+" "+a; }
  30.480 +        static String comma(String[] v) { return comma(v, ""); }
  30.481 +        static String comma(String sep, String[] v) {
  30.482 +            if (v.length == 0)  return "";
  30.483 +            String res = sep+v[0];
  30.484 +            for (int i = 1; i < v.length; i++)  res += ", "+v[i];
  30.485 +            return res;
  30.486 +        }
  30.487 +        static String transform(String string) {
  30.488 +            for (VAR var : values())
  30.489 +                string = string.replaceAll(var.pattern, var.binding);
  30.490 +            return string;
  30.491 +        }
  30.492 +    }
  30.493 +    static String[] stringsIn(String[] strings, int beg, int end) {
  30.494 +        return Arrays.copyOfRange(strings, beg, Math.min(end, strings.length));
  30.495 +    }
  30.496 +    static String[] stringsBefore(String[] strings, int pos) {
  30.497 +        return stringsIn(strings, 0, pos);
  30.498 +    }
  30.499 +    static String[] stringsAfter(String[] strings, int pos) {
  30.500 +        return stringsIn(strings, pos, strings.length);
  30.501 +    }
  30.502 +    static int indexAfter(String[] strings, int pos, String tag) {
  30.503 +        return Math.min(indexBefore(strings, pos, tag) + 1, strings.length);
  30.504 +    }
  30.505 +    static int indexBefore(String[] strings, int pos, String tag) {
  30.506 +        for (int i = pos, end = strings.length; ; i++) {
  30.507 +            if (i == end || strings[i].endsWith(tag))  return i;
  30.508 +        }
  30.509 +    }
  30.510 +    static int MIN_ARITY, MAX_ARITY, MAX_RCAT, MAX_REFS, MAX_INTS, MAX_LONGS;
  30.511 +    static boolean ALL_ARG_TYPES, ALL_RETURN_TYPES;
  30.512 +    static HashSet<String> done = new HashSet<String>();
  30.513 +    public static void main(String... av) {
  30.514 +        for (String[] template : TEMPLATES) {
  30.515 +            int forLinesLimit = indexBefore(template, 0, "@each-cat@");
  30.516 +            String[] forLines = stringsBefore(template, forLinesLimit);
  30.517 +            template = stringsAfter(template, forLinesLimit);
  30.518 +            for (String forLine : forLines)
  30.519 +                expandTemplate(forLine, template);
  30.520 +        }
  30.521 +    }
  30.522 +    static void expandTemplate(String forLine, String[] template) {
  30.523 +        String[] params = forLine.split("[^0-9]+");
  30.524 +        if (params[0].length() == 0)  params = stringsAfter(params, 1);
  30.525 +        System.out.println("//params="+Arrays.asList(params));
  30.526 +        int pcur = 0;
  30.527 +        MIN_ARITY = Integer.valueOf(params[pcur++]);
  30.528 +        MAX_ARITY = Integer.valueOf(params[pcur++]);
  30.529 +        MAX_RCAT  = Integer.valueOf(params[pcur++]);
  30.530 +        MAX_REFS  = Integer.valueOf(params[pcur++]);
  30.531 +        MAX_INTS  = Integer.valueOf(params[pcur++]);
  30.532 +        MAX_LONGS = Integer.valueOf(params[pcur++]);
  30.533 +        if (pcur != params.length)  throw new RuntimeException("bad extra param: "+forLine);
  30.534 +        if (MAX_RCAT >= TYPES.length)  MAX_RCAT = TYPES.length - 1;
  30.535 +        ALL_ARG_TYPES = (indexBefore(template, 0, "@each-Tv@") < template.length);
  30.536 +        ALL_RETURN_TYPES = (indexBefore(template, 0, "@each-R@") < template.length);
  30.537 +        for (int nargs = MIN_ARITY; nargs <= MAX_ARITY; nargs++) {
  30.538 +            for (int rcat = 0; rcat <= MAX_RCAT; rcat++) {
  30.539 +                expandTemplate(template, true, rcat, nargs, 0, 0);
  30.540 +                if (ALL_ARG_TYPES)  break;
  30.541 +                expandTemplateForPrims(template, true, rcat, nargs, 1, 1);
  30.542 +                if (ALL_RETURN_TYPES)  break;
  30.543 +            }
  30.544 +        }
  30.545 +    }
  30.546 +    static String catstr(int rcat, int nrefs, int nints, int nlongs) {
  30.547 +        int nargs = nrefs + nints + nlongs;
  30.548 +        String cat = TCHARS[rcat] + nargs;
  30.549 +        if (!ALL_ARG_TYPES)  cat += (nints==0?"":"I"+nints)+(nlongs==0?"":"J"+nlongs);
  30.550 +        return cat;
  30.551 +    }
  30.552 +    static void expandTemplateForPrims(String[] template, boolean topLevel, int rcat, int nargs, int minints, int minlongs) {
  30.553 +        for (int isLong = 0; isLong <= 1; isLong++) {
  30.554 +            for (int nprims = 1; nprims <= nargs; nprims++) {
  30.555 +                int nrefs = nargs - nprims;
  30.556 +                int nints = ((1-isLong) * nprims);
  30.557 +                int nlongs = (isLong * nprims);
  30.558 +                expandTemplate(template, topLevel, rcat, nrefs, nints, nlongs);
  30.559 +            }
  30.560 +        }
  30.561 +    }
  30.562 +    static void expandTemplate(String[] template, boolean topLevel,
  30.563 +                               int rcat, int nrefs, int nints, int nlongs) {
  30.564 +        int nargs = nrefs + nints + nlongs;
  30.565 +        if (nrefs > MAX_REFS || nints > MAX_INTS || nlongs > MAX_LONGS)  return;
  30.566 +        VAR.makeBindings(topLevel, rcat, nrefs, nints, nlongs);
  30.567 +        if (topLevel && !done.add(VAR.cat.binding)) {
  30.568 +            System.out.println("    //repeat "+VAR.cat.binding);
  30.569 +            return;
  30.570 +        }
  30.571 +        for (int i = 0; i < template.length; i++) {
  30.572 +            String line = template[i];
  30.573 +            if (line.endsWith("@each-cat@")) {
  30.574 +                // ignore
  30.575 +            } else if (line.endsWith("@each-R@")) {
  30.576 +                int blockEnd = indexAfter(template, i, "@end-R@");
  30.577 +                String[] block = stringsIn(template, i+1, blockEnd-1);
  30.578 +                for (int rcat1 = rcat; rcat1 <= MAX_RCAT; rcat1++)
  30.579 +                    expandTemplate(block, false, rcat1, nrefs, nints, nlongs);
  30.580 +                VAR.makeBindings(topLevel, rcat, nrefs, nints, nlongs);
  30.581 +                i = blockEnd-1; continue;
  30.582 +            } else if (line.endsWith("@each-Tv@")) {
  30.583 +                int blockEnd = indexAfter(template, i, "@end-Tv@");
  30.584 +                String[] block = stringsIn(template, i+1, blockEnd-1);
  30.585 +                expandTemplate(block, false, rcat, nrefs, nints, nlongs);
  30.586 +                expandTemplateForPrims(block, false, rcat, nargs, nints+1, nlongs+1);
  30.587 +                VAR.makeBindings(topLevel, rcat, nrefs, nints, nlongs);
  30.588 +                i = blockEnd-1; continue;
  30.589 +            } else {
  30.590 +                System.out.println(VAR.transform(line));
  30.591 +            }
  30.592 +        }
  30.593 +    }
  30.594 +}
  30.595 +//}}} */
  30.596 +//params=[0, 3, 4, 99, 99, 99]
  30.597 +    static class A0 extends Adapter {
  30.598 +        protected A0(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.599 +        protected A0(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.600 +        protected A0 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A0(e, i, c, t); }
  30.601 +        protected Object target()   { return invoker.<Object>invoke(target); }
  30.602 +        protected Object targetA0() { return target(); }
  30.603 +        protected Object invoke_L() { return return_L(targetA0()); }
  30.604 +        protected int    invoke_I() { return return_I(targetA0()); }
  30.605 +        protected long   invoke_J() { return return_J(targetA0()); }
  30.606 +        protected float  invoke_F() { return return_F(targetA0()); }
  30.607 +        protected double invoke_D() { return return_D(targetA0()); }
  30.608 +    }
  30.609 +    static class A1 extends Adapter {
  30.610 +        protected A1(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.611 +        protected A1(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.612 +        protected A1 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A1(e, i, c, t); }
  30.613 +        protected Object target(Object a0)   { return invoker.<Object>invoke(target, a0); }
  30.614 +        protected Object targetA1(Object a0) { return target(a0); }
  30.615 +        protected Object targetA1(int    a0) { return target(a0); }
  30.616 +        protected Object targetA1(long   a0) { return target(a0); }
  30.617 +        protected Object invoke_L(Object a0) { return return_L(targetA1(a0)); }
  30.618 +        protected int    invoke_I(Object a0) { return return_I(targetA1(a0)); }
  30.619 +        protected long   invoke_J(Object a0) { return return_J(targetA1(a0)); }
  30.620 +        protected float  invoke_F(Object a0) { return return_F(targetA1(a0)); }
  30.621 +        protected double invoke_D(Object a0) { return return_D(targetA1(a0)); }
  30.622 +        protected Object invoke_L(int    a0) { return return_L(targetA1(a0)); }
  30.623 +        protected int    invoke_I(int    a0) { return return_I(targetA1(a0)); }
  30.624 +        protected long   invoke_J(int    a0) { return return_J(targetA1(a0)); }
  30.625 +        protected float  invoke_F(int    a0) { return return_F(targetA1(a0)); }
  30.626 +        protected double invoke_D(int    a0) { return return_D(targetA1(a0)); }
  30.627 +        protected Object invoke_L(long   a0) { return return_L(targetA1(a0)); }
  30.628 +        protected int    invoke_I(long   a0) { return return_I(targetA1(a0)); }
  30.629 +        protected long   invoke_J(long   a0) { return return_J(targetA1(a0)); }
  30.630 +        protected float  invoke_F(long   a0) { return return_F(targetA1(a0)); }
  30.631 +        protected double invoke_D(long   a0) { return return_D(targetA1(a0)); }
  30.632 +    }
  30.633 +    static class A2 extends Adapter {
  30.634 +        protected A2(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.635 +        protected A2(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.636 +        protected A2 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A2(e, i, c, t); }
  30.637 +        protected Object target(Object a0, Object a1)   { return invoker.<Object>invoke(target, a0, a1); }
  30.638 +        protected Object targetA2(Object a0, Object a1) { return target(a0, a1); }
  30.639 +        protected Object targetA2(Object a0, int    a1) { return target(a0, a1); }
  30.640 +        protected Object targetA2(int    a0, int    a1) { return target(a0, a1); }
  30.641 +        protected Object targetA2(Object a0, long   a1) { return target(a0, a1); }
  30.642 +        protected Object targetA2(long   a0, long   a1) { return target(a0, a1); }
  30.643 +        protected Object invoke_L(Object a0, Object a1) { return return_L(targetA2(a0, a1)); }
  30.644 +        protected int    invoke_I(Object a0, Object a1) { return return_I(targetA2(a0, a1)); }
  30.645 +        protected long   invoke_J(Object a0, Object a1) { return return_J(targetA2(a0, a1)); }
  30.646 +        protected float  invoke_F(Object a0, Object a1) { return return_F(targetA2(a0, a1)); }
  30.647 +        protected double invoke_D(Object a0, Object a1) { return return_D(targetA2(a0, a1)); }
  30.648 +        protected Object invoke_L(Object a0, int    a1) { return return_L(targetA2(a0, a1)); }
  30.649 +        protected int    invoke_I(Object a0, int    a1) { return return_I(targetA2(a0, a1)); }
  30.650 +        protected long   invoke_J(Object a0, int    a1) { return return_J(targetA2(a0, a1)); }
  30.651 +        protected float  invoke_F(Object a0, int    a1) { return return_F(targetA2(a0, a1)); }
  30.652 +        protected double invoke_D(Object a0, int    a1) { return return_D(targetA2(a0, a1)); }
  30.653 +        protected Object invoke_L(int    a0, int    a1) { return return_L(targetA2(a0, a1)); }
  30.654 +        protected int    invoke_I(int    a0, int    a1) { return return_I(targetA2(a0, a1)); }
  30.655 +        protected long   invoke_J(int    a0, int    a1) { return return_J(targetA2(a0, a1)); }
  30.656 +        protected float  invoke_F(int    a0, int    a1) { return return_F(targetA2(a0, a1)); }
  30.657 +        protected double invoke_D(int    a0, int    a1) { return return_D(targetA2(a0, a1)); }
  30.658 +        protected Object invoke_L(Object a0, long   a1) { return return_L(targetA2(a0, a1)); }
  30.659 +        protected int    invoke_I(Object a0, long   a1) { return return_I(targetA2(a0, a1)); }
  30.660 +        protected long   invoke_J(Object a0, long   a1) { return return_J(targetA2(a0, a1)); }
  30.661 +        protected float  invoke_F(Object a0, long   a1) { return return_F(targetA2(a0, a1)); }
  30.662 +        protected double invoke_D(Object a0, long   a1) { return return_D(targetA2(a0, a1)); }
  30.663 +        protected Object invoke_L(long   a0, long   a1) { return return_L(targetA2(a0, a1)); }
  30.664 +        protected int    invoke_I(long   a0, long   a1) { return return_I(targetA2(a0, a1)); }
  30.665 +        protected long   invoke_J(long   a0, long   a1) { return return_J(targetA2(a0, a1)); }
  30.666 +        protected float  invoke_F(long   a0, long   a1) { return return_F(targetA2(a0, a1)); }
  30.667 +        protected double invoke_D(long   a0, long   a1) { return return_D(targetA2(a0, a1)); }
  30.668 +    }
  30.669 +    static class A3 extends Adapter {
  30.670 +        protected A3(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.671 +        protected A3(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.672 +        protected A3 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A3(e, i, c, t); }
  30.673 +        protected Object target(Object a0, Object a1, Object a2)   { return invoker.<Object>invoke(target, a0, a1, a2); }
  30.674 +        protected Object targetA3(Object a0, Object a1, Object a2) { return target(a0, a1, a2); }
  30.675 +        protected Object targetA3(Object a0, Object a1, int    a2) { return target(a0, a1, a2); }
  30.676 +        protected Object targetA3(Object a0, int    a1, int    a2) { return target(a0, a1, a2); }
  30.677 +        protected Object targetA3(int    a0, int    a1, int    a2) { return target(a0, a1, a2); }
  30.678 +        protected Object targetA3(Object a0, Object a1, long   a2) { return target(a0, a1, a2); }
  30.679 +        protected Object targetA3(Object a0, long   a1, long   a2) { return target(a0, a1, a2); }
  30.680 +        protected Object targetA3(long   a0, long   a1, long   a2) { return target(a0, a1, a2); }
  30.681 +        protected Object invoke_L(Object a0, Object a1, Object a2) { return return_L(targetA3(a0, a1, a2)); }
  30.682 +        protected int    invoke_I(Object a0, Object a1, Object a2) { return return_I(targetA3(a0, a1, a2)); }
  30.683 +        protected long   invoke_J(Object a0, Object a1, Object a2) { return return_J(targetA3(a0, a1, a2)); }
  30.684 +        protected float  invoke_F(Object a0, Object a1, Object a2) { return return_F(targetA3(a0, a1, a2)); }
  30.685 +        protected double invoke_D(Object a0, Object a1, Object a2) { return return_D(targetA3(a0, a1, a2)); }
  30.686 +        protected Object invoke_L(Object a0, Object a1, int    a2) { return return_L(targetA3(a0, a1, a2)); }
  30.687 +        protected int    invoke_I(Object a0, Object a1, int    a2) { return return_I(targetA3(a0, a1, a2)); }
  30.688 +        protected long   invoke_J(Object a0, Object a1, int    a2) { return return_J(targetA3(a0, a1, a2)); }
  30.689 +        protected float  invoke_F(Object a0, Object a1, int    a2) { return return_F(targetA3(a0, a1, a2)); }
  30.690 +        protected double invoke_D(Object a0, Object a1, int    a2) { return return_D(targetA3(a0, a1, a2)); }
  30.691 +        protected Object invoke_L(Object a0, int    a1, int    a2) { return return_L(targetA3(a0, a1, a2)); }
  30.692 +        protected int    invoke_I(Object a0, int    a1, int    a2) { return return_I(targetA3(a0, a1, a2)); }
  30.693 +        protected long   invoke_J(Object a0, int    a1, int    a2) { return return_J(targetA3(a0, a1, a2)); }
  30.694 +        protected float  invoke_F(Object a0, int    a1, int    a2) { return return_F(targetA3(a0, a1, a2)); }
  30.695 +        protected double invoke_D(Object a0, int    a1, int    a2) { return return_D(targetA3(a0, a1, a2)); }
  30.696 +        protected Object invoke_L(int    a0, int    a1, int    a2) { return return_L(targetA3(a0, a1, a2)); }
  30.697 +        protected int    invoke_I(int    a0, int    a1, int    a2) { return return_I(targetA3(a0, a1, a2)); }
  30.698 +        protected long   invoke_J(int    a0, int    a1, int    a2) { return return_J(targetA3(a0, a1, a2)); }
  30.699 +        protected float  invoke_F(int    a0, int    a1, int    a2) { return return_F(targetA3(a0, a1, a2)); }
  30.700 +        protected double invoke_D(int    a0, int    a1, int    a2) { return return_D(targetA3(a0, a1, a2)); }
  30.701 +        protected Object invoke_L(Object a0, Object a1, long   a2) { return return_L(targetA3(a0, a1, a2)); }
  30.702 +        protected int    invoke_I(Object a0, Object a1, long   a2) { return return_I(targetA3(a0, a1, a2)); }
  30.703 +        protected long   invoke_J(Object a0, Object a1, long   a2) { return return_J(targetA3(a0, a1, a2)); }
  30.704 +        protected float  invoke_F(Object a0, Object a1, long   a2) { return return_F(targetA3(a0, a1, a2)); }
  30.705 +        protected double invoke_D(Object a0, Object a1, long   a2) { return return_D(targetA3(a0, a1, a2)); }
  30.706 +        protected Object invoke_L(Object a0, long   a1, long   a2) { return return_L(targetA3(a0, a1, a2)); }
  30.707 +        protected int    invoke_I(Object a0, long   a1, long   a2) { return return_I(targetA3(a0, a1, a2)); }
  30.708 +        protected long   invoke_J(Object a0, long   a1, long   a2) { return return_J(targetA3(a0, a1, a2)); }
  30.709 +        protected float  invoke_F(Object a0, long   a1, long   a2) { return return_F(targetA3(a0, a1, a2)); }
  30.710 +        protected double invoke_D(Object a0, long   a1, long   a2) { return return_D(targetA3(a0, a1, a2)); }
  30.711 +        protected Object invoke_L(long   a0, long   a1, long   a2) { return return_L(targetA3(a0, a1, a2)); }
  30.712 +        protected int    invoke_I(long   a0, long   a1, long   a2) { return return_I(targetA3(a0, a1, a2)); }
  30.713 +        protected long   invoke_J(long   a0, long   a1, long   a2) { return return_J(targetA3(a0, a1, a2)); }
  30.714 +        protected float  invoke_F(long   a0, long   a1, long   a2) { return return_F(targetA3(a0, a1, a2)); }
  30.715 +        protected double invoke_D(long   a0, long   a1, long   a2) { return return_D(targetA3(a0, a1, a2)); }
  30.716 +    }
  30.717 +//params=[4, 5, 2, 99, 99, 99]
  30.718 +    static class A4 extends Adapter {
  30.719 +        protected A4(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.720 +        protected A4(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.721 +        protected A4 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A4(e, i, c, t); }
  30.722 +        protected Object target(Object a0, Object a1, Object a2, Object a3)   { return invoker.<Object>invoke(target, a0, a1, a2, a3); }
  30.723 +        protected Object targetA4(Object a0, Object a1, Object a2, Object a3) { return target(a0, a1, a2, a3); }
  30.724 +        protected Object targetA4(Object a0, Object a1, Object a2, int    a3) { return target(a0, a1, a2, a3); }
  30.725 +        protected Object targetA4(Object a0, Object a1, int    a2, int    a3) { return target(a0, a1, a2, a3); }
  30.726 +        protected Object targetA4(Object a0, int    a1, int    a2, int    a3) { return target(a0, a1, a2, a3); }
  30.727 +        protected Object targetA4(int    a0, int    a1, int    a2, int    a3) { return target(a0, a1, a2, a3); }
  30.728 +        protected Object targetA4(Object a0, Object a1, Object a2, long   a3) { return target(a0, a1, a2, a3); }
  30.729 +        protected Object targetA4(Object a0, Object a1, long   a2, long   a3) { return target(a0, a1, a2, a3); }
  30.730 +        protected Object targetA4(Object a0, long   a1, long   a2, long   a3) { return target(a0, a1, a2, a3); }
  30.731 +        protected Object targetA4(long   a0, long   a1, long   a2, long   a3) { return target(a0, a1, a2, a3); }
  30.732 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3) { return return_L(targetA4(a0, a1, a2, a3)); }
  30.733 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3) { return return_I(targetA4(a0, a1, a2, a3)); }
  30.734 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3) { return return_J(targetA4(a0, a1, a2, a3)); }
  30.735 +        protected Object invoke_L(Object a0, Object a1, Object a2, int    a3) { return return_L(targetA4(a0, a1, a2, a3)); }
  30.736 +        protected int    invoke_I(Object a0, Object a1, Object a2, int    a3) { return return_I(targetA4(a0, a1, a2, a3)); }
  30.737 +        protected long   invoke_J(Object a0, Object a1, Object a2, int    a3) { return return_J(targetA4(a0, a1, a2, a3)); }
  30.738 +        protected Object invoke_L(Object a0, Object a1, int    a2, int    a3) { return return_L(targetA4(a0, a1, a2, a3)); }
  30.739 +        protected int    invoke_I(Object a0, Object a1, int    a2, int    a3) { return return_I(targetA4(a0, a1, a2, a3)); }
  30.740 +        protected long   invoke_J(Object a0, Object a1, int    a2, int    a3) { return return_J(targetA4(a0, a1, a2, a3)); }
  30.741 +        protected Object invoke_L(Object a0, int    a1, int    a2, int    a3) { return return_L(targetA4(a0, a1, a2, a3)); }
  30.742 +        protected int    invoke_I(Object a0, int    a1, int    a2, int    a3) { return return_I(targetA4(a0, a1, a2, a3)); }
  30.743 +        protected long   invoke_J(Object a0, int    a1, int    a2, int    a3) { return return_J(targetA4(a0, a1, a2, a3)); }
  30.744 +        protected Object invoke_L(int    a0, int    a1, int    a2, int    a3) { return return_L(targetA4(a0, a1, a2, a3)); }
  30.745 +        protected int    invoke_I(int    a0, int    a1, int    a2, int    a3) { return return_I(targetA4(a0, a1, a2, a3)); }
  30.746 +        protected long   invoke_J(int    a0, int    a1, int    a2, int    a3) { return return_J(targetA4(a0, a1, a2, a3)); }
  30.747 +        protected Object invoke_L(Object a0, Object a1, Object a2, long   a3) { return return_L(targetA4(a0, a1, a2, a3)); }
  30.748 +        protected int    invoke_I(Object a0, Object a1, Object a2, long   a3) { return return_I(targetA4(a0, a1, a2, a3)); }
  30.749 +        protected long   invoke_J(Object a0, Object a1, Object a2, long   a3) { return return_J(targetA4(a0, a1, a2, a3)); }
  30.750 +        protected Object invoke_L(Object a0, Object a1, long   a2, long   a3) { return return_L(targetA4(a0, a1, a2, a3)); }
  30.751 +        protected int    invoke_I(Object a0, Object a1, long   a2, long   a3) { return return_I(targetA4(a0, a1, a2, a3)); }
  30.752 +        protected long   invoke_J(Object a0, Object a1, long   a2, long   a3) { return return_J(targetA4(a0, a1, a2, a3)); }
  30.753 +        protected Object invoke_L(Object a0, long   a1, long   a2, long   a3) { return return_L(targetA4(a0, a1, a2, a3)); }
  30.754 +        protected int    invoke_I(Object a0, long   a1, long   a2, long   a3) { return return_I(targetA4(a0, a1, a2, a3)); }
  30.755 +        protected long   invoke_J(Object a0, long   a1, long   a2, long   a3) { return return_J(targetA4(a0, a1, a2, a3)); }
  30.756 +        protected Object invoke_L(long   a0, long   a1, long   a2, long   a3) { return return_L(targetA4(a0, a1, a2, a3)); }
  30.757 +        protected int    invoke_I(long   a0, long   a1, long   a2, long   a3) { return return_I(targetA4(a0, a1, a2, a3)); }
  30.758 +        protected long   invoke_J(long   a0, long   a1, long   a2, long   a3) { return return_J(targetA4(a0, a1, a2, a3)); }
  30.759 +    }
  30.760 +    static class A5 extends Adapter {
  30.761 +        protected A5(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.762 +        protected A5(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.763 +        protected A5 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A5(e, i, c, t); }
  30.764 +        protected Object target(Object a0, Object a1, Object a2, Object a3, Object a4)   { return invoker.<Object>invoke(target, a0, a1, a2, a3, a4); }
  30.765 +        protected Object targetA5(Object a0, Object a1, Object a2, Object a3, Object a4) { return target(a0, a1, a2, a3, a4); }
  30.766 +        protected Object targetA5(Object a0, Object a1, Object a2, Object a3, int    a4) { return target(a0, a1, a2, a3, a4); }
  30.767 +        protected Object targetA5(Object a0, Object a1, Object a2, int    a3, int    a4) { return target(a0, a1, a2, a3, a4); }
  30.768 +        protected Object targetA5(Object a0, Object a1, int    a2, int    a3, int    a4) { return target(a0, a1, a2, a3, a4); }
  30.769 +        protected Object targetA5(Object a0, int    a1, int    a2, int    a3, int    a4) { return target(a0, a1, a2, a3, a4); }
  30.770 +        protected Object targetA5(int    a0, int    a1, int    a2, int    a3, int    a4) { return target(a0, a1, a2, a3, a4); }
  30.771 +        protected Object targetA5(Object a0, Object a1, Object a2, Object a3, long   a4) { return target(a0, a1, a2, a3, a4); }
  30.772 +        protected Object targetA5(Object a0, Object a1, Object a2, long   a3, long   a4) { return target(a0, a1, a2, a3, a4); }
  30.773 +        protected Object targetA5(Object a0, Object a1, long   a2, long   a3, long   a4) { return target(a0, a1, a2, a3, a4); }
  30.774 +        protected Object targetA5(Object a0, long   a1, long   a2, long   a3, long   a4) { return target(a0, a1, a2, a3, a4); }
  30.775 +        protected Object targetA5(long   a0, long   a1, long   a2, long   a3, long   a4) { return target(a0, a1, a2, a3, a4); }
  30.776 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.777 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.778 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.779 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, int    a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.780 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, int    a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.781 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, int    a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.782 +        protected Object invoke_L(Object a0, Object a1, Object a2, int    a3, int    a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.783 +        protected int    invoke_I(Object a0, Object a1, Object a2, int    a3, int    a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.784 +        protected long   invoke_J(Object a0, Object a1, Object a2, int    a3, int    a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.785 +        protected Object invoke_L(Object a0, Object a1, int    a2, int    a3, int    a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.786 +        protected int    invoke_I(Object a0, Object a1, int    a2, int    a3, int    a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.787 +        protected long   invoke_J(Object a0, Object a1, int    a2, int    a3, int    a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.788 +        protected Object invoke_L(Object a0, int    a1, int    a2, int    a3, int    a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.789 +        protected int    invoke_I(Object a0, int    a1, int    a2, int    a3, int    a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.790 +        protected long   invoke_J(Object a0, int    a1, int    a2, int    a3, int    a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.791 +        protected Object invoke_L(int    a0, int    a1, int    a2, int    a3, int    a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.792 +        protected int    invoke_I(int    a0, int    a1, int    a2, int    a3, int    a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.793 +        protected long   invoke_J(int    a0, int    a1, int    a2, int    a3, int    a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.794 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, long   a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.795 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, long   a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.796 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, long   a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.797 +        protected Object invoke_L(Object a0, Object a1, Object a2, long   a3, long   a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.798 +        protected int    invoke_I(Object a0, Object a1, Object a2, long   a3, long   a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.799 +        protected long   invoke_J(Object a0, Object a1, Object a2, long   a3, long   a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.800 +        protected Object invoke_L(Object a0, Object a1, long   a2, long   a3, long   a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.801 +        protected int    invoke_I(Object a0, Object a1, long   a2, long   a3, long   a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.802 +        protected long   invoke_J(Object a0, Object a1, long   a2, long   a3, long   a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.803 +        protected Object invoke_L(Object a0, long   a1, long   a2, long   a3, long   a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.804 +        protected int    invoke_I(Object a0, long   a1, long   a2, long   a3, long   a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.805 +        protected long   invoke_J(Object a0, long   a1, long   a2, long   a3, long   a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.806 +        protected Object invoke_L(long   a0, long   a1, long   a2, long   a3, long   a4) { return return_L(targetA5(a0, a1, a2, a3, a4)); }
  30.807 +        protected int    invoke_I(long   a0, long   a1, long   a2, long   a3, long   a4) { return return_I(targetA5(a0, a1, a2, a3, a4)); }
  30.808 +        protected long   invoke_J(long   a0, long   a1, long   a2, long   a3, long   a4) { return return_J(targetA5(a0, a1, a2, a3, a4)); }
  30.809 +    }
  30.810 +//params=[6, 10, 2, 99, 0, 99]
  30.811 +    static class A6 extends Adapter {
  30.812 +        protected A6(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.813 +        protected A6(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.814 +        protected A6 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A6(e, i, c, t); }
  30.815 +        protected Object target(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5)   { return invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5); }
  30.816 +        protected Object targetA6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return target(a0, a1, a2, a3, a4, a5); }
  30.817 +        protected Object targetA6(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5) { return target(a0, a1, a2, a3, a4, a5); }
  30.818 +        protected Object targetA6(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5) { return target(a0, a1, a2, a3, a4, a5); }
  30.819 +        protected Object targetA6(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5) { return target(a0, a1, a2, a3, a4, a5); }
  30.820 +        protected Object targetA6(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5) { return target(a0, a1, a2, a3, a4, a5); }
  30.821 +        protected Object targetA6(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5) { return target(a0, a1, a2, a3, a4, a5); }
  30.822 +        protected Object targetA6(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5) { return target(a0, a1, a2, a3, a4, a5); }
  30.823 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return return_L(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.824 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return return_I(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.825 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return return_J(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.826 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5) { return return_L(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.827 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5) { return return_I(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.828 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5) { return return_J(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.829 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5) { return return_L(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.830 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5) { return return_I(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.831 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5) { return return_J(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.832 +        protected Object invoke_L(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5) { return return_L(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.833 +        protected int    invoke_I(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5) { return return_I(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.834 +        protected long   invoke_J(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5) { return return_J(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.835 +        protected Object invoke_L(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5) { return return_L(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.836 +        protected int    invoke_I(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5) { return return_I(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.837 +        protected long   invoke_J(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5) { return return_J(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.838 +        protected Object invoke_L(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5) { return return_L(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.839 +        protected int    invoke_I(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5) { return return_I(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.840 +        protected long   invoke_J(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5) { return return_J(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.841 +        protected Object invoke_L(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5) { return return_L(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.842 +        protected int    invoke_I(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5) { return return_I(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.843 +        protected long   invoke_J(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5) { return return_J(targetA6(a0, a1, a2, a3, a4, a5)); }
  30.844 +    }
  30.845 +    static class A7 extends Adapter {
  30.846 +        protected A7(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.847 +        protected A7(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.848 +        protected A7 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A7(e, i, c, t); }
  30.849 +        protected Object target(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6)   { return invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5, a6); }
  30.850 +        protected Object targetA7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return target(a0, a1, a2, a3, a4, a5, a6); }
  30.851 +        protected Object targetA7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6) { return target(a0, a1, a2, a3, a4, a5, a6); }
  30.852 +        protected Object targetA7(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6) { return target(a0, a1, a2, a3, a4, a5, a6); }
  30.853 +        protected Object targetA7(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6) { return target(a0, a1, a2, a3, a4, a5, a6); }
  30.854 +        protected Object targetA7(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6) { return target(a0, a1, a2, a3, a4, a5, a6); }
  30.855 +        protected Object targetA7(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return target(a0, a1, a2, a3, a4, a5, a6); }
  30.856 +        protected Object targetA7(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return target(a0, a1, a2, a3, a4, a5, a6); }
  30.857 +        protected Object targetA7(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return target(a0, a1, a2, a3, a4, a5, a6); }
  30.858 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return return_L(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.859 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return return_I(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.860 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return return_J(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.861 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6) { return return_L(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.862 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6) { return return_I(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.863 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6) { return return_J(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.864 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6) { return return_L(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.865 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6) { return return_I(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.866 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6) { return return_J(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.867 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6) { return return_L(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.868 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6) { return return_I(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.869 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6) { return return_J(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.870 +        protected Object invoke_L(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6) { return return_L(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.871 +        protected int    invoke_I(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6) { return return_I(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.872 +        protected long   invoke_J(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6) { return return_J(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.873 +        protected Object invoke_L(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return return_L(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.874 +        protected int    invoke_I(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return return_I(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.875 +        protected long   invoke_J(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return return_J(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.876 +        protected Object invoke_L(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return return_L(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.877 +        protected int    invoke_I(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return return_I(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.878 +        protected long   invoke_J(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return return_J(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.879 +        protected Object invoke_L(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return return_L(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.880 +        protected int    invoke_I(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return return_I(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.881 +        protected long   invoke_J(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6) { return return_J(targetA7(a0, a1, a2, a3, a4, a5, a6)); }
  30.882 +    }
  30.883 +    static class A8 extends Adapter {
  30.884 +        protected A8(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.885 +        protected A8(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.886 +        protected A8 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A8(e, i, c, t); }
  30.887 +        protected Object target(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7)   { return invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5, a6, a7); }
  30.888 +        protected Object targetA8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return target(a0, a1, a2, a3, a4, a5, a6, a7); }
  30.889 +        protected Object targetA8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7) { return target(a0, a1, a2, a3, a4, a5, a6, a7); }
  30.890 +        protected Object targetA8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7) { return target(a0, a1, a2, a3, a4, a5, a6, a7); }
  30.891 +        protected Object targetA8(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7) { return target(a0, a1, a2, a3, a4, a5, a6, a7); }
  30.892 +        protected Object targetA8(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7) { return target(a0, a1, a2, a3, a4, a5, a6, a7); }
  30.893 +        protected Object targetA8(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return target(a0, a1, a2, a3, a4, a5, a6, a7); }
  30.894 +        protected Object targetA8(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return target(a0, a1, a2, a3, a4, a5, a6, a7); }
  30.895 +        protected Object targetA8(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return target(a0, a1, a2, a3, a4, a5, a6, a7); }
  30.896 +        protected Object targetA8(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return target(a0, a1, a2, a3, a4, a5, a6, a7); }
  30.897 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return return_L(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.898 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return return_I(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.899 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return return_J(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.900 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7) { return return_L(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.901 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7) { return return_I(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.902 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7) { return return_J(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.903 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7) { return return_L(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.904 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7) { return return_I(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.905 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7) { return return_J(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.906 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7) { return return_L(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.907 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7) { return return_I(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.908 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7) { return return_J(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.909 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7) { return return_L(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.910 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7) { return return_I(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.911 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7) { return return_J(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.912 +        protected Object invoke_L(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_L(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.913 +        protected int    invoke_I(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_I(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.914 +        protected long   invoke_J(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_J(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.915 +        protected Object invoke_L(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_L(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.916 +        protected int    invoke_I(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_I(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.917 +        protected long   invoke_J(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_J(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.918 +        protected Object invoke_L(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_L(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.919 +        protected int    invoke_I(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_I(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.920 +        protected long   invoke_J(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_J(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.921 +        protected Object invoke_L(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_L(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.922 +        protected int    invoke_I(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_I(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.923 +        protected long   invoke_J(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7) { return return_J(targetA8(a0, a1, a2, a3, a4, a5, a6, a7)); }
  30.924 +    }
  30.925 +    static class A9 extends Adapter {
  30.926 +        protected A9(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.927 +        protected A9(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.928 +        protected A9 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A9(e, i, c, t); }
  30.929 +        protected Object target(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8)   { return invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.930 +        protected Object targetA9(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.931 +        protected Object targetA9(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, long   a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.932 +        protected Object targetA9(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7, long   a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.933 +        protected Object targetA9(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7, long   a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.934 +        protected Object targetA9(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7, long   a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.935 +        protected Object targetA9(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.936 +        protected Object targetA9(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.937 +        protected Object targetA9(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.938 +        protected Object targetA9(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.939 +        protected Object targetA9(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
  30.940 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.941 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.942 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.943 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, long   a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.944 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, long   a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.945 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, long   a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.946 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7, long   a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.947 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7, long   a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.948 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7, long   a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.949 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7, long   a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.950 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7, long   a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.951 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7, long   a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.952 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7, long   a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.953 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7, long   a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.954 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7, long   a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.955 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.956 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.957 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.958 +        protected Object invoke_L(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.959 +        protected int    invoke_I(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.960 +        protected long   invoke_J(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.961 +        protected Object invoke_L(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.962 +        protected int    invoke_I(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.963 +        protected long   invoke_J(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.964 +        protected Object invoke_L(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.965 +        protected int    invoke_I(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.966 +        protected long   invoke_J(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.967 +        protected Object invoke_L(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_L(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.968 +        protected int    invoke_I(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_I(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.969 +        protected long   invoke_J(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8) { return return_J(targetA9(a0, a1, a2, a3, a4, a5, a6, a7, a8)); }
  30.970 +    }
  30.971 +    static class A10 extends Adapter {
  30.972 +        protected A10(MethodHandle entryPoint) { super(entryPoint); }  // to build prototype
  30.973 +        protected A10(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { super(e, i, c, t); }
  30.974 +        protected A10 makeInstance(MethodHandle e, MethodHandle i, MethodHandle c, MethodHandle t) { return new A10(e, i, c, t); }
  30.975 +        protected Object target(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9)   { return invoker.<Object>invoke(target, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.976 +        protected Object targetA10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.977 +        protected Object targetA10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.978 +        protected Object targetA10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, long   a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.979 +        protected Object targetA10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7, long   a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.980 +        protected Object targetA10(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7, long   a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.981 +        protected Object targetA10(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.982 +        protected Object targetA10(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.983 +        protected Object targetA10(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.984 +        protected Object targetA10(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.985 +        protected Object targetA10(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.986 +        protected Object targetA10(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return target(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
  30.987 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.988 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.989 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.990 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.991 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.992 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.993 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, long   a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.994 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, long   a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.995 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, long   a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.996 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7, long   a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.997 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7, long   a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.998 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, long   a7, long   a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
  30.999 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7, long   a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1000 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7, long   a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1001 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, long   a6, long   a7, long   a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1002 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1003 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1004 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, Object a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1005 +        protected Object invoke_L(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1006 +        protected int    invoke_I(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1007 +        protected long   invoke_J(Object a0, Object a1, Object a2, Object a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1008 +        protected Object invoke_L(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1009 +        protected int    invoke_I(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1010 +        protected long   invoke_J(Object a0, Object a1, Object a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1011 +        protected Object invoke_L(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1012 +        protected int    invoke_I(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1013 +        protected long   invoke_J(Object a0, Object a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1014 +        protected Object invoke_L(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1015 +        protected int    invoke_I(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1016 +        protected long   invoke_J(Object a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1017 +        protected Object invoke_L(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_L(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1018 +        protected int    invoke_I(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_I(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1019 +        protected long   invoke_J(long   a0, long   a1, long   a2, long   a3, long   a4, long   a5, long   a6, long   a7, long   a8, long   a9) { return return_J(targetA10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
 30.1020 +    }
 30.1021 +}
    31.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    31.2 +++ b/src/share/classes/sun/dyn/anon/AnonymousClassLoader.java	Tue May 05 22:40:09 2009 -0700
    31.3 @@ -0,0 +1,297 @@
    31.4 +/*
    31.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    31.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    31.7 + *
    31.8 + * This code is free software; you can redistribute it and/or modify it
    31.9 + * under the terms of the GNU General Public License version 2 only, as
   31.10 + * published by the Free Software Foundation.  Sun designates this
   31.11 + * particular file as subject to the "Classpath" exception as provided
   31.12 + * by Sun in the LICENSE file that accompanied this code.
   31.13 + *
   31.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   31.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   31.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   31.17 + * version 2 for more details (a copy is included in the LICENSE file that
   31.18 + * accompanied this code).
   31.19 + *
   31.20 + * You should have received a copy of the GNU General Public License version
   31.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   31.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   31.23 + *
   31.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   31.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   31.26 + * have any questions.
   31.27 + */
   31.28 +
   31.29 +package sun.dyn.anon;
   31.30 +
   31.31 +import java.io.IOException;
   31.32 +import java.io.InputStream;
   31.33 +import java.lang.reflect.InvocationTargetException;
   31.34 +import java.lang.reflect.Method;
   31.35 +
   31.36 +/**
   31.37 + * Anonymous class loader.  Will load any valid classfile, producing
   31.38 + * a {@link Class} metaobject, without installing that class in the
   31.39 + * system dictionary.  Therefore, {@link Class#forName(String)} will never
   31.40 + * produce a reference to an anonymous class.
   31.41 + * <p>
   31.42 + * The access permissions of the anonymous class are borrowed from
   31.43 + * a <em>host class</em>.  The new class behaves as if it were an
   31.44 + * inner class of the host class.  It can access the host's private
   31.45 + * members, if the creator of the class loader has permission to
   31.46 + * do so (or to create accessible reflective objects).
   31.47 + * <p>
   31.48 + * When the anonymous class is loaded, elements of its constant pool
   31.49 + * can be patched to new values.  This provides a hook to pre-resolve
   31.50 + * named classes in the constant pool to other classes, including
   31.51 + * anonymous ones.  Also, string constants can be pre-resolved to
   31.52 + * any reference.  (The verifier treats non-string, non-class reference
   31.53 + * constants as plain objects.)
   31.54 + *  <p>
   31.55 + * Why include the patching function?  It makes some use cases much easier.
   31.56 + * Second, the constant pool needed some internal patching anyway,
   31.57 + * to anonymize the loaded class itself.  Finally, if you are going
   31.58 + * to use this seriously, you'll want to build anonymous classes
   31.59 + * on top of pre-existing anonymous classes, and that requires patching.
   31.60 + *
   31.61 + * <p>%%% TO-DO:
   31.62 + * <ul>
   31.63 + * <li>needs better documentation</li>
   31.64 + * <li>needs more security work (for safe delegation)</li>
   31.65 + * <li>needs a clearer story about error processing</li>
   31.66 + * <li>patch member references also (use ';' as delimiter char)</li>
   31.67 + * <li>patch method references to (conforming) method handles</li>
   31.68 + * </ul>
   31.69 + *
   31.70 + * @author jrose
   31.71 + * @author Remi Forax
   31.72 + * @see <a href="http://blogs.sun.com/jrose/entry/anonymous_classes_in_the_vm">
   31.73 + *      http://blogs.sun.com/jrose/entry/anonymous_classes_in_the_vm</a>
   31.74 + */
   31.75 +
   31.76 +public class AnonymousClassLoader {
   31.77 +    final Class<?> hostClass;
   31.78 +
   31.79 +    // Note: Do not refactor the calls to checkHostClass unless you
   31.80 +    //       also adjust this constant:
   31.81 +    private static int CHC_CALLERS = 3;
   31.82 +
   31.83 +    public AnonymousClassLoader() {
   31.84 +        this.hostClass = checkHostClass(null);
   31.85 +    }
   31.86 +    public AnonymousClassLoader(Class<?> hostClass) {
   31.87 +        this.hostClass = checkHostClass(hostClass);
   31.88 +    }
   31.89 +
   31.90 +    private static Class<?> getTopLevelClass(Class<?> clazz) {
   31.91 +      for(Class<?> outer = clazz.getDeclaringClass(); outer != null;
   31.92 +          outer = outer.getDeclaringClass()) {
   31.93 +        clazz = outer;
   31.94 +      }
   31.95 +      return clazz;
   31.96 +    }
   31.97 +
   31.98 +    private static Class<?> checkHostClass(Class<?> hostClass) {
   31.99 +        // called only from the constructor
  31.100 +        // does a context-sensitive check on caller class
  31.101 +        // CC[0..3] = {Reflection, this.checkHostClass, this.<init>, caller}
  31.102 +        Class<?> caller = sun.reflect.Reflection.getCallerClass(CHC_CALLERS);
  31.103 +
  31.104 +        if (caller == null) {
  31.105 +            // called from the JVM directly
  31.106 +            if (hostClass == null)
  31.107 +                return AnonymousClassLoader.class; // anything central will do
  31.108 +            return hostClass;
  31.109 +        }
  31.110 +
  31.111 +        if (hostClass == null)
  31.112 +            hostClass = caller; // default value is caller itself
  31.113 +
  31.114 +        // anonymous class will access hostClass on behalf of caller
  31.115 +        Class<?> callee = hostClass;
  31.116 +
  31.117 +        if (caller == callee)
  31.118 +            // caller can always nominate itself to grant caller's own access rights
  31.119 +            return hostClass;
  31.120 +
  31.121 +        // normalize caller and callee to their top-level classes:
  31.122 +        caller = getTopLevelClass(caller);
  31.123 +        callee = getTopLevelClass(callee);
  31.124 +        if (caller == callee)
  31.125 +            return caller;
  31.126 +
  31.127 +        ClassLoader callerCL = caller.getClassLoader();
  31.128 +        if (callerCL == null) {
  31.129 +            // caller is trusted code, so accept the proposed hostClass
  31.130 +            return hostClass;
  31.131 +        }
  31.132 +
  31.133 +        // %%% should do something with doPrivileged, because trusted
  31.134 +        // code should have a way to execute on behalf of
  31.135 +        // partially-trusted clients
  31.136 +
  31.137 +        // Does the caller have the right to access the private
  31.138 +        // members of the callee?  If not, raise an error.
  31.139 +        final int ACC_PRIVATE = 2;
  31.140 +        try {
  31.141 +            sun.reflect.Reflection.ensureMemberAccess(caller, callee, null, ACC_PRIVATE);
  31.142 +        } catch (IllegalAccessException ee) {
  31.143 +            throw new IllegalArgumentException(ee);
  31.144 +        }
  31.145 +
  31.146 +        return hostClass;
  31.147 +    }
  31.148 +
  31.149 +    public Class<?> loadClass(byte[] classFile) {
  31.150 +        if (defineAnonymousClass == null) {
  31.151 +            // no JVM support; try to fake an approximation
  31.152 +            try {
  31.153 +                return fakeLoadClass(new ConstantPoolParser(classFile).createPatch());
  31.154 +            } catch (InvalidConstantPoolFormatException ee) {
  31.155 +                throw new IllegalArgumentException(ee);
  31.156 +            }
  31.157 +        }
  31.158 +        return loadClass(classFile, null);
  31.159 +    }
  31.160 +
  31.161 +    public Class<?> loadClass(ConstantPoolPatch classPatch) {
  31.162 +        if (defineAnonymousClass == null) {
  31.163 +            // no JVM support; try to fake an approximation
  31.164 +            return fakeLoadClass(classPatch);
  31.165 +        }
  31.166 +        Object[] patches = classPatch.patchArray;
  31.167 +        // Convert class names (this late in the game)
  31.168 +        // to use slash '/' instead of dot '.'.
  31.169 +        // Java likes dots, but the JVM likes slashes.
  31.170 +        for (int i = 0; i < patches.length; i++) {
  31.171 +            Object value = patches[i];
  31.172 +            if (value != null) {
  31.173 +                byte tag = classPatch.getTag(i);
  31.174 +                switch (tag) {
  31.175 +                case ConstantPoolVisitor.CONSTANT_Class:
  31.176 +                    if (value instanceof String) {
  31.177 +                        if (patches == classPatch.patchArray)
  31.178 +                            patches = patches.clone();
  31.179 +                        patches[i] = ((String)value).replace('.', '/');
  31.180 +                    }
  31.181 +                    break;
  31.182 +                case ConstantPoolVisitor.CONSTANT_Fieldref:
  31.183 +                case ConstantPoolVisitor.CONSTANT_Methodref:
  31.184 +                case ConstantPoolVisitor.CONSTANT_InterfaceMethodref:
  31.185 +                case ConstantPoolVisitor.CONSTANT_NameAndType:
  31.186 +                    // When/if the JVM supports these patches,
  31.187 +                    // we'll probably need to reformat them also.
  31.188 +                    // Meanwhile, let the class loader create the error.
  31.189 +                    break;
  31.190 +                }
  31.191 +            }
  31.192 +        }
  31.193 +        return loadClass(classPatch.outer.classFile, classPatch.patchArray);
  31.194 +    }
  31.195 +
  31.196 +    private Class<?> loadClass(byte[] classFile, Object[] patchArray) {
  31.197 +        try {
  31.198 +            return (Class<?>)
  31.199 +                defineAnonymousClass.invoke(unsafe,
  31.200 +                                            hostClass, classFile, patchArray);
  31.201 +        } catch (Exception ex) {
  31.202 +            throwReflectedException(ex);
  31.203 +            throw new RuntimeException("error loading into "+hostClass, ex);
  31.204 +        }
  31.205 +    }
  31.206 +
  31.207 +    private static void throwReflectedException(Exception ex) {
  31.208 +        if (ex instanceof InvocationTargetException) {
  31.209 +            Throwable tex = ((InvocationTargetException)ex).getTargetException();
  31.210 +            if (tex instanceof Error)
  31.211 +                throw (Error) tex;
  31.212 +            ex = (Exception) tex;
  31.213 +        }
  31.214 +        if (ex instanceof RuntimeException) {
  31.215 +            throw (RuntimeException) ex;
  31.216 +        }
  31.217 +    }
  31.218 +
  31.219 +    private Class<?> fakeLoadClass(ConstantPoolPatch classPatch) {
  31.220 +        // Implementation:
  31.221 +        // 1. Make up a new name nobody has used yet.
  31.222 +        // 2. Inspect the tail-header of the class to find the this_class index.
  31.223 +        // 3. Patch the CONSTANT_Class for this_class to the new name.
  31.224 +        // 4. Add other CP entries required by (e.g.) string patches.
  31.225 +        // 5. Flatten Class constants down to their names, making sure that
  31.226 +        //    the host class loader can pick them up again accurately.
  31.227 +        // 6. Generate the edited class file bytes.
  31.228 +        //
  31.229 +        // Potential limitations:
  31.230 +        // * The class won't be truly anonymous, and may interfere with others.
  31.231 +        // * Flattened class constants might not work, because of loader issues.
  31.232 +        // * Pseudo-string constants will not flatten down to real strings.
  31.233 +        // * Method handles will (of course) fail to flatten to linkage strings.
  31.234 +        if (true)  throw new UnsupportedOperationException("NYI");
  31.235 +        Object[] cpArray;
  31.236 +        try {
  31.237 +            cpArray = classPatch.getOriginalCP();
  31.238 +        } catch (InvalidConstantPoolFormatException ex) {
  31.239 +            throw new RuntimeException(ex);
  31.240 +        }
  31.241 +        int thisClassIndex = classPatch.getParser().getThisClassIndex();
  31.242 +        String thisClassName = (String) cpArray[thisClassIndex];
  31.243 +        synchronized (AnonymousClassLoader.class) {
  31.244 +            thisClassName = thisClassName+"\\|"+(++fakeNameCounter);
  31.245 +        }
  31.246 +        classPatch.putUTF8(thisClassIndex, thisClassName);
  31.247 +        byte[] classFile = null;
  31.248 +        return unsafe.defineClass(null, classFile, 0, classFile.length,
  31.249 +                                  hostClass.getClassLoader(),
  31.250 +                                  hostClass.getProtectionDomain());
  31.251 +    }
  31.252 +    private static int fakeNameCounter = 99999;
  31.253 +
  31.254 +    // ignore two warnings on this line:
  31.255 +    static sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
  31.256 +    // preceding line requires that this class be on the boot class path
  31.257 +
  31.258 +    static private final Method defineAnonymousClass;
  31.259 +    static {
  31.260 +        Method dac = null;
  31.261 +        Class<? extends sun.misc.Unsafe> unsafeClass = unsafe.getClass();
  31.262 +        try {
  31.263 +            dac = unsafeClass.getMethod("defineAnonymousClass",
  31.264 +                                        Class.class,
  31.265 +                                        byte[].class,
  31.266 +                                        Object[].class);
  31.267 +        } catch (Exception ee) {
  31.268 +            dac = null;
  31.269 +        }
  31.270 +        defineAnonymousClass = dac;
  31.271 +    }
  31.272 +
  31.273 +    private static void noJVMSupport() {
  31.274 +        throw new UnsupportedOperationException("no JVM support for anonymous classes");
  31.275 +    }
  31.276 +
  31.277 +
  31.278 +    private static native Class<?> loadClassInternal(Class<?> hostClass,
  31.279 +                                                     byte[] classFile,
  31.280 +                                                     Object[] patchArray);
  31.281 +
  31.282 +    public static byte[] readClassFile(Class<?> templateClass) throws IOException {
  31.283 +        String templateName = templateClass.getName();
  31.284 +        int lastDot = templateName.lastIndexOf('.');
  31.285 +        java.net.URL url = templateClass.getResource(templateName.substring(lastDot+1)+".class");
  31.286 +        java.net.URLConnection connection = url.openConnection();
  31.287 +        int contentLength = connection.getContentLength();
  31.288 +        if (contentLength < 0)
  31.289 +            throw new IOException("invalid content length "+contentLength);
  31.290 +
  31.291 +        byte[] classFile = new byte[contentLength];
  31.292 +        InputStream tcs = connection.getInputStream();
  31.293 +        for (int fill = 0, nr; fill < classFile.length; fill += nr) {
  31.294 +            nr = tcs.read(classFile, fill, classFile.length - fill);
  31.295 +            if (nr < 0)
  31.296 +                throw new IOException("premature end of file");
  31.297 +        }
  31.298 +        return classFile;
  31.299 +    }
  31.300 +}
    32.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    32.2 +++ b/src/share/classes/sun/dyn/anon/ConstantPoolParser.java	Tue May 05 22:40:09 2009 -0700
    32.3 @@ -0,0 +1,368 @@
    32.4 +/*
    32.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    32.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    32.7 + *
    32.8 + * This code is free software; you can redistribute it and/or modify it
    32.9 + * under the terms of the GNU General Public License version 2 only, as
   32.10 + * published by the Free Software Foundation.  Sun designates this
   32.11 + * particular file as subject to the "Classpath" exception as provided
   32.12 + * by Sun in the LICENSE file that accompanied this code.
   32.13 + *
   32.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   32.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   32.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   32.17 + * version 2 for more details (a copy is included in the LICENSE file that
   32.18 + * accompanied this code).
   32.19 + *
   32.20 + * You should have received a copy of the GNU General Public License version
   32.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   32.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   32.23 + *
   32.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   32.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   32.26 + * have any questions.
   32.27 + */
   32.28 +
   32.29 +package sun.dyn.anon;
   32.30 +
   32.31 +import java.io.IOException;
   32.32 +import java.io.OutputStream;
   32.33 +import java.nio.BufferUnderflowException;
   32.34 +import java.nio.ByteBuffer;
   32.35 +
   32.36 +import static sun.dyn.anon.ConstantPoolVisitor.*;
   32.37 +
   32.38 +/** A constant pool parser.
   32.39 + */
   32.40 +public class ConstantPoolParser {
   32.41 +    final byte[] classFile;
   32.42 +    final byte[] tags;
   32.43 +    final char[] firstHeader;  // maghi, maglo, minor, major, cplen
   32.44 +
   32.45 +    // these are filled in on first parse:
   32.46 +    int endOffset;
   32.47 +    char[] secondHeader;       // flags, this_class, super_class, intlen
   32.48 +
   32.49 +    // used to decode UTF8 array
   32.50 +    private char[] charArray = new char[80];
   32.51 +
   32.52 +    /** Creates a constant pool parser.
   32.53 +     * @param classFile an array of bytes containing a class.
   32.54 +     * @throws InvalidConstantPoolFormatException if the header of the class has errors.
   32.55 +     */
   32.56 +    public ConstantPoolParser(byte[] classFile) throws InvalidConstantPoolFormatException {
   32.57 +        this.classFile = classFile;
   32.58 +        this.firstHeader = parseHeader(classFile);
   32.59 +        this.tags = new byte[firstHeader[4]];
   32.60 +    }
   32.61 +
   32.62 +    /** Create a constant pool parser by loading the bytecodes of the
   32.63 +     *  class taken as argument.
   32.64 +     *
   32.65 +     * @param templateClass the class to parse.
   32.66 +     *
   32.67 +     * @throws IOException raised if an I/O occurs when loading
   32.68 +     *  the bytecode of the template class.
   32.69 +     * @throws InvalidConstantPoolFormatException if the header of the class has errors.
   32.70 +     *
   32.71 +     * @see #ConstantPoolParser(byte[])
   32.72 +     * @see AnonymousClassLoader#readClassFile(Class)
   32.73 +     */
   32.74 +    public ConstantPoolParser(Class<?> templateClass) throws IOException, InvalidConstantPoolFormatException {
   32.75 +        this(AnonymousClassLoader.readClassFile(templateClass));
   32.76 +    }
   32.77 +
   32.78 +    /** Creates an empty patch to patch the class file
   32.79 +     *  used by the current parser.
   32.80 +     * @return a new class patch.
   32.81 +     */
   32.82 +    public ConstantPoolPatch createPatch() {
   32.83 +        return new ConstantPoolPatch(this);
   32.84 +    }
   32.85 +
   32.86 +    /** Report the tag of the indicated CP entry.
   32.87 +     * @param index
   32.88 +     * @return one of {@link ConstantPoolVisitor#CONSTANT_Utf8}, etc.
   32.89 +     */
   32.90 +    public byte getTag(int index) {
   32.91 +        getEndOffset();  // trigger an exception if we haven't parsed yet
   32.92 +        return tags[index];
   32.93 +    }
   32.94 +
   32.95 +    /** Report the length of the constant pool. */
   32.96 +    public int getLength() {
   32.97 +        return firstHeader[4];
   32.98 +    }
   32.99 +
  32.100 +    /** Report the offset, within the class file, of the start of the constant pool. */
  32.101 +    public int getStartOffset() {
  32.102 +        return firstHeader.length * 2;
  32.103 +    }
  32.104 +
  32.105 +    /** Report the offset, within the class file, of the end of the constant pool. */
  32.106 +    public int getEndOffset() {
  32.107 +        if (endOffset == 0)
  32.108 +            throw new IllegalStateException("class file has not yet been parsed");
  32.109 +        return endOffset;
  32.110 +    }
  32.111 +
  32.112 +    /** Report the CP index of this class's own name. */
  32.113 +    public int getThisClassIndex() {
  32.114 +        getEndOffset();   // provoke exception if not yet parsed
  32.115 +        return secondHeader[1];
  32.116 +    }
  32.117 +
  32.118 +    /** Report the total size of the class file. */
  32.119 +    public int getTailLength() {
  32.120 +        return classFile.length - getEndOffset();
  32.121 +    }
  32.122 +
  32.123 +    /** Write the head (header plus constant pool)
  32.124 +     *  of the class file to the indicated stream.
  32.125 +     */
  32.126 +    public void writeHead(OutputStream out) throws IOException {
  32.127 +        out.write(classFile, 0, getEndOffset());
  32.128 +    }
  32.129 +
  32.130 +    /** Write the head (header plus constant pool)
  32.131 +     *  of the class file to the indicated stream,
  32.132 +     *  incorporating the non-null entries of the given array
  32.133 +     *  as patches.
  32.134 +     */
  32.135 +    void writePatchedHead(OutputStream out, Object[] patchArray) {
  32.136 +        // this will be useful to partially emulate the class loader on old JVMs
  32.137 +        throw new UnsupportedOperationException("Not yet implemented");
  32.138 +    }
  32.139 +
  32.140 +    /** Write the tail (everything after the constant pool)
  32.141 +     *  of the class file to the indicated stream.
  32.142 +     */
  32.143 +    public void writeTail(OutputStream out) throws IOException {
  32.144 +        out.write(classFile, getEndOffset(), getTailLength());
  32.145 +    }
  32.146 +
  32.147 +    private static char[] parseHeader(byte[] classFile) throws InvalidConstantPoolFormatException {
  32.148 +        char[] result = new char[5];
  32.149 +        ByteBuffer buffer = ByteBuffer.wrap(classFile);
  32.150 +        for (int i = 0; i < result.length; i++)
  32.151 +            result[i] = (char) getUnsignedShort(buffer);
  32.152 +        int magic = result[0] << 16 | result[1] << 0;
  32.153 +        if (magic != 0xCAFEBABE)
  32.154 +            throw new InvalidConstantPoolFormatException("invalid magic number "+magic);
  32.155 +        // skip major, minor version
  32.156 +        int len = result[4];
  32.157 +        if (len < 1)
  32.158 +            throw new InvalidConstantPoolFormatException("constant pool length < 1");
  32.159 +        return result;
  32.160 +    }
  32.161 +
  32.162 +    /** Parse the constant pool of the class
  32.163 +     *  calling a method visit* each time a constant pool entry is parsed.
  32.164 +     *
  32.165 +     *  The order of the calls to visit* is not guaranteed to be the same
  32.166 +     *  than the order of the constant pool entry in the bytecode array.
  32.167 +     *
  32.168 +     * @param visitor
  32.169 +     * @throws InvalidConstantPoolFormatException
  32.170 +     */
  32.171 +    public void parse(ConstantPoolVisitor visitor) throws InvalidConstantPoolFormatException {
  32.172 +        ByteBuffer buffer = ByteBuffer.wrap(classFile);
  32.173 +        buffer.position(getStartOffset()); //skip header
  32.174 +
  32.175 +        Object[] values = new Object[getLength()];
  32.176 +        try {
  32.177 +            parseConstantPool(buffer, values, visitor);
  32.178 +        } catch(BufferUnderflowException e) {
  32.179 +            throw new InvalidConstantPoolFormatException(e);
  32.180 +        }
  32.181 +        if (endOffset == 0) {
  32.182 +            endOffset = buffer.position();
  32.183 +            secondHeader = new char[4];
  32.184 +            for (int i = 0; i < secondHeader.length; i++) {
  32.185 +                secondHeader[i] = (char) getUnsignedShort(buffer);
  32.186 +            }
  32.187 +        }
  32.188 +        resolveConstantPool(values, visitor);
  32.189 +    }
  32.190 +
  32.191 +    private char[] getCharArray(int utfLength) {
  32.192 +        if (utfLength <= charArray.length)
  32.193 +            return charArray;
  32.194 +        return charArray = new char[utfLength];
  32.195 +    }
  32.196 +
  32.197 +    private void parseConstantPool(ByteBuffer buffer, Object[] values, ConstantPoolVisitor visitor) throws InvalidConstantPoolFormatException {
  32.198 +        for (int i = 1; i < tags.length; ) {
  32.199 +            byte tag = (byte) getUnsignedByte(buffer);
  32.200 +            assert(tags[i] == 0 || tags[i] == tag);
  32.201 +            tags[i] = tag;
  32.202 +            switch (tag) {
  32.203 +                case CONSTANT_Utf8:
  32.204 +                    int utfLen = getUnsignedShort(buffer);
  32.205 +                    String value = getUTF8(buffer, utfLen, getCharArray(utfLen));
  32.206 +                    visitor.visitUTF8(i, CONSTANT_Utf8, value);
  32.207 +                    tags[i] = tag;
  32.208 +                    values[i++] = value;
  32.209 +                    break;
  32.210 +                case CONSTANT_Integer:
  32.211 +                    visitor.visitConstantValue(i, tag, buffer.getInt());
  32.212 +                    i++;
  32.213 +                    break;
  32.214 +                case CONSTANT_Float:
  32.215 +                    visitor.visitConstantValue(i, tag, buffer.getFloat());
  32.216 +                    i++;
  32.217 +                    break;
  32.218 +                case CONSTANT_Long:
  32.219 +                    visitor.visitConstantValue(i, tag, buffer.getLong());
  32.220 +                    i+=2;
  32.221 +                    break;
  32.222 +                case CONSTANT_Double:
  32.223 +                    visitor.visitConstantValue(i, tag, buffer.getDouble());
  32.224 +                    i+=2;
  32.225 +                    break;
  32.226 +
  32.227 +                case CONSTANT_Class:    // fall through:
  32.228 +                case CONSTANT_String:
  32.229 +                    tags[i] = tag;
  32.230 +                    values[i++] = new int[] { getUnsignedShort(buffer) };
  32.231 +                    break;
  32.232 +
  32.233 +                case CONSTANT_Fieldref:           // fall through:
  32.234 +                case CONSTANT_Methodref:          // fall through:
  32.235 +                case CONSTANT_InterfaceMethodref: // fall through:
  32.236 +                case CONSTANT_NameAndType:
  32.237 +                    tags[i] = tag;
  32.238 +                    values[i++] = new int[] { getUnsignedShort(buffer), getUnsignedShort(buffer) };
  32.239 +                    break;
  32.240 +                default:
  32.241 +                    throw new AssertionError("invalid constant "+tag);
  32.242 +            }
  32.243 +        }
  32.244 +    }
  32.245 +
  32.246 +    private void resolveConstantPool(Object[] values, ConstantPoolVisitor visitor) {
  32.247 +        // clean out the int[] values, which are temporary
  32.248 +        for (int beg = 1, end = values.length-1, beg2, end2;
  32.249 +             beg <= end;
  32.250 +             beg = beg2, end = end2) {
  32.251 +             beg2 = end; end2 = beg-1;
  32.252 +             //System.out.println("CP resolve pass: "+beg+".."+end);
  32.253 +             for (int i = beg; i <= end; i++) {
  32.254 +                  Object value = values[i];
  32.255 +                  if (!(value instanceof int[]))
  32.256 +                      continue;
  32.257 +                  int[] array = (int[]) value;
  32.258 +                  byte tag = tags[i];
  32.259 +                  switch (tag) {
  32.260 +                      case CONSTANT_String:
  32.261 +                          String stringBody = (String) values[array[0]];
  32.262 +                          visitor.visitConstantString(i, tag, stringBody, array[0]);
  32.263 +                          values[i] = null;
  32.264 +                          break;
  32.265 +                      case CONSTANT_Class: {
  32.266 +                          String className = (String) values[array[0]];
  32.267 +                          // use the external form favored by Class.forName:
  32.268 +                          className = className.replace('/', '.');
  32.269 +                          visitor.visitConstantString(i, tag, className, array[0]);
  32.270 +                          values[i] = className;
  32.271 +                          break;
  32.272 +                      }
  32.273 +                      case CONSTANT_NameAndType: {
  32.274 +                          String memberName = (String) values[array[0]];
  32.275 +                          String signature  = (String) values[array[1]];
  32.276 +                          visitor.visitDescriptor(i, tag, memberName, signature,
  32.277 +                                                  array[0], array[1]);
  32.278 +                          values[i] = new String[] {memberName, signature};
  32.279 +                          break;
  32.280 +                      }
  32.281 +                      case CONSTANT_Fieldref:           // fall through:
  32.282 +                      case CONSTANT_Methodref:          // fall through:
  32.283 +                      case CONSTANT_InterfaceMethodref: {
  32.284 +                              Object className   = values[array[0]];
  32.285 +                              Object nameAndType = values[array[1]];
  32.286 +                              if (!(className instanceof String) ||
  32.287 +                                  !(nameAndType instanceof String[])) {
  32.288 +                                   // one more pass is needed
  32.289 +                                   if (beg2 > i)  beg2 = i;
  32.290 +                                   if (end2 < i)  end2 = i;
  32.291 +                                   continue;
  32.292 +                              }
  32.293 +                              String[] nameAndTypeArray = (String[]) nameAndType;
  32.294 +                              visitor.visitMemberRef(i, tag,
  32.295 +                                  (String)className,
  32.296 +                                  nameAndTypeArray[0],
  32.297 +                                  nameAndTypeArray[1],
  32.298 +                                  array[0], array[1]);
  32.299 +                              values[i] = null;
  32.300 +                          }
  32.301 +                          break;
  32.302 +                      default:
  32.303 +                          continue;
  32.304 +                }
  32.305 +            }
  32.306 +        }
  32.307 +    }
  32.308 +
  32.309 +    private static int getUnsignedByte(ByteBuffer buffer) {
  32.310 +        return buffer.get() & 0xFF;
  32.311 +    }
  32.312 +
  32.313 +    private static int getUnsignedShort(ByteBuffer buffer) {
  32.314 +        int b1 = getUnsignedByte(buffer);
  32.315 +        int b2 = getUnsignedByte(buffer);
  32.316 +        return (b1 << 8) + (b2 << 0);
  32.317 +    }
  32.318 +
  32.319 +    private static String getUTF8(ByteBuffer buffer, int utfLen, char[] charArray) throws InvalidConstantPoolFormatException {
  32.320 +      int utfLimit = buffer.position() + utfLen;
  32.321 +      int index = 0;
  32.322 +      while (buffer.position() < utfLimit) {
  32.323 +          int c = buffer.get() & 0xff;
  32.324 +          if (c > 127) {
  32.325 +              buffer.position(buffer.position() - 1);
  32.326 +              return getUTF8Extended(buffer, utfLimit, charArray, index);
  32.327 +          }
  32.328 +          charArray[index++] = (char)c;
  32.329 +      }
  32.330 +      return new String(charArray, 0, index);
  32.331 +    }
  32.332 +
  32.333 +    private static String getUTF8Extended(ByteBuffer buffer, int utfLimit, char[] charArray, int index) throws InvalidConstantPoolFormatException {
  32.334 +        int c, c2, c3;
  32.335 +        while (buffer.position() < utfLimit) {
  32.336 +            c = buffer.get() & 0xff;
  32.337 +            switch (c >> 4) {
  32.338 +                case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
  32.339 +                    /* 0xxxxxxx*/
  32.340 +                    charArray[index++] = (char)c;
  32.341 +                    break;
  32.342 +                case 12: case 13:
  32.343 +                    /* 110x xxxx   10xx xxxx*/
  32.344 +                    c2 = buffer.get();
  32.345 +                    if ((c2 & 0xC0) != 0x80)
  32.346 +                        throw new InvalidConstantPoolFormatException(
  32.347 +                            "malformed input around byte " + buffer.position());
  32.348 +                     charArray[index++] = (char)(((c  & 0x1F) << 6) |
  32.349 +                                                  (c2 & 0x3F));
  32.350 +                    break;
  32.351 +                case 14:
  32.352 +                    /* 1110 xxxx  10xx xxxx  10xx xxxx */
  32.353 +                    c2 = buffer.get();
  32.354 +                    c3 = buffer.get();
  32.355 +                    if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80))
  32.356 +                       throw new InvalidConstantPoolFormatException(
  32.357 +                          "malformed input around byte " + (buffer.position()));
  32.358 +                    charArray[index++] = (char)(((c  & 0x0F) << 12) |
  32.359 +                                                ((c2 & 0x3F) << 6)  |
  32.360 +                                                ((c3 & 0x3F) << 0));
  32.361 +                    break;
  32.362 +                default:
  32.363 +                    /* 10xx xxxx,  1111 xxxx */
  32.364 +                    throw new InvalidConstantPoolFormatException(
  32.365 +                        "malformed input around byte " + buffer.position());
  32.366 +            }
  32.367 +        }
  32.368 +        // The number of chars produced may be less than utflen
  32.369 +        return new String(charArray, 0, index);
  32.370 +    }
  32.371 +}
    33.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    33.2 +++ b/src/share/classes/sun/dyn/anon/ConstantPoolPatch.java	Tue May 05 22:40:09 2009 -0700
    33.3 @@ -0,0 +1,503 @@
    33.4 +/*
    33.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    33.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    33.7 + *
    33.8 + * This code is free software; you can redistribute it and/or modify it
    33.9 + * under the terms of the GNU General Public License version 2 only, as
   33.10 + * published by the Free Software Foundation.  Sun designates this
   33.11 + * particular file as subject to the "Classpath" exception as provided
   33.12 + * by Sun in the LICENSE file that accompanied this code.
   33.13 + *
   33.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   33.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   33.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   33.17 + * version 2 for more details (a copy is included in the LICENSE file that
   33.18 + * accompanied this code).
   33.19 + *
   33.20 + * You should have received a copy of the GNU General Public License version
   33.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   33.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   33.23 + *
   33.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   33.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   33.26 + * have any questions.
   33.27 + */
   33.28 +
   33.29 +package sun.dyn.anon;
   33.30 +
   33.31 +import java.io.IOException;
   33.32 +import java.io.OutputStream;
   33.33 +import java.util.Arrays;
   33.34 +import java.util.HashSet;
   33.35 +import java.util.IdentityHashMap;
   33.36 +import java.util.Map;
   33.37 +
   33.38 +import static sun.dyn.anon.ConstantPoolVisitor.*;
   33.39 +
   33.40 +/** A class and its patched constant pool.
   33.41 + *
   33.42 + *  This class allow to modify (patch) a constant pool
   33.43 + *  by changing the value of its entry.
   33.44 + *  Entry are referenced using index that can be get
   33.45 + *  by parsing the constant pool using
   33.46 + *  {@link ConstantPoolParser#parse(ConstantPoolVisitor)}.
   33.47 + *
   33.48 + * @see ConstantPoolVisitor
   33.49 + * @see ConstantPoolParser#createPatch()
   33.50 + */
   33.51 +public class ConstantPoolPatch {
   33.52 +    final ConstantPoolParser outer;
   33.53 +    final Object[] patchArray;
   33.54 +
   33.55 +    ConstantPoolPatch(ConstantPoolParser outer) {
   33.56 +        this.outer      = outer;
   33.57 +        this.patchArray = new Object[outer.getLength()];
   33.58 +    }
   33.59 +
   33.60 +    /** Create a {@link ConstantPoolParser} and
   33.61 +     *  a {@link ConstantPoolPatch} in one step.
   33.62 +     *  Equivalent to {@code new ConstantPoolParser(classFile).createPatch()}.
   33.63 +     *
   33.64 +     * @param classFile an array of bytes containing a class.
   33.65 +     * @see #ConstantPoolParser(Class)
   33.66 +     */
   33.67 +    public ConstantPoolPatch(byte[] classFile) throws InvalidConstantPoolFormatException {
   33.68 +        this(new ConstantPoolParser(classFile));
   33.69 +    }
   33.70 +
   33.71 +    /** Create a {@link ConstantPoolParser} and
   33.72 +     *  a {@link ConstantPoolPatch} in one step.
   33.73 +     *  Equivalent to {@code new ConstantPoolParser(templateClass).createPatch()}.
   33.74 +     *
   33.75 +     * @param templateClass the class to parse.
   33.76 +     * @see #ConstantPoolParser(Class)
   33.77 +     */
   33.78 +    public ConstantPoolPatch(Class<?> templateClass) throws IOException, InvalidConstantPoolFormatException {
   33.79 +        this(new ConstantPoolParser(templateClass));
   33.80 +    }
   33.81 +
   33.82 +
   33.83 +    /** Creates a patch from an existing patch.
   33.84 +     *  All changes are copied from that patch.
   33.85 +     * @param patch a patch
   33.86 +     *
   33.87 +     * @see ConstantPoolParser#createPatch()
   33.88 +     */
   33.89 +    public ConstantPoolPatch(ConstantPoolPatch patch) {
   33.90 +        outer      = patch.outer;
   33.91 +        patchArray = patch.patchArray.clone();
   33.92 +    }
   33.93 +
   33.94 +    /** Which parser built this patch? */
   33.95 +    public ConstantPoolParser getParser() {
   33.96 +        return outer;
   33.97 +    }
   33.98 +
   33.99 +    /** Report the tag at the given index in the constant pool. */
  33.100 +    public byte getTag(int index) {
  33.101 +        return outer.getTag(index);
  33.102 +    }
  33.103 +
  33.104 +    /** Report the current patch at the given index of the constant pool.
  33.105 +     *  Null means no patch will be made.
  33.106 +     *  To observe the unpatched entry at the given index, use
  33.107 +     *  {@link #getParser()}{@code .}@link ConstantPoolParser#parse(ConstantPoolVisitor)}
  33.108 +     */
  33.109 +    public Object getPatch(int index) {
  33.110 +        Object value = patchArray[index];
  33.111 +        if (value == null)  return null;
  33.112 +        switch (getTag(index)) {
  33.113 +        case CONSTANT_Fieldref:
  33.114 +        case CONSTANT_Methodref:
  33.115 +        case CONSTANT_InterfaceMethodref:
  33.116 +            if (value instanceof String)
  33.117 +                value = stripSemis(2, (String) value);
  33.118 +            break;
  33.119 +        case CONSTANT_NameAndType:
  33.120 +            if (value instanceof String)
  33.121 +                value = stripSemis(1, (String) value);
  33.122 +            break;
  33.123 +        }
  33.124 +        return value;
  33.125 +    }
  33.126 +
  33.127 +    /** Clear all patches. */
  33.128 +    public void clear() {
  33.129 +        Arrays.fill(patchArray, null);
  33.130 +    }
  33.131 +
  33.132 +    /** Clear one patch. */
  33.133 +    public void clear(int index) {
  33.134 +        patchArray[index] = null;
  33.135 +    }
  33.136 +
  33.137 +    /** Produce the patches as an array. */
  33.138 +    public Object[] getPatches() {
  33.139 +        return patchArray.clone();
  33.140 +    }
  33.141 +
  33.142 +    /** Produce the original constant pool as an array. */
  33.143 +    public Object[] getOriginalCP() throws InvalidConstantPoolFormatException {
  33.144 +        return getOriginalCP(0, patchArray.length, -1);
  33.145 +    }
  33.146 +
  33.147 +    /** Walk the constant pool, applying patches using the given map.
  33.148 +     *
  33.149 +     * @param utf8Map Utf8 strings to modify, if encountered
  33.150 +     * @param classMap Classes (or their names) to modify, if encountered
  33.151 +     * @param valueMap Constant values to modify, if encountered
  33.152 +     * @param deleteUsedEntries if true, delete map entries that are used
  33.153 +     */
  33.154 +    public void putPatches(final Map<String,String> utf8Map,
  33.155 +                           final Map<String,Object> classMap,
  33.156 +                           final Map<Object,Object> valueMap,
  33.157 +                           boolean deleteUsedEntries) throws InvalidConstantPoolFormatException {
  33.158 +        final HashSet<String> usedUtf8Keys;
  33.159 +        final HashSet<String> usedClassKeys;
  33.160 +        final HashSet<Object> usedValueKeys;
  33.161 +        if (deleteUsedEntries) {
  33.162 +            usedUtf8Keys  = (utf8Map  == null) ? null : new HashSet<String>();
  33.163 +            usedClassKeys = (classMap == null) ? null : new HashSet<String>();
  33.164 +            usedValueKeys = (valueMap == null) ? null : new HashSet<Object>();
  33.165 +        } else {
  33.166 +            usedUtf8Keys = null;
  33.167 +            usedClassKeys = null;
  33.168 +            usedValueKeys = null;
  33.169 +        }
  33.170 +
  33.171 +        outer.parse(new ConstantPoolVisitor() {
  33.172 +
  33.173 +            @Override
  33.174 +            public void visitUTF8(int index, byte tag, String utf8) {
  33.175 +                putUTF8(index, utf8Map.get(utf8));
  33.176 +                if (usedUtf8Keys != null)  usedUtf8Keys.add(utf8);
  33.177 +            }
  33.178 +
  33.179 +            @Override
  33.180 +            public void visitConstantValue(int index, byte tag, Object value) {
  33.181 +                putConstantValue(index, tag, valueMap.get(value));
  33.182 +                if (usedValueKeys != null)  usedValueKeys.add(value);
  33.183 +            }
  33.184 +
  33.185 +            @Override
  33.186 +            public void visitConstantString(int index, byte tag, String name, int nameIndex) {
  33.187 +                if (tag == CONSTANT_Class) {
  33.188 +                    putConstantValue(index, tag, classMap.get(name));
  33.189 +                    if (usedClassKeys != null)  usedClassKeys.add(name);
  33.190 +                } else {
  33.191 +                    assert(tag == CONSTANT_String);
  33.192 +                    visitConstantValue(index, tag, name);
  33.193 +                }
  33.194 +            }
  33.195 +        });
  33.196 +        if (usedUtf8Keys != null)   utf8Map.keySet().removeAll(usedUtf8Keys);
  33.197 +        if (usedClassKeys != null)  classMap.keySet().removeAll(usedClassKeys);
  33.198 +        if (usedValueKeys != null)  valueMap.keySet().removeAll(usedValueKeys);
  33.199 +    }
  33.200 +
  33.201 +    Object[] getOriginalCP(final int startIndex,
  33.202 +                           final int endIndex,
  33.203 +                           final int tagMask) throws InvalidConstantPoolFormatException {
  33.204 +        final Object[] cpArray = new Object[endIndex - startIndex];
  33.205 +        outer.parse(new ConstantPoolVisitor() {
  33.206 +
  33.207 +            void show(int index, byte tag, Object value) {
  33.208 +                if (index < startIndex || index >= endIndex)  return;
  33.209 +                if (((1 << tag) & tagMask) == 0)  return;
  33.210 +                cpArray[index - startIndex] = value;
  33.211 +            }
  33.212 +
  33.213 +            @Override
  33.214 +            public void visitUTF8(int index, byte tag, String utf8) {
  33.215 +                show(index, tag, utf8);
  33.216 +            }
  33.217 +
  33.218 +            @Override
  33.219 +            public void visitConstantValue(int index, byte tag, Object value) {
  33.220 +                assert(tag != CONSTANT_String);
  33.221 +                show(index, tag, value);
  33.222 +            }
  33.223 +
  33.224 +            @Override
  33.225 +            public void visitConstantString(int index, byte tag,
  33.226 +                                            String value, int j) {
  33.227 +                show(index, tag, value);
  33.228 +            }
  33.229 +
  33.230 +            @Override
  33.231 +            public void visitMemberRef(int index, byte tag,
  33.232 +                    String className, String memberName,
  33.233 +                    String signature,
  33.234 +                    int j, int k) {
  33.235 +                show(index, tag, new String[]{ className, memberName, signature });
  33.236 +            }
  33.237 +
  33.238 +            @Override
  33.239 +            public void visitDescriptor(int index, byte tag,
  33.240 +                    String memberName, String signature,
  33.241 +                    int j, int k) {
  33.242 +                show(index, tag, new String[]{ memberName, signature });
  33.243 +            }
  33.244 +        });
  33.245 +        return cpArray;
  33.246 +    }
  33.247 +
  33.248 +    /** Write the head (header plus constant pool)
  33.249 +     *  of the patched class file to the indicated stream.
  33.250 +     */
  33.251 +    void writeHead(OutputStream out) throws IOException {
  33.252 +        outer.writePatchedHead(out, patchArray);
  33.253 +    }
  33.254 +
  33.255 +    /** Write the tail (everything after the constant pool)
  33.256 +     *  of the patched class file to the indicated stream.
  33.257 +     */
  33.258 +    void writeTail(OutputStream out) throws IOException {
  33.259 +        outer.writeTail(out);
  33.260 +    }
  33.261 +
  33.262 +    private void checkConstantTag(byte tag, Object value) {
  33.263 +        if (value == null)
  33.264 +            throw new IllegalArgumentException(
  33.265 +                    "invalid null constant value");
  33.266 +        if (classForTag(tag) != value.getClass())
  33.267 +            throw new IllegalArgumentException(
  33.268 +                    "invalid constant value"
  33.269 +                    + (tag == CONSTANT_None ? ""
  33.270 +                        : " for tag "+tagName(tag))
  33.271 +                    + " of class "+value.getClass());
  33.272 +    }
  33.273 +
  33.274 +    private void checkTag(int index, byte putTag) {
  33.275 +        byte tag = outer.tags[index];
  33.276 +        if (tag != putTag)
  33.277 +            throw new IllegalArgumentException(
  33.278 +                "invalid put operation"
  33.279 +                + " for " + tagName(putTag)
  33.280 +                + " at index " + index + " found " + tagName(tag));
  33.281 +    }
  33.282 +
  33.283 +    private void checkTagMask(int index, int tagBitMask) {
  33.284 +        byte tag = outer.tags[index];
  33.285 +        int tagBit = ((tag & 0x1F) == tag) ? (1 << tag) : 0;
  33.286 +        if ((tagBit & tagBitMask) == 0)
  33.287 +            throw new IllegalArgumentException(
  33.288 +                "invalid put operation"
  33.289 +                + " at index " + index + " found " + tagName(tag));
  33.290 +    }
  33.291 +
  33.292 +    private static void checkMemberName(String memberName) {
  33.293 +        if (memberName.indexOf(';') >= 0)
  33.294 +            throw new IllegalArgumentException("memberName " + memberName + " contains a ';'");
  33.295 +    }
  33.296 +
  33.297 +    /** Set the entry of the constant pool indexed by index to
  33.298 +     *  a new string.
  33.299 +     *
  33.300 +     * @param index an index to a constant pool entry containing a
  33.301 +     *        {@link ConstantPoolVisitor#CONSTANT_Utf8} value.
  33.302 +     * @param utf8 a string
  33.303 +     *
  33.304 +     * @see ConstantPoolVisitor#visitUTF8(int, byte, String)
  33.305 +     */
  33.306 +    public void putUTF8(int index, String utf8) {
  33.307 +        if (utf8 == null) { clear(index); return; }
  33.308 +        checkTag(index, CONSTANT_Utf8);
  33.309 +        patchArray[index] = utf8;
  33.310 +    }
  33.311 +
  33.312 +    /** Set the entry of the constant pool indexed by index to
  33.313 +     *  a new value, depending on its dynamic type.
  33.314 +     *
  33.315 +     * @param index an index to a constant pool entry containing a
  33.316 +     *        one of the following structures:
  33.317 +     *        {@link ConstantPoolVisitor#CONSTANT_Integer},
  33.318 +     *        {@link ConstantPoolVisitor#CONSTANT_Float},
  33.319 +     *        {@link ConstantPoolVisitor#CONSTANT_Long},
  33.320 +     *        {@link ConstantPoolVisitor#CONSTANT_Double},
  33.321 +     *        {@link ConstantPoolVisitor#CONSTANT_String}, or
  33.322 +     *        {@link ConstantPoolVisitor#CONSTANT_Class}
  33.323 +     * @param value a boxed int, float, long or double; or a string or class object
  33.324 +     * @throws IllegalArgumentException if the type of the constant does not
  33.325 +     *         match the constant pool entry type,
  33.326 +     *         as reported by {@link #getTag(int)}
  33.327 +     *
  33.328 +     * @see #putConstantValue(int, byte, Object)
  33.329 +     * @see ConstantPoolVisitor#visitConstantValue(int, byte, Object)
  33.330 +     * @see ConstantPoolVisitor#visitConstantString(int, byte, String, int)
  33.331 +     */
  33.332 +    public void putConstantValue(int index, Object value) {
  33.333 +        if (value == null) { clear(index); return; }
  33.334 +        byte tag = tagForConstant(value.getClass());
  33.335 +        checkConstantTag(tag, value);
  33.336 +        checkTag(index, tag);
  33.337 +        patchArray[index] = value;
  33.338 +    }
  33.339 +
  33.340 +    /** Set the entry of the constant pool indexed by index to
  33.341 +     *  a new value.
  33.342 +     *
  33.343 +     * @param index an index to a constant pool entry matching the given tag
  33.344 +     * @param tag one of the following values:
  33.345 +     *        {@link ConstantPoolVisitor#CONSTANT_Integer},
  33.346 +     *        {@link ConstantPoolVisitor#CONSTANT_Float},
  33.347 +     *        {@link ConstantPoolVisitor#CONSTANT_Long},
  33.348 +     *        {@link ConstantPoolVisitor#CONSTANT_Double},
  33.349 +     *        {@link ConstantPoolVisitor#CONSTANT_String}, or
  33.350 +     *        {@link ConstantPoolVisitor#CONSTANT_Class}
  33.351 +     * @param value a boxed number, string, or class object
  33.352 +     * @throws IllegalArgumentException if the type of the constant does not
  33.353 +     *         match the constant pool entry type, or if a class name contains
  33.354 +     *         '/' or ';'
  33.355 +     *
  33.356 +     * @see #putConstantValue(int, Object)
  33.357 +     * @see ConstantPoolVisitor#visitConstantValue(int, byte, Object)
  33.358 +     * @see ConstantPoolVisitor#visitConstantString(int, byte, String, int)
  33.359 +     */
  33.360 +    public void putConstantValue(int index, byte tag, Object value) {
  33.361 +        if (value == null) { clear(index); return; }
  33.362 +        checkTag(index, tag);
  33.363 +        if (tag == CONSTANT_Class && value instanceof String) {
  33.364 +            checkClassName((String) value);
  33.365 +        } else if (tag == CONSTANT_String) {
  33.366 +            // the JVM accepts any object as a patch for a string
  33.367 +        } else {
  33.368 +            // make sure the incoming value is the right type
  33.369 +            checkConstantTag(tag, value);
  33.370 +        }
  33.371 +        checkTag(index, tag);
  33.372 +        patchArray[index] = value;
  33.373 +    }
  33.374 +
  33.375 +    /** Set the entry of the constant pool indexed by index to
  33.376 +     *  a new {@link ConstantPoolVisitor#CONSTANT_NameAndType} value.
  33.377 +     *
  33.378 +     * @param index an index to a constant pool entry containing a
  33.379 +     *        {@link ConstantPoolVisitor#CONSTANT_NameAndType} value.
  33.380 +     * @param memberName a memberName
  33.381 +     * @param signature a signature
  33.382 +     * @throws IllegalArgumentException if memberName contains the character ';'
  33.383 +     *
  33.384 +     * @see ConstantPoolVisitor#visitDescriptor(int, byte, String, String, int, int)
  33.385 +     */
  33.386 +    public void putDescriptor(int index, String memberName, String signature) {
  33.387 +        checkTag(index, CONSTANT_NameAndType);
  33.388 +        checkMemberName(memberName);
  33.389 +        patchArray[index] = addSemis(memberName, signature);
  33.390 +    }
  33.391 +
  33.392 +    /** Set the entry of the constant pool indexed by index to
  33.393 +     *  a new {@link ConstantPoolVisitor#CONSTANT_Fieldref},
  33.394 +     *  {@link ConstantPoolVisitor#CONSTANT_Methodref}, or
  33.395 +     *  {@link ConstantPoolVisitor#CONSTANT_InterfaceMethodref} value.
  33.396 +     *
  33.397 +     * @param index an index to a constant pool entry containing a member reference
  33.398 +     * @param className a class name
  33.399 +     * @param memberName a field or method name
  33.400 +     * @param signature a field or method signature
  33.401 +     * @throws IllegalArgumentException if memberName contains the character ';'
  33.402 +     *             or signature is not a correct signature
  33.403 +     *
  33.404 +     * @see ConstantPoolVisitor#visitMemberRef(int, byte, String, String, String, int, int)
  33.405 +     */
  33.406 +    public void putMemberRef(int index, byte tag,
  33.407 +                    String className, String memberName, String signature) {
  33.408 +        checkTagMask(tag, CONSTANT_MemberRef_MASK);
  33.409 +        checkTag(index, tag);
  33.410 +        checkClassName(className);
  33.411 +        checkMemberName(memberName);
  33.412 +        if (signature.startsWith("(") == (tag == CONSTANT_Fieldref))
  33.413 +            throw new IllegalArgumentException("bad signature: "+signature);
  33.414 +        patchArray[index] = addSemis(className, memberName, signature);
  33.415 +    }
  33.416 +
  33.417 +    static private final int CONSTANT_MemberRef_MASK =
  33.418 +              CONSTANT_Fieldref
  33.419 +            | CONSTANT_Methodref
  33.420 +            | CONSTANT_InterfaceMethodref;
  33.421 +
  33.422 +    private static final Map<Class<?>, Byte> CONSTANT_VALUE_CLASS_TAG
  33.423 +        = new IdentityHashMap<Class<?>, Byte>();
  33.424 +    private static final Class[] CONSTANT_VALUE_CLASS = new Class[16];
  33.425 +    static {
  33.426 +        Object[][] values = {
  33.427 +            {Integer.class, CONSTANT_Integer},
  33.428 +            {Long.class, CONSTANT_Long},
  33.429 +            {Float.class, CONSTANT_Float},
  33.430 +            {Double.class, CONSTANT_Double},
  33.431 +            {String.class, CONSTANT_String},
  33.432 +            {Class.class, CONSTANT_Class}
  33.433 +        };
  33.434 +        for (Object[] value : values) {
  33.435 +            Class<?> cls = (Class<?>)value[0];
  33.436 +            Byte     tag = (Byte) value[1];
  33.437 +            CONSTANT_VALUE_CLASS_TAG.put(cls, tag);
  33.438 +            CONSTANT_VALUE_CLASS[(byte)tag] = cls;
  33.439 +        }
  33.440 +    }
  33.441 +
  33.442 +    static Class<?> classForTag(byte tag) {
  33.443 +        if ((tag & 0xFF) >= CONSTANT_VALUE_CLASS.length)
  33.444 +            return null;
  33.445 +        return CONSTANT_VALUE_CLASS[tag];
  33.446 +    }
  33.447 +
  33.448 +    static byte tagForConstant(Class<?> cls) {
  33.449 +        Byte tag = CONSTANT_VALUE_CLASS_TAG.get(cls);
  33.450 +        return (tag == null) ? CONSTANT_None : (byte)tag;
  33.451 +    }
  33.452 +
  33.453 +    private static void checkClassName(String className) {
  33.454 +        if (className.indexOf('/') >= 0 || className.indexOf(';') >= 0)
  33.455 +            throw new IllegalArgumentException("invalid class name " + className);
  33.456 +    }
  33.457 +
  33.458 +    static String addSemis(String name, String... names) {
  33.459 +        StringBuilder buf = new StringBuilder(name.length() * 5);
  33.460 +        buf.append(name);
  33.461 +        for (String name2 : names) {
  33.462 +            buf.append(';').append(name2);
  33.463 +        }
  33.464 +        String res = buf.toString();
  33.465 +        assert(stripSemis(names.length, res)[0].equals(name));
  33.466 +        assert(stripSemis(names.length, res)[1].equals(names[0]));
  33.467 +        assert(names.length == 1 ||
  33.468 +               stripSemis(names.length, res)[2].equals(names[1]));
  33.469 +        return res;
  33.470 +    }
  33.471 +
  33.472 +    static String[] stripSemis(int count, String string) {
  33.473 +        String[] res = new String[count+1];
  33.474 +        int pos = 0;
  33.475 +        for (int i = 0; i < count; i++) {
  33.476 +            int pos2 = string.indexOf(';', pos);
  33.477 +            if (pos2 < 0)  pos2 = string.length();  // yuck
  33.478 +            res[i] = string.substring(pos, pos2);
  33.479 +            pos = pos2;
  33.480 +        }
  33.481 +        res[count] = string.substring(pos);
  33.482 +        return res;
  33.483 +    }
  33.484 +
  33.485 +    public String toString() {
  33.486 +        StringBuilder buf = new StringBuilder(this.getClass().getName());
  33.487 +        buf.append("{");
  33.488 +        Object[] origCP = null;
  33.489 +        for (int i = 0; i < patchArray.length; i++) {
  33.490 +            if (patchArray[i] == null)  continue;
  33.491 +            if (origCP != null) {
  33.492 +                buf.append(", ");
  33.493 +            } else {
  33.494 +                try {
  33.495 +                    origCP = getOriginalCP();
  33.496 +                } catch (InvalidConstantPoolFormatException ee) {
  33.497 +                    origCP = new Object[0];
  33.498 +                }
  33.499 +            }
  33.500 +            Object orig = (i < origCP.length) ? origCP[i] : "?";
  33.501 +            buf.append(orig).append("=").append(patchArray[i]);
  33.502 +        }
  33.503 +        buf.append("}");
  33.504 +        return buf.toString();
  33.505 +    }
  33.506 +}
    34.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    34.2 +++ b/src/share/classes/sun/dyn/anon/ConstantPoolVisitor.java	Tue May 05 22:40:09 2009 -0700
    34.3 @@ -0,0 +1,192 @@
    34.4 +/*
    34.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    34.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    34.7 + *
    34.8 + * This code is free software; you can redistribute it and/or modify it
    34.9 + * under the terms of the GNU General Public License version 2 only, as
   34.10 + * published by the Free Software Foundation.  Sun designates this
   34.11 + * particular file as subject to the "Classpath" exception as provided
   34.12 + * by Sun in the LICENSE file that accompanied this code.
   34.13 + *
   34.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   34.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   34.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   34.17 + * version 2 for more details (a copy is included in the LICENSE file that
   34.18 + * accompanied this code).
   34.19 + *
   34.20 + * You should have received a copy of the GNU General Public License version
   34.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   34.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   34.23 + *
   34.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   34.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   34.26 + * have any questions.
   34.27 + */
   34.28 +
   34.29 +package sun.dyn.anon;
   34.30 +
   34.31 +/**
   34.32 + * A visitor called by {@link ConstantPoolParser#parse(ConstantPoolVisitor)}
   34.33 + * when a constant pool entry is parsed.
   34.34 + * <p>
   34.35 + * A visit* method is called when a constant pool entry is parsed.
   34.36 + * The first argument is always the constant pool index.
   34.37 + * The second argument is always the constant pool tag,
   34.38 + * even for methods like {@link #visitUTF8(int, byte, String)} which only apply to one tag.
   34.39 + * String arguments refer to Utf8 or NameAndType entries declared elsewhere,
   34.40 + * and are always accompanied by the indexes of those entries.
   34.41 + * <p>
   34.42 + * The order of the calls to the visit* methods is not necessarily related
   34.43 + * to the order of the entries in the constant pool.
   34.44 + * If one entry has a reference to another entry, the latter (lower-level)
   34.45 + * entry will be visited first.
   34.46 + * <p>
   34.47 + * The following table shows the relation between constant pool entry
   34.48 + * types and the corresponding visit* methods:
   34.49 + *
   34.50 + * <table border=1 cellpadding=5 summary="constant pool visitor methods">
   34.51 + * <tr><th>Tag(s)</th><th>Method</th></tr>
   34.52 + * <tr>
   34.53 + *   <td>{@link #CONSTANT_Utf8}</td>
   34.54 + *   <td>{@link #visitUTF8(int, byte, String)}</td>
   34.55 + * </tr><tr>
   34.56 + *   <td>{@link #CONSTANT_Integer}, {@link #CONSTANT_Float},
   34.57 + *       {@link #CONSTANT_Long}, {@link #CONSTANT_Double}</td>
   34.58 + *   <td>{@link #visitConstantValue(int, byte, Object)}</td>
   34.59 + * </tr><tr>
   34.60 + *   <td>{@link #CONSTANT_String}, {@link #CONSTANT_Class}</td>
   34.61 + *   <td>{@link #visitConstantString(int, byte, String, int)}</td>
   34.62 + * </tr><tr>
   34.63 + *   <td>{@link #CONSTANT_NameAndType}</td>
   34.64 + *   <td>{@link #visitDescriptor(int, byte, String, String, int, int)}</td>
   34.65 + * </tr><tr>
   34.66 + *   <td>{@link #CONSTANT_Fieldref},
   34.67 + *       {@link #CONSTANT_Methodref},
   34.68 + *       {@link #CONSTANT_InterfaceMethodref}</td>
   34.69 + *   <td>{@link #visitMemberRef(int, byte, String, String, String, int, int)}</td>
   34.70 + * </tr>
   34.71 + * </table>
   34.72 + *
   34.73 + * @see ConstantPoolPatch
   34.74 + * @author Remi Forax
   34.75 + * @author jrose
   34.76 + */
   34.77 +public class ConstantPoolVisitor {
   34.78 +  /** Called each time an UTF8 constant pool entry is found.
   34.79 +   * @param index the constant pool index
   34.80 +   * @param tag always {@link #CONSTANT_Utf8}
   34.81 +   * @param utf8 string encoded in modified UTF-8 format passed as a {@code String}
   34.82 +   *
   34.83 +   * @see ConstantPoolPatch#putUTF8(int, String)
   34.84 +   */
   34.85 +  public void visitUTF8(int index, byte tag, String utf8) {
   34.86 +    // do nothing
   34.87 +  }
   34.88 +
   34.89 +  /** Called for each constant pool entry that encodes an integer,
   34.90 +   *  a float, a long, or a double.
   34.91 +   *  Constant strings and classes are not managed by this method but
   34.92 +   *  by {@link #visitConstantString(int, byte, String, int)}.
   34.93 +   *
   34.94 +   * @param index the constant pool index
   34.95 +   * @param tag one of {@link #CONSTANT_Integer},
   34.96 +   *            {@link #CONSTANT_Float},
   34.97 +   *            {@link #CONSTANT_Long},
   34.98 +   *            or {@link #CONSTANT_Double}
   34.99 +   * @param value encoded value
  34.100 +   *
  34.101 +   * @see ConstantPoolPatch#putConstantValue(int, Object)
  34.102 +   */
  34.103 +  public void visitConstantValue(int index, byte tag, Object value) {
  34.104 +    // do nothing
  34.105 +  }
  34.106 +
  34.107 +  /** Called for each constant pool entry that encodes a string or a class.
  34.108 +   * @param index the constant pool index
  34.109 +   * @param tag one of {@link #CONSTANT_String},
  34.110 +   *            {@link #CONSTANT_Class},
  34.111 +   * @param name string body or class name (using dot separator)
  34.112 +   * @param nameIndex the index of the Utf8 string for the name
  34.113 +   *
  34.114 +   * @see ConstantPoolPatch#putConstantValue(int, byte, Object)
  34.115 +   */
  34.116 +  public void visitConstantString(int index, byte tag,
  34.117 +                                  String name, int nameIndex) {
  34.118 +    // do nothing
  34.119 +  }
  34.120 +
  34.121 +  /** Called for each constant pool entry that encodes a name and type.
  34.122 +   * @param index the constant pool index
  34.123 +   * @param tag always {@link #CONSTANT_NameAndType}
  34.124 +   * @param memberName a field or method name
  34.125 +   * @param signature the member signature
  34.126 +   * @param memberNameIndex index of the Utf8 string for the member name
  34.127 +   * @param signatureIndex index of the Utf8 string for the signature
  34.128 +   *
  34.129 +   * @see ConstantPoolPatch#putDescriptor(int, String, String)
  34.130 +   */
  34.131 +  public void visitDescriptor(int index, byte tag,
  34.132 +                              String memberName, String signature,
  34.133 +                              int memberNameIndex, int signatureIndex) {
  34.134 +    // do nothing
  34.135 +  }
  34.136 +
  34.137 +  /** Called for each constant pool entry that encodes a field or method.
  34.138 +   * @param index the constant pool index
  34.139 +   * @param tag one of {@link #CONSTANT_Fieldref},
  34.140 +   *            or {@link #CONSTANT_Methodref},
  34.141 +   *            or {@link #CONSTANT_InterfaceMethodref}
  34.142 +   * @param className the class name (using dot separator)
  34.143 +   * @param memberName name of the field or method
  34.144 +   * @param signature the field or method signature
  34.145 +   * @param classNameIndex index of the Utf8 string for the class name
  34.146 +   * @param descriptorIndex index of the NameAndType descriptor constant
  34.147 +   *
  34.148 +   * @see ConstantPoolPatch#putMemberRef(int, byte, String, String, String)
  34.149 +   */
  34.150 +  public void visitMemberRef(int index, byte tag,
  34.151 +                             String className, String memberName, String signature,
  34.152 +                             int classNameIndex, int descriptorIndex) {
  34.153 +    // do nothing
  34.154 +  }
  34.155 +
  34.156 +    public static final byte
  34.157 +      CONSTANT_None = 0,
  34.158 +      CONSTANT_Utf8 = 1,
  34.159 +      //CONSTANT_Unicode = 2,               /* unused */
  34.160 +      CONSTANT_Integer = 3,
  34.161 +      CONSTANT_Float = 4,
  34.162 +      CONSTANT_Long = 5,
  34.163 +      CONSTANT_Double = 6,
  34.164 +      CONSTANT_Class = 7,
  34.165 +      CONSTANT_String = 8,
  34.166 +      CONSTANT_Fieldref = 9,
  34.167 +      CONSTANT_Methodref = 10,
  34.168 +      CONSTANT_InterfaceMethodref = 11,
  34.169 +      CONSTANT_NameAndType = 12;
  34.170 +
  34.171 +    private static String[] TAG_NAMES = {
  34.172 +        "Empty",
  34.173 +        "Utf8",
  34.174 +        null, //"Unicode",
  34.175 +        "Integer",
  34.176 +        "Float",
  34.177 +        "Long",
  34.178 +        "Double",
  34.179 +        "Class",
  34.180 +        "String",
  34.181 +        "Fieldref",
  34.182 +        "Methodref",
  34.183 +        "InterfaceMethodref",
  34.184 +        "NameAndType"
  34.185 +    };
  34.186 +
  34.187 +    public static String tagName(byte tag) {
  34.188 +        String name = null;
  34.189 +        if ((tag & 0xFF) < TAG_NAMES.length)
  34.190 +            name = TAG_NAMES[tag];
  34.191 +        if (name == null)
  34.192 +            name = "Unknown#"+(tag&0xFF);
  34.193 +        return name;
  34.194 +    }
  34.195 +}
    35.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    35.2 +++ b/src/share/classes/sun/dyn/anon/InvalidConstantPoolFormatException.java	Tue May 05 22:40:09 2009 -0700
    35.3 @@ -0,0 +1,45 @@
    35.4 +/*
    35.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    35.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    35.7 + *
    35.8 + * This code is free software; you can redistribute it and/or modify it
    35.9 + * under the terms of the GNU General Public License version 2 only, as
   35.10 + * published by the Free Software Foundation.  Sun designates this
   35.11 + * particular file as subject to the "Classpath" exception as provided
   35.12 + * by Sun in the LICENSE file that accompanied this code.
   35.13 + *
   35.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   35.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   35.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   35.17 + * version 2 for more details (a copy is included in the LICENSE file that
   35.18 + * accompanied this code).
   35.19 + *
   35.20 + * You should have received a copy of the GNU General Public License version
   35.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   35.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   35.23 + *
   35.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   35.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   35.26 + * have any questions.
   35.27 + */
   35.28 +
   35.29 +package sun.dyn.anon;
   35.30 +
   35.31 +/** Exception used when there is an error in the constant pool
   35.32 + *  format.
   35.33 + */
   35.34 +public class InvalidConstantPoolFormatException extends Exception {
   35.35 +    private static final long serialVersionUID=-6103888330523770949L;
   35.36 +
   35.37 +    public InvalidConstantPoolFormatException(String message,Throwable cause) {
   35.38 +        super(message,cause);
   35.39 +    }
   35.40 +
   35.41 +    public InvalidConstantPoolFormatException(String message) {
   35.42 +        super(message);
   35.43 +    }
   35.44 +
   35.45 +    public InvalidConstantPoolFormatException(Throwable cause) {
   35.46 +        super(cause);
   35.47 +    }
   35.48 +}
    36.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    36.2 +++ b/src/share/classes/sun/dyn/empty/Empty.java	Tue May 05 22:40:09 2009 -0700
    36.3 @@ -0,0 +1,36 @@
    36.4 +/*
    36.5 + * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
    36.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    36.7 + *
    36.8 + * This code is free software; you can redistribute it and/or modify it
    36.9 + * under the terms of the GNU General Public License version 2 only, as
   36.10 + * published by the Free Software Foundation.  Sun designates this
   36.11 + * particular file as subject to the "Classpath" exception as provided
   36.12 + * by Sun in the LICENSE file that accompanied this code.
   36.13 + *
   36.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   36.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   36.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   36.17 + * version 2 for more details (a copy is included in the LICENSE file that
   36.18 + * accompanied this code).
   36.19 + *
   36.20 + * You should have received a copy of the GNU General Public License version
   36.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   36.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   36.23 + *
   36.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   36.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   36.26 + * have any questions.
   36.27 + */
   36.28 +
   36.29 +package sun.dyn.empty;
   36.30 +
   36.31 +/**
   36.32 + * An empty class in an empty package.
   36.33 + * Used as a proxy for unprivileged code, since making access checks
   36.34 + * against it will only succeed against public methods in public types.
   36.35 + * @author jrose
   36.36 + */
   36.37 +public class Empty {
   36.38 +    private Empty() { throw new InternalError(); }
   36.39 +}
    37.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    37.2 +++ b/src/share/classes/sun/dyn/package-info.java	Tue May 05 22:40:09 2009 -0700
    37.3 @@ -0,0 +1,35 @@
    37.4 +/*
    37.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    37.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    37.7 + *
    37.8 + * This code is free software; you can redistribute it and/or modify it
    37.9 + * under the terms of the GNU General Public License version 2 only, as
   37.10 + * published by the Free Software Foundation.  Sun designates this
   37.11 + * particular file as subject to the "Classpath" exception as provided
   37.12 + * by Sun in the LICENSE file that accompanied this code.
   37.13 + *
   37.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   37.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   37.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   37.17 + * version 2 for more details (a copy is included in the LICENSE file that
   37.18 + * accompanied this code).
   37.19 + *
   37.20 + * You should have received a copy of the GNU General Public License version
   37.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   37.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   37.23 + *
   37.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   37.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   37.26 + * have any questions.
   37.27 + */
   37.28 +
   37.29 +/**
   37.30 + * Implementation details for JSR 292 RI, package java.dyn.
   37.31 + * This particular version is specific to Hotspot.
   37.32 + * There is also a backport version of this sub-package which uses reflection,
   37.33 + * and can therefore run (slowly) on older versions of Java.
   37.34 + * Other JVM vendors may create their own versions of this sub-package.
   37.35 + * @author jrose
   37.36 + */
   37.37 +
   37.38 +package sun.dyn;
    38.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    38.2 +++ b/src/share/classes/sun/dyn/util/BytecodeName.java	Tue May 05 22:40:09 2009 -0700
    38.3 @@ -0,0 +1,711 @@
    38.4 +/*
    38.5 + * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
    38.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    38.7 + *
    38.8 + * This code is free software; you can redistribute it and/or modify it
    38.9 + * under the terms of the GNU General Public License version 2 only, as
   38.10 + * published by the Free Software Foundation.  Sun designates this
   38.11 + * particular file as subject to the "Classpath" exception as provided
   38.12 + * by Sun in the LICENSE file that accompanied this code.
   38.13 + *
   38.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   38.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   38.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   38.17 + * version 2 for more details (a copy is included in the LICENSE file that
   38.18 + * accompanied this code).
   38.19 + *
   38.20 + * You should have received a copy of the GNU General Public License version
   38.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   38.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   38.23 + *
   38.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   38.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   38.26 + * have any questions.
   38.27 + */
   38.28 +
   38.29 +package sun.dyn.util;
   38.30 +
   38.31 +/**
   38.32 + * Utility routines for dealing with bytecode-level names.
   38.33 + * Includes universal mangling rules for the JVM.
   38.34 + *
   38.35 + * <h3>Avoiding Dangerous Characters </h3>
   38.36 + *
   38.37 + * <p>
   38.38 + * The JVM defines a very small set of characters which are illegal
   38.39 + * in name spellings.  We will slightly extend and regularize this set
   38.40 + * into a group of <cite>dangerous characters</cite>.
   38.41 + * These characters will then be replaced, in mangled names, by escape sequences.
   38.42 + * In addition, accidental escape sequences must be further escaped.
   38.43 + * Finally, a special prefix will be applied if and only if
   38.44 + * the mangling would otherwise fail to begin with the escape character.
   38.45 + * This happens to cover the corner case of the null string,
   38.46 + * and also clearly marks symbols which need demangling.
   38.47 + * </p>
   38.48 + * <p>
   38.49 + * Dangerous characters are the union of all characters forbidden
   38.50 + * or otherwise restricted by the JVM specification,
   38.51 + * plus their mates, if they are brackets
   38.52 + * (<code><big><b>[</b></big></code> and <code><big><b>]</b></big></code>,
   38.53 + * <code><big><b>&lt;</b></big></code> and <code><big><b>&gt;</b></big></code>),
   38.54 + * plus, arbitrarily, the colon character <code><big><b>:</b></big></code>.
   38.55 + * There is no distinction between type, method, and field names.
   38.56 + * This makes it easier to convert between mangled names of different
   38.57 + * types, since they do not need to be decoded (demangled).
   38.58 + * </p>
   38.59 + * <p>
   38.60 + * The escape character is backslash <code><big><b>\</b></big></code>
   38.61 + * (also known as reverse solidus).
   38.62 + * This character is, until now, unheard of in bytecode names,
   38.63 + * but traditional in the proposed role.
   38.64 + *
   38.65 + * </p>
   38.66 + * <h3> Replacement Characters </h3>
   38.67 + *
   38.68 + *
   38.69 + * <p>
   38.70 + * Every escape sequence is two characters
   38.71 + * (in fact, two UTF8 bytes) beginning with
   38.72 + * the escape character and followed by a
   38.73 + * <cite>replacement character</cite>.
   38.74 + * (Since the replacement character is never a backslash,
   38.75 + * iterated manglings do not double in size.)
   38.76 + * </p>
   38.77 + * <p>
   38.78 + * Each dangerous character has some rough visual similarity
   38.79 + * to its corresponding replacement character.
   38.80 + * This makes mangled symbols easier to recognize by sight.
   38.81 + * </p>
   38.82 + * <p>
   38.83 + * The dangerous characters are
   38.84 + * <code><big><b>/</b></big></code> (forward slash, used to delimit package components),
   38.85 + * <code><big><b>.</b></big></code> (dot, also a package delimiter),
   38.86 + * <code><big><b>;</b></big></code> (semicolon, used in signatures),
   38.87 + * <code><big><b>$</b></big></code> (dollar, used in inner classes and synthetic members),
   38.88 + * <code><big><b>&lt;</b></big></code> (left angle),
   38.89 + * <code><big><b>&gt;</b></big></code> (right angle),
   38.90 + * <code><big><b>[</b></big></code> (left square bracket, used in array types),
   38.91 + * <code><big><b>]</b></big></code> (right square bracket, reserved in this scheme for language use),
   38.92 + * and <code><big><b>:</b></big></code> (colon, reserved in this scheme for language use).
   38.93 + * Their replacements are, respectively,
   38.94 + * <code><big><b>|</b></big></code> (vertical bar),
   38.95 + * <code><big><b>,</b></big></code> (comma),
   38.96 + * <code><big><b>?</b></big></code> (question mark),
   38.97 + * <code><big><b>%</b></big></code> (percent),
   38.98 + * <code><big><b>^</b></big></code> (caret),
   38.99 + * <code><big><b>_</b></big></code> (underscore), and
  38.100 + * <code><big><b>{</b></big></code> (left curly bracket),
  38.101 + * <code><big><b>}</b></big></code> (right curly bracket),
  38.102 + * <code><big><b>!</b></big></code> (exclamation mark).
  38.103 + * In addition, the replacement character for the escape character itself is
  38.104 + * <code><big><b>-</b></big></code> (hyphen),
  38.105 + * and the replacement character for the null prefix is
  38.106 + * <code><big><b>=</b></big></code> (equal sign).
  38.107 + * </p>
  38.108 + * <p>
  38.109 + * An escape character <code><big><b>\</b></big></code>
  38.110 + * followed by any of these replacement characters
  38.111 + * is an escape sequence, and there are no other escape sequences.
  38.112 + * An equal sign is only part of an escape sequence
  38.113 + * if it is the second character in the whole string, following a backslash.
  38.114 + * Two consecutive backslashes do <em>not</em> form an escape sequence.
  38.115 + * </p>
  38.116 + * <p>
  38.117 + * Each escape sequence replaces a so-called <cite>original character</cite>
  38.118 + * which is either one of the dangerous characters or the escape character.
  38.119 + * A null prefix replaces an initial null string, not a character.
  38.120 + * </p>
  38.121 + * <p>
  38.122 + * All this implies that escape sequences cannot overlap and may be
  38.123 + * determined all at once for a whole string.  Note that a spelling
  38.124 + * string can contain <cite>accidental escapes</cite>, apparent escape
  38.125 + * sequences which must not be interpreted as manglings.
  38.126 + * These are disabled by replacing their leading backslash with an
  38.127 + * escape sequence (<code><big><b>\-</b></big></code>).  To mangle a string, three logical steps
  38.128 + * are required, though they may be carried out in one pass:
  38.129 + * </p>
  38.130 + * <ol>
  38.131 + *   <li>In each accidental escape, replace the backslash with an escape sequence
  38.132 + * (<code><big><b>\-</b></big></code>).</li>
  38.133 + *   <li>Replace each dangerous character with an escape sequence
  38.134 + * (<code><big><b>\|</b></big></code> for <code><big><b>/</b></big></code>, etc.).</li>
  38.135 + *   <li>If the first two steps introduced any change, <em>and</em>
  38.136 + * if the string does not already begin with a backslash, prepend a null prefix (<code><big><b>\=</b></big></code>).</li>
  38.137 + * </ol>
  38.138 + *
  38.139 + * To demangle a mangled string that begins with an escape,
  38.140 + * remove any null prefix, and then replace (in parallel)
  38.141 + * each escape sequence by its original character.
  38.142 + * <p>Spelling strings which contain accidental
  38.143 + * escapes <em>must</em> have them replaced, even if those
  38.144 + * strings do not contain dangerous characters.
  38.145 + * This restriction means that mangling a string always
  38.146 + * requires a scan of the string for escapes.
  38.147 + * But then, a scan would be required anyway,
  38.148 + * to check for dangerous characters.
  38.149 + *
  38.150 + * </p>
  38.151 + * <h3> Nice Properties </h3>
  38.152 + *
  38.153 + * <p>
  38.154 + * If a bytecode name does not contain any escape sequence,
  38.155 + * demangling is a no-op:  The string demangles to itself.
  38.156 + * Such a string is called <cite>self-mangling</cite>.
  38.157 + * Almost all strings are self-mangling.
  38.158 + * In practice, to demangle almost any name &ldquo;found in nature&rdquo;,
  38.159 + * simply verify that it does not begin with a backslash.
  38.160 + * </p>
  38.161 + * <p>
  38.162 + * Mangling is a one-to-one function, while demangling
  38.163 + * is a many-to-one function.
  38.164 + * A mangled string is defined as <cite>validly mangled</cite> if
  38.165 + * it is in fact the unique mangling of its spelling string.
  38.166 + * Three examples of invalidly mangled strings are <code><big><b>\=foo</b></big></code>,
  38.167 + * <code><big><b>\-bar</b></big></code>, and <code><big><b>baz\!</b></big></code>, which demangle to <code><big><b>foo</b></big></code>, <code><big><b>\bar</b></big></code>, and
  38.168 + * <code><big><b>baz\!</b></big></code>, but then remangle to <code><big><b>foo</b></big></code>, <code><big><b>\bar</b></big></code>, and <code><big><b>\=baz\-!</b></big></code>.
  38.169 + * If a language back-end or runtime is using mangled names,
  38.170 + * it should never present an invalidly mangled bytecode
  38.171 + * name to the JVM.  If the runtime encounters one,
  38.172 + * it should also report an error, since such an occurrence
  38.173 + * probably indicates a bug in name encoding which
  38.174 + * will lead to errors in linkage.
  38.175 + * However, this note does not propose that the JVM verifier
  38.176 + * detect invalidly mangled names.
  38.177 + * </p>
  38.178 + * <p>
  38.179 + * As a result of these rules, it is a simple matter to
  38.180 + * compute validly mangled substrings and concatenations
  38.181 + * of validly mangled strings, and (with a little care)
  38.182 + * these correspond to corresponding operations on their
  38.183 + * spelling strings.
  38.184 + * </p>
  38.185 + * <ul>
  38.186 + *   <li>Any prefix of a validly mangled string is also validly mangled,
  38.187 + * although a null prefix may need to be removed.</li>
  38.188 + *   <li>Any suffix of a validly mangled string is also validly mangled,
  38.189 + * although a null prefix may need to be added.</li>
  38.190 + *   <li>Two validly mangled strings, when concatenated,
  38.191 + * are also validly mangled, although any null prefix
  38.192 + * must be removed from the second string,
  38.193 + * and a trailing backslash on the first string may need escaping,
  38.194 + * if it would participate in an accidental escape when followed
  38.195 + * by the first character of the second string.</li>
  38.196 + * </ul>
  38.197 + * <p>If languages that include non-Java symbol spellings use this
  38.198 + * mangling convention, they will enjoy the following advantages:
  38.199 + * </p>
  38.200 + * <ul>
  38.201 + *   <li>They can interoperate via symbols they share in common.</li>
  38.202 + *   <li>Low-level tools, such as backtrace printers, will have readable displays.</li>
  38.203 + *   <li>Future JVM and language extensions can safely use the dangerous characters
  38.204 + * for structuring symbols, but will never interfere with valid spellings.</li>
  38.205 + *   <li>Runtimes and compilers can use standard libraries for mangling and demangling.</li>
  38.206 + *   <li>Occasional transliterations and name composition will be simple and regular,
  38.207 + * for classes, methods, and fields.</li>
  38.208 + *   <li>Bytecode names will continue to be compact.
  38.209 + * When mangled, spellings will at most double in length, either in
  38.210 + * UTF8 or UTF16 format, and most will not change at all.</li>
  38.211 + * </ul>
  38.212 + *
  38.213 + *
  38.214 + * <h3> Suggestions for Human Readable Presentations </h3>
  38.215 + *
  38.216 + *
  38.217 + * <p>
  38.218 + * For human readable displays of symbols,
  38.219 + * it will be better to present a string-like quoted
  38.220 + * representation of the spelling, because JVM users
  38.221 + * are generally familiar with such tokens.
  38.222 + * We suggest using single or double quotes before and after
  38.223 + * mangled symbols which are not valid Java identifiers,
  38.224 + * with quotes, backslashes, and non-printing characters
  38.225 + * escaped as if for literals in the Java language.
  38.226 + * </p>
  38.227 + * <p>
  38.228 + * For example, an HTML-like spelling
  38.229 + * <code><big><b>&lt;pre&gt;</b></big></code> mangles to
  38.230 + * <code><big><b>\^pre\_</b></big></code> and could
  38.231 + * display more cleanly as
  38.232 + * <code><big><b>'&lt;pre&gt;'</b></big></code>,
  38.233 + * with the quotes included.
  38.234 + * Such string-like conventions are <em>not</em> suitable
  38.235 + * for mangled bytecode names, in part because
  38.236 + * dangerous characters must be eliminated, rather
  38.237 + * than just quoted.  Otherwise internally structured
  38.238 + * strings like package prefixes and method signatures
  38.239 + * could not be reliably parsed.
  38.240 + * </p>
  38.241 + * <p>
  38.242 + * In such human-readable displays, invalidly mangled
  38.243 + * names should <em>not</em> be demangled and quoted,
  38.244 + * for this would be misleading.  Likewise, JVM symbols
  38.245 + * which contain dangerous characters (like dots in field
  38.246 + * names or brackets in method names) should not be
  38.247 + * simply quoted.  The bytecode names
  38.248 + * <code><big><b>\=phase\,1</b></big></code> and
  38.249 + * <code><big><b>phase.1</b></big></code> are distinct,
  38.250 + * and in demangled displays they should be presented as
  38.251 + * <code><big><b>'phase.1'</b></big></code> and something like
  38.252 + * <code><big><b>'phase'.1</b></big></code>, respectively.
  38.253 + * </p>
  38.254 + *
  38.255 + * @author John Rose
  38.256 + * @version 1.2, 02/06/2008
  38.257 + * @see http://blogs.sun.com/jrose/entry/symbolic_freedom_in_the_vm
  38.258 + */
  38.259 +public class BytecodeName {
  38.260 +    private BytecodeName() { }  // static only class
  38.261 +
  38.262 +    /** Given a source name, produce the corresponding bytecode name.
  38.263 +     * The source name should not be qualified, because any syntactic
  38.264 +     * markers (dots, slashes, dollar signs, colons, etc.) will be mangled.
  38.265 +     * @param s the source name
  38.266 +     * @return a valid bytecode name which represents the source name
  38.267 +     */
  38.268 +    public static String toBytecodeName(String s) {
  38.269 +        String bn = mangle(s);
  38.270 +        assert((Object)bn == s || looksMangled(bn)) : bn;
  38.271 +        assert(s.equals(toSourceName(bn))) : s;
  38.272 +        return bn;
  38.273 +    }
  38.274 +
  38.275 +    /** Given an unqualified bytecode name, produce the corresponding source name.
  38.276 +     * The bytecode name must not contain dangerous characters.
  38.277 +     * In particular, it must not be qualified or segmented by colon {@code ':'}.
  38.278 +     * @param s the bytecode name
  38.279 +     * @return the source name, which may possibly have unsafe characters
  38.280 +     * @throws IllegalArgumentException if the bytecode name is not {@link #isSafeBytecodeName safe}
  38.281 +     * @see #isSafeBytecodeName(java.lang.String)
  38.282 +     */
  38.283 +    public static String toSourceName(String s) {
  38.284 +        checkSafeBytecodeName(s);
  38.285 +        String sn = s;
  38.286 +        if (looksMangled(s)) {
  38.287 +            sn = demangle(s);
  38.288 +            assert(s.equals(mangle(sn))) : s+" => "+sn+" => "+mangle(sn);
  38.289 +        }
  38.290 +        return sn;
  38.291 +    }
  38.292 +
  38.293 +    /**
  38.294 +     * Given a bytecode name from a classfile, separate it into
  38.295 +     * components delimited by dangerous characters.
  38.296 +     * Each resulting array element will be either a dangerous character,
  38.297 +     * or else a safe bytecode name.
  38.298 +     * (The safe name might possibly be mangled to hide further dangerous characters.)
  38.299 +     * For example, the qualified class name {@code java/lang/String}
  38.300 +     * will be parsed into the array {@code {"java", '/', "lang", '/', "String"}}.
  38.301 +     * The name {@code &lt;init&gt;} will be parsed into { '&lt;', "init", '&gt;'}}
  38.302 +     * The name {@code foo/bar$:baz} will be parsed into
  38.303 +     * {@code {"foo", '/', "bar", '$', ':', "baz"}}.
  38.304 +     */
  38.305 +    public static Object[] parseBytecodeName(String s) {
  38.306 +        int slen = s.length();
  38.307 +        Object[] res = null;
  38.308 +        for (int pass = 0; pass <= 1; pass++) {
  38.309 +            int fillp = 0;
  38.310 +            int lasti = 0;
  38.311 +            for (int i = 0; i <= slen; i++) {
  38.312 +                int whichDC = -1;
  38.313 +                if (i < slen) {
  38.314 +                    whichDC = DANGEROUS_CHARS.indexOf(s.charAt(i));
  38.315 +                    if (whichDC < DANGEROUS_CHAR_FIRST_INDEX)  continue;
  38.316 +                }
  38.317 +                // got to end of string or next dangerous char
  38.318 +                if (lasti < i) {
  38.319 +                    // normal component
  38.320 +                    if (pass != 0)
  38.321 +                        res[fillp] = s.substring(lasti, i);
  38.322 +                    fillp++;
  38.323 +                    lasti = i+1;
  38.324 +                }
  38.325 +                if (whichDC >= DANGEROUS_CHAR_FIRST_INDEX) {
  38.326 +                    if (pass != 0)
  38.327 +                        res[fillp] = DANGEROUS_CHARS_CA[whichDC];
  38.328 +                    fillp++;
  38.329 +                }
  38.330 +            }
  38.331 +            if (pass != 0)  break;
  38.332 +            // between passes, build the result array
  38.333 +            res = new String[fillp];
  38.334 +            if (fillp <= 1) {
  38.335 +                if (fillp != 0)  res[0] = s;
  38.336 +                break;
  38.337 +            }
  38.338 +        }
  38.339 +        return res;
  38.340 +    }
  38.341 +
  38.342 +    /**
  38.343 +     * Given a series of components, create a bytecode name for a classfile.
  38.344 +     * This is the inverse of {@link #parseBytecodeName(java.lang.String)}.
  38.345 +     * Each component must either be an interned one-character string of
  38.346 +     * a dangerous character, or else a safe bytecode name.
  38.347 +     * @param components a series of name components
  38.348 +     * @return the concatenation of all components
  38.349 +     * @throws IllegalArgumentException if any component contains an unsafe
  38.350 +     *          character, and is not an interned one-character string
  38.351 +     * @throws NullPointerException if any component is null
  38.352 +     */
  38.353 +    public static String unparseBytecodeName(Object[] components) {
  38.354 +        for (Object c : components) {
  38.355 +            if (c instanceof String)
  38.356 +                checkSafeBytecodeName((String) c);  // may fail
  38.357 +        }
  38.358 +        return appendAll(components);
  38.359 +    }
  38.360 +    private static String appendAll(Object[] components) {
  38.361 +        if (components.length <= 1) {
  38.362 +            if (components.length == 1) {
  38.363 +                return String.valueOf(components[0]);
  38.364 +            }
  38.365 +            return "";
  38.366 +        }
  38.367 +        int slen = 0;
  38.368 +        for (Object c : components) {
  38.369 +            if (c instanceof String)
  38.370 +                slen += String.valueOf(c).length();
  38.371 +            else
  38.372 +                slen += 1;
  38.373 +        }
  38.374 +        StringBuilder sb = new StringBuilder(slen);
  38.375 +        for (Object c : components) {
  38.376 +            sb.append(c);
  38.377 +        }
  38.378 +        return sb.toString();
  38.379 +    }
  38.380 +
  38.381 +    /**
  38.382 +     * Given a bytecode name, produce the corresponding display name.
  38.383 +     * This is the source name, plus quotes if needed.
  38.384 +     * If the bytecode name contains dangerous characters,
  38.385 +     * assume that they are being used as punctuation,
  38.386 +     * and pass them through unchanged.
  38.387 +     * @param s the original bytecode name (which may be qualified)
  38.388 +     * @return a human-readable presentation
  38.389 +     */
  38.390 +    public static String toDisplayName(String s) {
  38.391 +        Object[] components = parseBytecodeName(s);
  38.392 +        for (int i = 0; i < components.length; i++) {
  38.393 +            if (!(components[i] instanceof String))
  38.394 +                continue;
  38.395 +            String c = (String) components[i];
  38.396 +            // pretty up the name by demangling it
  38.397 +            String sn = toSourceName(c);
  38.398 +            if ((Object)sn != c || !isJavaIdent(sn)) {
  38.399 +                components[i] = quoteDisplay(sn);
  38.400 +            }
  38.401 +        }
  38.402 +        return appendAll(components);
  38.403 +    }
  38.404 +    private static boolean isJavaIdent(String s) {
  38.405 +        int slen = s.length();
  38.406 +        if (slen == 0)  return false;
  38.407 +        if (!Character.isUnicodeIdentifierStart(s.charAt(0)))
  38.408 +            return false;
  38.409 +        for (int i = 1; i < slen; i++) {
  38.410 +            if (!Character.isUnicodeIdentifierPart(s.charAt(0)))
  38.411 +                return false;
  38.412 +        }
  38.413 +        return true;
  38.414 +    }
  38.415 +    private static String quoteDisplay(String s) {
  38.416 +        // TO DO:  Replace wierd characters in s by C-style escapes.
  38.417 +        return "'"+s.replaceAll("['\\\\]", "\\\\$0")+"'";
  38.418 +    }
  38.419 +
  38.420 +    private static void checkSafeBytecodeName(String s)
  38.421 +            throws IllegalArgumentException {
  38.422 +        if (!isSafeBytecodeName(s)) {
  38.423 +            throw new IllegalArgumentException(s);
  38.424 +        }
  38.425 +    }
  38.426 +
  38.427 +    /**
  38.428 +     * Report whether a simple name is safe as a bytecode name.
  38.429 +     * Such names are acceptable in class files as class, method, and field names.
  38.430 +     * Additionally, they are free of "dangerous" characters, even if those
  38.431 +     * characters are legal in some (or all) names in class files.
  38.432 +     * @param s the proposed bytecode name
  38.433 +     * @return true if the name is non-empty and all of its characters are safe
  38.434 +     */
  38.435 +    public static boolean isSafeBytecodeName(String s) {
  38.436 +        if (s.length() == 0)  return false;
  38.437 +        // check occurrences of each DANGEROUS char
  38.438 +        for (char xc : DANGEROUS_CHARS_A) {
  38.439 +            if (xc == ESCAPE_C)  continue;  // not really that dangerous
  38.440 +            if (s.indexOf(xc) >= 0)  return false;
  38.441 +        }
  38.442 +        return true;
  38.443 +    }
  38.444 +
  38.445 +    /**
  38.446 +     * Report whether a character is safe in a bytecode name.
  38.447 +     * This is true of any unicode character except the following
  38.448 +     * <em>dangerous characters</em>: {@code ".;:$[]<>/"}.
  38.449 +     * @param s the proposed character
  38.450 +     * @return true if the character is safe to use in classfiles
  38.451 +     */
  38.452 +    public static boolean isSafeBytecodeChar(char c) {
  38.453 +        return DANGEROUS_CHARS.indexOf(c) < DANGEROUS_CHAR_FIRST_INDEX;
  38.454 +    }
  38.455 +
  38.456 +    private static boolean looksMangled(String s) {
  38.457 +        return s.charAt(0) == ESCAPE_C;
  38.458 +    }
  38.459 +
  38.460 +    private static String mangle(String s) {
  38.461 +        if (s.length() == 0)
  38.462 +            return NULL_ESCAPE;
  38.463 +
  38.464 +        // build this lazily, when we first need an escape:
  38.465 +        StringBuilder sb = null;
  38.466 +
  38.467 +        for (int i = 0, slen = s.length(); i < slen; i++) {
  38.468 +            char c = s.charAt(i);
  38.469 +
  38.470 +            boolean needEscape = false;
  38.471 +            if (c == ESCAPE_C) {
  38.472 +                if (i+1 < slen) {
  38.473 +                    char c1 = s.charAt(i+1);
  38.474 +                    if ((i == 0 && c1 == NULL_ESCAPE_C)
  38.475 +                        || c1 != originalOfReplacement(c1)) {
  38.476 +                        // an accidental escape
  38.477 +                        needEscape = true;
  38.478 +                    }
  38.479 +                }
  38.480 +            } else {
  38.481 +                needEscape = isDangerous(c);
  38.482 +            }
  38.483 +
  38.484 +            if (!needEscape) {
  38.485 +                if (sb != null)  sb.append(c);
  38.486 +                continue;
  38.487 +            }
  38.488 +
  38.489 +            // build sb if this is the first escape
  38.490 +            if (sb == null) {
  38.491 +                sb = new StringBuilder(s.length()+10);
  38.492 +                // mangled names must begin with a backslash:
  38.493 +                if (s.charAt(0) != ESCAPE_C && i > 0)
  38.494 +                    sb.append(NULL_ESCAPE);
  38.495 +                // append the string so far, which is unremarkable:
  38.496 +                sb.append(s.substring(0, i));
  38.497 +            }
  38.498 +
  38.499 +            // rewrite \ to \-, / to \|, etc.
  38.500 +            sb.append(ESCAPE_C);
  38.501 +            sb.append(replacementOf(c));
  38.502 +        }
  38.503 +
  38.504 +        if (sb != null)   return sb.toString();
  38.505 +
  38.506 +        return s;
  38.507 +    }
  38.508 +
  38.509 +    private static String demangle(String s) {
  38.510 +        // build this lazily, when we first meet an escape:
  38.511 +        StringBuilder sb = null;
  38.512 +
  38.513 +        int stringStart = 0;
  38.514 +        if (s.startsWith(NULL_ESCAPE))
  38.515 +            stringStart = 2;
  38.516 +
  38.517 +        for (int i = stringStart, slen = s.length(); i < slen; i++) {
  38.518 +            char c = s.charAt(i);
  38.519 +
  38.520 +            if (c == ESCAPE_C && i+1 < slen) {
  38.521 +                // might be an escape sequence
  38.522 +                char rc = s.charAt(i+1);
  38.523 +                char oc = originalOfReplacement(rc);
  38.524 +                if (oc != rc) {
  38.525 +                    // build sb if this is the first escape
  38.526 +                    if (sb == null) {
  38.527 +                        sb = new StringBuilder(s.length());
  38.528 +                        // append the string so far, which is unremarkable:
  38.529 +                        sb.append(s.substring(stringStart, i));
  38.530 +                    }
  38.531 +                    ++i;  // skip both characters
  38.532 +                    c = oc;
  38.533 +                }
  38.534 +            }
  38.535 +
  38.536 +            if (sb != null)
  38.537 +                sb.append(c);
  38.538 +        }
  38.539 +
  38.540 +        if (sb != null)   return sb.toString();
  38.541 +
  38.542 +        return s.substring(stringStart);
  38.543 +    }
  38.544 +
  38.545 +    static char ESCAPE_C = '\\';
  38.546 +    // empty escape sequence to avoid a null name or illegal prefix
  38.547 +    static char NULL_ESCAPE_C = '=';
  38.548 +    static String NULL_ESCAPE = ESCAPE_C+""+NULL_ESCAPE_C;
  38.549 +
  38.550 +    static final String DANGEROUS_CHARS   = "\\/.;:$[]<>"; // \\ must be first
  38.551 +    static final String REPLACEMENT_CHARS =  "-|,?!%{}^_";
  38.552 +    static final int DANGEROUS_CHAR_FIRST_INDEX = 1; // index after \\
  38.553 +    static char[] DANGEROUS_CHARS_A   = DANGEROUS_CHARS.toCharArray();
  38.554 +    static char[] REPLACEMENT_CHARS_A = REPLACEMENT_CHARS.toCharArray();
  38.555 +    static final Character[] DANGEROUS_CHARS_CA;
  38.556 +    static {
  38.557 +        Character[] dcca = new Character[DANGEROUS_CHARS.length()];
  38.558 +        for (int i = 0; i < dcca.length; i++)
  38.559 +            dcca[i] = Character.valueOf(DANGEROUS_CHARS.charAt(i));
  38.560 +        DANGEROUS_CHARS_CA = dcca;
  38.561 +    }
  38.562 +
  38.563 +    static final long[] SPECIAL_BITMAP = new long[2];  // 128 bits
  38.564 +    static {
  38.565 +        String SPECIAL = DANGEROUS_CHARS + REPLACEMENT_CHARS;
  38.566 +        //System.out.println("SPECIAL = "+SPECIAL);
  38.567 +        for (char c : SPECIAL.toCharArray()) {
  38.568 +            SPECIAL_BITMAP[c >>> 6] |= 1L << c;
  38.569 +        }
  38.570 +    }
  38.571 +    static boolean isSpecial(char c) {
  38.572 +        if ((c >>> 6) < SPECIAL_BITMAP.length)
  38.573 +            return ((SPECIAL_BITMAP[c >>> 6] >> c) & 1) != 0;
  38.574 +        else
  38.575 +            return false;
  38.576 +    }
  38.577 +    static char replacementOf(char c) {
  38.578 +        if (!isSpecial(c))  return c;
  38.579 +        int i = DANGEROUS_CHARS.indexOf(c);
  38.580 +        if (i < 0)  return c;
  38.581 +        return REPLACEMENT_CHARS.charAt(i);
  38.582 +    }
  38.583 +    static char originalOfReplacement(char c) {
  38.584 +        if (!isSpecial(c))  return c;
  38.585 +        int i = REPLACEMENT_CHARS.indexOf(c);
  38.586 +        if (i < 0)  return c;
  38.587 +        return DANGEROUS_CHARS.charAt(i);
  38.588 +    }
  38.589 +    static boolean isDangerous(char c) {
  38.590 +        if (!isSpecial(c))  return false;
  38.591 +        return (DANGEROUS_CHARS.indexOf(c) >= DANGEROUS_CHAR_FIRST_INDEX);
  38.592 +    }
  38.593 +    static int indexOfDangerousChar(String s, int from) {
  38.594 +        for (int i = from, slen = s.length(); i < slen; i++) {
  38.595 +            if (isDangerous(s.charAt(i)))
  38.596 +                return i;
  38.597 +        }
  38.598 +        return -1;
  38.599 +    }
  38.600 +    static int lastIndexOfDangerousChar(String s, int from) {
  38.601 +        for (int i = Math.min(from, s.length()-1); i >= 0; i--) {
  38.602 +            if (isDangerous(s.charAt(i)))
  38.603 +                return i;
  38.604 +        }
  38.605 +        return -1;
  38.606 +    }
  38.607 +
  38.608 +    // test driver
  38.609 +    static void main(String[] av) {
  38.610 +        // If verbose is enabled, quietly check everything.
  38.611 +        // Otherwise, print the output for the user to check.
  38.612 +        boolean verbose = false;
  38.613 +
  38.614 +        int maxlen = 0;
  38.615 +
  38.616 +        while (av.length > 0 && av[0].startsWith("-")) {
  38.617 +            String flag = av[0].intern();
  38.618 +            av = java.util.Arrays.copyOfRange(av, 1, av.length); // Java 1.6 or later
  38.619 +            if (flag == "-" || flag == "--")  break;
  38.620 +            else if (flag == "-q")
  38.621 +                verbose = false;
  38.622 +            else if (flag == "-v")
  38.623 +                verbose = true;
  38.624 +            else if (flag.startsWith("-l"))
  38.625 +                maxlen = Integer.valueOf(flag.substring(2));
  38.626 +            else
  38.627 +                throw new Error("Illegal flag argument: "+flag);
  38.628 +        }
  38.629 +
  38.630 +        if (maxlen == 0)
  38.631 +            maxlen = (verbose ? 2 : 4);
  38.632 +        if (verbose)  System.out.println("Note: maxlen = "+maxlen);
  38.633 +
  38.634 +        switch (av.length) {
  38.635 +        case 0: av = new String[] {
  38.636 +                    DANGEROUS_CHARS.substring(0) +
  38.637 +                    REPLACEMENT_CHARS.substring(0, 1) +
  38.638 +                    NULL_ESCAPE + "x"
  38.639 +                }; // and fall through:
  38.640 +        case 1:
  38.641 +            char[] cv = av[0].toCharArray();
  38.642 +            av = new String[cv.length];
  38.643 +            int avp = 0;
  38.644 +            for (char c : cv) {
  38.645 +                String s = String.valueOf(c);
  38.646 +                if (c == 'x')  s = "foo";  // tradition...
  38.647 +                av[avp++] = s;
  38.648 +            }
  38.649 +        }
  38.650 +        if (verbose)
  38.651 +            System.out.println("Note: Verbose output mode enabled.  Use '-q' to suppress.");
  38.652 +        Tester t = new Tester();
  38.653 +        t.maxlen = maxlen;
  38.654 +        t.verbose = verbose;
  38.655 +        t.tokens = av;
  38.656 +        t.test("", 0);
  38.657 +    }
  38.658 +
  38.659 +    static class Tester {
  38.660 +        boolean verbose;
  38.661 +        int maxlen;
  38.662 +        java.util.Map<String,String> map = new java.util.HashMap<String,String>();
  38.663 +        String[] tokens;
  38.664 +
  38.665 +        void test(String stringSoFar, int tokensSoFar) {
  38.666 +            test(stringSoFar);
  38.667 +            if (tokensSoFar <= maxlen) {
  38.668 +                for (String token : tokens) {
  38.669 +                    if (token.length() == 0)  continue;  // skip empty tokens
  38.670 +                    if (stringSoFar.indexOf(token) != stringSoFar.lastIndexOf(token))
  38.671 +                        continue;   // there are already two occs. of this token
  38.672 +                    if (token.charAt(0) == ESCAPE_C && token.length() == 1 && maxlen < 4)
  38.673 +                        test(stringSoFar+token, tokensSoFar);  // want lots of \'s
  38.674 +                    else if (tokensSoFar < maxlen)
  38.675 +                        test(stringSoFar+token, tokensSoFar+1);
  38.676 +                }
  38.677 +            }
  38.678 +        }
  38.679 +
  38.680 +        void test(String s) {
  38.681 +            // for small batches, do not test the null string
  38.682 +            if (s.length() == 0 && maxlen >=1 && maxlen <= 2)  return;
  38.683 +            String bn = testSourceName(s);
  38.684 +            if (bn == null)  return;
  38.685 +            if (bn == s) {
  38.686 +                //if (verbose)  System.out.println(s+" == id");
  38.687 +            } else {
  38.688 +                if (verbose)  System.out.println(s+" => "+bn+" "+toDisplayName(bn));
  38.689 +                String bnbn = testSourceName(bn);
  38.690 +                if (bnbn == null)  return;
  38.691 +                if (verbose)  System.out.println(bn+" => "+bnbn+" "+toDisplayName(bnbn));
  38.692 +                /*
  38.693 +                String bn3 = testSourceName(bnbn);
  38.694 +                if (bn3 == null)  return;
  38.695 +                if (verbose)  System.out.println(bnbn+" => "+bn3);
  38.696 +                */
  38.697 +            }
  38.698 +        }
  38.699 +
  38.700 +        String testSourceName(String s) {
  38.701 +            if (map.containsKey(s))  return null;
  38.702 +            String bn = toBytecodeName(s);
  38.703 +            map.put(s, bn);
  38.704 +            String sn = toSourceName(bn);
  38.705 +            if (!sn.equals(s)) {
  38.706 +                String bad = (s+" => "+bn+" != "+sn);
  38.707 +                if (!verbose)  throw new Error("Bad mangling: "+bad);
  38.708 +                System.out.println("*** "+bad);
  38.709 +                return null;
  38.710 +            }
  38.711 +            return bn;
  38.712 +        }
  38.713 +    }
  38.714 +}
    39.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    39.2 +++ b/src/share/classes/sun/dyn/util/BytecodeSignature.java	Tue May 05 22:40:09 2009 -0700
    39.3 @@ -0,0 +1,137 @@
    39.4 +/*
    39.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    39.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    39.7 + *
    39.8 + * This code is free software; you can redistribute it and/or modify it
    39.9 + * under the terms of the GNU General Public License version 2 only, as
   39.10 + * published by the Free Software Foundation.  Sun designates this
   39.11 + * particular file as subject to the "Classpath" exception as provided
   39.12 + * by Sun in the LICENSE file that accompanied this code.
   39.13 + *
   39.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   39.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   39.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   39.17 + * version 2 for more details (a copy is included in the LICENSE file that
   39.18 + * accompanied this code).
   39.19 + *
   39.20 + * You should have received a copy of the GNU General Public License version
   39.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   39.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   39.23 + *
   39.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   39.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   39.26 + * have any questions.
   39.27 + */
   39.28 +
   39.29 +package sun.dyn.util;
   39.30 +
   39.31 +import java.dyn.MethodType;
   39.32 +import java.util.ArrayList;
   39.33 +import java.util.List;
   39.34 +
   39.35 +/**
   39.36 + * Utility routines for dealing with bytecode-level signatures.
   39.37 + * @author jrose
   39.38 + */
   39.39 +public class BytecodeSignature {
   39.40 +
   39.41 +    private BytecodeSignature() { }  // cannot instantiate
   39.42 +
   39.43 +    public static List<Class<?>> parseMethod(String bytecodeSignature, ClassLoader loader) {
   39.44 +        return parseMethod(bytecodeSignature, 0, bytecodeSignature.length(), loader);
   39.45 +    }
   39.46 +
   39.47 +    static List<Class<?>> parseMethod(String bytecodeSignature,
   39.48 +            int start, int end, ClassLoader loader) {
   39.49 +        if (loader == null)
   39.50 +            loader = ClassLoader.getSystemClassLoader();
   39.51 +        String str = bytecodeSignature;
   39.52 +        int[] i = {start};
   39.53 +        ArrayList<Class<?>> ptypes = new ArrayList<Class<?>>();
   39.54 +        if (i[0] < end && str.charAt(i[0]) == '(') {
   39.55 +            ++i[0];  // skip '('
   39.56 +            while (i[0] < end && str.charAt(i[0]) != ')') {
   39.57 +                Class<?> pt = parseSig(str, i, end, loader);
   39.58 +                if (pt == null || pt == void.class)
   39.59 +                    parseError(str, "bad argument type");
   39.60 +                ptypes.add(pt);
   39.61 +            }
   39.62 +            ++i[0];  // skip ')'
   39.63 +        } else {
   39.64 +            parseError(str, "not a method type");
   39.65 +        }
   39.66 +        Class<?> rtype = parseSig(str, i, end, loader);
   39.67 +        if (rtype == null || i[0] != end)
   39.68 +            parseError(str, "bad return type");
   39.69 +        ptypes.add(rtype);
   39.70 +        return ptypes;
   39.71 +    }
   39.72 +
   39.73 +    static private void parseError(String str, String msg) {
   39.74 +        throw new IllegalArgumentException("bad signature: "+str+": "+msg);
   39.75 +    }
   39.76 +
   39.77 +    static private Class<?> parseSig(String str, int[] i, int end, ClassLoader loader) {
   39.78 +        if (i[0] == end)  return null;
   39.79 +        char c = str.charAt(i[0]++);
   39.80 +        if (c == 'L') {
   39.81 +            int begc = i[0], endc = str.indexOf(';', begc);
   39.82 +            if (endc < 0)  return null;
   39.83 +            i[0] = endc+1;
   39.84 +            String name = str.substring(begc, endc).replace('/', '.');
   39.85 +            try {
   39.86 +                return loader.loadClass(name);
   39.87 +            } catch (ClassNotFoundException ex) {
   39.88 +                throw new TypeNotPresentException(name, ex);
   39.89 +            }
   39.90 +        } else if (c == '[') {
   39.91 +            Class<?> t = parseSig(str, i, end, loader);
   39.92 +            if (t != null)
   39.93 +                t = java.lang.reflect.Array.newInstance(t, 0).getClass();
   39.94 +            return t;
   39.95 +        } else {
   39.96 +            return Wrapper.forBasicType(c).primitiveType();
   39.97 +        }
   39.98 +    }
   39.99 +
  39.100 +    public static String unparse(Class<?> type) {
  39.101 +        StringBuilder sb = new StringBuilder();
  39.102 +        unparseSig(type, sb);
  39.103 +        return sb.toString();
  39.104 +    }
  39.105 +
  39.106 +    public static String unparse(MethodType type) {
  39.107 +        return unparseMethod(type.returnType(), type.parameterList());
  39.108 +    }
  39.109 +
  39.110 +    public static String unparse(Object type) {
  39.111 +        if (type instanceof Class<?>)
  39.112 +            return unparse((Class<?>) type);
  39.113 +        if (type instanceof MethodType)
  39.114 +            return unparse((MethodType) type);
  39.115 +        return (String) type;
  39.116 +    }
  39.117 +
  39.118 +    public static String unparseMethod(Class<?> rtype, List<Class<?>> ptypes) {
  39.119 +        StringBuilder sb = new StringBuilder();
  39.120 +        sb.append('(');
  39.121 +        for (Class<?> pt : ptypes)
  39.122 +            unparseSig(pt, sb);
  39.123 +        sb.append(')');
  39.124 +        unparseSig(rtype, sb);
  39.125 +        return sb.toString();
  39.126 +    }
  39.127 +
  39.128 +    static private void unparseSig(Class<?> t, StringBuilder sb) {
  39.129 +        char c = Wrapper.forBasicType(t).basicTypeChar();
  39.130 +        if (c != 'L') {
  39.131 +            sb.append(c);
  39.132 +        } else {
  39.133 +            boolean lsemi = (!t.isArray());
  39.134 +            if (lsemi)  sb.append('L');
  39.135 +            sb.append(t.getName().replace('.', '/'));
  39.136 +            if (lsemi)  sb.append(';');
  39.137 +        }
  39.138 +    }
  39.139 +
  39.140 +}
    40.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    40.2 +++ b/src/share/classes/sun/dyn/util/ValueConversions.java	Tue May 05 22:40:09 2009 -0700
    40.3 @@ -0,0 +1,563 @@
    40.4 +/*
    40.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    40.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    40.7 + *
    40.8 + * This code is free software; you can redistribute it and/or modify it
    40.9 + * under the terms of the GNU General Public License version 2 only, as
   40.10 + * published by the Free Software Foundation.  Sun designates this
   40.11 + * particular file as subject to the "Classpath" exception as provided
   40.12 + * by Sun in the LICENSE file that accompanied this code.
   40.13 + *
   40.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   40.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   40.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   40.17 + * version 2 for more details (a copy is included in the LICENSE file that
   40.18 + * accompanied this code).
   40.19 + *
   40.20 + * You should have received a copy of the GNU General Public License version
   40.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   40.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   40.23 + *
   40.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   40.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   40.26 + * have any questions.
   40.27 + */
   40.28 +
   40.29 +package sun.dyn.util;
   40.30 +
   40.31 +import java.dyn.*;
   40.32 +import java.dyn.MethodHandles.Lookup;
   40.33 +import java.util.EnumMap;
   40.34 +import sun.dyn.Access;
   40.35 +import sun.dyn.AdapterMethodHandle;
   40.36 +import sun.dyn.MethodHandleImpl;
   40.37 +
   40.38 +public class ValueConversions {
   40.39 +    private static final Access IMPL_TOKEN = Access.getToken();
   40.40 +    private static final Lookup IMPL_LOOKUP = MethodHandleImpl.getLookup(IMPL_TOKEN);
   40.41 +
   40.42 +    private static EnumMap<Wrapper, MethodHandle>[] newWrapperCaches(int n) {
   40.43 +        EnumMap<Wrapper, MethodHandle>[] caches
   40.44 +                = (EnumMap<Wrapper, MethodHandle>[]) new EnumMap[n];  // unchecked warning expected here
   40.45 +        for (int i = 0; i < n; i++)
   40.46 +            caches[i] = new EnumMap<Wrapper, MethodHandle>(Wrapper.class);
   40.47 +        return caches;
   40.48 +    }
   40.49 +
   40.50 +    /// Converting references to values.
   40.51 +
   40.52 +    static int unboxInteger(Object x) {
   40.53 +        if (x == null)  return 0;  // never NPE
   40.54 +        return ((Integer) x).intValue();
   40.55 +    }
   40.56 +
   40.57 +    static byte unboxByte(Object x) {
   40.58 +        if (x == null)  return 0;  // never NPE
   40.59 +        return ((Byte) x).byteValue();
   40.60 +    }
   40.61 +
   40.62 +    static short unboxShort(Object x) {
   40.63 +        if (x == null)  return 0;  // never NPE
   40.64 +        return ((Short) x).shortValue();
   40.65 +    }
   40.66 +
   40.67 +    static boolean unboxBoolean(Object x) {
   40.68 +        if (x == null)  return false;  // never NPE
   40.69 +        return ((Boolean) x).booleanValue();
   40.70 +    }
   40.71 +
   40.72 +    static char unboxCharacter(Object x) {
   40.73 +        if (x == null)  return 0;  // never NPE
   40.74 +        return ((Character) x).charValue();
   40.75 +    }
   40.76 +
   40.77 +    static long unboxLong(Object x) {
   40.78 +        if (x == null)  return 0;  // never NPE
   40.79 +        return ((Long) x).longValue();
   40.80 +    }
   40.81 +
   40.82 +    static float unboxFloat(Object x) {
   40.83 +        if (x == null)  return 0;  // never NPE
   40.84 +        return ((Float) x).floatValue();
   40.85 +    }
   40.86 +
   40.87 +    static double unboxDouble(Object x) {
   40.88 +        if (x == null)  return 0;  // never NPE
   40.89 +        return ((Double) x).doubleValue();
   40.90 +    }
   40.91 +
   40.92 +    /// Converting references to "raw" values.
   40.93 +    /// A raw primitive value is always an int or long.
   40.94 +
   40.95 +    static int unboxByteRaw(Object x) {
   40.96 +        return unboxByte(x);
   40.97 +    }
   40.98 +
   40.99 +    static int unboxShortRaw(Object x) {
  40.100 +        return unboxShort(x);
  40.101 +    }
  40.102 +
  40.103 +    static int unboxBooleanRaw(Object x) {
  40.104 +        return unboxBoolean(x) ? 1 : 0;
  40.105 +    }
  40.106 +
  40.107 +    static int unboxCharacterRaw(Object x) {
  40.108 +        return unboxCharacter(x);
  40.109 +    }
  40.110 +
  40.111 +    static int unboxFloatRaw(Object x) {
  40.112 +        return Float.floatToIntBits(unboxFloat(x));
  40.113 +    }
  40.114 +
  40.115 +    static long unboxDoubleRaw(Object x) {
  40.116 +        return Double.doubleToRawLongBits(unboxDouble(x));
  40.117 +    }
  40.118 +
  40.119 +    private static MethodType unboxType(Wrapper wrap, boolean raw) {
  40.120 +        return MethodType.make(rawWrapper(wrap, raw).primitiveType(), wrap.wrapperType());
  40.121 +    }
  40.122 +
  40.123 +    private static final EnumMap<Wrapper, MethodHandle>[]
  40.124 +            UNBOX_CONVERSIONS = newWrapperCaches(4);
  40.125 +
  40.126 +    private static MethodHandle unbox(Wrapper wrap, boolean exact, boolean raw) {
  40.127 +        EnumMap<Wrapper, MethodHandle> cache = UNBOX_CONVERSIONS[(exact?1:0)+(raw?2:0)];
  40.128 +        MethodHandle mh = cache.get(wrap);
  40.129 +        if (mh != null) {
  40.130 +            return mh;
  40.131 +        }
  40.132 +        // slow path
  40.133 +        switch (wrap) {
  40.134 +            case OBJECT:
  40.135 +                mh = IDENTITY; break;
  40.136 +            case VOID:
  40.137 +                mh = raw ? ALWAYS_ZERO : IGNORE; break;
  40.138 +            case INT: case LONG:
  40.139 +                // these guys don't need separate raw channels
  40.140 +                if (raw)  mh = unbox(wrap, exact, false);
  40.141 +                break;
  40.142 +        }
  40.143 +        if (mh != null) {
  40.144 +            cache.put(wrap, mh);
  40.145 +            return mh;
  40.146 +        }
  40.147 +        // look up the method
  40.148 +        String name = "unbox" + wrap.simpleName() + (raw ? "Raw" : "");
  40.149 +        MethodType type = unboxType(wrap, raw);
  40.150 +        if (!exact)
  40.151 +            // actually, type is wrong; the Java method takes Object
  40.152 +            mh = IMPL_LOOKUP.findStatic(ValueConversions.class, name, type.erase());
  40.153 +        else
  40.154 +            mh = retype(type, unbox(wrap, !exact, raw));
  40.155 +        if (mh != null) {
  40.156 +            cache.put(wrap, mh);
  40.157 +            return mh;
  40.158 +        }
  40.159 +        throw new IllegalArgumentException("cannot find unbox adapter for " + wrap + (raw ? " (raw)" : ""));
  40.160 +    }
  40.161 +
  40.162 +    public static MethodHandle unbox(Wrapper type, boolean exact) {
  40.163 +        return unbox(type, exact, false);
  40.164 +    }
  40.165 +
  40.166 +    public static MethodHandle unboxRaw(Wrapper type, boolean exact) {
  40.167 +        return unbox(type, exact, true);
  40.168 +    }
  40.169 +
  40.170 +    public static MethodHandle unbox(Class<?> type, boolean exact) {
  40.171 +        return unbox(Wrapper.forPrimitiveType(type), exact, false);
  40.172 +    }
  40.173 +
  40.174 +    public static MethodHandle unboxRaw(Class<?> type, boolean exact) {
  40.175 +        return unbox(Wrapper.forPrimitiveType(type), exact, true);
  40.176 +    }
  40.177 +
  40.178 +    /// Converting primitives to references
  40.179 +
  40.180 +    static Integer boxInteger(int x) {
  40.181 +        return x;
  40.182 +    }
  40.183 +
  40.184 +    static Byte boxByte(byte x) {
  40.185 +        return x;
  40.186 +    }
  40.187 +
  40.188 +    static Short boxShort(short x) {
  40.189 +        return x;
  40.190 +    }
  40.191 +
  40.192 +    static Boolean boxBoolean(boolean x) {
  40.193 +        return x;
  40.194 +    }
  40.195 +
  40.196 +    static Character boxCharacter(char x) {
  40.197 +        return x;
  40.198 +    }
  40.199 +
  40.200 +    static Long boxLong(long x) {
  40.201 +        return x;
  40.202 +    }
  40.203 +
  40.204 +    static Float boxFloat(float x) {
  40.205 +        return x;
  40.206 +    }
  40.207 +
  40.208 +    static Double boxDouble(double x) {
  40.209 +        return x;
  40.210 +    }
  40.211 +
  40.212 +    /// Converting raw primitives to references
  40.213 +
  40.214 +    static Byte boxByteRaw(int x) {
  40.215 +        return boxByte((byte)x);
  40.216 +    }
  40.217 +
  40.218 +    static Short boxShortRaw(int x) {
  40.219 +        return boxShort((short)x);
  40.220 +    }
  40.221 +
  40.222 +    static Boolean boxBooleanRaw(int x) {
  40.223 +        return boxBoolean(x != 0);
  40.224 +    }
  40.225 +
  40.226 +    static Character boxCharacterRaw(int x) {
  40.227 +        return boxCharacter((char)x);
  40.228 +    }
  40.229 +
  40.230 +    static Float boxFloatRaw(int x) {
  40.231 +        return boxFloat(Float.intBitsToFloat(x));
  40.232 +    }
  40.233 +
  40.234 +    static Double boxDoubleRaw(long x) {
  40.235 +        return boxDouble(Double.longBitsToDouble(x));
  40.236 +    }
  40.237 +
  40.238 +    // a raw void value is (arbitrarily) a garbage int
  40.239 +    static Void boxVoidRaw(int x) {
  40.240 +        return null;
  40.241 +    }
  40.242 +
  40.243 +    private static MethodType boxType(Wrapper wrap, boolean raw) {
  40.244 +        // be exact, since return casts are hard to compose
  40.245 +        Class<?> boxType = wrap.wrapperType();
  40.246 +        return MethodType.make(boxType, rawWrapper(wrap, raw).primitiveType());
  40.247 +    }
  40.248 +
  40.249 +    private static Wrapper rawWrapper(Wrapper wrap, boolean raw) {
  40.250 +        if (raw)  return wrap.isDoubleWord() ? Wrapper.LONG : Wrapper.INT;
  40.251 +        return wrap;
  40.252 +    }
  40.253 +
  40.254 +    private static final EnumMap<Wrapper, MethodHandle>[]
  40.255 +            BOX_CONVERSIONS = newWrapperCaches(4);
  40.256 +
  40.257 +    private static MethodHandle box(Wrapper wrap, boolean exact, boolean raw) {
  40.258 +        EnumMap<Wrapper, MethodHandle> cache = BOX_CONVERSIONS[(exact?1:0)+(raw?2:0)];
  40.259 +        MethodHandle mh = cache.get(wrap);
  40.260 +        if (mh != null) {
  40.261 +            return mh;
  40.262 +        }
  40.263 +        // slow path
  40.264 +        switch (wrap) {
  40.265 +            case OBJECT:
  40.266 +                mh = IDENTITY; break;
  40.267 +            case VOID:
  40.268 +                if (!raw)  mh = ZERO_OBJECT;
  40.269 +                break;
  40.270 +            case INT: case LONG:
  40.271 +                // these guys don't need separate raw channels
  40.272 +                if (raw)  mh = box(wrap, exact, false);
  40.273 +                break;
  40.274 +        }
  40.275 +        if (mh != null) {
  40.276 +            cache.put(wrap, mh);
  40.277 +            return mh;
  40.278 +        }
  40.279 +        // look up the method
  40.280 +        String name = "box" + wrap.simpleName() + (raw ? "Raw" : "");
  40.281 +        MethodType type = boxType(wrap, raw);
  40.282 +        if (exact)
  40.283 +            mh = IMPL_LOOKUP.findStatic(ValueConversions.class, name, type);
  40.284 +        else
  40.285 +            mh = retype(type.erase(), box(wrap, !exact, raw));
  40.286 +        if (mh != null) {
  40.287 +            cache.put(wrap, mh);
  40.288 +            return mh;
  40.289 +        }
  40.290 +        throw new IllegalArgumentException("cannot find box adapter for " + wrap + (raw ? " (raw)" : ""));
  40.291 +    }
  40.292 +
  40.293 +    public static MethodHandle box(Class<?> type, boolean exact) {
  40.294 +        return box(Wrapper.forPrimitiveType(type), exact, false);
  40.295 +    }
  40.296 +
  40.297 +    public static MethodHandle boxRaw(Class<?> type, boolean exact) {
  40.298 +        return box(Wrapper.forPrimitiveType(type), exact, true);
  40.299 +    }
  40.300 +
  40.301 +    public static MethodHandle box(Wrapper type, boolean exact) {
  40.302 +        return box(type, exact, false);
  40.303 +    }
  40.304 +
  40.305 +    public static MethodHandle boxRaw(Wrapper type, boolean exact) {
  40.306 +        return box(type, exact, true);
  40.307 +    }
  40.308 +
  40.309 +    /// Kludges for when raw values get accidentally boxed.
  40.310 +
  40.311 +    static Byte reboxRawByte(Object x) {
  40.312 +        if (x instanceof Byte)  return (Byte) x;
  40.313 +        return boxByteRaw(unboxInteger(x));
  40.314 +    }
  40.315 +
  40.316 +    static Short reboxRawShort(Object x) {
  40.317 +        if (x instanceof Short)  return (Short) x;
  40.318 +        return boxShortRaw(unboxInteger(x));
  40.319 +    }
  40.320 +
  40.321 +    static Boolean reboxRawBoolean(Object x) {
  40.322 +        if (x instanceof Boolean)  return (Boolean) x;
  40.323 +        return boxBooleanRaw(unboxInteger(x));
  40.324 +    }
  40.325 +
  40.326 +    static Character reboxRawCharacter(Object x) {
  40.327 +        if (x instanceof Character)  return (Character) x;
  40.328 +        return boxCharacterRaw(unboxInteger(x));
  40.329 +    }
  40.330 +
  40.331 +    static Float reboxRawFloat(Object x) {
  40.332 +        if (x instanceof Float)  return (Float) x;
  40.333 +        return boxFloatRaw(unboxInteger(x));
  40.334 +    }
  40.335 +
  40.336 +    static Double reboxRawDouble(Object x) {
  40.337 +        if (x instanceof Double)  return (Double) x;
  40.338 +        return boxDoubleRaw(unboxLong(x));
  40.339 +    }
  40.340 +
  40.341 +    private static MethodType reboxType(Wrapper wrap) {
  40.342 +        Class<?> boxType = wrap.wrapperType();
  40.343 +        return MethodType.make(boxType, Object.class);
  40.344 +    }
  40.345 +
  40.346 +    private static final EnumMap<Wrapper, MethodHandle>[]
  40.347 +            REBOX_CONVERSIONS = newWrapperCaches(2);
  40.348 +
  40.349 +    public static MethodHandle rebox(Wrapper wrap, boolean exact) {
  40.350 +        EnumMap<Wrapper, MethodHandle> cache = REBOX_CONVERSIONS[exact?1:0];
  40.351 +        MethodHandle mh = cache.get(wrap);
  40.352 +        if (mh != null) {
  40.353 +            return mh;
  40.354 +        }
  40.355 +        // slow path
  40.356 +        switch (wrap) {
  40.357 +            case OBJECT:
  40.358 +                mh = IDENTITY; break;
  40.359 +            case VOID:
  40.360 +                throw new IllegalArgumentException("cannot rebox a void");
  40.361 +            case INT: case LONG:
  40.362 +                mh = cast(wrap.wrapperType(), exact);
  40.363 +                break;
  40.364 +        }
  40.365 +        if (mh != null) {
  40.366 +            cache.put(wrap, mh);
  40.367 +            return mh;
  40.368 +        }
  40.369 +        // look up the method
  40.370 +        String name = "reboxRaw" + wrap.simpleName();
  40.371 +        MethodType type = reboxType(wrap);
  40.372 +        if (exact)
  40.373 +            mh = IMPL_LOOKUP.findStatic(ValueConversions.class, name, type);
  40.374 +        else
  40.375 +            mh = retype(IDENTITY.type(), rebox(wrap, !exact));
  40.376 +        if (mh != null) {
  40.377 +            cache.put(wrap, mh);
  40.378 +            return mh;
  40.379 +        }
  40.380 +        throw new IllegalArgumentException("cannot find rebox adapter for " + wrap);
  40.381 +    }
  40.382 +
  40.383 +    public static MethodHandle rebox(Class<?> type, boolean exact) {
  40.384 +        return rebox(Wrapper.forPrimitiveType(type), exact);
  40.385 +    }
  40.386 +
  40.387 +    /// Width-changing conversions between int and long.
  40.388 +
  40.389 +    static long widenInt(int x) {
  40.390 +        return x;
  40.391 +    }
  40.392 +
  40.393 +    static int narrowLong(long x) {
  40.394 +        return (int) x;
  40.395 +    }
  40.396 +
  40.397 +    /// Constant functions
  40.398 +
  40.399 +    static void ignore(Object x) {
  40.400 +        // no value to return; this is an unbox of null
  40.401 +        return;
  40.402 +    }
  40.403 +
  40.404 +    static void empty() {
  40.405 +        return;
  40.406 +    }
  40.407 +
  40.408 +    static Object zeroObject() {
  40.409 +        return null;
  40.410 +    }
  40.411 +
  40.412 +    static int zeroInteger() {
  40.413 +        return 0;
  40.414 +    }
  40.415 +
  40.416 +    static long zeroLong() {
  40.417 +        return 0;
  40.418 +    }
  40.419 +
  40.420 +    static float zeroFloat() {
  40.421 +        return 0;
  40.422 +    }
  40.423 +
  40.424 +    static double zeroDouble() {
  40.425 +        return 0;
  40.426 +    }
  40.427 +
  40.428 +    private static final EnumMap<Wrapper, MethodHandle>[]
  40.429 +            ZERO_CONSTANT_FUNCTIONS = newWrapperCaches(1);
  40.430 +
  40.431 +    public static MethodHandle zeroConstantFunction(Wrapper wrap) {
  40.432 +        EnumMap<Wrapper, MethodHandle> cache = ZERO_CONSTANT_FUNCTIONS[0];
  40.433 +        MethodHandle mh = cache.get(wrap);
  40.434 +        if (mh != null) {
  40.435 +            return mh;
  40.436 +        }
  40.437 +        // slow path
  40.438 +        MethodType type = MethodType.make(wrap.primitiveType());
  40.439 +        switch (wrap) {
  40.440 +            case VOID:
  40.441 +                mh = EMPTY;
  40.442 +                break;
  40.443 +            case INT: case LONG: case FLOAT: case DOUBLE:
  40.444 +                mh = IMPL_LOOKUP.findStatic(ValueConversions.class, "zero"+wrap.simpleName(), type);
  40.445 +                break;
  40.446 +        }
  40.447 +        if (mh != null) {
  40.448 +            cache.put(wrap, mh);
  40.449 +            return mh;
  40.450 +        }
  40.451 +
  40.452 +        // use the raw method
  40.453 +        Wrapper rawWrap = wrap.rawPrimitive();
  40.454 +        if (rawWrap != wrap) {
  40.455 +            mh = retype(type, zeroConstantFunction(rawWrap));
  40.456 +        }
  40.457 +        if (mh != null) {
  40.458 +            cache.put(wrap, mh);
  40.459 +            return mh;
  40.460 +        }
  40.461 +        throw new IllegalArgumentException("cannot find zero constant for " + wrap);
  40.462 +    }
  40.463 +
  40.464 +    /// Converting references to references.
  40.465 +
  40.466 +    /**
  40.467 +     * Value-killing function.
  40.468 +     * @param x an arbitrary reference value
  40.469 +     * @return a null
  40.470 +     */
  40.471 +    static Object alwaysNull(Object x) {
  40.472 +        return null;
  40.473 +    }
  40.474 +
  40.475 +    /**
  40.476 +     * Value-killing function.
  40.477 +     * @param x an arbitrary reference value
  40.478 +     * @return a zero
  40.479 +     */
  40.480 +    static int alwaysZero(Object x) {
  40.481 +        return 0;
  40.482 +    }
  40.483 +
  40.484 +    /**
  40.485 +     * Identity function.
  40.486 +     * @param x an arbitrary reference value
  40.487 +     * @return the same value x
  40.488 +     */
  40.489 +    static <T> T identity(T x) {
  40.490 +        return x;
  40.491 +    }
  40.492 +
  40.493 +    /**
  40.494 +     * Identity function, with reference cast.
  40.495 +     * @param t an arbitrary reference type
  40.496 +     * @param x an arbitrary reference value
  40.497 +     * @return the same value x
  40.498 +     */
  40.499 +    static <T,U> T castReference(Class<? extends T> t, U x) {
  40.500 +        return t.cast(x);
  40.501 +    }
  40.502 +
  40.503 +    private static final MethodHandle IDENTITY, CAST_REFERENCE, ALWAYS_NULL, ALWAYS_ZERO, ZERO_OBJECT, IGNORE, EMPTY;
  40.504 +    static {
  40.505 +        try {
  40.506 +            MethodType idType = MethodType.makeGeneric(1);
  40.507 +            MethodType castType = idType.insertParameterType(0, Class.class);
  40.508 +            MethodType alwaysZeroType = idType.changeReturnType(int.class);
  40.509 +            MethodType ignoreType = idType.changeReturnType(void.class);
  40.510 +            MethodType zeroObjectType = MethodType.makeGeneric(0);
  40.511 +            IDENTITY = IMPL_LOOKUP.findStatic(ValueConversions.class, "identity", idType);
  40.512 +            //CAST_REFERENCE = IMPL_LOOKUP.findVirtual(Class.class, "cast", idType);
  40.513 +            CAST_REFERENCE = IMPL_LOOKUP.findStatic(ValueConversions.class, "castReference", castType);
  40.514 +            ALWAYS_NULL = IMPL_LOOKUP.findStatic(ValueConversions.class, "alwaysNull", idType);
  40.515 +            ALWAYS_ZERO = IMPL_LOOKUP.findStatic(ValueConversions.class, "alwaysZero", alwaysZeroType);
  40.516 +            ZERO_OBJECT = IMPL_LOOKUP.findStatic(ValueConversions.class, "zeroObject", zeroObjectType);
  40.517 +            IGNORE = IMPL_LOOKUP.findStatic(ValueConversions.class, "ignore", ignoreType);
  40.518 +            EMPTY = IMPL_LOOKUP.findStatic(ValueConversions.class, "empty", ignoreType.dropParameterType(0));
  40.519 +        } catch (RuntimeException ex) {
  40.520 +            throw ex;
  40.521 +        }
  40.522 +    }
  40.523 +
  40.524 +    private static final EnumMap<Wrapper, MethodHandle> WRAPPER_CASTS
  40.525 +            = new EnumMap<Wrapper, MethodHandle>(Wrapper.class);
  40.526 +
  40.527 +    private static final EnumMap<Wrapper, MethodHandle> EXACT_WRAPPER_CASTS
  40.528 +            = new EnumMap<Wrapper, MethodHandle>(Wrapper.class);
  40.529 +
  40.530 +    /** Return a method that casts its sole argument (an Object) to the given type
  40.531 +     *  and returns it as the given type (if exact is true), or as plain Object (if erase is true).
  40.532 +     */
  40.533 +    public static MethodHandle cast(Class<?> type, boolean exact) {
  40.534 +        if (type.isPrimitive())  throw new IllegalArgumentException("cannot cast primitive type "+type);
  40.535 +        MethodHandle mh = null;
  40.536 +        Wrapper wrap = null;
  40.537 +        EnumMap<Wrapper, MethodHandle> cache = null;
  40.538 +        if (Wrapper.isWrapperType(type)) {
  40.539 +            wrap = Wrapper.forWrapperType(type);
  40.540 +            cache = (exact ? EXACT_WRAPPER_CASTS : WRAPPER_CASTS);
  40.541 +            mh = cache.get(wrap);
  40.542 +            if (mh != null)  return mh;
  40.543 +        }
  40.544 +        if (VerifyType.isNullReferenceConversion(Object.class, type))
  40.545 +            mh = IDENTITY;
  40.546 +        else if (VerifyType.isNullType(type))
  40.547 +            mh = ALWAYS_NULL;
  40.548 +        else
  40.549 +            mh = MethodHandles.insertArgument(CAST_REFERENCE, 0, type);
  40.550 +        if (exact) {
  40.551 +            MethodType xmt = MethodType.make(type, Object.class);
  40.552 +            mh = AdapterMethodHandle.makeRawRetypeOnly(IMPL_TOKEN, xmt, mh);
  40.553 +        }
  40.554 +        if (cache != null)
  40.555 +            cache.put(wrap, mh);
  40.556 +        return mh;
  40.557 +    }
  40.558 +
  40.559 +    public static MethodHandle identity() {
  40.560 +        return IDENTITY;
  40.561 +    }
  40.562 +
  40.563 +    private static MethodHandle retype(MethodType type, MethodHandle mh) {
  40.564 +        return AdapterMethodHandle.makeRetypeOnly(IMPL_TOKEN, type, mh);
  40.565 +    }
  40.566 +}
    41.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    41.2 +++ b/src/share/classes/sun/dyn/util/VerifyAccess.java	Tue May 05 22:40:09 2009 -0700
    41.3 @@ -0,0 +1,169 @@
    41.4 +/*
    41.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    41.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    41.7 + *
    41.8 + * This code is free software; you can redistribute it and/or modify it
    41.9 + * under the terms of the GNU General Public License version 2 only, as
   41.10 + * published by the Free Software Foundation.  Sun designates this
   41.11 + * particular file as subject to the "Classpath" exception as provided
   41.12 + * by Sun in the LICENSE file that accompanied this code.
   41.13 + *
   41.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   41.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   41.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   41.17 + * version 2 for more details (a copy is included in the LICENSE file that
   41.18 + * accompanied this code).
   41.19 + *
   41.20 + * You should have received a copy of the GNU General Public License version
   41.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   41.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   41.23 + *
   41.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   41.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   41.26 + * have any questions.
   41.27 + */
   41.28 +
   41.29 +package sun.dyn.util;
   41.30 +
   41.31 +import java.dyn.LinkagePermission;
   41.32 +import java.lang.reflect.Modifier;
   41.33 +import sun.dyn.Access;
   41.34 +
   41.35 +/**
   41.36 + * This class centralizes information about the JVM's linkage access control.
   41.37 + * @author jrose
   41.38 + */
   41.39 +public class VerifyAccess {
   41.40 +
   41.41 +    private VerifyAccess() { }  // cannot instantiate
   41.42 +
   41.43 +    /**
   41.44 +     * Evaluate the JVM linkage rules for access to the given method on behalf of caller.
   41.45 +     * Return non-null if and only if the given accessing class has at least partial
   41.46 +     * privileges to invoke the given method.  The return value {@code Object.class}
   41.47 +     * denotes unlimited privileges.
   41.48 +     * <p>
   41.49 +     * Some circumstances require an additional check on the
   41.50 +     * leading parameter (the receiver) of the method, if it is non-static.
   41.51 +     * In the case of {@code invokespecial} ({@code doDispatch} is false),
   41.52 +     * the leading parameter must be the accessing class or a subclass.
   41.53 +     * In the case of a call to a {@code protected} method outside the same
   41.54 +     * package, the same constraint applies.
   41.55 +     * @param m the proposed callee
   41.56 +     * @param doDispatch if false, a non-static m will be invoked as if by {@code invokespecial}
   41.57 +     * @param lookupClass the class for which the access check is being made
   41.58 +     * @return null if the method is not accessible, else a receiver type constraint, else {@code Object.class}
   41.59 +     */
   41.60 +    public static Class<?> isAccessible(Class<?> defc, int mods,
   41.61 +            boolean doDispatch, Class<?> lookupClass) {
   41.62 +        if (!isAccessible(defc, lookupClass))
   41.63 +            return null;
   41.64 +        Class<?> constraint = Object.class;
   41.65 +        if (!doDispatch && !Modifier.isStatic(mods)) {
   41.66 +            constraint = lookupClass;
   41.67 +        }
   41.68 +        if (Modifier.isPublic(mods))
   41.69 +            return constraint;
   41.70 +        if (Modifier.isPrivate(mods))
   41.71 +            return isSamePackageMember(defc, lookupClass) ? constraint : null;
   41.72 +        if (isSamePackage(defc, lookupClass))
   41.73 +            return constraint;
   41.74 +        if (Modifier.isProtected(mods) && defc.isAssignableFrom(lookupClass))
   41.75 +            return constraint;
   41.76 +        // else it is private or package scoped, and not close enough
   41.77 +        return null;
   41.78 +    }
   41.79 +
   41.80 +    /**
   41.81 +     * Evaluate the JVM linkage rules for access to the given class on behalf of caller.
   41.82 +     */
   41.83 +    public static boolean isAccessible(Class<?> refc, Class<?> lookupClass) {
   41.84 +        int mods = refc.getModifiers();
   41.85 +        if (Modifier.isPublic(mods))
   41.86 +            return true;
   41.87 +        if (isSamePackage(lookupClass, refc))
   41.88 +            return true;
   41.89 +        return false;
   41.90 +    }
   41.91 +
   41.92 +    /**
   41.93 +     * Test if two classes have the same class loader and package qualifier.
   41.94 +     * @param class1
   41.95 +     * @param class2
   41.96 +     * @return whether they are in the same package
   41.97 +     */
   41.98 +    public static boolean isSamePackage(Class<?> class1, Class<?> class2) {
   41.99 +        if (class1 == class2)
  41.100 +            return true;
  41.101 +        if (loadersAreRelated(class1.getClassLoader(), class2.getClassLoader()))
  41.102 +            return false;
  41.103 +        String name1 = class1.getName(), name2 = class2.getName();
  41.104 +        int dot = name1.lastIndexOf('.');
  41.105 +        if (dot != name2.lastIndexOf('.'))
  41.106 +            return false;
  41.107 +        for (int i = 0; i < dot; i++) {
  41.108 +            if (name1.charAt(i) != name2.charAt(i))
  41.109 +                return false;
  41.110 +        }
  41.111 +        return true;
  41.112 +    }
  41.113 +
  41.114 +    /**
  41.115 +     * Test if two classes are defined as part of the same package member (top-level class).
  41.116 +     * If this is true, they can share private access with each other.
  41.117 +     * @param class1
  41.118 +     * @param class2
  41.119 +     * @return whether they are identical or nested together
  41.120 +     */
  41.121 +    public static boolean isSamePackageMember(Class<?> class1, Class<?> class2) {
  41.122 +        if (class1 == class2)
  41.123 +            return true;
  41.124 +        if (!isSamePackage(class1, class2))
  41.125 +            return false;
  41.126 +        if (getOutermostEnclosingClass(class1) != getOutermostEnclosingClass(class2))
  41.127 +            return false;
  41.128 +        return true;
  41.129 +    }
  41.130 +
  41.131 +    private static Class<?> getOutermostEnclosingClass(Class<?> c) {
  41.132 +        Class<?> pkgmem = c;
  41.133 +        for (Class<?> enc = c; (enc = enc.getEnclosingClass()) != null; )
  41.134 +            pkgmem = enc;
  41.135 +        return pkgmem;
  41.136 +    }
  41.137 +
  41.138 +    private static boolean loadersAreRelated(ClassLoader loader1, ClassLoader loader2) {
  41.139 +        if (loader1 == loader2 || loader1 == null || loader2 == null) {
  41.140 +            return true;
  41.141 +        }
  41.142 +        for (ClassLoader scan1 = loader1;
  41.143 +                scan1 != null; scan1 = scan1.getParent()) {
  41.144 +            if (scan1 == loader2)  return true;
  41.145 +        }
  41.146 +        for (ClassLoader scan2 = loader2;
  41.147 +                scan2 != null; scan2 = scan2.getParent()) {
  41.148 +            if (scan2 == loader1)  return true;
  41.149 +        }
  41.150 +        return false;
  41.151 +    }
  41.152 +
  41.153 +    /**
  41.154 +     * Ensure the requesting class have privileges to perform invokedynamic
  41.155 +     * linkage operations on subjectClass.  True if requestingClass is
  41.156 +     * Access.class (meaning the request originates from the JVM) or if the
  41.157 +     * classes are in the same package and have consistent class loaders.
  41.158 +     * (The subject class loader must be identical with or be a child of
  41.159 +     * the requesting class loader.)
  41.160 +     * @param requestingClass
  41.161 +     * @param subjectClass
  41.162 +     */
  41.163 +    public static void checkBootstrapPrivilege(Class requestingClass, Class subjectClass,
  41.164 +                                               String permissionName) {
  41.165 +        if (requestingClass == Access.class)  return;
  41.166 +        if (requestingClass == subjectClass)  return;
  41.167 +        SecurityManager security = System.getSecurityManager();
  41.168 +        if (security == null)  return;  // open season
  41.169 +        if (isSamePackage(requestingClass, subjectClass))  return;
  41.170 +        security.checkPermission(new LinkagePermission(permissionName, requestingClass));
  41.171 +    }
  41.172 +}
    42.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    42.2 +++ b/src/share/classes/sun/dyn/util/VerifyType.java	Tue May 05 22:40:09 2009 -0700
    42.3 @@ -0,0 +1,219 @@
    42.4 +/*
    42.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    42.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    42.7 + *
    42.8 + * This code is free software; you can redistribute it and/or modify it
    42.9 + * under the terms of the GNU General Public License version 2 only, as
   42.10 + * published by the Free Software Foundation.  Sun designates this
   42.11 + * particular file as subject to the "Classpath" exception as provided
   42.12 + * by Sun in the LICENSE file that accompanied this code.
   42.13 + *
   42.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   42.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   42.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   42.17 + * version 2 for more details (a copy is included in the LICENSE file that
   42.18 + * accompanied this code).
   42.19 + *
   42.20 + * You should have received a copy of the GNU General Public License version
   42.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   42.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   42.23 + *
   42.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   42.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   42.26 + * have any questions.
   42.27 + */
   42.28 +
   42.29 +package sun.dyn.util;
   42.30 +
   42.31 +import java.dyn.MethodType;
   42.32 +
   42.33 +/**
   42.34 + * This class centralizes information about the JVM verifier
   42.35 + * and its requirements about type correctness.
   42.36 + * @author jrose
   42.37 + */
   42.38 +public class VerifyType {
   42.39 +
   42.40 +    private VerifyType() { }  // cannot instantiate
   42.41 +
   42.42 +    /**
   42.43 +     * True if a value can be stacked as the source type and unstacked as the
   42.44 +     * destination type, without violating the JVM's type consistency.
   42.45 +     *
   42.46 +     * @param call the type of a stacked value
   42.47 +     * @param recv the type by which we'd like to treat it
   42.48 +     * @return whether the retyping can be done without motion or reformatting
   42.49 +     */
   42.50 +    public static boolean isNullConversion(Class<?> src, Class<?> dst) {
   42.51 +        if (src == dst)            return true;
   42.52 +        // Verifier allows any interface to be treated as Object:
   42.53 +        if (dst.isInterface())     dst = Object.class;
   42.54 +        if (src.isInterface())     src = Object.class;
   42.55 +        if (src == dst)            return true;  // check again
   42.56 +        if (dst == void.class)     return true;  // drop any return value
   42.57 +        if (isNullType(src))       return !dst.isPrimitive();
   42.58 +        if (!src.isPrimitive())    return dst.isAssignableFrom(src);
   42.59 +        // Verifier allows an int to carry byte, short, char, or even boolean:
   42.60 +        if (dst == int.class)      return Wrapper.forPrimitiveType(src).isSubwordOrInt();
   42.61 +        return false;
   42.62 +    }
   42.63 +
   42.64 +    /**
   42.65 +     * Specialization of isNullConversion to reference types.
   42.66 +
   42.67 +     * @param call the type of a stacked value
   42.68 +     * @param recv the reference type by which we'd like to treat it
   42.69 +     * @return whether the retyping can be done without a cast
   42.70 +     */
   42.71 +    public static boolean isNullReferenceConversion(Class<?> src, Class<?> dst) {
   42.72 +        assert(!dst.isPrimitive());
   42.73 +        if (dst.isInterface())  return true;   // verifier allows this
   42.74 +        if (isNullType(src))    return true;
   42.75 +        return dst.isAssignableFrom(src);
   42.76 +    }
   42.77 +
   42.78 +    /**
   42.79 +     * Is the given type either java.lang.Void or java.lang.Null?
   42.80 +     * These types serve as markers for bare nulls and therefore
   42.81 +     * may be promoted to any type.  This is secure, since
   42.82 +     */
   42.83 +    public static boolean isNullType(Class<?> type) {
   42.84 +        if (type == null)  return false;
   42.85 +        return type == NULL_CLASS_1 || type == NULL_CLASS_2;
   42.86 +    }
   42.87 +    private static final Class<?> NULL_CLASS_1, NULL_CLASS_2;
   42.88 +    static {
   42.89 +        Class<?> nullClass1 = null, nullClass2 = null;
   42.90 +        try {
   42.91 +            nullClass1 = Class.forName("java.lang.Null");
   42.92 +        } catch (ClassNotFoundException ex) {
   42.93 +            // OK, we'll cope
   42.94 +        }
   42.95 +        NULL_CLASS_1 = nullClass1;
   42.96 +
   42.97 +        // This one may also be used as a null type.
   42.98 +        // TO DO: Decide if we really want to legitimize it here.
   42.99 +        // Probably we do, unless java.lang.Null really makes it into Java 7
  42.100 +        nullClass2 = Void.class;
  42.101 +        NULL_CLASS_2 = nullClass2;
  42.102 +    }
  42.103 +
  42.104 +    /**
  42.105 +     * True if a method handle can receive a call under a slightly different
  42.106 +     * method type, without moving or reformatting any stack elements.
  42.107 +     *
  42.108 +     * @param call the type of call being made
  42.109 +     * @param recv the type of the method handle receiving the call
  42.110 +     * @return whether the retyping can be done without motion or reformatting
  42.111 +     */
  42.112 +    public static boolean isNullConversion(MethodType call, MethodType recv) {
  42.113 +        if (call == recv)  return true;
  42.114 +        int len = call.parameterCount();
  42.115 +        if (len != recv.parameterCount())  return false;
  42.116 +        for (int i = 0; i < len; i++)
  42.117 +            if (!isNullConversion(call.parameterType(i), recv.parameterType(i)))
  42.118 +                return false;
  42.119 +        return isNullConversion(recv.returnType(), call.returnType());
  42.120 +    }
  42.121 +
  42.122 +    //TO DO: isRawConversion
  42.123 +
  42.124 +    /**
  42.125 +     * Determine if the JVM verifier allows a value of type call to be
  42.126 +     * passed to a formal parameter (or return variable) of type recv.
  42.127 +     * Returns 1 if the verifier allows the types to match without conversion.
  42.128 +     * Returns -1 if the types can be made to match by a JVM-supported adapter.
  42.129 +     * Cases supported are:
  42.130 +     * <ul><li>checkcast
  42.131 +     * </li><li>conversion between any two integral types (but not floats)
  42.132 +     * </li><li>unboxing from a wrapper to its corresponding primitive type
  42.133 +     * </li><li>conversion in either direction between float and double
  42.134 +     * </li></ul>
  42.135 +     * (Autoboxing is not supported here; it must be done via Java code.)
  42.136 +     * Returns 0 otherwise.
  42.137 +     */
  42.138 +    public static int canPassUnchecked(Class<?> src, Class<?> dst) {
  42.139 +        if (src == dst)
  42.140 +            return 1;
  42.141 +
  42.142 +        if (dst.isPrimitive()) {
  42.143 +            if (dst == void.class)
  42.144 +                // Return anything to a caller expecting void.
  42.145 +                // This is a property of the implementation, which links
  42.146 +                // return values via a register rather than via a stack push.
  42.147 +                // This makes it possible to ignore cleanly.
  42.148 +                return 1;
  42.149 +            if (src == void.class)
  42.150 +                return 0;  // void-to-something?
  42.151 +            if (!src.isPrimitive())
  42.152 +                // Cannot pass a reference to any primitive type (exc. void).
  42.153 +                return 0;
  42.154 +            Wrapper sw = Wrapper.forPrimitiveType(src);
  42.155 +            Wrapper dw = Wrapper.forPrimitiveType(dst);
  42.156 +            if (sw.isSubwordOrInt() && dw.isSubwordOrInt()) {
  42.157 +                if (sw.bitWidth() >= dw.bitWidth())
  42.158 +                    return -1;   // truncation may be required
  42.159 +                if (!dw.isSigned() && sw.isSigned())
  42.160 +                    return -1;   // sign elimination may be required
  42.161 +            }
  42.162 +            if (src == float.class || dst == float.class) {
  42.163 +                if (src == double.class || dst == double.class)
  42.164 +                    return -1;   // floating conversion may be required
  42.165 +                else
  42.166 +                    return 0;    // other primitive conversions NYI
  42.167 +            } else {
  42.168 +                // all fixed-point conversions are supported
  42.169 +                return 0;
  42.170 +            }
  42.171 +        } else if (src.isPrimitive()) {
  42.172 +            // Cannot pass a primitive to any reference type.
  42.173 +            // (Maybe allow null.class?)
  42.174 +            return 0;
  42.175 +        }
  42.176 +
  42.177 +        // Handle reference types in the rest of the block:
  42.178 +
  42.179 +        // The verifier treats interfaces exactly like Object.
  42.180 +        if (isNullReferenceConversion(src, dst))
  42.181 +            // pass any reference to object or an arb. interface
  42.182 +            return 1;
  42.183 +        // else it's a definite "maybe" (cast is required)
  42.184 +        return -1;
  42.185 +    }
  42.186 +
  42.187 +    public static int canPassRaw(Class<?> src, Class<?> dst) {
  42.188 +        if (dst.isPrimitive()) {
  42.189 +            if (dst == void.class)
  42.190 +                // As above, return anything to a caller expecting void.
  42.191 +                return 1;
  42.192 +            if (src == void.class)
  42.193 +                // Special permission for raw conversions: allow a void
  42.194 +                // to be captured as a garbage int.
  42.195 +                // Caller promises that the actual value will be disregarded.
  42.196 +                return dst == int.class ? 1 : 0;
  42.197 +            if (!src.isPrimitive())
  42.198 +                return 0;
  42.199 +            Wrapper sw = Wrapper.forPrimitiveType(src);
  42.200 +            Wrapper dw = Wrapper.forPrimitiveType(dst);
  42.201 +            if (sw.stackSlots() == dw.stackSlots())
  42.202 +                return 1;  // can do a reinterpret-cast on a stacked primitive
  42.203 +            if (sw.isSubwordOrInt() && dw == Wrapper.VOID)
  42.204 +                return 1;  // can drop an outgoing int value
  42.205 +            return 0;
  42.206 +        } else if (src.isPrimitive()) {
  42.207 +            return 0;
  42.208 +        }
  42.209 +
  42.210 +        // Both references.
  42.211 +        if (isNullReferenceConversion(src, dst))
  42.212 +            return 1;
  42.213 +        return -1;
  42.214 +    }
  42.215 +
  42.216 +    public static boolean isSpreadArgType(Class<?> spreadArg) {
  42.217 +        return spreadArg.isArray();
  42.218 +    }
  42.219 +    public static Class<?> spreadArgElementType(Class<?> spreadArg, int i) {
  42.220 +        return spreadArg.getComponentType();
  42.221 +    }
  42.222 +}
    43.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    43.2 +++ b/src/share/classes/sun/dyn/util/Wrapper.java	Tue May 05 22:40:09 2009 -0700
    43.3 @@ -0,0 +1,467 @@
    43.4 +/*
    43.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    43.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    43.7 + *
    43.8 + * This code is free software; you can redistribute it and/or modify it
    43.9 + * under the terms of the GNU General Public License version 2 only, as
   43.10 + * published by the Free Software Foundation.  Sun designates this
   43.11 + * particular file as subject to the "Classpath" exception as provided
   43.12 + * by Sun in the LICENSE file that accompanied this code.
   43.13 + *
   43.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   43.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   43.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   43.17 + * version 2 for more details (a copy is included in the LICENSE file that
   43.18 + * accompanied this code).
   43.19 + *
   43.20 + * You should have received a copy of the GNU General Public License version
   43.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   43.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   43.23 + *
   43.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   43.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   43.26 + * have any questions.
   43.27 + */
   43.28 +
   43.29 +package sun.dyn.util;
   43.30 +
   43.31 +public enum Wrapper {
   43.32 +    INT(Integer.class, int.class, 'I', (Integer)(int)0, Format.signed(32)),
   43.33 +    LONG(Long.class, long.class, 'J', (Long)(long)0, Format.signed(64)),
   43.34 +    BYTE(Byte.class, byte.class, 'B', (Byte)(byte)0, Format.signed(8)),
   43.35 +    SHORT(Short.class, short.class, 'S', (Short)(short)0, Format.signed(16)),
   43.36 +    CHAR(Character.class, char.class, 'C', (Character)(char)0, Format.unsigned(16)),
   43.37 +    BOOLEAN(Boolean.class, boolean.class, 'Z', (Boolean)false, Format.unsigned(1)),
   43.38 +    FLOAT(Float.class, float.class, 'F', (Float)(float)0, Format.floating(32)),
   43.39 +    DOUBLE(Double.class, double.class, 'D', (Double)(double)0, Format.floating(64)),
   43.40 +    VOID(Void.class, void.class, 'V', null, Format.other(0)),
   43.41 +    //NULL(Null.class, null.class, 'N', null, Format.other(1)),
   43.42 +    OBJECT(Object.class, Object.class, 'L', null, Format.other(1)),
   43.43 +    ;
   43.44 +
   43.45 +    private final Class<?> wrapperType;
   43.46 +    private final Class<?> primitiveType;
   43.47 +    private final char     basicTypeChar;
   43.48 +    private final Object   zero;
   43.49 +    private final int      format;
   43.50 +    private final String   simpleName;
   43.51 +
   43.52 +    private Wrapper(Class<?> wtype, Class<?> ptype, char tchar, Object zero, int format) {
   43.53 +        this.wrapperType = wtype;
   43.54 +        this.primitiveType = ptype;
   43.55 +        this.basicTypeChar = tchar;
   43.56 +        this.zero = zero;
   43.57 +        this.format = format;
   43.58 +        this.simpleName = wtype.getSimpleName();
   43.59 +    }
   43.60 +
   43.61 +    private static abstract class Format {
   43.62 +        static final int SLOT_SHIFT = 0, SIZE_SHIFT = 2, KIND_SHIFT = 12;
   43.63 +        static final int
   43.64 +                SIGNED   = (-1) << KIND_SHIFT,
   43.65 +                UNSIGNED = 0    << KIND_SHIFT,
   43.66 +                FLOATING = 1    << KIND_SHIFT;
   43.67 +        static final int
   43.68 +                SLOT_MASK = ((1<<(SIZE_SHIFT-SLOT_SHIFT))-1),
   43.69 +                SIZE_MASK = ((1<<(KIND_SHIFT-SIZE_SHIFT))-1);
   43.70 +        static int format(int kind, int size, int slots) {
   43.71 +            assert(((kind >> KIND_SHIFT) << KIND_SHIFT) == kind);
   43.72 +            assert((size & (size-1)) == 0); // power of two
   43.73 +            assert((kind == SIGNED)   ? (size > 0) :
   43.74 +                   (kind == UNSIGNED) ? (size > 0) :
   43.75 +                   (kind == FLOATING) ? (size == 32 || size == 64)  :
   43.76 +                   false);
   43.77 +            assert((slots == 2) ? (size == 64) :
   43.78 +                   (slots == 1) ? (size <= 32) :
   43.79 +                   false);
   43.80 +            return kind | (size << SIZE_SHIFT) | (slots << SLOT_SHIFT);
   43.81 +        }
   43.82 +        static int
   43.83 +                INT      = SIGNED   | (32 << SIZE_SHIFT) | (1 << SLOT_SHIFT),
   43.84 +                BOOLEAN  = UNSIGNED | (1  << SIZE_SHIFT) | (1 << SLOT_SHIFT),
   43.85 +                FLOAT    = FLOATING | (32 << SIZE_SHIFT) | (1 << SLOT_SHIFT),
   43.86 +                VOID     = UNSIGNED | (0  << SIZE_SHIFT) | (0 << SLOT_SHIFT),
   43.87 +                NUM_MASK = (-1) << SIZE_SHIFT;
   43.88 +        static int signed(int size)   { return format(SIGNED,   size, (size > 32 ? 2 : 1)); }
   43.89 +        static int unsigned(int size) { return format(UNSIGNED, size, (size > 32 ? 2 : 1)); }
   43.90 +        static int floating(int size) { return format(FLOATING, size, (size > 32 ? 2 : 1)); }
   43.91 +        static int other(int slots)   { return slots << SLOT_SHIFT; }
   43.92 +    }
   43.93 +
   43.94 +    /// format queries:
   43.95 +
   43.96 +    /** How many bits are in the wrapped value?  Returns 0 for OBJECT or VOID. */
   43.97 +    public int     bitWidth()      { return (format >> Format.SIZE_SHIFT) & Format.SIZE_MASK; }
   43.98 +    /** How many JVM stack slots occupied by the wrapped value?  Returns 0 for VOID. */
   43.99 +    public int     stackSlots()    { return (format >> Format.SLOT_SHIFT) & Format.SLOT_MASK; }
  43.100 +    /** Does the wrapped value occupy a single JVM stack slot? */
  43.101 +    public boolean isSingleWord()  { return (format & (1 << Format.SLOT_SHIFT)) != 0; }
  43.102 +    /** Does the wrapped value occupy two JVM stack slots? */
  43.103 +    public boolean isDoubleWord()  { return (format & (2 << Format.SLOT_SHIFT)) != 0; }
  43.104 +    /** Is the wrapped type numeric (not void or object)? */
  43.105 +    public boolean isNumeric()     { return (format & Format.NUM_MASK) != 0; }
  43.106 +    /** Is the wrapped type a primitive other than float, double, or void? */
  43.107 +    public boolean isIntegral()    { return isNumeric() && format < Format.FLOAT; }
  43.108 +    /** Is the wrapped type one of int, boolean, byte, char, or short? */
  43.109 +    public boolean isSubwordOrInt() { return isIntegral() && isSingleWord(); }
  43.110 +    /* Is the wrapped value a signed integral type (one of byte, short, int, or long)? */
  43.111 +    public boolean isSigned()      { return format < Format.VOID; }
  43.112 +    /* Is the wrapped value an unsigned integral type (one of boolean or char)? */
  43.113 +    public boolean isUnsigned()    { return format >= Format.BOOLEAN && format < Format.FLOAT; }
  43.114 +    /** Is the wrapped type either float or double? */
  43.115 +    public boolean isFloating()    { return format >= Format.FLOAT; }
  43.116 +
  43.117 +    /** Produce a zero value for the given wrapper type.
  43.118 +     *  This will be a numeric zero for a number or character,
  43.119 +     *  false for a boolean, and null for a reference or void.
  43.120 +     *  The common thread is that this is what is contained
  43.121 +     *  in a default-initialized variable of the given primitive
  43.122 +     *  type.  (For void, it is what a reflective method returns
  43.123 +     *  instead of no value at all.)
  43.124 +     */
  43.125 +    public Object zero() { return zero; }
  43.126 +
  43.127 +    /** Produce a zero value for the given wrapper type T.
  43.128 +     *  The optinoal argument must a type compatible with this wrapper.
  43.129 +     *  Equivalent to {@code this.cast(this.zero(), type)}.
  43.130 +     */
  43.131 +    public <T> T zero(Class<T> type) { return cast(zero, type); }
  43.132 +
  43.133 +//    /** Produce a wrapper for the given wrapper or primitive type. */
  43.134 +//    public static Wrapper valueOf(Class<?> type) {
  43.135 +//        if (isPrimitiveType(type))
  43.136 +//            return forPrimitiveType(type);
  43.137 +//        else
  43.138 +//            return forWrapperType(type);
  43.139 +//    }
  43.140 +
  43.141 +    /** Return the wrapper that wraps values of the given type.
  43.142 +     *  The type may be {@code Object}, meaning the {@code OBJECT} wrapper.
  43.143 +     *  Otherwise, the type must be a primitive.
  43.144 +     *  @throws IllegalArgumentException for unexpected types
  43.145 +     */
  43.146 +    public static Wrapper forPrimitiveType(Class<?> type) {
  43.147 +        Wrapper w = FROM_PRIM[hashPrim(type)];
  43.148 +        if (w != null && w.primitiveType == type) {
  43.149 +            return w;
  43.150 +        }
  43.151 +        if (type.isPrimitive())
  43.152 +            throw new InternalError(); // redo hash function
  43.153 +        throw newIllegalArgumentException("not primitive: "+type);
  43.154 +    }
  43.155 +
  43.156 +    /** Return the wrapper that wraps values into the given wrapper type.
  43.157 +     *  If it is {@code Object} or an interface, return {@code OBJECT}.
  43.158 +     *  Otherwise, it must be a wrapper type.
  43.159 +     *  The type must not be a primitive type.
  43.160 +     *  @throws IllegalArgumentException for unexpected types
  43.161 +     */
  43.162 +    public static Wrapper forWrapperType(Class<?> type) {
  43.163 +        Wrapper w = findWrapperType(type);
  43.164 +        if (w != null)  return w;
  43.165 +        for (Wrapper x : values())
  43.166 +            if (w.wrapperType == type)
  43.167 +                throw new InternalError(); // redo hash function
  43.168 +        throw newIllegalArgumentException("not wrapper: "+type);
  43.169 +    }
  43.170 +
  43.171 +    static Wrapper findWrapperType(Class<?> type) {
  43.172 +        Wrapper w = FROM_WRAP[hashWrap(type)];
  43.173 +        if (w != null && w.wrapperType == type) {
  43.174 +            return w;
  43.175 +        }
  43.176 +        if (type.isInterface())
  43.177 +            return OBJECT;
  43.178 +        return null;
  43.179 +    }
  43.180 +
  43.181 +    /** Return the wrapper that corresponds to the given bytecode
  43.182 +     *  signature character.  Return {@code OBJECT} for the character 'L'.
  43.183 +     *  @throws IllegalArgumentException for any non-signature character or {@code '['}.
  43.184 +     */
  43.185 +    public static Wrapper forBasicType(char type) {
  43.186 +        Wrapper w = FROM_CHAR[hashChar(type)];
  43.187 +        if (w != null && w.basicTypeChar == type) {
  43.188 +            return w;
  43.189 +        }
  43.190 +        for (Wrapper x : values())
  43.191 +            if (w.basicTypeChar == type)
  43.192 +                throw new InternalError(); // redo hash function
  43.193 +        throw newIllegalArgumentException("not basic type char: "+type);
  43.194 +    }
  43.195 +
  43.196 +    /** Return the wrapper for the given type, if it is
  43.197 +     *  a primitive type, else return {@code OBJECT}.
  43.198 +     */
  43.199 +    public static Wrapper forBasicType(Class<?> type) {
  43.200 +        if (type.isPrimitive())
  43.201 +            return forPrimitiveType(type);
  43.202 +        return OBJECT;  // any reference, including wrappers or arrays
  43.203 +    }
  43.204 +
  43.205 +    // Note on perfect hashes:
  43.206 +    //   for signature chars c, do (c + (c >> 1)) % 16
  43.207 +    //   for primitive type names n, do (n[0] + n[2]) % 16
  43.208 +    // The type name hash works for both primitive and wrapper names.
  43.209 +    // You can add "java/lang/Object" to the primitive names.
  43.210 +    // But you add the wrapper name Object, use (n[2] + (3*n[1])) % 16.
  43.211 +    private static final Wrapper[] FROM_PRIM = new Wrapper[16];
  43.212 +    private static final Wrapper[] FROM_WRAP = new Wrapper[16];
  43.213 +    private static final Wrapper[] FROM_CHAR = new Wrapper[16];
  43.214 +    private static int hashPrim(Class<?> x) {
  43.215 +        String xn = x.getName();
  43.216 +        if (xn.length() < 3)  return 0;
  43.217 +        return (xn.charAt(0) + xn.charAt(2)) % 16;
  43.218 +    }
  43.219 +    private static int hashWrap(Class<?> x) {
  43.220 +        String xn = x.getName();
  43.221 +        final int offset = 10; assert(offset == "java.lang.".length());
  43.222 +        if (xn.length() < offset+3)  return 0;
  43.223 +        return (3*xn.charAt(offset+1) + xn.charAt(offset+2)) % 16;
  43.224 +    }
  43.225 +    private static int hashChar(char x) {
  43.226 +        return (x + (x >> 1)) % 16;
  43.227 +    }
  43.228 +    static {
  43.229 +        for (Wrapper w : values()) {
  43.230 +            int pi = hashPrim(w.primitiveType);
  43.231 +            int wi = hashWrap(w.wrapperType);
  43.232 +            int ci = hashChar(w.basicTypeChar);
  43.233 +            assert(FROM_PRIM[pi] == null);
  43.234 +            assert(FROM_WRAP[wi] == null);
  43.235 +            assert(FROM_CHAR[ci] == null);
  43.236 +            FROM_PRIM[pi] = w;
  43.237 +            FROM_WRAP[wi] = w;
  43.238 +            FROM_CHAR[ci] = w;
  43.239 +        }
  43.240 +        //assert(jdk.sun.dyn.util.WrapperTest.test(false));
  43.241 +    }
  43.242 +
  43.243 +    /** What is the primitive type wrapped by this wrapper? */
  43.244 +    public Class<?> primitiveType() { return primitiveType; }
  43.245 +
  43.246 +    /** What is the wrapper type for this wrapper? */
  43.247 +    public Class<?> wrapperType() { return wrapperType; }
  43.248 +
  43.249 +    /** What is the wrapper type for this wrapper?
  43.250 +     * The example type must be the wrapper type,
  43.251 +     * or the corresponding primitive type.
  43.252 +     * The resulting class type has the same type parameter.
  43.253 +     */
  43.254 +    public <T> Class<T> wrapperType(Class<T> exampleType) {
  43.255 +        if (exampleType == wrapperType) {
  43.256 +            return exampleType;
  43.257 +        } else if (exampleType == primitiveType ||
  43.258 +                   wrapperType == Object.class ||
  43.259 +                   exampleType.isInterface()) {
  43.260 +            return forceType(wrapperType, exampleType);
  43.261 +        }
  43.262 +        throw new ClassCastException(exampleType + " not <:" + wrapperType);
  43.263 +    }
  43.264 +
  43.265 +    /** If {@code type} is a primitive type, return the corresponding
  43.266 +     *  wrapper type, else return {@code type} unchanged.
  43.267 +     */
  43.268 +    public static <T> Class<T> asWrapperType(Class<T> type) {
  43.269 +        if (type.isPrimitive()) {
  43.270 +            return forPrimitiveType(type).wrapperType(type);
  43.271 +        }
  43.272 +        return type;
  43.273 +    }
  43.274 +
  43.275 +    /** If {@code type} is a wrapper type, return the corresponding
  43.276 +     *  primitive type, else return {@code type} unchanged.
  43.277 +     */
  43.278 +    public static <T> Class<T> asPrimitiveType(Class<T> type) {
  43.279 +        Wrapper w = findWrapperType(type);
  43.280 +        if (w != null) {
  43.281 +            return forceType(w.primitiveType(), type);
  43.282 +        }
  43.283 +        return type;
  43.284 +    }
  43.285 +
  43.286 +    /** Query:  Is the given type a wrapper, such as {@code Integer} or {@code Void}? */
  43.287 +    public static boolean isWrapperType(Class<?> type) {
  43.288 +        return findWrapperType(type) != null;
  43.289 +    }
  43.290 +
  43.291 +    /** Query:  Is the given type a primitive, such as {@code int} or {@code void}? */
  43.292 +    public static boolean isPrimitiveType(Class<?> type) {
  43.293 +        return type.isPrimitive();
  43.294 +    }
  43.295 +
  43.296 +    /** What is the bytecode signature character for this wrapper's
  43.297 +     *  primitive type?
  43.298 +     */
  43.299 +    public char basicTypeChar() { return basicTypeChar; }
  43.300 +
  43.301 +    /** What is the simple name of the wrapper type?
  43.302 +     */
  43.303 +    public String simpleName() { return simpleName; }
  43.304 +
  43.305 +//    /** Wrap a value in the given type, which may be either a primitive or wrapper type.
  43.306 +//     *  Performs standard primitive conversions, including truncation and float conversions.
  43.307 +//     */
  43.308 +//    public static <T> T wrap(Object x, Class<T> type) {
  43.309 +//        return Wrapper.valueOf(type).cast(x, type);
  43.310 +//    }
  43.311 +
  43.312 +    /** Cast a wrapped value to the given type, which may be either a primitive or wrapper type.
  43.313 +     *  Performs standard primitive conversions, including truncation and float conversions.
  43.314 +     *  The given type must be compatible with this wrapper.  That is, it must either
  43.315 +     *  be the wrapper type (or a subtype, in the case of {@code OBJECT} or else
  43.316 +     *  it must be the wrapper's primitive type.
  43.317 +     *  @throws ClassCastException if the given type is not compatible with this wrapper
  43.318 +     */
  43.319 +    public <T> T cast(Object x, Class<T> type) {
  43.320 +        Class<T> wtype = wrapperType(type);
  43.321 +        if (wtype.isInstance(x))
  43.322 +            return wtype.cast(x);
  43.323 +        return wtype.cast(wrap(x));
  43.324 +    }
  43.325 +
  43.326 +    /** Cast a reference type to another reference type.
  43.327 +     * If the target type is an interface, perform no runtime check.
  43.328 +     * (This loophole is safe, and is allowed by the JVM verifier.)
  43.329 +     * If the target type is a primitive, change it to a wrapper.
  43.330 +     */
  43.331 +    static <T> Class<T> forceType(Class<?> type, Class<T> exampleType) {
  43.332 +        assert(type == exampleType ||
  43.333 +               type == asWrapperType(exampleType) ||
  43.334 +               type == Object.class && exampleType.isInterface());
  43.335 +        Class<T> result = (Class<T>) type;  // unchecked warning is expected here
  43.336 +        return result;
  43.337 +    }
  43.338 +
  43.339 +    /** Wrap a value in this wrapper's type.
  43.340 +     * Performs standard primitive conversions, including truncation and float conversions.
  43.341 +     * Performs returns the unchanged reference for {@code OBJECT}.
  43.342 +     * Returns null for {@code VOID}.
  43.343 +     * Returns a zero value for a null input.
  43.344 +     * @throws ClassCastException if this wrapper is numeric and the operand
  43.345 +     *                            is not a number, character, boolean, or null
  43.346 +     */
  43.347 +    public Object wrap(Object x) {
  43.348 +        // do non-numeric wrappers first
  43.349 +        switch (basicTypeChar) {
  43.350 +            case 'L': return x;
  43.351 +            case 'V': return null;
  43.352 +        }
  43.353 +        Number xn = numberValue(x);
  43.354 +        switch (basicTypeChar) {
  43.355 +            case 'I': return Integer.valueOf(xn.intValue());
  43.356 +            case 'J': return Long.valueOf(xn.longValue());
  43.357 +            case 'F': return Float.valueOf(xn.floatValue());
  43.358 +            case 'D': return Double.valueOf(xn.doubleValue());
  43.359 +            case 'S': return Short.valueOf((short) xn.intValue());
  43.360 +            case 'B': return Byte.valueOf((byte) xn.intValue());
  43.361 +            case 'C': return Character.valueOf((char) xn.intValue());
  43.362 +            case 'Z': return Boolean.valueOf(boolValue(xn.longValue()));
  43.363 +        }
  43.364 +        throw new InternalError("bad wrapper");
  43.365 +    }
  43.366 +
  43.367 +    /** Wrap a value (an int or smaller value) in this wrapper's type.
  43.368 +     * Performs standard primitive conversions, including truncation and float conversions.
  43.369 +     * Produces an {@code Integer} for {@code OBJECT}, although the exact type
  43.370 +     * of the operand is not known.
  43.371 +     * Returns null for {@code VOID}.
  43.372 +     */
  43.373 +    public Object wrap(int x) {
  43.374 +        if (basicTypeChar == 'L')  return (Integer)x;
  43.375 +        switch (basicTypeChar) {
  43.376 +            case 'L': throw newIllegalArgumentException("cannot wrap to object type");
  43.377 +            case 'V': return null;
  43.378 +            case 'I': return Integer.valueOf((int)x);
  43.379 +            case 'J': return Long.valueOf(x);
  43.380 +            case 'F': return Float.valueOf(x);
  43.381 +            case 'D': return Double.valueOf(x);
  43.382 +            case 'S': return Short.valueOf((short) x);
  43.383 +            case 'B': return Byte.valueOf((byte) x);
  43.384 +            case 'C': return Character.valueOf((char) x);
  43.385 +            case 'Z': return Boolean.valueOf(boolValue(x));
  43.386 +        }
  43.387 +        throw new InternalError("bad wrapper");
  43.388 +    }
  43.389 +
  43.390 +    /** Wrap a value (a long or smaller value) in this wrapper's type.
  43.391 +     * Does not perform floating point conversion.
  43.392 +     * Produces a {@code Long} for {@code OBJECT}, although the exact type
  43.393 +     * of the operand is not known.
  43.394 +     * Returns null for {@code VOID}.
  43.395 +     */
  43.396 +    public Object wrapRaw(long x) {
  43.397 +        switch (basicTypeChar) {
  43.398 +            case 'F':  return Float.valueOf(Float.intBitsToFloat((int)x));
  43.399 +            case 'D':  return Double.valueOf(Double.longBitsToDouble(x));
  43.400 +            case 'L':  // same as 'J':
  43.401 +            case 'J':  return (Long) x;
  43.402 +        }
  43.403 +        // Other wrapping operations are just the same, given that the
  43.404 +        // operand is already promoted to an int.
  43.405 +        return wrap((int)x);
  43.406 +    }
  43.407 +
  43.408 +    /** Produce bitwise value which encodes the given wrapped value.
  43.409 +     * Does not perform floating point conversion.
  43.410 +     * Returns zero for {@code VOID}.
  43.411 +     */
  43.412 +    public long unwrapRaw(Object x) {
  43.413 +        switch (basicTypeChar) {
  43.414 +            case 'F':  return Float.floatToRawIntBits((Float) x);
  43.415 +            case 'D':  return Double.doubleToRawLongBits((Double) x);
  43.416 +
  43.417 +            case 'L': throw newIllegalArgumentException("cannot unwrap from sobject type");
  43.418 +            case 'V': return 0;
  43.419 +            case 'I': return (int)(Integer) x;
  43.420 +            case 'J': return (long)(Long) x;
  43.421 +            case 'S': return (short)(Short) x;
  43.422 +            case 'B': return (byte)(Byte) x;
  43.423 +            case 'C': return (char)(Character) x;
  43.424 +            case 'Z': return (boolean)(Boolean) x ? 1 : 0;
  43.425 +        }
  43.426 +        throw new InternalError("bad wrapper");
  43.427 +    }
  43.428 +
  43.429 +    /** Report what primitive type holds this guy's raw value. */
  43.430 +    public Class<?> rawPrimitiveType() {
  43.431 +        return rawPrimitive().primitiveType();
  43.432 +    }
  43.433 +
  43.434 +    /** Report, as a wrapper, what primitive type holds this guy's raw value.
  43.435 +     *  Returns self for INT, LONG, OBJECT; returns LONG for DOUBLE,
  43.436 +     *  else returns INT.
  43.437 +     */
  43.438 +    public Wrapper rawPrimitive() {
  43.439 +        switch (basicTypeChar) {
  43.440 +            case 'S': case 'B':
  43.441 +            case 'C': case 'Z':
  43.442 +            case 'V':
  43.443 +            case 'F':
  43.444 +                return INT;
  43.445 +            case 'D':
  43.446 +                return LONG;
  43.447 +        }
  43.448 +        return this;
  43.449 +    }
  43.450 +
  43.451 +    private static Number numberValue(Object x) {
  43.452 +        if (x instanceof Number)     return (Number)x;
  43.453 +        if (x instanceof Character)  return (int)(Character)x;
  43.454 +        if (x instanceof Boolean)    return (Boolean)x ? 1 : 0;
  43.455 +        // Remaining allowed case of void:  Must be a null reference.
  43.456 +        return (Number)x;
  43.457 +    }
  43.458 +
  43.459 +    private static boolean boolValue(long bits) {
  43.460 +        //bits &= 1;  // simple 31-bit zero extension
  43.461 +        return (bits != 0);
  43.462 +    }
  43.463 +
  43.464 +    private static RuntimeException newIllegalArgumentException(String message, Object x) {
  43.465 +        return newIllegalArgumentException(message + x);
  43.466 +    }
  43.467 +    private static RuntimeException newIllegalArgumentException(String message) {
  43.468 +        return new IllegalArgumentException(message);
  43.469 +    }
  43.470 +}
    44.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    44.2 +++ b/src/share/classes/sun/dyn/util/package-info.java	Tue May 05 22:40:09 2009 -0700
    44.3 @@ -0,0 +1,31 @@
    44.4 +/*
    44.5 + * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
    44.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    44.7 + *
    44.8 + * This code is free software; you can redistribute it and/or modify it
    44.9 + * under the terms of the GNU General Public License version 2 only, as
   44.10 + * published by the Free Software Foundation.  Sun designates this
   44.11 + * particular file as subject to the "Classpath" exception as provided
   44.12 + * by Sun in the LICENSE file that accompanied this code.
   44.13 + *
   44.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   44.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   44.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   44.17 + * version 2 for more details (a copy is included in the LICENSE file that
   44.18 + * accompanied this code).
   44.19 + *
   44.20 + * You should have received a copy of the GNU General Public License version
   44.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   44.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   44.23 + *
   44.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   44.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
   44.26 + * have any questions.
   44.27 + */
   44.28 +
   44.29 +/**
   44.30 + * Extra support for using JSR 292 RI, package java.dyn.
   44.31 + * @author jrose
   44.32 + */
   44.33 +
   44.34 +package sun.dyn.util;
    45.1 --- a/src/share/classes/sun/misc/Unsafe.java	Mon May 04 22:16:02 2009 -0700
    45.2 +++ b/src/share/classes/sun/misc/Unsafe.java	Tue May 05 22:40:09 2009 -0700
    45.3 @@ -1,5 +1,5 @@
    45.4  /*
    45.5 - * Copyright 2000-2006 Sun Microsystems, Inc.  All Rights Reserved.
    45.6 + * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
    45.7   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    45.8   *
    45.9   * This code is free software; you can redistribute it and/or modify it
   45.10 @@ -811,6 +811,25 @@
   45.11  
   45.12      public native Class defineClass(String name, byte[] b, int off, int len);
   45.13  
   45.14 +    /**
   45.15 +     * Define a class but do not make it known to the class loader or system dictionary.
   45.16 +     * <p>
   45.17 +     * For each CP entry, the corresponding CP patch must either be null or have
   45.18 +     * the a format that matches its tag:
   45.19 +     * <ul>
   45.20 +     * <li>Integer, Long, Float, Double: the corresponding wrapper object type from java.lang
   45.21 +     * <li>Utf8: a string (must have suitable syntax if used as signature or name)
   45.22 +     * <li>Class: any java.lang.Class object
   45.23 +     * <li>String: any object (not just a java.lang.String)
   45.24 +     * <li>InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments
   45.25 +     * </ul>
   45.26 +     * @params hostClass context for linkage, access control, protection domain, and class loader
   45.27 +     * @params data      bytes of a class file
   45.28 +     * @params cpPatches where non-null entries exist, they replace corresponding CP entries in data
   45.29 +     */
   45.30 +    public native Class defineAnonymousClass(Class hostClass, byte[] data, Object[] cpPatches);
   45.31 +
   45.32 +
   45.33      /** Allocate an instance but do not run any constructor.
   45.34          Initializes the class if it has not yet been. */
   45.35      public native Object allocateInstance(Class cls)
    46.1 --- a/src/share/javavm/export/classfile_constants.h	Mon May 04 22:16:02 2009 -0700
    46.2 +++ b/src/share/javavm/export/classfile_constants.h	Tue May 05 22:40:09 2009 -0700
    46.3 @@ -1,5 +1,5 @@
    46.4  /*
    46.5 - * Copyright 2004-2005 Sun Microsystems, Inc.  All Rights Reserved.
    46.6 + * Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
    46.7   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    46.8   *
    46.9   * This code is free software; you can redistribute it and/or modify it
   46.10 @@ -306,7 +306,7 @@
   46.11      JVM_OPC_invokespecial       = 183,
   46.12      JVM_OPC_invokestatic        = 184,
   46.13      JVM_OPC_invokeinterface     = 185,
   46.14 -    JVM_OPC_xxxunusedxxx        = 186,
   46.15 +    JVM_OPC_invokedynamic       = 186,
   46.16      JVM_OPC_new                 = 187,
   46.17      JVM_OPC_newarray            = 188,
   46.18      JVM_OPC_anewarray           = 189,
   46.19 @@ -515,7 +515,7 @@
   46.20     3,   /* invokespecial */             \
   46.21     3,   /* invokestatic */              \
   46.22     5,   /* invokeinterface */           \
   46.23 -   0,   /* xxxunusedxxx */              \
   46.24 +   5,   /* invokedynamic */             \
   46.25     3,   /* new */                       \
   46.26     2,   /* newarray */                  \
   46.27     3,   /* anewarray */                 \
    47.1 --- a/src/share/native/common/check_code.c	Mon May 04 22:16:02 2009 -0700
    47.2 +++ b/src/share/native/common/check_code.c	Tue May 05 22:40:09 2009 -0700
    47.3 @@ -1,5 +1,5 @@
    47.4  /*
    47.5 - * Copyright 1994-2008 Sun Microsystems, Inc.  All Rights Reserved.
    47.6 + * Copyright 1994-2009 Sun Microsystems, Inc.  All Rights Reserved.
    47.7   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    47.8   *
    47.9   * This code is free software; you can redistribute it and/or modify it
   47.10 @@ -1223,16 +1223,20 @@
   47.11      case JVM_OPC_invokevirtual:
   47.12      case JVM_OPC_invokespecial:
   47.13      case JVM_OPC_invokestatic:
   47.14 +    case JVM_OPC_invokedynamic:
   47.15      case JVM_OPC_invokeinterface: {
   47.16          /* Make sure the constant pool item is the right type. */
   47.17          int key = (code[offset + 1] << 8) + code[offset + 2];
   47.18          const char *methodname;
   47.19          jclass cb = context->class;
   47.20          fullinfo_type clazz_info;
   47.21 -        int is_constructor, is_internal;
   47.22 +        int is_constructor, is_internal, is_invokedynamic;
   47.23          int kind = (opcode == JVM_OPC_invokeinterface
   47.24                              ? 1 << JVM_CONSTANT_InterfaceMethodref
   47.25 +                  : opcode == JVM_OPC_invokedynamic
   47.26 +                            ? 1 << JVM_CONSTANT_NameAndType
   47.27                              : 1 << JVM_CONSTANT_Methodref);
   47.28 +        is_invokedynamic = opcode == JVM_OPC_invokedynamic;
   47.29          /* Make sure the constant pool item is the right type. */
   47.30          verify_constant_pool_type(context, key, kind);
   47.31          methodname = JVM_GetCPMethodNameUTF(env, cb, key);
   47.32 @@ -1241,8 +1245,11 @@
   47.33          is_internal = methodname[0] == '<';
   47.34          pop_and_free(context);
   47.35  
   47.36 -        clazz_info = cp_index_to_class_fullinfo(context, key,
   47.37 -                                                JVM_CONSTANT_Methodref);
   47.38 +        if (is_invokedynamic)
   47.39 +          clazz_info = context->object_info;  // anything will do
   47.40 +        else
   47.41 +          clazz_info = cp_index_to_class_fullinfo(context, key,
   47.42 +                                                  JVM_CONSTANT_Methodref);
   47.43          this_idata->operand.i = key;
   47.44          this_idata->operand2.fi = clazz_info;
   47.45          if (is_constructor) {
   47.46 @@ -1304,6 +1311,11 @@
   47.47                          "Fourth operand byte of invokeinterface must be zero");
   47.48              }
   47.49              pop_and_free(context);
   47.50 +        } else if (opcode == JVM_OPC_invokedynamic) {
   47.51 +            if (code[offset + 3] != 0 || code[offset + 4] != 0) {
   47.52 +                CCerror(context,
   47.53 +                        "Third and fourth operand bytes of invokedynamic must be zero");
   47.54 +            }
   47.55          } else if (opcode == JVM_OPC_invokevirtual
   47.56                        || opcode == JVM_OPC_invokespecial)
   47.57              set_protected(context, inumber, key, opcode);
   47.58 @@ -1990,6 +2002,7 @@
   47.59  
   47.60          case JVM_OPC_invokevirtual: case JVM_OPC_invokespecial:
   47.61          case JVM_OPC_invokeinit:    /* invokespecial call to <init> */
   47.62 +        case JVM_OPC_invokedynamic:
   47.63          case JVM_OPC_invokestatic: case JVM_OPC_invokeinterface: {
   47.64              /* The top stuff on the stack depends on the method signature */
   47.65              int operand = this_idata->operand.i;
   47.66 @@ -2005,7 +2018,8 @@
   47.67                  print_formatted_methodname(context, operand);
   47.68              }
   47.69  #endif
   47.70 -            if (opcode != JVM_OPC_invokestatic)
   47.71 +            if (opcode != JVM_OPC_invokestatic &&
   47.72 +                opcode != JVM_OPC_invokedynamic)
   47.73                  /* First, push the object */
   47.74                  *ip++ = (opcode == JVM_OPC_invokeinit ? '@' : 'A');
   47.75              for (p = signature + 1; *p != JVM_SIGNATURE_ENDFUNC; ) {
   47.76 @@ -2290,6 +2304,7 @@
   47.77  
   47.78          case JVM_OPC_invokevirtual: case JVM_OPC_invokespecial:
   47.79          case JVM_OPC_invokeinit:
   47.80 +        case JVM_OPC_invokedynamic:
   47.81          case JVM_OPC_invokeinterface: case JVM_OPC_invokestatic: {
   47.82              int operand = this_idata->operand.i;
   47.83              const char *signature =
   47.84 @@ -2299,7 +2314,8 @@
   47.85              int item;
   47.86              const char *p;
   47.87              check_and_push(context, signature, VM_STRING_UTF);
   47.88 -            if (opcode == JVM_OPC_invokestatic) {
   47.89 +            if (opcode == JVM_OPC_invokestatic ||
   47.90 +                opcode == JVM_OPC_invokedynamic) {
   47.91                  item = 0;
   47.92              } else if (opcode == JVM_OPC_invokeinit) {
   47.93                  fullinfo_type init_type = this_idata->operand2.fi;
   47.94 @@ -2680,6 +2696,7 @@
   47.95  
   47.96          case JVM_OPC_invokevirtual: case JVM_OPC_invokespecial:
   47.97          case JVM_OPC_invokeinit:
   47.98 +        case JVM_OPC_invokedynamic:
   47.99          case JVM_OPC_invokestatic: case JVM_OPC_invokeinterface: {
  47.100              /* Look to signature to determine correct result. */
  47.101              int operand = this_idata->operand.i;
    48.1 --- a/src/share/native/common/opcodes.in_out	Mon May 04 22:16:02 2009 -0700
    48.2 +++ b/src/share/native/common/opcodes.in_out	Tue May 05 22:40:09 2009 -0700
    48.3 @@ -1,5 +1,5 @@
    48.4  /* 
    48.5 - * Copyright 1998 Sun Microsystems, Inc.  All Rights Reserved.
    48.6 + * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
    48.7   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    48.8   *
    48.9   * This code is free software; you can redistribute it and/or modify it
   48.10 @@ -210,7 +210,7 @@
   48.11     {"?", "?"}, 		/* invokespecial */
   48.12     {"?", "?"}, 		/* invokestatic */
   48.13     {"?", "?"}, 		/* invokeinterface */
   48.14 -   {"?", "?"}, 		/* xxxunusedxxx */
   48.15 +   {"?", "?"}, 		/* invokedynamic */
   48.16     {"", "A"}, 		/* new */
   48.17     {"I", "A"}, 		/* newarray */
   48.18     {"I", "A"}, 		/* anewarray */