1 /*
   2  * Copyright (c) 2014, 2018, 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 import java.io.File;
  26 import java.io.FileOutputStream;
  27 import jdk.test.lib.process.OutputAnalyzer;
  28 import java.nio.file.Files;
  29 
  30 import java.util.*;
  31 import jdk.internal.org.objectweb.asm.*;
  32 
  33 /**
  34  * The testsets contained in this class are executed by ./VerifierTest_*.java, so that
  35  * individual testsets can be executed in parallel to shorten the total time required.
  36  */
  37 public class VerifierTest implements Opcodes {
  38     // Test verification settings for dumping & runtime
  39     static final String VFY_ALL = "-Xverify:all";
  40     static final String VFY_REMOTE = "-Xverify:remote"; // default
  41     static final String VFY_NONE = "-Xverify:none";
  42 
  43     static final String ERR =
  44         "ERROR: class VerifierTestC was loaded unexpectedly";
  45     static final String MAP_FAIL =
  46         "shared archive file was created with less restrictive verification setting";
  47     static final String VFY_ERR = "java.lang.VerifyError";
  48     static final String PASS_RESULT = "Hi, how are you?";
  49 
  50     enum Testset1Part {
  51         A, B
  52     }
  53 
  54     public static void main(String[] args) throws Exception {
  55         String subCaseId = args[0];
  56         String jarName_verifier_test_tmp = "verifier_test_tmp" + "_" + subCaseId;
  57         String jarName_verifier_test = "verifier_test" + "_" + subCaseId;
  58         String jarName_greet = "greet" + "_" + subCaseId;
  59         String jarName_hi = "hi" + "_" + subCaseId;
  60 
  61 
  62         JarBuilder.build(jarName_verifier_test_tmp, "VerifierTest0", "VerifierTestA",
  63                          "VerifierTestB", "VerifierTestC", "VerifierTestD", "VerifierTestE",
  64                          "UnverifiableBase", "UnverifiableIntf", "UnverifiableIntfSub");
  65         JarBuilder.build(jarName_greet, "Greet");
  66         JarBuilder.build(jarName_hi, "Hi", "Hi$MyClass");
  67 
  68         File dir = new File(System.getProperty("test.classes", "."));
  69         File jarSrcFile = new File(dir, jarName_verifier_test_tmp + ".jar");
  70         File jarFile = new File(dir, jarName_verifier_test + ".jar");
  71         String jar = jarFile.getPath();
  72 
  73         if (!jarFile.exists() || jarFile.lastModified() < jarSrcFile.lastModified()) {
  74             createTestJarFile(jarSrcFile, jarFile);
  75         } else {
  76             System.out.println("Already up-to-date: " + jarFile);
  77         }
  78 
  79         String noAppClasses[] = TestCommon.list("");
  80         String appClasses[] = TestCommon.list("UnverifiableBase",
  81                                               "UnverifiableIntf",
  82                                               "UnverifiableIntfSub",
  83                                               "VerifierTestA",
  84                                               "VerifierTestB",
  85                                               "VerifierTestC",
  86                                               "VerifierTestD",
  87                                               "VerifierTestE",
  88                                               "VerifierTest0");
  89 
  90 
  91         switch (subCaseId) {
  92         case "0":         testset_0(jar, noAppClasses, appClasses);                 return;
  93         case "1A":        testset_1(jar, noAppClasses, appClasses, Testset1Part.A); return;
  94         case "1B":        testset_1(jar, noAppClasses, appClasses, Testset1Part.B); return;
  95         case "2":         testset_2(jarName_greet, jarName_hi);                   return;
  96         default:
  97             throw new RuntimeException("Unknown option: " + subCaseId);
  98         }
  99     }
 100 
 101     static void testset_0(String jar, String[] noAppClasses, String[] appClasses) throws Exception {
 102         // Dumping should fail if the IgnoreUnverifiableClassesDuringDump
 103         // option is not enabled.
 104         OutputAnalyzer output = TestCommon.dump(jar, appClasses,
 105                             "-XX:+UnlockDiagnosticVMOptions",
 106                             "-XX:-IgnoreUnverifiableClassesDuringDump");
 107         output.shouldContain("Please remove the unverifiable classes");
 108         output.shouldHaveExitValue(1);
 109 
 110         // By default, bad classes should be ignored during dumping.
 111         TestCommon.testDump(jar, appClasses);
 112     }
 113 
 114     static void checkRuntimeOutput(OutputAnalyzer output, String expected) throws Exception {
 115         output.shouldContain(expected);
 116         if (expected.equals(PASS_RESULT) ||
 117             expected.equals(VFY_ERR)) {
 118             output.shouldHaveExitValue(0);
 119         } else {
 120             output.shouldNotHaveExitValue(0);
 121         }
 122     }
 123 
 124     static void testset_1(String jar, String[] noAppClasses, String[] appClasses, Testset1Part part)
 125         throws Exception
 126     {
 127         String config[][] = {
 128             // {dump_list, dumptime_verification_setting,
 129             //  runtime_verification_setting, expected_output_str},
 130 
 131             // Dump app/ext with -Xverify:remote
 132             {"app",   VFY_REMOTE, VFY_REMOTE, VFY_ERR},
 133             {"app",   VFY_REMOTE, VFY_ALL,    MAP_FAIL},
 134             {"app",   VFY_REMOTE, VFY_NONE,   ERR },
 135             // Dump app/ext with -Xverify:all
 136             {"app",   VFY_ALL,    VFY_REMOTE, VFY_ERR },
 137             {"app",   VFY_ALL,    VFY_ALL,    VFY_ERR },
 138             {"app",   VFY_ALL,    VFY_NONE,   ERR },
 139             // Dump app/ext with -Xverify:none
 140             {"app",   VFY_NONE,   VFY_REMOTE, MAP_FAIL},
 141             {"app",   VFY_NONE,   VFY_ALL,    MAP_FAIL},
 142             {"app",   VFY_NONE,   VFY_NONE,   ERR },
 143             // Dump sys only with -Xverify:remote
 144             {"noApp", VFY_REMOTE, VFY_REMOTE, VFY_ERR},
 145             {"noApp", VFY_REMOTE, VFY_ALL,    VFY_ERR},
 146             {"noApp", VFY_REMOTE, VFY_NONE,   ERR},
 147             // Dump sys only with -Xverify:all
 148             {"noApp", VFY_ALL, VFY_REMOTE,    VFY_ERR},
 149             {"noApp", VFY_ALL, VFY_ALL,       VFY_ERR},
 150             {"noApp", VFY_ALL, VFY_NONE,      ERR},
 151             // Dump sys only with -Xverify:none
 152             {"noApp", VFY_NONE, VFY_REMOTE,   VFY_ERR},
 153             {"noApp", VFY_NONE, VFY_ALL,      VFY_ERR},
 154             {"noApp", VFY_NONE, VFY_NONE,     ERR},
 155         };
 156 
 157         int loop_start, loop_stop;
 158 
 159         // Further break down testset_1 into two parts (to be invoked from VerifierTest_1A.java
 160         // and VerifierTest_1B.java) to improve parallel test execution time.
 161         switch (part) {
 162         case A:
 163             loop_start = 0;
 164             loop_stop  = 9;
 165             break;
 166         case B:
 167         default:
 168             assert part == Testset1Part.B;
 169             loop_start = 9;
 170             loop_stop  = config.length;
 171             break;
 172         }
 173 
 174         String prev_dump_setting = "";
 175         for (int i = loop_start; i < loop_stop; i ++) {
 176             String dump_list[] = config[i][0].equals("app") ? appClasses :
 177                 noAppClasses;
 178             String dump_setting = config[i][1];
 179             String runtime_setting = config[i][2];
 180             String expected_output_str = config[i][3];
 181             System.out.println("Test case [" + i + "]: dumping " + config[i][0] +
 182                                " with " + dump_setting +
 183                                ", run with " + runtime_setting);
 184             if (!dump_setting.equals(prev_dump_setting)) {
 185                 OutputAnalyzer dumpOutput = TestCommon.dump(
 186                                                             jar, dump_list, dump_setting,
 187                                                             // FIXME: the following options are for working around a GC
 188                                                             // issue - assert failure when dumping archive with the -Xverify:all
 189                                                             "-Xms256m",
 190                                                             "-Xmx256m");
 191             }
 192             TestCommon.run("-cp", jar,
 193                            runtime_setting,
 194                            "VerifierTest0")
 195                 .ifNoMappingFailure(output -> checkRuntimeOutput(output, expected_output_str));
 196             prev_dump_setting = dump_setting;
 197         }
 198     }
 199 
 200     static void testset_2(String jarName_greet, String jarName_hi) throws Exception {
 201         String appClasses[];
 202         String jar;
 203 
 204         // The following section is for testing the scenarios where
 205         // the classes are verifiable during dump time.
 206         appClasses = TestCommon.list("Hi",
 207                                      "Greet",
 208                                      "Hi$MyClass");
 209         jar = TestCommon.getTestJar(jarName_hi + ".jar") + File.pathSeparator +
 210             TestCommon.getTestJar(jarName_greet + ".jar");
 211         String config2[][] = {
 212             // {dump_list, dumptime_verification_setting,
 213             //  runtime_verification_setting, expected_output_str},
 214 
 215             // Dump app/ext with -Xverify:remote
 216             {"app",   VFY_REMOTE, VFY_REMOTE, PASS_RESULT},
 217             {"app",   VFY_REMOTE, VFY_ALL,    MAP_FAIL},
 218             {"app",   VFY_REMOTE, VFY_NONE,   PASS_RESULT },
 219             // Dump app/ext with -Xverify:all
 220             {"app",   VFY_ALL,    VFY_REMOTE, PASS_RESULT },
 221             {"app",   VFY_ALL,    VFY_ALL,    PASS_RESULT },
 222             {"app",   VFY_ALL,    VFY_NONE,   PASS_RESULT },
 223             // Dump app/ext with -Xverify:none
 224             {"app",   VFY_NONE,   VFY_REMOTE, MAP_FAIL},
 225             {"app",   VFY_NONE,   VFY_ALL,    MAP_FAIL},
 226             {"app",   VFY_NONE,   VFY_NONE,   PASS_RESULT },
 227         };
 228         for (int i = 0; i < config2.length; i ++) {
 229             // config2[i][0] is always set to "app" in this test
 230             String dump_setting = config2[i][1];
 231             String runtime_setting = config2[i][2];
 232             String expected_output_str = config2[i][3];
 233             System.out.println("Test case [" + i + "]: dumping " + config2[i][0] +
 234                                " with " + dump_setting +
 235                                ", run with " + runtime_setting);
 236             OutputAnalyzer dumpOutput = TestCommon.dump(
 237                                                         jar, appClasses, dump_setting,
 238                                                         "-XX:+UnlockDiagnosticVMOptions",
 239                                                         // FIXME: the following options are for working around a GC
 240                                                         // issue - assert failure when dumping archive with the -Xverify:all
 241                                                         "-Xms256m",
 242                                                         "-Xmx256m");
 243             TestCommon.run("-cp", jar,
 244                            runtime_setting,
 245                            "Hi")
 246                 .ifNoMappingFailure(output -> checkRuntimeOutput(output, expected_output_str));
 247         }
 248     }
 249 
 250     static void createTestJarFile(File jarSrcFile, File jarFile) throws Exception {
 251         jarFile.delete();
 252         Files.copy(jarSrcFile.toPath(), jarFile.toPath());
 253 
 254         File dir = new File(System.getProperty("test.classes", "."));
 255         File outdir = new File(dir, "verifier_test_classes");
 256         outdir.mkdir();
 257 
 258         writeClassFile(new File(outdir, "UnverifiableBase.class"), makeUnverifiableBase());
 259         writeClassFile(new File(outdir, "UnverifiableIntf.class"), makeUnverifiableIntf());
 260 
 261         JarBuilder.update(jarFile.getPath(), outdir.getPath());
 262     }
 263 
 264     static void writeClassFile(File file, byte bytecodes[]) throws Exception {
 265         try (FileOutputStream fos = new FileOutputStream(file)) {
 266             fos.write(bytecodes);
 267         }
 268     }
 269 
 270     // This was obtained using JDK8: java jdk.internal.org.objectweb.asm.util.ASMifier tmpclasses/UnverifiableBase.class
 271     static byte[] makeUnverifiableBase() throws Exception {
 272         ClassWriter cw = new ClassWriter(0);
 273         FieldVisitor fv;
 274         MethodVisitor mv;
 275         AnnotationVisitor av0;
 276 
 277         cw.visit(V1_8, ACC_SUPER, "UnverifiableBase", null, "java/lang/Object", null);
 278         {
 279             fv = cw.visitField(ACC_FINAL + ACC_STATIC, "x", "LVerifierTest;", null, null);
 280             fv.visitEnd();
 281         }
 282         {
 283             mv = cw.visitMethod(0, "<init>", "()V", null, null);
 284             mv.visitCode();
 285             mv.visitVarInsn(ALOAD, 0);
 286             mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
 287             mv.visitInsn(RETURN);
 288             mv.visitMaxs(1, 1);
 289             mv.visitEnd();
 290         }
 291         {
 292             mv = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
 293             mv.visitCode();
 294             mv.visitTypeInsn(NEW, "VerifierTest0");
 295             mv.visitInsn(DUP);
 296             mv.visitMethodInsn(INVOKESPECIAL, "VerifierTest0", "<init>", "()V", false);
 297             mv.visitFieldInsn(PUTSTATIC, "UnverifiableBase", "x", "LVerifierTest;");
 298             mv.visitInsn(RETURN);
 299             mv.visitMaxs(2, 0);
 300             mv.visitEnd();
 301         }
 302         addBadMethod(cw);
 303         cw.visitEnd();
 304 
 305         return cw.toByteArray();
 306     }
 307 
 308     // This was obtained using JDK8: java jdk.internal.org.objectweb.asm.util.ASMifier tmpclasses/UnverifiableIntf.class
 309     static byte[] makeUnverifiableIntf() throws Exception {
 310         ClassWriter cw = new ClassWriter(0);
 311         FieldVisitor fv;
 312         MethodVisitor mv;
 313         AnnotationVisitor av0;
 314 
 315         cw.visit(V1_8, ACC_ABSTRACT + ACC_INTERFACE, "UnverifiableIntf", null, "java/lang/Object", null);
 316 
 317         {
 318             fv = cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, "x", "LVerifierTest0;", null, null);
 319             fv.visitEnd();
 320         }
 321         {
 322             mv = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
 323             mv.visitCode();
 324             mv.visitTypeInsn(NEW, "VerifierTest0");
 325             mv.visitInsn(DUP);
 326             mv.visitMethodInsn(INVOKESPECIAL, "VerifierTest0", "<init>", "()V", false);
 327             mv.visitFieldInsn(PUTSTATIC, "UnverifiableIntf", "x", "LVerifierTest0;");
 328             mv.visitInsn(RETURN);
 329             mv.visitMaxs(2, 0);
 330             mv.visitEnd();
 331         }
 332         addBadMethod(cw);
 333         cw.visitEnd();
 334 
 335         return cw.toByteArray();
 336     }
 337 
 338     // Add a bad method to make the class fail verification.
 339     static void addBadMethod(ClassWriter cw) throws Exception {
 340         MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "bad", "()V", null, null);
 341         mv.visitCode();
 342         mv.visitInsn(ARETURN); //  java.lang.VerifyError: Operand stack underflow
 343         mv.visitMaxs(2, 2);
 344         mv.visitEnd();
 345     }
 346 }