1 package org.ibex.classgen;
6 /** Class generation object representing the whole classfile */
7 public class ClassFile extends Type.Class.Body {
8 private final Type.Class thisType;
9 private final Type.Class superType;
10 private final Type.Class[] interfaces;
11 private final short minor;
12 private final short major;
14 private final Vector fields = new Vector();
15 public final Vector methods = new Vector();
17 static String flagsToString(int flags, boolean isClass) {
18 StringBuffer sb = new StringBuffer(32);
19 if ((flags & PUBLIC) != 0) sb.append("public ");
20 if ((flags & PRIVATE) != 0) sb.append("private ");
21 if ((flags & PROTECTED) != 0) sb.append("protected ");
22 if ((flags & STATIC) != 0) sb.append("static ");
23 if ((flags & FINAL) != 0) sb.append("final ");
24 if ((flags & ABSTRACT) != 0) sb.append("abstract ");
25 if (!isClass && (flags & SYNCHRONIZED) != 0) sb.append("synchronized ");
26 if (!isClass && (flags & NATIVE) != 0) sb.append("native ");
27 if (!isClass && (flags & STRICT) != 0) sb.append("strictfp ");
28 if (!isClass && (flags & VOLATILE) != 0) sb.append("volatile ");
29 if (!isClass && (flags & TRANSIENT) != 0) sb.append("transient ");
33 public Type.Class getType() { return thisType; }
34 public int getFlags() { return flags; }
36 String debugToString() { return debugToString(new StringBuffer(4096)).toString(); }
37 StringBuffer debugToString(StringBuffer sb) {
38 sb.append(flagsToString(flags,true));
39 sb.append((flags & INTERFACE) != 0 ? "interface " : "class ");
40 sb.append(thisType.debugToString());
41 if (superType != null) sb.append(" extends " + superType.debugToString());
42 if (interfaces != null && interfaces.length > 0) sb.append(" implements");
43 for(int i=0; i<interfaces.length; i++) sb.append((i==0?" ":", ")+interfaces[i].debugToString());
45 sb.append(" // v"+major+"."+minor);
46 ConstantPool.Utf8Key sourceFile = (ConstantPool.Utf8Key) attrs.get("SourceFile");
47 if (sourceFile != null) sb.append(" from " + sourceFile.s);
49 for(int i=0; i<fields.size(); i++) {
51 ((FieldGen)fields.elementAt(i)).debugToString(sb);
54 for(int i=0; i<methods.size(); i++) {
55 ((MethodGen)methods.elementAt(i)).debugToString(sb,thisType.getShortName());
62 public ClassFile(Type.Class thisType, Type.Class superType, int flags) { this(thisType, superType, flags, null); }
63 public ClassFile(Type.Class thisType, Type.Class superType, int flags, Type.Class[] interfaces) {
64 thisType.super(flags, new AttrGen());
65 this.thisType = thisType;
66 this.superType = superType;
67 this.interfaces = interfaces;
72 /** Adds a new method to this class
73 @param name The name of the method (not the signature, just the name)
74 @param ret The return type of the method
75 @param args The arguments to the method
76 @param flags The flags for the method
77 (PUBLIC, PRIVATE, PROTECTED, STATIC, SYNCHRONIZED, NATIVE, ABSTRACT, STRICT)
78 @return A new MethodGen object for the method
79 @exception IllegalArgumentException if illegal flags are specified
83 public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
84 MethodGen mg = new MethodGen(getType().method(name, ret, args), flags);
85 methods.addElement(mg);
89 /** Adds a new field to this class
90 @param name The name of the filed (not the signature, just the name)
91 @param type The type of the field
92 @param flags The flags for the field
93 (PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, VOLATILE, TRANSIENT)
94 @return A new FieldGen object for the method
95 @exception IllegalArgumentException if illegal flags are specified
99 public final FieldGen addField(String name, Type type, int flags) {
100 FieldGen fg = new FieldGen(getType().field(name, type), flags);
101 fields.addElement(fg);
105 /** Sets the source value of the SourceFile attribute of this class
106 @param sourceFile The string to be uses as the SourceFile of this class
108 public void setSourceFile(String sourceFile) { attrs.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
110 /** Writes the classfile data to the file specifed
111 @see ClassFile#dump(OutputStream)
113 public void dump(String file) throws IOException { dump(new File(file)); }
115 /** Writes the classfile data to the file specified
116 If <i>f</i> is a directory directory components under it are created for the package the class is in (like javac's -d option)
117 @see ClassFile#dump(OutputStream)
119 public void dump(File f) throws IOException {
120 if(f.isDirectory()) {
121 String[] a = thisType.components();
123 for(i=0;i<a.length-1;i++) {
124 f = new File(f, a[i]);
127 f = new File(f, a[i] + ".class");
129 OutputStream os = new FileOutputStream(f);
134 /** Writes the classfile data to the outputstream specified
135 @param os The stream to write the class to
136 @exception IOException if an IOException occures while writing the class data
137 @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
138 @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
140 public void dump(OutputStream os) throws IOException {
141 DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
146 private void _dump(DataOutput o) throws IOException {
147 ConstantPool cp = new ConstantPool();
150 if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
151 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish(cp);
152 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish(cp);
158 o.writeInt(0xcafebabe); // magic
159 o.writeShort(minor); // minor_version
160 o.writeShort(major); // major_version
162 cp.dump(o); // constant_pool
165 o.writeShort(cp.getIndex(thisType)); // this_class
166 o.writeShort(cp.getIndex(superType)); // super_class
168 o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
169 if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
171 o.writeShort(fields.size()); // fields_count
172 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
174 o.writeShort(methods.size()); // methods_count
175 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
177 attrs.dump(o,cp); // attributes
180 public static ClassFile read(String s) throws IOException { return read(new File(s)); }
181 public static ClassFile read(File f) throws ClassReadExn, IOException {
182 InputStream is = new FileInputStream(f);
183 ClassFile ret = read(is);
188 public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
190 return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
191 } catch(RuntimeException e) {
193 throw new ClassReadExn("invalid constant pool entry");
197 public ClassFile(DataInput i) throws IOException { this(i, false); }
198 public ClassFile(DataInput i, boolean ssa) throws IOException {
199 this(i.readInt(), i.readShort(), i.readShort(), new ConstantPool(i), i.readShort(), i, ssa);
201 private ClassFile(int magic, short minor, short major, ConstantPool cp,
202 short flags, DataInput i, boolean ssa) throws IOException {
203 this(magic, minor, major, cp, flags, (Type.Class)cp.getKeyByIndex(i.readShort()), i, ssa);
205 private ClassFile(int magic, short minor, short major, ConstantPool cp, short flags,
206 Type.Class thisType, DataInput i, boolean ssa) throws IOException {
207 thisType.super(flags, null);
208 if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
211 this.thisType = thisType;
212 superType = (Type.Class) cp.getKeyByIndex(i.readShort());
213 interfaces = new Type.Class[i.readShort()];
214 for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class) cp.getKeyByIndex(i.readShort());
215 int numFields = i.readShort();
216 for(int j=0; j<numFields; j++) fields.addElement(new FieldGen(this.getType(), i, cp));
217 int numMethods = i.readShort();
218 for(int j=0; j<numMethods; j++) methods.addElement(ssa
219 ? new JSSA(this.getType(), i, cp)
220 : new MethodGen(this.getType(), i, cp));
221 readAttributes(i, cp);
223 // FEATURE: Support these
224 // NOTE: Until we can support them properly we HAVE to delete them,
225 // they'll be incorrect after we rewrite the constant pool, etc
226 attrs.remove("InnerClasses");
229 /** Thrown when class generation fails for a reason not under the control of the user
230 (IllegalStateExceptions are thrown in those cases */
231 // FEATURE: This should probably be a checked exception
232 public static class Exn extends RuntimeException {
233 public Exn(String s) { super(s); }
236 public static class ClassReadExn extends IOException {
237 public ClassReadExn(String s) { super(s); }
240 static class AttrGen {
241 private final Hashtable ht = new Hashtable();
244 AttrGen(DataInput in, ConstantPool cp) throws IOException {
245 int size = in.readShort();
246 for(int i=0; i<size; i++) {
247 String name = cp.getUtf8KeyByIndex(in.readUnsignedShort());
248 int length = in.readInt();
249 if ((name.equals("SourceFile")||name.equals("ConstantValue")) && length == 2) {
250 ht.put(name, cp.getKeyByIndex(in.readUnsignedShort()));
252 byte[] buf = new byte[length];
259 public Object get(String s) { return ht.get(s); }
260 public void put(String s, Object data) { ht.put(s, data); }
261 public boolean contains(String s) { return ht.get(s) != null; }
262 public void remove(String s) { ht.remove(s); }
263 public int size() { return ht.size(); }
265 void finish(ConstantPool cp) {
266 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
267 String name = (String) e.nextElement();
268 Object val = ht.get(name);
270 if(!(val instanceof byte[])) cp.add(val);
274 void dump(DataOutput o, ConstantPool cp) throws IOException {
275 o.writeShort(size());
276 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
277 String name = (String) e.nextElement();
278 Object val = ht.get(name);
279 o.writeShort(cp.getUtf8Index(name));
280 if(val instanceof byte[]) {
281 byte[] buf = (byte[]) val;
282 o.writeInt(buf.length);
286 o.writeShort(cp.getIndex(val));
292 public static void main(String[] args) throws Exception {
293 if(args.length >= 2 && args[0].equals("copyto")) {
294 File dest = new File(args[1]);
296 for(int i=2;i<args.length;i++) {
297 System.err.println("Copying " + args[i]);
298 read(args[i]).dump(dest);
301 else if (args.length==1) {
302 if (args[0].endsWith(".class")) {
303 System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))).debugToString());
305 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
306 System.out.println(new ClassFile(new DataInputStream(is)).debugToString());
310 Type.Class me = new Type.Class("Test");
311 ClassFile cg = new ClassFile("Test", "java.lang.Object", PUBLIC|SUPER|FINAL);
312 FieldGen fg = cg.addField("foo", Type.INT, PUBLIC|STATIC);
314 MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, STATIC|PUBLIC);
318 mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
320 mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
322 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
323 mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
324 Type.VOID, new Type[]{Type.INT}));
325 //mg.add(IINC, new int[]{0, 1});
327 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
331 mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));
333 mg.add(IF_ICMPLT, top);
335 cg.dump("Test.class");