BadClass.java revision 2942:08092deced3f
1/* 2 * Copyright (c) 2014, 2015, 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 * @test 26 * @bug 6898851 27 * @summary Compiling against this corrupt class file causes a stacktrace from javac 28 * @modules jdk.jdeps/com.sun.tools.classfile 29 */ 30 31import java.io.File; 32import java.io.FileWriter; 33import java.io.StringWriter; 34import java.io.PrintWriter; 35import java.io.IOException; 36 37import com.sun.tools.classfile.ClassFile; 38import com.sun.tools.classfile.ClassWriter; 39import com.sun.tools.javac.Main; 40 41public class BadClass { 42 // Create and compile file containing body; return compiler output 43 static String makeClass(String dir, String filename, String body) throws IOException { 44 File file = new File(dir, filename); 45 try (FileWriter fw = new FileWriter(file)) { 46 fw.write(body); 47 } 48 49 StringWriter sw = new StringWriter(); 50 PrintWriter pw = new PrintWriter(sw); 51 String args[] = { "-cp", dir, "-d", dir, "-XDrawDiagnostics", file.getPath() }; 52 Main.compile(args, pw); 53 pw.close(); 54 return sw.toString(); 55 } 56 57 public static void main(String... args) throws Exception { 58 new File("d1").mkdir(); 59 new File("d2").mkdir(); 60 61 // Step 1. build an empty class with an interface 62 makeClass("d1", "Empty.java", "abstract class Empty implements Readable {}"); 63 64 // Step 2. Modify classfile to have invalid constant pool index 65 ClassFile cf = ClassFile.read(new File("d1","Empty.class")); 66 cf.interfaces[0] = cf.constant_pool.size() + 10; 67 ClassWriter cw = new ClassWriter(); 68 cw.write(cf, new File("d2","Empty.class")); 69 70 // Step 3. Compile use of invalid class 71 String result = makeClass("d2", "EmptyUse.java", "class EmptyUse { Empty e; }"); 72 if (!result.contains("compiler.misc.bad.class.file")) { 73 System.out.println(result); 74 throw new Exception("test failed"); 75 } 76 } 77} 78