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