1 /*
   2  * Copyright (c) 2013, 2016, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 
  25 package org.graalvm.compiler.core.test;
  26 
  27 import java.io.ByteArrayOutputStream;
  28 import java.io.IOException;
  29 import java.io.InputStream;
  30 import java.lang.reflect.Constructor;
  31 import java.util.HashMap;
  32 
  33 import org.graalvm.compiler.debug.DebugContext;
  34 import org.graalvm.compiler.java.GraphBuilderPhase;
  35 import org.graalvm.compiler.nodes.StructuredGraph;
  36 import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
  37 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
  38 import org.graalvm.compiler.nodes.java.RegisterFinalizerNode;
  39 import org.graalvm.compiler.options.OptionValues;
  40 import org.graalvm.compiler.phases.OptimisticOptimizations;
  41 import org.graalvm.compiler.phases.common.CanonicalizerPhase;
  42 import org.graalvm.compiler.phases.common.inlining.InliningPhase;
  43 import org.graalvm.compiler.phases.tiers.HighTierContext;
  44 import org.junit.Assert;
  45 import org.junit.Test;
  46 
  47 import jdk.vm.ci.meta.Assumptions;
  48 import jdk.vm.ci.meta.Assumptions.Assumption;
  49 import jdk.vm.ci.meta.Assumptions.LeafType;
  50 import jdk.vm.ci.meta.Assumptions.NoFinalizableSubclass;
  51 import jdk.vm.ci.meta.ResolvedJavaMethod;
  52 
  53 public class FinalizableSubclassTest extends GraalCompilerTest {
  54 
  55     /**
  56      * used as template to generate class files at runtime.
  57      */
  58     public static class NoFinalizerEverAAAA {
  59     }
  60 
  61     public static class NoFinalizerYetAAAA {
  62     }
  63 
  64     public static final class WithFinalizerAAAA extends NoFinalizerYetAAAA {
  65 
  66         @SuppressWarnings("deprecation")
  67         @Override
  68         protected void finalize() throws Throwable {
  69             super.finalize();
  70         }
  71     }
  72 
  73     private StructuredGraph parseAndProcess(Class<?> cl, AllowAssumptions allowAssumptions) {
  74         Constructor<?>[] constructors = cl.getConstructors();
  75         Assert.assertTrue(constructors.length == 1);
  76         final ResolvedJavaMethod javaMethod = getMetaAccess().lookupJavaMethod(constructors[0]);
  77         OptionValues options = getInitialOptions();
  78         StructuredGraph graph = new StructuredGraph.Builder(options, getDebugContext(options, null, javaMethod), allowAssumptions).method(javaMethod).build();
  79 
  80         GraphBuilderConfiguration conf = GraphBuilderConfiguration.getSnippetDefault(getDefaultGraphBuilderPlugins());
  81         new GraphBuilderPhase.Instance(getMetaAccess(), getProviders().getStampProvider(), getProviders().getConstantReflection(), getProviders().getConstantFieldProvider(), conf,
  82                         OptimisticOptimizations.ALL, null).apply(graph);
  83         HighTierContext context = new HighTierContext(getProviders(), getDefaultGraphBuilderSuite(), OptimisticOptimizations.ALL);
  84         new InliningPhase(new CanonicalizerPhase()).apply(graph, context);
  85         new CanonicalizerPhase().apply(graph, context);
  86         return graph;
  87     }
  88 
  89     private void checkForRegisterFinalizeNode(Class<?> cl, boolean shouldContainFinalizer, AllowAssumptions allowAssumptions) {
  90         StructuredGraph graph = parseAndProcess(cl, allowAssumptions);
  91         Assert.assertTrue(graph.getNodes().filter(RegisterFinalizerNode.class).count() == (shouldContainFinalizer ? 1 : 0));
  92         int noFinalizerAssumption = 0;
  93         Assumptions assumptions = graph.getAssumptions();
  94         if (assumptions != null) {
  95             for (Assumption a : assumptions) {
  96                 if (a instanceof NoFinalizableSubclass) {
  97                     noFinalizerAssumption++;
  98                 } else if (a instanceof LeafType) {
  99                     // Need to also allow leaf type assumption instead of no finalizable subclass
 100                     // assumption.
 101                     noFinalizerAssumption++;
 102                 }
 103             }
 104         }
 105         Assert.assertTrue(noFinalizerAssumption == (shouldContainFinalizer ? 0 : 1));
 106     }
 107 
 108     /**
 109      * Use a custom class loader to generate classes, to make sure the given classes are loaded in
 110      * correct order.
 111      */
 112     @Test
 113     public void test1() throws ClassNotFoundException {
 114         DebugContext debug = getDebugContext();
 115         for (int i = 0; i < 2; i++) {
 116             ClassTemplateLoader loader = new ClassTemplateLoader(debug);
 117             checkForRegisterFinalizeNode(loader.findClass("NoFinalizerEverAAAA"), true, AllowAssumptions.NO);
 118             checkForRegisterFinalizeNode(loader.findClass("NoFinalizerEverAAAA"), false, AllowAssumptions.YES);
 119 
 120             checkForRegisterFinalizeNode(loader.findClass("NoFinalizerYetAAAA"), false, AllowAssumptions.YES);
 121 
 122             checkForRegisterFinalizeNode(loader.findClass("WithFinalizerAAAA"), true, AllowAssumptions.YES);
 123             checkForRegisterFinalizeNode(loader.findClass("NoFinalizerYetAAAA"), true, AllowAssumptions.YES);
 124         }
 125     }
 126 
 127     private static class ClassTemplateLoader extends ClassLoader {
 128 
 129         private static int loaderInstance = 0;
 130 
 131         private final String replaceTo;
 132         private HashMap<String, Class<?>> cache = new HashMap<>();
 133 
 134         private final DebugContext debug;
 135 
 136         ClassTemplateLoader(DebugContext debug) {
 137             loaderInstance++;
 138             this.debug = debug;
 139             replaceTo = String.format("%04d", loaderInstance);
 140         }
 141 
 142         @Override
 143         protected Class<?> findClass(final String name) throws ClassNotFoundException {
 144             String nameReplaced = name.replaceAll("AAAA", replaceTo);
 145             if (cache.containsKey(nameReplaced)) {
 146                 return cache.get(nameReplaced);
 147             }
 148 
 149             // copy classfile to byte array
 150             byte[] classData = null;
 151             try {
 152                 InputStream is = FinalizableSubclassTest.class.getResourceAsStream("FinalizableSubclassTest$" + name + ".class");
 153                 assert is != null;
 154                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 155 
 156                 byte[] buf = new byte[1024];
 157                 int size;
 158                 while ((size = is.read(buf, 0, buf.length)) != -1) {
 159                     baos.write(buf, 0, size);
 160                 }
 161                 baos.flush();
 162                 classData = baos.toByteArray();
 163             } catch (IOException e) {
 164                 Assert.fail("can't access class: " + name);
 165             }
 166 
 167             dumpStringsInByteArray(debug, classData);
 168 
 169             // replace all occurrences of "AAAA" in classfile
 170             int index = -1;
 171             while ((index = indexOfAAAA(classData, index + 1)) != -1) {
 172                 replaceAAAA(classData, index, replaceTo);
 173             }
 174             dumpStringsInByteArray(debug, classData);
 175 
 176             Class<?> c = defineClass(null, classData, 0, classData.length);
 177             cache.put(nameReplaced, c);
 178             return c;
 179         }
 180 
 181         private static int indexOfAAAA(byte[] b, int index) {
 182             for (int i = index; i < b.length; i++) {
 183                 boolean match = true;
 184                 for (int j = i; j < i + 4; j++) {
 185                     if (b[j] != (byte) 'A') {
 186                         match = false;
 187                         break;
 188                     }
 189                 }
 190                 if (match) {
 191                     return i;
 192                 }
 193             }
 194             return -1;
 195         }
 196 
 197         private static void replaceAAAA(byte[] b, int index, String replacer) {
 198             assert replacer.length() == 4;
 199             for (int i = index; i < index + 4; i++) {
 200                 b[i] = (byte) replacer.charAt(i - index);
 201             }
 202         }
 203 
 204         private static void dumpStringsInByteArray(DebugContext debug, byte[] b) {
 205             boolean wasChar = true;
 206             StringBuilder sb = new StringBuilder();
 207             for (Byte x : b) {
 208                 // check for [a-zA-Z0-9]
 209                 if ((x >= 0x41 && x <= 0x7a) || (x >= 0x30 && x <= 0x39)) {
 210                     if (!wasChar) {
 211                         debug.log(sb + "");
 212                         sb.setLength(0);
 213                     }
 214                     sb.append(String.format("%c", x));
 215                     wasChar = true;
 216                 } else {
 217                     wasChar = false;
 218                 }
 219             }
 220             debug.log(sb + "");
 221         }
 222     }
 223 }