001: /*
002: * @(#)CodeLoader.java 1.2 04/12/06
003: *
004: * Copyright (c) 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package pnuts.compiler;
010:
011: import java.io.FileOutputStream;
012: import java.io.IOException;
013: import java.security.AccessController;
014: import java.security.PrivilegedAction;
015: import java.security.ProtectionDomain;
016:
017: /**
018: * This class is used with JDK1.2 or higher, to define classes from bytecode.
019: * The resulting class is in the same protection domain of
020: * pnuts.compiler.CodeLoader class.
021: */
022: class CodeLoader extends ClassLoader {
023:
024: private final static boolean DEBUG = false;
025:
026: private int count = 0;
027:
028: private ProtectionDomain domain;
029:
030: CodeLoader() {
031: init();
032: }
033:
034: CodeLoader(ClassLoader loader) {
035: super (loader);
036: init();
037: }
038:
039: void init() {
040: this .domain = getClass().getProtectionDomain();
041: }
042:
043: protected Class findClass(String name)
044: throws ClassNotFoundException {
045:
046: ClassLoader parent = (ClassLoader) AccessController
047: .doPrivileged(new PrivilegedAction() {
048: public Object run() {
049: return getParent();
050: }
051: });
052: try {
053: if (parent != null) {
054: return parent.loadClass(name);
055: }
056: } catch (ClassNotFoundException e) {
057: }
058: return findSystemClass(name);
059: }
060:
061: /**
062: * Resolve a class
063: */
064: void resolve(Class c) {
065: try {
066: resolveClass(c);
067: } catch (VerifyError ve) {
068: throw ve;
069: }
070: }
071:
072: /**
073: * Defines a class from a byte code array. This method can be called until
074: * seal() method is called,
075: */
076: Class define(final String name, final byte data[],
077: final int offset, final int length) {
078: if (DEBUG) {
079: // System.out.println(name + ", " + data.length + ", " + offset + ",
080: // " + length);
081: try {
082: FileOutputStream fout = new FileOutputStream(name
083: + ".class");
084: fout.write(data, offset, length);
085: fout.close();
086: } catch (IOException e) {
087: e.printStackTrace();
088: }
089: }
090: return (Class) AccessController
091: .doPrivileged(new PrivilegedAction() {
092: public Object run() {
093: return defineClass(name, data, offset, length,
094: domain);
095: }
096: });
097: }
098:
099: synchronized int nextCount() {
100: return count++;
101: }
102: }
|