1 /*
   2  * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.access.SharedSecrets;
  29 import jdk.internal.loader.BootLoader;
  30 import jdk.internal.org.objectweb.asm.ClassWriter;
  31 import jdk.internal.org.objectweb.asm.FieldVisitor;
  32 import jdk.internal.org.objectweb.asm.MethodVisitor;
  33 import jdk.internal.vm.annotation.Stable;
  34 import sun.invoke.util.BytecodeName;
  35 
  36 import java.lang.reflect.Constructor;
  37 import java.lang.reflect.Field;
  38 import java.lang.reflect.Modifier;
  39 import java.security.AccessController;
  40 import java.security.PrivilegedAction;
  41 import java.security.ProtectionDomain;
  42 import java.util.ArrayList;
  43 import java.util.Collections;
  44 import java.util.List;
  45 import java.util.Objects;
  46 import java.util.concurrent.ConcurrentHashMap;
  47 import java.util.function.Function;
  48 
  49 import static java.lang.invoke.LambdaForm.*;
  50 import static java.lang.invoke.MethodHandleNatives.Constants.REF_getStatic;
  51 import static java.lang.invoke.MethodHandleNatives.Constants.REF_putStatic;
  52 import static java.lang.invoke.MethodHandleStatics.*;
  53 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  54 import static jdk.internal.org.objectweb.asm.Opcodes.*;
  55 
  56 /**
  57  * Class specialization code.
  58  * @param <T> top class under which species classes are created.
  59  * @param <K> key which identifies individual specializations.
  60  * @param <S> species data type.
  61  */
  62 /*non-public*/
  63 abstract class ClassSpecializer<T,K,S extends ClassSpecializer<T,K,S>.SpeciesData> {
  64     private final Class<T> topClass;
  65     private final Class<K> keyType;
  66     private final Class<S> metaType;
  67     private final MemberName sdAccessor;
  68     private final String sdFieldName;
  69     private final List<MemberName> transformMethods;
  70     private final MethodType baseConstructorType;
  71     private final S topSpecies;
  72     private final ConcurrentHashMap<K, Object> cache = new ConcurrentHashMap<>();
  73     private final Factory factory;
  74     private @Stable boolean topClassIsSuper;
  75 
  76     /** Return the top type mirror, for type {@code T} */
  77     public final Class<T> topClass() { return topClass; }
  78 
  79     /** Return the key type mirror, for type {@code K} */
  80     public final Class<K> keyType() { return keyType; }
  81 
  82     /** Return the species metadata type mirror, for type {@code S} */
  83     public final Class<S> metaType() { return metaType; }
  84 
  85     /** Report the leading arguments (if any) required by every species factory.
  86      * Every species factory adds its own field types as additional arguments,
  87      * but these arguments always come first, in every factory method.
  88      */
  89     protected MethodType baseConstructorType() { return baseConstructorType; }
  90 
  91     /** Return the trivial species for the null sequence of arguments. */
  92     protected final S topSpecies() { return topSpecies; }
  93 
  94     /** Return the list of transform methods originally given at creation of this specializer. */
  95     protected final List<MemberName> transformMethods() { return transformMethods; }
  96 
  97     /** Return the factory object used to build and load concrete species code. */
  98     protected final Factory factory() { return factory; }
  99 
 100     /**
 101      * Constructor for this class specializer.
 102      * @param topClass type mirror for T
 103      * @param keyType type mirror for K
 104      * @param metaType type mirror for S
 105      * @param baseConstructorType principal constructor type
 106      * @param sdAccessor the method used to get the speciesData
 107      * @param sdFieldName the name of the species data field, inject the speciesData object
 108      * @param transformMethods optional list of transformMethods
 109      */
 110     protected ClassSpecializer(Class<T> topClass,
 111                                Class<K> keyType,
 112                                Class<S> metaType,
 113                                MethodType baseConstructorType,
 114                                MemberName sdAccessor,
 115                                String sdFieldName,
 116                                List<MemberName> transformMethods) {
 117         this.topClass = topClass;
 118         this.keyType = keyType;
 119         this.metaType = metaType;
 120         this.sdAccessor = sdAccessor;
 121         this.transformMethods = List.copyOf(transformMethods);
 122         this.sdFieldName = sdFieldName;
 123         this.baseConstructorType = baseConstructorType.changeReturnType(void.class);
 124         this.factory = makeFactory();
 125         K tsk = topSpeciesKey();
 126         S topSpecies = null;
 127         if (tsk != null && topSpecies == null) {
 128             // if there is a key, build the top species if needed:
 129             topSpecies = findSpecies(tsk);
 130         }
 131         this.topSpecies = topSpecies;
 132     }
 133 
 134     // Utilities for subclass constructors:
 135     protected static <T> Constructor<T> reflectConstructor(Class<T> defc, Class<?>... ptypes) {
 136         try {
 137             return defc.getDeclaredConstructor(ptypes);
 138         } catch (NoSuchMethodException ex) {
 139             throw newIAE(defc.getName()+"("+MethodType.methodType(void.class, ptypes)+")", ex);
 140         }
 141     }
 142 
 143     protected static Field reflectField(Class<?> defc, String name) {
 144         try {
 145             return defc.getDeclaredField(name);
 146         } catch (NoSuchFieldException ex) {
 147             throw newIAE(defc.getName()+"."+name, ex);
 148         }
 149     }
 150 
 151     private static RuntimeException newIAE(String message, Throwable cause) {
 152         return new IllegalArgumentException(message, cause);
 153     }
 154 
 155     private static final Function<Object, Object> CREATE_RESERVATION = new Function<>() {
 156         @Override
 157         public Object apply(Object key) {
 158             return new Object();
 159         }
 160     };
 161 
 162     public final S findSpecies(K key) {
 163         // Note:  Species instantiation may throw VirtualMachineError because of
 164         // code cache overflow.  If this happens the species bytecode may be
 165         // loaded but not linked to its species metadata (with MH's etc).
 166         // That will cause a throw out of Factory.loadSpecies.
 167         //
 168         // In a later attempt to get the same species, the already-loaded
 169         // class will be present in the system dictionary, causing an
 170         // error when the species generator tries to reload it.
 171         // We try to detect this case and link the pre-existing code.
 172         //
 173         // Although it would be better to start fresh by loading a new
 174         // copy, we have to salvage the previously loaded but broken code.
 175         // (As an alternative, we might spin a new class with a new name,
 176         // or use the anonymous class mechanism.)
 177         //
 178         // In the end, as long as everybody goes through this findSpecies method,
 179         // it will ensure only one SpeciesData will be set successfully on a
 180         // concrete class if ever.
 181         // The concrete class is published via SpeciesData instance
 182         // returned here only after the class and species data are linked together.
 183         Object speciesDataOrReservation = cache.computeIfAbsent(key, CREATE_RESERVATION);
 184         // Separating the creation of a placeholder SpeciesData instance above
 185         // from the loading and linking a real one below ensures we can never
 186         // accidentally call computeIfAbsent recursively.
 187         S speciesData;
 188         if (speciesDataOrReservation.getClass() == Object.class) {
 189             synchronized (speciesDataOrReservation) {
 190                 Object existingSpeciesData = cache.get(key);
 191                 if (existingSpeciesData == speciesDataOrReservation) { // won the race
 192                     // create a new SpeciesData...
 193                     speciesData = newSpeciesData(key);
 194                     // load and link it...
 195                     speciesData = factory.loadSpecies(speciesData);
 196                     if (!cache.replace(key, existingSpeciesData, speciesData)) {
 197                         throw newInternalError("Concurrent loadSpecies");
 198                     }
 199                 } else { // lost the race; the retrieved existingSpeciesData is the final
 200                     speciesData = metaType.cast(existingSpeciesData);
 201                 }
 202             }
 203         } else {
 204             speciesData = metaType.cast(speciesDataOrReservation);
 205         }
 206         assert(speciesData != null && speciesData.isResolved());
 207         return speciesData;
 208     }
 209 
 210     /**
 211      * Meta-data wrapper for concrete subtypes of the top class.
 212      * Each concrete subtype corresponds to a given sequence of basic field types (LIJFD).
 213      * The fields are immutable; their values are fully specified at object construction.
 214      * Each species supplies an array of getter functions which may be used in lambda forms.
 215      * A concrete value is always constructed from the full tuple of its field values,
 216      * accompanied by the required constructor parameters.
 217      * There *may* also be transforms which cloning a species instance and
 218      * either replace a constructor parameter or add one or more new field values.
 219      * The shortest possible species has zero fields.
 220      * Subtypes are not interrelated among themselves by subtyping, even though
 221      * it would appear that a shorter species could serve as a supertype of a
 222      * longer one which extends it.
 223      */
 224     public abstract class SpeciesData {
 225         // Bootstrapping requires circular relations Class -> SpeciesData -> Class
 226         // Therefore, we need non-final links in the chain.  Use @Stable fields.
 227         private final K key;
 228         private final List<Class<?>> fieldTypes;
 229         @Stable private Class<? extends T> speciesCode;
 230         @Stable private List<MethodHandle> factories;
 231         @Stable private List<MethodHandle> getters;
 232         @Stable private List<LambdaForm.NamedFunction> nominalGetters;
 233         @Stable private final MethodHandle[] transformHelpers = new MethodHandle[transformMethods.size()];
 234 
 235         protected SpeciesData(K key) {
 236             this.key = keyType.cast(Objects.requireNonNull(key));
 237             List<Class<?>> types = deriveFieldTypes(key);
 238             this.fieldTypes = List.copyOf(types);
 239         }
 240 
 241         public final K key() {
 242             return key;
 243         }
 244 
 245         protected final List<Class<?>> fieldTypes() {
 246             return fieldTypes;
 247         }
 248 
 249         protected final int fieldCount() {
 250             return fieldTypes.size();
 251         }
 252 
 253         protected ClassSpecializer<T,K,S> outer() {
 254             return ClassSpecializer.this;
 255         }
 256 
 257         protected final boolean isResolved() {
 258             return speciesCode != null && factories != null && !factories.isEmpty();
 259         }
 260 
 261         @Override public String toString() {
 262             return metaType.getSimpleName() + "[" + key.toString() + " => " + (isResolved() ? speciesCode.getSimpleName() : "UNRESOLVED") + "]";
 263         }
 264 
 265         @Override
 266         public int hashCode() {
 267             return key.hashCode();
 268         }
 269 
 270         @Override
 271         public boolean equals(Object obj) {
 272             if (!(obj instanceof ClassSpecializer.SpeciesData)) {
 273                 return false;
 274             }
 275             @SuppressWarnings("rawtypes")
 276             ClassSpecializer.SpeciesData that = (ClassSpecializer.SpeciesData) obj;
 277             return this.outer() == that.outer() && this.key.equals(that.key);
 278         }
 279 
 280         /** Throws NPE if this species is not yet resolved. */
 281         protected final Class<? extends T> speciesCode() {
 282             return Objects.requireNonNull(speciesCode);
 283         }
 284 
 285         /**
 286          * Return a {@link MethodHandle} which can get the indexed field of this species.
 287          * The return type is the type of the species field it accesses.
 288          * The argument type is the {@code fieldHolder} class of this species.
 289          */
 290         protected MethodHandle getter(int i) {
 291             return getters.get(i);
 292         }
 293 
 294         /**
 295          * Return a {@link LambdaForm.Name} containing a {@link LambdaForm.NamedFunction} that
 296          * represents a MH bound to a generic invoker, which in turn forwards to the corresponding
 297          * getter.
 298          */
 299         protected LambdaForm.NamedFunction getterFunction(int i) {
 300             LambdaForm.NamedFunction nf = nominalGetters.get(i);
 301             assert(nf.memberDeclaringClassOrNull() == speciesCode());
 302             assert(nf.returnType() == BasicType.basicType(fieldTypes.get(i)));
 303             return nf;
 304         }
 305 
 306         protected List<LambdaForm.NamedFunction> getterFunctions() {
 307             return nominalGetters;
 308         }
 309 
 310         protected List<MethodHandle> getters() {
 311             return getters;
 312         }
 313 
 314         protected MethodHandle factory() {
 315             return factories.get(0);
 316         }
 317 
 318         protected MethodHandle transformHelper(int whichtm) {
 319             MethodHandle mh = transformHelpers[whichtm];
 320             if (mh != null)  return mh;
 321             mh = deriveTransformHelper(transformMethods().get(whichtm), whichtm);
 322             // Do a little type checking before we start using the MH.
 323             // (It will be called with invokeBasic, so this is our only chance.)
 324             final MethodType mt = transformHelperType(whichtm);
 325             mh = mh.asType(mt);
 326             return transformHelpers[whichtm] = mh;
 327         }
 328 
 329         private final MethodType transformHelperType(int whichtm) {
 330             MemberName tm = transformMethods().get(whichtm);
 331             ArrayList<Class<?>> args = new ArrayList<>();
 332             ArrayList<Class<?>> fields = new ArrayList<>();
 333             Collections.addAll(args, tm.getParameterTypes());
 334             fields.addAll(fieldTypes());
 335             List<Class<?>> helperArgs = deriveTransformHelperArguments(tm, whichtm, args, fields);
 336             return MethodType.methodType(tm.getReturnType(), helperArgs);
 337         }
 338 
 339         // Hooks for subclasses:
 340 
 341         /**
 342          * Given a key, derive the list of field types, which all instances of this
 343          * species must store.
 344          */
 345         protected abstract List<Class<?>> deriveFieldTypes(K key);
 346 
 347         /**
 348          * Given the index of a method in the transforms list, supply a factory
 349          * method that takes the arguments of the transform, plus the local fields,
 350          * and produce a value of the required type.
 351          * You can override this to return null or throw if there are no transforms.
 352          * This method exists so that the transforms can be "grown" lazily.
 353          * This is necessary if the transform *adds* a field to an instance,
 354          * which sometimtes requires the creation, on the fly, of an extended species.
 355          * This method is only called once for any particular parameter.
 356          * The species caches the result in a private array.
 357          *
 358          * @param transform the transform being implemented
 359          * @param whichtm the index of that transform in the original list of transforms
 360          * @return the method handle which creates a new result from a mix of transform
 361          * arguments and field values
 362          */
 363         protected abstract MethodHandle deriveTransformHelper(MemberName transform, int whichtm);
 364 
 365         /**
 366          * During code generation, this method is called once per transform to determine
 367          * what is the mix of arguments to hand to the transform-helper.  The bytecode
 368          * which marshals these arguments is open-coded in the species-specific transform.
 369          * The two lists are of opaque objects, which you shouldn't do anything with besides
 370          * reordering them into the output list.  (They are both mutable, to make editing
 371          * easier.)  The imputed types of the args correspond to the transform's parameter
 372          * list, while the imputed types of the fields correspond to the species field types.
 373          * After code generation, this method may be called occasionally by error-checking code.
 374          *
 375          * @param transform the transform being implemented
 376          * @param whichtm the index of that transform in the original list of transforms
 377          * @param args a list of opaque objects representing the incoming transform arguments
 378          * @param fields a list of opaque objects representing the field values of the receiver
 379          * @param <X> the common element type of the various lists
 380          * @return a new list
 381          */
 382         protected abstract <X> List<X> deriveTransformHelperArguments(MemberName transform, int whichtm,
 383                                                                       List<X> args, List<X> fields);
 384 
 385         /** Given a key, generate the name of the class which implements the species for that key.
 386          * This algorithm must be stable.
 387          *
 388          * @return class name, which by default is {@code outer().topClass().getName() + "$Species_" + deriveTypeString(key)}
 389          */
 390         protected String deriveClassName() {
 391             return outer().topClass().getName() + "$Species_" + deriveTypeString();
 392         }
 393 
 394         /**
 395          * Default implementation collects basic type characters,
 396          * plus possibly type names, if some types don't correspond
 397          * to basic types.
 398          *
 399          * @return a string suitable for use in a class name
 400          */
 401         protected String deriveTypeString() {
 402             List<Class<?>> types = fieldTypes();
 403             StringBuilder buf = new StringBuilder();
 404             StringBuilder end = new StringBuilder();
 405             for (Class<?> type : types) {
 406                 BasicType basicType = BasicType.basicType(type);
 407                 if (basicType.basicTypeClass() == type) {
 408                     buf.append(basicType.basicTypeChar());
 409                 } else {
 410                     buf.append('V');
 411                     end.append(classSig(type));
 412                 }
 413             }
 414             String typeString;
 415             if (end.length() > 0) {
 416                 typeString = BytecodeName.toBytecodeName(buf.append("_").append(end).toString());
 417             } else {
 418                 typeString = buf.toString();
 419             }
 420             return LambdaForm.shortenSignature(typeString);
 421         }
 422 
 423         /**
 424          * Report what immediate super-class to use for the concrete class of this species.
 425          * Normally this is {@code topClass}, but if that is an interface, the factory must override.
 426          * The super-class must provide a constructor which takes the {@code baseConstructorType} arguments, if any.
 427          * This hook also allows the code generator to use more than one canned supertype for species.
 428          *
 429          * @return the super-class of the class to be generated
 430          */
 431         protected Class<? extends T> deriveSuperClass() {
 432             final Class<T> topc = topClass();
 433             if (!topClassIsSuper) {
 434                 try {
 435                     final Constructor<T> con = reflectConstructor(topc, baseConstructorType().parameterArray());
 436                     if (!topc.isInterface() && !Modifier.isPrivate(con.getModifiers())) {
 437                         topClassIsSuper = true;
 438                     }
 439                 } catch (Exception|InternalError ex) {
 440                     // fall through...
 441                 }
 442                 if (!topClassIsSuper) {
 443                     throw newInternalError("must override if the top class cannot serve as a super class");
 444                 }
 445             }
 446             return topc;
 447         }
 448     }
 449 
 450     protected abstract S newSpeciesData(K key);
 451 
 452     protected K topSpeciesKey() {
 453         return null;  // null means don't report a top species
 454     }
 455 
 456     /**
 457      * Code generation support for instances.
 458      * Subclasses can modify the behavior.
 459      */
 460     public class Factory {
 461         /**
 462          * Get a concrete subclass of the top class for a given combination of bound types.
 463          *
 464          * @param speciesData the species requiring the class, not yet linked
 465          * @return a linked version of the same species
 466          */
 467         S loadSpecies(S speciesData) {
 468             String className = speciesData.deriveClassName();
 469             assert(className.indexOf('/') < 0) : className;
 470             Class<?> salvage = null;
 471             try {
 472                 salvage = BootLoader.loadClassOrNull(className);
 473                 if (TRACE_RESOLVE && salvage != null) {
 474                     // Used by jlink species pregeneration plugin, see
 475                     // jdk.tools.jlink.internal.plugins.GenerateJLIClassesPlugin
 476                     System.out.println("[SPECIES_RESOLVE] " + className + " (salvaged)");
 477                 }
 478             } catch (Error ex) {
 479                 if (TRACE_RESOLVE) {
 480                     System.out.println("[SPECIES_FRESOLVE] " + className + " (Error) " + ex.getMessage());
 481                 }
 482             }
 483             final Class<? extends T> speciesCode;
 484             if (salvage != null) {
 485                 speciesCode = salvage.asSubclass(topClass());
 486                 linkSpeciesDataToCode(speciesData, speciesCode);
 487                 linkCodeToSpeciesData(speciesCode, speciesData, true);
 488             } else {
 489                 // Not pregenerated, generate the class
 490                 try {
 491                     speciesCode = generateConcreteSpeciesCode(className, speciesData);
 492                     if (TRACE_RESOLVE) {
 493                         // Used by jlink species pregeneration plugin, see
 494                         // jdk.tools.jlink.internal.plugins.GenerateJLIClassesPlugin
 495                         System.out.println("[SPECIES_RESOLVE] " + className + " (generated)");
 496                     }
 497                     // This operation causes a lot of churn:
 498                     linkSpeciesDataToCode(speciesData, speciesCode);
 499                     // This operation commits the relation, but causes little churn:
 500                     linkCodeToSpeciesData(speciesCode, speciesData, false);
 501                 } catch (Error ex) {
 502                     if (TRACE_RESOLVE) {
 503                         System.out.println("[SPECIES_RESOLVE] " + className + " (Error #2)" );
 504                     }
 505                     // We can get here if there is a race condition loading a class.
 506                     // Or maybe we are out of resources.  Back out of the CHM.get and retry.
 507                     throw ex;
 508                 }
 509             }
 510 
 511             if (!speciesData.isResolved()) {
 512                 throw newInternalError("bad species class linkage for " + className + ": " + speciesData);
 513             }
 514             assert(speciesData == loadSpeciesDataFromCode(speciesCode));
 515             return speciesData;
 516         }
 517 
 518         /**
 519          * Generate a concrete subclass of the top class for a given combination of bound types.
 520          *
 521          * A concrete species subclass roughly matches the following schema:
 522          *
 523          * <pre>
 524          * class Species_[[types]] extends [[T]] {
 525          *     final [[S]] speciesData() { return ... }
 526          *     static [[T]] make([[fields]]) { return ... }
 527          *     [[fields]]
 528          *     final [[T]] transform([[args]]) { return ... }
 529          * }
 530          * </pre>
 531          *
 532          * The {@code [[types]]} signature is precisely the key for the species.
 533          *
 534          * The {@code [[fields]]} section consists of one field definition per character in
 535          * the type signature, adhering to the naming schema described in the definition of
 536          * {@link #chooseFieldName}.
 537          *
 538          * For example, a concrete species for two references and one integral bound value
 539          * has a shape like the following:
 540          *
 541          * <pre>
 542          * class TopClass { ... private static
 543          * final class Species_LLI extends TopClass {
 544          *     final Object argL0;
 545          *     final Object argL1;
 546          *     final int argI2;
 547          *     private Species_LLI(CT ctarg, ..., Object argL0, Object argL1, int argI2) {
 548          *         super(ctarg, ...);
 549          *         this.argL0 = argL0;
 550          *         this.argL1 = argL1;
 551          *         this.argI2 = argI2;
 552          *     }
 553          *     final SpeciesData speciesData() { return BMH_SPECIES; }
 554          *     @Stable static SpeciesData BMH_SPECIES; // injected afterwards
 555          *     static TopClass make(CT ctarg, ..., Object argL0, Object argL1, int argI2) {
 556          *         return new Species_LLI(ctarg, ..., argL0, argL1, argI2);
 557          *     }
 558          *     final TopClass copyWith(CT ctarg, ...) {
 559          *         return new Species_LLI(ctarg, ..., argL0, argL1, argI2);
 560          *     }
 561          *     // two transforms, for the sake of illustration:
 562          *     final TopClass copyWithExtendL(CT ctarg, ..., Object narg) {
 563          *         return BMH_SPECIES.transform(L_TYPE).invokeBasic(ctarg, ..., argL0, argL1, argI2, narg);
 564          *     }
 565          *     final TopClass copyWithExtendI(CT ctarg, ..., int narg) {
 566          *         return BMH_SPECIES.transform(I_TYPE).invokeBasic(ctarg, ..., argL0, argL1, argI2, narg);
 567          *     }
 568          * }
 569          * </pre>
 570          *
 571          * @param className of the species
 572          * @param speciesData what species we are generating
 573          * @return the generated concrete TopClass class
 574          */
 575         Class<? extends T> generateConcreteSpeciesCode(String className, ClassSpecializer<T,K,S>.SpeciesData speciesData) {
 576             byte[] classFile = generateConcreteSpeciesCodeFile(className, speciesData);
 577 
 578             // load class
 579             InvokerBytecodeGenerator.maybeDump(classBCName(className), classFile);
 580             ClassLoader cl = topClass.getClassLoader();
 581             ProtectionDomain pd = null;
 582             if (cl != null) {
 583                 pd = AccessController.doPrivileged(
 584                         new PrivilegedAction<>() {
 585                             @Override
 586                             public ProtectionDomain run() {
 587                                 return topClass().getProtectionDomain();
 588                             }
 589                         });
 590             }
 591             Class<?> speciesCode = SharedSecrets.getJavaLangAccess()
 592                     .defineClass(cl, className, classFile, pd, "_ClassSpecializer_generateConcreteSpeciesCode");
 593             return speciesCode.asSubclass(topClass());
 594         }
 595 
 596         // These are named like constants because there is only one per specialization scheme:
 597         private final String SPECIES_DATA = classBCName(metaType);
 598         private final String SPECIES_DATA_SIG = classSig(SPECIES_DATA);
 599         private final String SPECIES_DATA_NAME = sdAccessor.getName();
 600         private final int SPECIES_DATA_MODS = sdAccessor.getModifiers();
 601         private final List<String> TRANSFORM_NAMES;  // derived from transformMethods
 602         private final List<MethodType> TRANSFORM_TYPES;
 603         private final List<Integer> TRANSFORM_MODS;
 604         {
 605             // Tear apart transformMethods to get the names, types, and modifiers.
 606             List<String> tns = new ArrayList<>();
 607             List<MethodType> tts = new ArrayList<>();
 608             List<Integer> tms = new ArrayList<>();
 609             for (int i = 0; i < transformMethods.size(); i++) {
 610                 MemberName tm = transformMethods.get(i);
 611                 tns.add(tm.getName());
 612                 final MethodType tt = tm.getMethodType();
 613                 tts.add(tt);
 614                 tms.add(tm.getModifiers());
 615             }
 616             TRANSFORM_NAMES = List.of(tns.toArray(new String[0]));
 617             TRANSFORM_TYPES = List.of(tts.toArray(new MethodType[0]));
 618             TRANSFORM_MODS = List.of(tms.toArray(new Integer[0]));
 619         }
 620         private static final int ACC_PPP = ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED;
 621 
 622         /*non-public*/ byte[] generateConcreteSpeciesCodeFile(String className0, ClassSpecializer<T,K,S>.SpeciesData speciesData) {
 623             final String className = classBCName(className0);
 624             final String superClassName = classBCName(speciesData.deriveSuperClass());
 625 
 626             final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 627             final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 628             cw.visit(V1_6, NOT_ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, superClassName, null);
 629 
 630             final String sourceFile = className.substring(className.lastIndexOf('.')+1);
 631             cw.visitSource(sourceFile, null);
 632 
 633             // emit static types and BMH_SPECIES fields
 634             FieldVisitor fw = cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, sdFieldName, SPECIES_DATA_SIG, null, null);
 635             fw.visitAnnotation(STABLE_SIG, true);
 636             fw.visitEnd();
 637 
 638             // handy holder for dealing with groups of typed values (ctor arguments and fields)
 639             class Var {
 640                 final int index;
 641                 final String name;
 642                 final Class<?> type;
 643                 final String desc;
 644                 final BasicType basicType;
 645                 final int slotIndex;
 646                 Var(int index, int slotIndex) {
 647                     this.index = index;
 648                     this.slotIndex = slotIndex;
 649                     name = null; type = null; desc = null;
 650                     basicType = BasicType.V_TYPE;
 651                 }
 652                 Var(String name, Class<?> type, Var prev) {
 653                     int slotIndex = prev.nextSlotIndex();
 654                     int index = prev.nextIndex();
 655                     if (name == null)  name = "x";
 656                     if (name.endsWith("#"))
 657                         name = name.substring(0, name.length()-1) + index;
 658                     assert(!type.equals(void.class));
 659                     String desc = classSig(type);
 660                     BasicType basicType = BasicType.basicType(type);
 661                     this.index = index;
 662                     this.name = name;
 663                     this.type = type;
 664                     this.desc = desc;
 665                     this.basicType = basicType;
 666                     this.slotIndex = slotIndex;
 667                 }
 668                 Var lastOf(List<Var> vars) {
 669                     int n = vars.size();
 670                     return (n == 0 ? this : vars.get(n-1));
 671                 }
 672                 <X> List<Var> fromTypes(List<X> types) {
 673                     Var prev = this;
 674                     ArrayList<Var> result = new ArrayList<>(types.size());
 675                     int i = 0;
 676                     for (X x : types) {
 677                         String vn = name;
 678                         Class<?> vt;
 679                         if (x instanceof Class) {
 680                             vt = (Class<?>) x;
 681                             // make the names friendlier if debugging
 682                             assert((vn = vn + "_" + (i++)) != null);
 683                         } else {
 684                             @SuppressWarnings("unchecked")
 685                             Var v = (Var) x;
 686                             vn = v.name;
 687                             vt = v.type;
 688                         }
 689                         prev = new Var(vn, vt, prev);
 690                         result.add(prev);
 691                     }
 692                     return result;
 693                 }
 694 
 695                 int slotSize() { return basicType.basicTypeSlots(); }
 696                 int nextIndex() { return index + (slotSize() == 0 ? 0 : 1); }
 697                 int nextSlotIndex() { return slotIndex >= 0 ? slotIndex + slotSize() : slotIndex; }
 698                 boolean isInHeap() { return slotIndex < 0; }
 699                 void emitVarInstruction(int asmop, MethodVisitor mv) {
 700                     if (asmop == ALOAD)
 701                         asmop = typeLoadOp(basicType.basicTypeChar());
 702                     else
 703                         throw new AssertionError("bad op="+asmop+" for desc="+desc);
 704                     mv.visitVarInsn(asmop, slotIndex);
 705                 }
 706                 public void emitFieldInsn(int asmop, MethodVisitor mv) {
 707                     mv.visitFieldInsn(asmop, className, name, desc);
 708                 }
 709             }
 710 
 711             final Var NO_THIS = new Var(0, 0),
 712                     AFTER_THIS = new Var(0, 1),
 713                     IN_HEAP = new Var(0, -1);
 714 
 715             // figure out the field types
 716             final List<Class<?>> fieldTypes = speciesData.fieldTypes();
 717             final List<Var> fields = new ArrayList<>(fieldTypes.size());
 718             {
 719                 Var nextF = IN_HEAP;
 720                 for (Class<?> ft : fieldTypes) {
 721                     String fn = chooseFieldName(ft, nextF.nextIndex());
 722                     nextF = new Var(fn, ft, nextF);
 723                     fields.add(nextF);
 724                 }
 725             }
 726 
 727             // emit bound argument fields
 728             for (Var field : fields) {
 729                 cw.visitField(ACC_FINAL, field.name, field.desc, null, null).visitEnd();
 730             }
 731 
 732             MethodVisitor mv;
 733 
 734             // emit implementation of speciesData()
 735             mv = cw.visitMethod((SPECIES_DATA_MODS & ACC_PPP) + ACC_FINAL,
 736                     SPECIES_DATA_NAME, "()" + SPECIES_DATA_SIG, null, null);
 737             mv.visitCode();
 738             mv.visitFieldInsn(GETSTATIC, className, sdFieldName, SPECIES_DATA_SIG);
 739             mv.visitInsn(ARETURN);
 740             mv.visitMaxs(0, 0);
 741             mv.visitEnd();
 742 
 743             // figure out the constructor arguments
 744             MethodType superCtorType = ClassSpecializer.this.baseConstructorType();
 745             MethodType thisCtorType = superCtorType.appendParameterTypes(fieldTypes);
 746 
 747             // emit constructor
 748             {
 749                 mv = cw.visitMethod(ACC_PRIVATE,
 750                         "<init>", methodSig(thisCtorType), null, null);
 751                 mv.visitCode();
 752                 mv.visitVarInsn(ALOAD, 0); // this
 753 
 754                 final List<Var> ctorArgs = AFTER_THIS.fromTypes(superCtorType.parameterList());
 755                 for (Var ca : ctorArgs) {
 756                     ca.emitVarInstruction(ALOAD, mv);
 757                 }
 758 
 759                 // super(ca...)
 760                 mv.visitMethodInsn(INVOKESPECIAL, superClassName,
 761                         "<init>", methodSig(superCtorType), false);
 762 
 763                 // store down fields
 764                 Var lastFV = AFTER_THIS.lastOf(ctorArgs);
 765                 for (Var f : fields) {
 766                     // this.argL1 = argL1
 767                     mv.visitVarInsn(ALOAD, 0);  // this
 768                     lastFV = new Var(f.name, f.type, lastFV);
 769                     lastFV.emitVarInstruction(ALOAD, mv);
 770                     f.emitFieldInsn(PUTFIELD, mv);
 771                 }
 772 
 773                 mv.visitInsn(RETURN);
 774                 mv.visitMaxs(0, 0);
 775                 mv.visitEnd();
 776             }
 777 
 778             // emit make()  ...factory method wrapping constructor
 779             {
 780                 MethodType ftryType = thisCtorType.changeReturnType(topClass());
 781                 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_STATIC,
 782                         "make", methodSig(ftryType), null, null);
 783                 mv.visitCode();
 784                 // make instance
 785                 mv.visitTypeInsn(NEW, className);
 786                 mv.visitInsn(DUP);
 787                 // load factory method arguments:  ctarg... and arg...
 788                 for (Var v : NO_THIS.fromTypes(ftryType.parameterList())) {
 789                     v.emitVarInstruction(ALOAD, mv);
 790                 }
 791 
 792                 // finally, invoke the constructor and return
 793                 mv.visitMethodInsn(INVOKESPECIAL, className,
 794                         "<init>", methodSig(thisCtorType), false);
 795                 mv.visitInsn(ARETURN);
 796                 mv.visitMaxs(0, 0);
 797                 mv.visitEnd();
 798             }
 799 
 800             // For each transform, emit the customized override of the transform method.
 801             // This method mixes together some incoming arguments (from the transform's
 802             // static type signature) with the field types themselves, and passes
 803             // the resulting mish-mosh of values to a method handle produced by
 804             // the species itself.  (Typically this method handle is the factory
 805             // method of this species or a related one.)
 806             for (int whichtm = 0; whichtm < TRANSFORM_NAMES.size(); whichtm++) {
 807                 final String     TNAME = TRANSFORM_NAMES.get(whichtm);
 808                 final MethodType TTYPE = TRANSFORM_TYPES.get(whichtm);
 809                 final int        TMODS = TRANSFORM_MODS.get(whichtm);
 810                 mv = cw.visitMethod((TMODS & ACC_PPP) | ACC_FINAL,
 811                         TNAME, TTYPE.toMethodDescriptorString(), null, E_THROWABLE);
 812                 mv.visitCode();
 813                 // return a call to the corresponding "transform helper", something like this:
 814                 //   MY_SPECIES.transformHelper(whichtm).invokeBasic(ctarg, ..., argL0, ..., xarg)
 815                 mv.visitFieldInsn(GETSTATIC, className,
 816                         sdFieldName, SPECIES_DATA_SIG);
 817                 emitIntConstant(whichtm, mv);
 818                 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA,
 819                         "transformHelper", "(I)" + MH_SIG, false);
 820 
 821                 List<Var> targs = AFTER_THIS.fromTypes(TTYPE.parameterList());
 822                 List<Var> tfields = new ArrayList<>(fields);
 823                 // mix them up and load them for the transform helper:
 824                 List<Var> helperArgs = speciesData.deriveTransformHelperArguments(transformMethods.get(whichtm), whichtm, targs, tfields);
 825                 List<Class<?>> helperTypes = new ArrayList<>(helperArgs.size());
 826                 for (Var ha : helperArgs) {
 827                     helperTypes.add(ha.basicType.basicTypeClass());
 828                     if (ha.isInHeap()) {
 829                         assert(tfields.contains(ha));
 830                         mv.visitVarInsn(ALOAD, 0);
 831                         ha.emitFieldInsn(GETFIELD, mv);
 832                     } else {
 833                         assert(targs.contains(ha));
 834                         ha.emitVarInstruction(ALOAD, mv);
 835                     }
 836                 }
 837 
 838                 // jump into the helper (which is probably a factory method)
 839                 final Class<?> rtype = TTYPE.returnType();
 840                 final BasicType rbt = BasicType.basicType(rtype);
 841                 MethodType invokeBasicType = MethodType.methodType(rbt.basicTypeClass(), helperTypes);
 842                 mv.visitMethodInsn(INVOKEVIRTUAL, MH,
 843                         "invokeBasic", methodSig(invokeBasicType), false);
 844                 if (rbt == BasicType.L_TYPE) {
 845                     mv.visitTypeInsn(CHECKCAST, classBCName(rtype));
 846                     mv.visitInsn(ARETURN);
 847                 } else {
 848                     throw newInternalError("NYI: transform of type "+rtype);
 849                 }
 850                 mv.visitMaxs(0, 0);
 851                 mv.visitEnd();
 852             }
 853 
 854             cw.visitEnd();
 855 
 856             return cw.toByteArray();
 857         }
 858 
 859         private int typeLoadOp(char t) {
 860             switch (t) {
 861             case 'L': return ALOAD;
 862             case 'I': return ILOAD;
 863             case 'J': return LLOAD;
 864             case 'F': return FLOAD;
 865             case 'D': return DLOAD;
 866             default : throw newInternalError("unrecognized type " + t);
 867             }
 868         }
 869 
 870         private void emitIntConstant(int con, MethodVisitor mv) {
 871             if (ICONST_M1 - ICONST_0 <= con && con <= ICONST_5 - ICONST_0)
 872                 mv.visitInsn(ICONST_0 + con);
 873             else if (con == (byte) con)
 874                 mv.visitIntInsn(BIPUSH, con);
 875             else if (con == (short) con)
 876                 mv.visitIntInsn(SIPUSH, con);
 877             else {
 878                 mv.visitLdcInsn(con);
 879             }
 880 
 881         }
 882 
 883         //
 884         // Getter MH generation.
 885         //
 886 
 887         private MethodHandle findGetter(Class<?> speciesCode, List<Class<?>> types, int index) {
 888             Class<?> fieldType = types.get(index);
 889             String fieldName = chooseFieldName(fieldType, index);
 890             try {
 891                 return IMPL_LOOKUP.findGetter(speciesCode, fieldName, fieldType);
 892             } catch (NoSuchFieldException | IllegalAccessException e) {
 893                 throw newInternalError(e);
 894             }
 895         }
 896 
 897         private List<MethodHandle> findGetters(Class<?> speciesCode, List<Class<?>> types) {
 898             MethodHandle[] mhs = new MethodHandle[types.size()];
 899             for (int i = 0; i < mhs.length; ++i) {
 900                 mhs[i] = findGetter(speciesCode, types, i);
 901                 assert(mhs[i].internalMemberName().getDeclaringClass() == speciesCode);
 902             }
 903             return List.of(mhs);
 904         }
 905 
 906         private List<MethodHandle> findFactories(Class<? extends T> speciesCode, List<Class<?>> types) {
 907             MethodHandle[] mhs = new MethodHandle[1];
 908             mhs[0] = findFactory(speciesCode, types);
 909             return List.of(mhs);
 910         }
 911 
 912         List<LambdaForm.NamedFunction> makeNominalGetters(List<Class<?>> types, List<MethodHandle> getters) {
 913             LambdaForm.NamedFunction[] nfs = new LambdaForm.NamedFunction[types.size()];
 914             for (int i = 0; i < nfs.length; ++i) {
 915                 nfs[i] = new LambdaForm.NamedFunction(getters.get(i));
 916             }
 917             return List.of(nfs);
 918         }
 919 
 920         //
 921         // Auxiliary methods.
 922         //
 923 
 924         protected void linkSpeciesDataToCode(ClassSpecializer<T,K,S>.SpeciesData speciesData, Class<? extends T> speciesCode) {
 925             speciesData.speciesCode = speciesCode.asSubclass(topClass);
 926             final List<Class<?>> types = speciesData.fieldTypes;
 927             speciesData.factories = this.findFactories(speciesCode, types);
 928             speciesData.getters = this.findGetters(speciesCode, types);
 929             speciesData.nominalGetters = this.makeNominalGetters(types, speciesData.getters);
 930         }
 931 
 932         private Field reflectSDField(Class<? extends T> speciesCode) {
 933             final Field field = reflectField(speciesCode, sdFieldName);
 934             assert(field.getType() == metaType);
 935             assert(Modifier.isStatic(field.getModifiers()));
 936             return field;
 937         }
 938 
 939         private S readSpeciesDataFromCode(Class<? extends T> speciesCode) {
 940             try {
 941                 MemberName sdField = IMPL_LOOKUP.resolveOrFail(REF_getStatic, speciesCode, sdFieldName, metaType);
 942                 Object base = MethodHandleNatives.staticFieldBase(sdField);
 943                 long offset = MethodHandleNatives.staticFieldOffset(sdField);
 944                 UNSAFE.loadFence();
 945                 return metaType.cast(UNSAFE.getReference(base, offset));
 946             } catch (Error err) {
 947                 throw err;
 948             } catch (Exception ex) {
 949                 throw newInternalError("Failed to load speciesData from speciesCode: " + speciesCode.getName(), ex);
 950             } catch (Throwable t) {
 951                 throw uncaughtException(t);
 952             }
 953         }
 954 
 955         protected S loadSpeciesDataFromCode(Class<? extends T> speciesCode) {
 956             if (speciesCode == topClass()) {
 957                 return topSpecies;
 958             }
 959             S result = readSpeciesDataFromCode(speciesCode);
 960             if (result.outer() != ClassSpecializer.this) {
 961                 throw newInternalError("wrong class");
 962             }
 963             return result;
 964         }
 965 
 966         protected void linkCodeToSpeciesData(Class<? extends T> speciesCode, ClassSpecializer<T,K,S>.SpeciesData speciesData, boolean salvage) {
 967             try {
 968                 assert(readSpeciesDataFromCode(speciesCode) == null ||
 969                     (salvage && readSpeciesDataFromCode(speciesCode).equals(speciesData)));
 970 
 971                 MemberName sdField = IMPL_LOOKUP.resolveOrFail(REF_putStatic, speciesCode, sdFieldName, metaType);
 972                 Object base = MethodHandleNatives.staticFieldBase(sdField);
 973                 long offset = MethodHandleNatives.staticFieldOffset(sdField);
 974                 UNSAFE.storeFence();
 975                 UNSAFE.putReference(base, offset, speciesData);
 976                 UNSAFE.storeFence();
 977             } catch (Error err) {
 978                 throw err;
 979             } catch (Exception ex) {
 980                 throw newInternalError("Failed to link speciesData to speciesCode: " + speciesCode.getName(), ex);
 981             } catch (Throwable t) {
 982                 throw uncaughtException(t);
 983             }
 984         }
 985 
 986         /**
 987          * Field names in concrete species classes adhere to this pattern:
 988          * type + index, where type is a single character (L, I, J, F, D).
 989          * The factory subclass can customize this.
 990          * The name is purely cosmetic, since it applies to a private field.
 991          */
 992         protected String chooseFieldName(Class<?> type, int index) {
 993             BasicType bt = BasicType.basicType(type);
 994             return "" + bt.basicTypeChar() + index;
 995         }
 996 
 997         MethodHandle findFactory(Class<? extends T> speciesCode, List<Class<?>> types) {
 998             final MethodType type = baseConstructorType().changeReturnType(topClass()).appendParameterTypes(types);
 999             try {
1000                 return IMPL_LOOKUP.findStatic(speciesCode, "make", type);
1001             } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) {
1002                 throw newInternalError(e);
1003             }
1004         }
1005     }
1006 
1007     /** Hook that virtualizes the Factory class, allowing subclasses to extend it. */
1008     protected Factory makeFactory() {
1009         return new Factory();
1010     }
1011 
1012 
1013     // Other misc helpers:
1014     private static final String MH = "java/lang/invoke/MethodHandle";
1015     private static final String MH_SIG = "L" + MH + ";";
1016     private static final String STABLE = "jdk/internal/vm/annotation/Stable";
1017     private static final String STABLE_SIG = "L" + STABLE + ";";
1018     private static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" };
1019     static {
1020         assert(MH_SIG.equals(classSig(MethodHandle.class)));
1021         assert(MH.equals(classBCName(MethodHandle.class)));
1022     }
1023 
1024     static String methodSig(MethodType mt) {
1025         return mt.toMethodDescriptorString();
1026     }
1027     static String classSig(Class<?> cls) {
1028         if (cls.isPrimitive() || cls.isArray())
1029             return MethodType.methodType(cls).toMethodDescriptorString().substring(2);
1030         return classSig(classBCName(cls));
1031     }
1032     static String classSig(String bcName) {
1033         assert(bcName.indexOf('.') < 0);
1034         assert(!bcName.endsWith(";"));
1035         assert(!bcName.startsWith("["));
1036         return "L" + bcName + ";";
1037     }
1038     static String classBCName(Class<?> cls) {
1039         return classBCName(className(cls));
1040     }
1041     static String classBCName(String str) {
1042         assert(str.indexOf('/') < 0) : str;
1043         return str.replace('.', '/');
1044     }
1045     static String className(Class<?> cls) {
1046         assert(!cls.isArray() && !cls.isPrimitive());
1047         return cls.getName();
1048     }
1049 }