1/* 2 * Copyright (c) 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 24import java.io.DataInputStream; 25import java.io.InputStream; 26import java.io.IOException; 27import java.io.PrintStream; 28import java.util.jar.JarFile; 29import java.util.zip.ZipEntry; 30 31public class CustomLoader extends ClassLoader { 32 private static PrintStream out = System.out; 33 public static ClassLoader myself; 34 public static ClassLoader agentClassLoader; 35 public static boolean failed = true; 36 37 public CustomLoader(ClassLoader classLoader) { 38 super(classLoader); 39 myself = this; 40 } 41 42 @Override 43 public Class<?> loadClass(String name) throws ClassNotFoundException { 44 out.println("CustomLoader: loading class: " + name); 45 if (name.equals("Agent")) { 46 Class c = null; 47 try { 48 byte[] buf = locateBytes(); 49 c = defineClass(name, buf, 0, buf.length); 50 } catch (IOException ex) { 51 throw new ClassNotFoundException(ex.getMessage()); 52 } 53 resolveClass(c); 54 out.println("CustomLoader.loadClass after resolveClass: " + name + 55 "; Class: " + c + "; ClassLoader: " + c.getClassLoader()); 56 return c; 57 } 58 return super.loadClass(name); 59 } 60 61 private byte[] locateBytes() throws IOException { 62 try { 63 JarFile jar = new JarFile("Agent.jar"); 64 InputStream is = jar.getInputStream(jar.getEntry("Agent.class")); 65 int len = is.available(); 66 byte[] buf = new byte[len]; 67 DataInputStream in = new DataInputStream(is); 68 in.readFully(buf); 69 return buf; 70 } catch (IOException ioe) { 71 ioe.printStackTrace(); 72 throw new IOException("Test failed due to IOException!"); 73 } 74 } 75 76 void appendToClassPathForInstrumentation(String path) { 77 out.println("CustomLoader.appendToClassPathForInstrumentation: " + 78 this + ", jar: " + path); 79 failed = false; 80 } 81} 82