public Class loadNewClass(String javaFile, String packageName) { Class myClass = null; String className = javaFile.replace(".java", ".class"); File inpFile = new File(className); int idx = className.lastIndexOf(File.separatorChar); String javaName = className.substring(idx + 1, className.indexOf(".")); int size = (int) inpFile.length(); byte[] ba = new byte[size]; try { FileInputStream fis = new FileInputStream(className); // read the entry int bytes_read = 0; while (bytes_read != size) { int r = fis.read(ba, bytes_read, size - bytes_read); if (r < 0) break; bytes_read += r; } if (bytes_read != size) throw new IOException("cannot read entry"); } catch (FileNotFoundException fnfExc) { System.out.println("File : " + className + " not found"); fnfExc.printStackTrace(); } catch (IOException ioExc) { System.out.println("IO Exception in JavaCompile trying to read class: "); ioExc.printStackTrace(); } try { String packageAppendedFileName = ""; if (packageName.isEmpty()) packageAppendedFileName = javaName; else packageAppendedFileName = packageName + "." + javaName; packageAppendedFileName.replace(File.separatorChar, '.'); myClass = defineClass(packageAppendedFileName, ba, 0, size); // SOS-StergAutoCompletionScalaSci.upDateAutoCompletion(myClass); String userClassName = myClass.getName(); JOptionPane.showMessageDialog(null, "Class " + userClassName + " loaded successfully !"); } catch (ClassFormatError exc) { System.out.println("error defining class " + inpFile); exc.printStackTrace(); } catch (Exception ex) { System.out.println("some error defining class " + inpFile); ex.printStackTrace(); } return myClass; }
/** * Pass-one verification basically means loading in a class file. The Java Virtual Machine * Specification is not too precise about what makes the difference between passes one and two. * The answer is that only pass one is performed on a class file as long as its resolution is not * requested; whereas pass two and pass three are performed during the resolution process. Only * four constraints to be checked are explicitely stated by The Java Virtual Machine * Specification, 2nd edition: * * <UL> * <LI>The first four bytes must contain the right magic number (0xCAFEBABE). * <LI>All recognized attributes must be of the proper length. * <LI>The class file must not be truncated or have extra bytes at the end. * <LI>The constant pool must not contain any superficially unrecognizable information. * </UL> * * A more in-depth documentation of what pass one should do was written by <A * HREF=mailto:[email protected]>Philip W. L. Fong</A>: * * <UL> * <LI>the file should not be truncated. * <LI>the file should not have extra bytes at the end. * <LI>all variable-length structures should be well-formatted: * <UL> * <LI>there should only be constant_pool_count-1 many entries in the constant pool. * <LI>all constant pool entries should have size the same as indicated by their type tag. * <LI>there are exactly interfaces_count many entries in the interfaces array of the * class file. * <LI>there are exactly fields_count many entries in the fields array of the class file. * <LI>there are exactly methods_count many entries in the methods array of the class * file. * <LI>there are exactly attributes_count many entries in the attributes array of the * class file, fields, methods, and code attribute. * <LI>there should be exactly attribute_length many bytes in each attribute. * Inconsistency between attribute_length and the actually size of the attribute * content should be uncovered. For example, in an Exceptions attribute, the actual * number of exceptions as required by the number_of_exceptions field might yeild an * attribute size that doesn't match the attribute_length. Such an anomaly should be * detected. * <LI>all attributes should have proper length. In particular, under certain context * (e.g. while parsing method_info), recognizable attributes (e.g. "Code" attribute) * should have correct format (e.g. attribute_length is 2). * </UL> * <LI>Also, certain constant values are checked for validity: * <UL> * <LI>The magic number should be 0xCAFEBABE. * <LI>The major and minor version numbers are valid. * <LI>All the constant pool type tags are recognizable. * <LI>All undocumented access flags are masked off before use. Strictly speaking, this is * not really a check. * <LI>The field this_class should point to a string that represents a legal non-array * class name, and this name should be the same as the class file being loaded. * <LI>the field super_class should point to a string that represents a legal non-array * class name. * <LI>Because some of the above checks require cross referencing the constant pool * entries, guards are set up to make sure that the referenced entries are of the * right type and the indices are within the legal range (0 < index < * constant_pool_count). * </UL> * <LI>Extra checks done in pass 1: * <UL> * <LI>the constant values of static fields should have the same type as the fields. * <LI>the number of words in a parameter list does not exceed 255 and locals_max. * <LI>the name and signature of fields and methods are verified to be of legal format. * </UL> * </UL> * * (From the Paper <A HREF=http://www.cs.sfu.ca/people/GradStudents/pwfong/personal/JVM/pass1/>The * Mysterious Pass One, first draft, September 2, 1997</A>.) </BR> However, most of this is done * by parsing a class file or generating a class file into BCEL's internal data structure. * <B>Therefore, all that is really done here is look up the class file from BCEL's * repository.</B> This is also motivated by the fact that some omitted things (like the check for * extra bytes at the end of the class file) are handy when actually using BCEL to repair a class * file (otherwise you would not be able to load it into BCEL). * * @see org.aspectj.apache.bcel.Repository */ public VerificationResult do_verify() { JavaClass jc; try { jc = getJavaClass(); // loads in the class file if not already done. if (jc != null) { /* If we find more constraints to check, we should do this in an own method. */ if (!myOwner.getClassName().equals(jc.getClassName())) { // This should maybe caught by BCEL: In case of renamed .class files we get wrong // JavaClass objects here. throw new LoadingException( "Wrong name: the internal name of the .class file '" + jc.getClassName() + "' does not match the file's name '" + myOwner.getClassName() + "'."); } } } catch (LoadingException e) { return new VerificationResult(VerificationResult.VERIFIED_REJECTED, e.getMessage()); } catch (ClassFormatError e) { // BCEL sometimes is a little harsh describing exceptual situations. return new VerificationResult(VerificationResult.VERIFIED_REJECTED, e.getMessage()); } catch (RuntimeException e) { // BCEL does not catch every possible RuntimeException; e.g. if // a constant pool index is referenced that does not exist. return new VerificationResult( VerificationResult.VERIFIED_REJECTED, "Parsing via BCEL did not succeed. " + e.getClass().getName() + " occured:\n" + Utility.getStackTrace(e)); } if (jc != null) { return VerificationResult.VR_OK; } else { // TODO: Maybe change Repository's behaviour to throw a LoadingException instead of just // returning "null" // if a class file cannot be found or in another way be looked up. return new VerificationResult( VerificationResult.VERIFIED_REJECTED, "Repository.lookup() failed. FILE NOT FOUND?"); } }
/** @param loader The SplitterLoader used to load the compiled source. Must not be null. */ public void load(SplitterLoader loader) { Class tempClass = loader.load_Class(className, directory + className + ".class"); if (tempClass != null) { try { splitter = (Splitter) tempClass.newInstance(); } catch (ClassFormatError ce) { ce.printStackTrace(System.out); } catch (InstantiationException ie) { ie.printStackTrace(System.out); } catch (IllegalAccessException iae) { iae.printStackTrace(System.out); } DummyInvariant dummy = new DummyInvariant(null); dummy.setFormats( daikonFormat, javaFormat, escFormat, simplifyFormat, ioaFormat, jmlFormat, dbcFormat, dummyDesired); splitter.makeDummyInvariant(dummy); errorMessage = "Splitter exists " + this.toString(); exists = true; } else { errorMessage = "No class data for " + this.toString() + ", to be loaded from " + directory + className + ".class"; exists = false; } }
public Class<?> toClass( ToClassInvokerPoolReference pool, CtClass cc, String classFileName, ClassLoader loader, ProtectionDomain domain) throws CannotCompileException { boolean trace = logger.isTraceEnabled(); pool.lockInCache(cc); final ClassLoader myloader = pool.getClassLoader(); if (myloader == null || tmpDir == null) { if (trace) logger.trace( this + " " + pool + ".toClass() myloader:" + myloader + " tmpDir:" + tmpDir + " default to superPool.toClass for " + cc.getName()); Class<?> clazz = pool.superPoolToClass(cc, loader, domain); if (trace) logger.trace(this + " " + pool + " myloader:" + myloader + " created class:" + clazz); return clazz; } Class<?> dynClass = null; try { File classFile = null; // Write the clas file to the tmpdir synchronized (tmplock) { classFile = new File(tmpDir, classFileName); if (trace) logger.trace( this + " " + pool + ".toClass() myloader:" + myloader + " writing bytes to " + classFile); File pkgDirs = classFile.getParentFile(); pkgDirs.mkdirs(); FileOutputStream stream = new FileOutputStream(classFile); stream.write(cc.toBytecode()); stream.flush(); stream.close(); classFile.deleteOnExit(); } // We have to clear Blacklist caches or the class will never // be found // ((UnifiedClassLoader)dcl).clearBlacklists(); // To be backward compatible RepositoryClassLoader rcl = (RepositoryClassLoader) myloader; rcl.clearClassBlackList(); rcl.clearResourceBlackList(); // Now load the class through the cl dynClass = myloader.loadClass(cc.getName()); if (trace) logger.trace(this + " " + pool + " myloader:" + myloader + " created class:" + dynClass); return dynClass; } catch (Exception ex) { ClassFormatError cfe = new ClassFormatError("Failed to load dyn class: " + cc.getName()); cfe.initCause(ex); throw cfe; } }
/** * Returns the {@code java.lang.Class} object for a proxy class given a class loader and an array * of interfaces. The proxy class will be defined by the specified class loader and will implement * all of the supplied interfaces. If a proxy class for the same permutation of interfaces has * already been defined by the class loader, then the existing proxy class will be returned; * otherwise, a proxy class for those interfaces will be generated dynamically and defined by the * class loader. * * <p>There are several restrictions on the parameters that may be passed to {@code * Proxy.getProxyClass}: * * <ul> * <li>All of the {@code Class} objects in the {@code interfaces} array must represent * interfaces, not classes or primitive types. * <li>No two elements in the {@code interfaces} array may refer to identical {@code Class} * objects. * <li>All of the interface types must be visible by name through the specified class loader. In * other words, for class loader {@code cl} and every interface {@code i}, the following * expression must be true: * <pre> * Class.forName(i.getName(), false, cl) == i * </pre> * <li>All non-public interfaces must be in the same package; otherwise, it would not be * possible for the proxy class to implement all of the interfaces, regardless of what * package it is defined in. * <li>For any set of member methods of the specified interfaces that have the same signature: * <ul> * <li>If the return type of any of the methods is a primitive type or void, then all of * the methods must have that same return type. * <li>Otherwise, one of the methods must have a return type that is assignable to all of * the return types of the rest of the methods. * </ul> * <li>The resulting proxy class must not exceed any limits imposed on classes by the virtual * machine. For example, the VM may limit the number of interfaces that a class may * implement to 65535; in that case, the size of the {@code interfaces} array must not * exceed 65535. * </ul> * * <p>If any of these restrictions are violated, {@code Proxy.getProxyClass} will throw an {@code * IllegalArgumentException}. If the {@code interfaces} array argument or any of its elements are * {@code null}, a {@code NullPointerException} will be thrown. * * <p>Note that the order of the specified proxy interfaces is significant: two requests for a * proxy class with the same combination of interfaces but in a different order will result in two * distinct proxy classes. * * @param loader the class loader to define the proxy class * @param interfaces the list of interfaces for the proxy class to implement * @return a proxy class that is defined in the specified class loader and that implements the * specified interfaces * @throws IllegalArgumentException if any of the restrictions on the parameters that may be * passed to {@code getProxyClass} are violated * @throws NullPointerException if the {@code interfaces} array argument or any of its elements * are {@code null} */ public static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces) throws IllegalArgumentException { if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); } Class<?> proxyClass = null; /* collect interface names to use as key for proxy class cache */ String[] interfaceNames = new String[interfaces.length]; // for detecting duplicates Set<Class<?>> interfaceSet = new HashSet<>(); for (int i = 0; i < interfaces.length; i++) { /* * Verify that the class loader resolves the name of this * interface to the same Class object. */ String interfaceName = interfaces[i].getName(); Class<?> interfaceClass = null; try { interfaceClass = Class.forName(interfaceName, false, loader); } catch (ClassNotFoundException e) { } if (interfaceClass != interfaces[i]) { throw new IllegalArgumentException(interfaces[i] + " is not visible from class loader"); } /* * Verify that the Class object actually represents an * interface. */ if (!interfaceClass.isInterface()) { throw new IllegalArgumentException(interfaceClass.getName() + " is not an interface"); } /* * Verify that this interface is not a duplicate. */ if (interfaceSet.contains(interfaceClass)) { throw new IllegalArgumentException("repeated interface: " + interfaceClass.getName()); } interfaceSet.add(interfaceClass); interfaceNames[i] = interfaceName; } /* * Using string representations of the proxy interfaces as * keys in the proxy class cache (instead of their Class * objects) is sufficient because we require the proxy * interfaces to be resolvable by name through the supplied * class loader, and it has the advantage that using a string * representation of a class makes for an implicit weak * reference to the class. */ List<String> key = Arrays.asList(interfaceNames); /* * Find or create the proxy class cache for the class loader. */ Map<List<String>, Object> cache; synchronized (loaderToCache) { cache = loaderToCache.get(loader); if (cache == null) { cache = new HashMap<>(); loaderToCache.put(loader, cache); } /* * This mapping will remain valid for the duration of this * method, without further synchronization, because the mapping * will only be removed if the class loader becomes unreachable. */ } /* * Look up the list of interfaces in the proxy class cache using * the key. This lookup will result in one of three possible * kinds of values: * null, if there is currently no proxy class for the list of * interfaces in the class loader, * the pendingGenerationMarker object, if a proxy class for the * list of interfaces is currently being generated, * or a weak reference to a Class object, if a proxy class for * the list of interfaces has already been generated. */ synchronized (cache) { /* * Note that we need not worry about reaping the cache for * entries with cleared weak references because if a proxy class * has been garbage collected, its class loader will have been * garbage collected as well, so the entire cache will be reaped * from the loaderToCache map. */ do { Object value = cache.get(key); if (value instanceof Reference) { proxyClass = (Class<?>) ((Reference) value).get(); } if (proxyClass != null) { // proxy class already generated: return it return proxyClass; } else if (value == pendingGenerationMarker) { // proxy class being generated: wait for it try { cache.wait(); } catch (InterruptedException e) { /* * The class generation that we are waiting for should * take a small, bounded time, so we can safely ignore * thread interrupts here. */ } continue; } else { /* * No proxy class for this list of interfaces has been * generated or is being generated, so we will go and * generate it now. Mark it as pending generation. */ cache.put(key, pendingGenerationMarker); break; } } while (true); } try { String proxyPkg = null; // package to define proxy class in /* * Record the package of a non-public proxy interface so that the * proxy class will be defined in the same package. Verify that * all non-public proxy interfaces are in the same package. */ for (int i = 0; i < interfaces.length; i++) { int flags = interfaces[i].getModifiers(); if (!Modifier.isPublic(flags)) { String name = interfaces[i].getName(); int n = name.lastIndexOf('.'); String pkg = ((n == -1) ? "" : name.substring(0, n + 1)); if (proxyPkg == null) { proxyPkg = pkg; } else if (!pkg.equals(proxyPkg)) { throw new IllegalArgumentException("non-public interfaces from different packages"); } } } if (proxyPkg == null) { // if no non-public proxy interfaces, proxyPkg = ""; // use the unnamed package } { /* * Choose a name for the proxy class to generate. */ long num; synchronized (nextUniqueNumberLock) { num = nextUniqueNumber++; } String proxyName = proxyPkg + proxyClassNamePrefix + num; /* * Verify that the class loader hasn't already * defined a class with the chosen name. */ /* * Generate the specified proxy class. */ byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces); try { proxyClass = defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); } catch (ClassFormatError e) { /* * A ClassFormatError here means that (barring bugs in the * proxy class generation code) there was some other * invalid aspect of the arguments supplied to the proxy * class creation (such as virtual machine limitations * exceeded). */ throw new IllegalArgumentException(e.toString()); } } // add to set of all generated proxy classes, for isProxyClass proxyClasses.put(proxyClass, null); } finally { /* * We must clean up the "pending generation" state of the proxy * class cache entry somehow. If a proxy class was successfully * generated, store it in the cache (with a weak reference); * otherwise, remove the reserved entry. In all cases, notify * all waiters on reserved entries in this cache. */ synchronized (cache) { if (proxyClass != null) { cache.put(key, new WeakReference<Class<?>>(proxyClass)); } else { cache.remove(key); } cache.notifyAll(); } } return proxyClass; }