VictimClassLoader.java revision 12158:0fe2815ffa74
1/* 2 * Copyright (c) 2012, 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 24public class VictimClassLoader extends ClassLoader { 25 public static long counter = 0; 26 27 private int which = (int) ++counter; 28 29 protected VictimClassLoader() { 30 super(VictimClassLoader.class.getClassLoader()); 31 } 32 33 protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { 34 Class c; 35 if (!name.endsWith("Victim")) { 36 c = super.loadClass(name, resolve); 37 return c; 38 } 39 40 c = findLoadedClass(name); 41 if (c != null) { 42 return c; 43 } 44 45 byte[] buf = readClassFile(name); 46 c = defineClass(name, buf, 0, buf.length); 47 resolveClass(c); 48 49 if (c.getClassLoader() != this) { 50 throw new AssertionError(); 51 } 52 53 Test8003720.println("loaded " + c + "#" + System.identityHashCode(c) + " in " + c.getClassLoader()); 54 return c; 55 } 56 57 static byte[] readClassFile(String name) { 58 try { 59 String rname = name.substring(name.lastIndexOf('.') + 1) + ".class"; 60 java.net.URL url = VictimClassLoader.class.getResource(rname); 61 Test8003720.println("found " + rname + " = " + url); 62 63 java.net.URLConnection connection = url.openConnection(); 64 int contentLength = connection.getContentLength(); 65 byte[] buf = readFully(connection.getInputStream(), contentLength); 66 67 return Asmator.fixup(buf); 68 } catch (java.io.IOException ex) { 69 throw new Error(ex); 70 } 71 } 72 73 static byte[] readFully(java.io.InputStream in, int len) throws java.io.IOException { 74 byte[] b = in.readAllBytes(); 75 if (len != -1 && b.length != len) 76 throw new java.io.IOException("Expected:" + len + ", actual:" + b.length); 77 return b; 78 } 79 80 public void finalize() { 81 Test8003720.println("Goodbye from " + this); 82 } 83 84 public String toString() { 85 return "VictimClassLoader#" + which; 86 } 87} 88