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 final Type.Class superType;
10 final Type.Class[] interfaces;
11 private final short minor;
12 private final short major;
14 private final Vector fields = new Vector();
15 private final Vector methods = new Vector();
17 public Type.Class.Method.Body[] methods() {
18 Type.Class.Method.Body[] ret = new Type.Class.Method.Body[methods.size()];
19 methods.copyInto(ret);
23 public Type.Class.Field.Body[] fields() {
24 Type.Class.Field.Body[] ret = new Type.Class.Field.Body[fields.size()];
29 static String flagsToString(int flags, boolean isClass) {
30 StringBuffer sb = new StringBuffer(32);
31 if ((flags & PUBLIC) != 0) sb.append("public ");
32 if ((flags & PRIVATE) != 0) sb.append("private ");
33 if ((flags & PROTECTED) != 0) sb.append("protected ");
34 if ((flags & STATIC) != 0) sb.append("static ");
35 if ((flags & FINAL) != 0) sb.append("final ");
36 if ((flags & ABSTRACT) != 0) sb.append("abstract ");
37 if (!isClass && (flags & SYNCHRONIZED) != 0) sb.append("synchronized ");
38 if (!isClass && (flags & NATIVE) != 0) sb.append("native ");
39 if (!isClass && (flags & STRICT) != 0) sb.append("strictfp ");
40 if (!isClass && (flags & VOLATILE) != 0) sb.append("volatile ");
41 if (!isClass && (flags & TRANSIENT) != 0) sb.append("transient ");
45 public Type.Class getType() { return thisType; }
46 public int getFlags() { return flags; }
48 public String toString() { return toString(new StringBuffer(4096)).toString(); }
49 StringBuffer toString(StringBuffer sb) {
50 sb.append(flagsToString(flags,true));
51 sb.append((flags & INTERFACE) != 0 ? "interface " : "class ");
52 sb.append(thisType.toString());
53 if (superType != null) sb.append(" extends " + superType.toString());
54 if (interfaces != null && interfaces.length > 0) sb.append(" implements");
55 for(int i=0; i<interfaces.length; i++) sb.append((i==0?" ":", ")+interfaces[i].toString());
57 sb.append(" // v"+major+"."+minor);
58 ConstantPool.Utf8Key sourceFile = (ConstantPool.Utf8Key) attrs.get("SourceFile");
59 if (sourceFile != null) sb.append(" from " + sourceFile.s);
61 for(int i=0; i<fields.size(); i++) {
63 ((FieldGen)fields.elementAt(i)).toString(sb);
66 for(int i=0; i<methods.size(); i++) {
67 ((MethodGen)methods.elementAt(i)).toString(sb,thisType.getShortName());
74 public ClassFile(Type.Class thisType, Type.Class superType, int flags) { this(thisType, superType, flags, null); }
75 public ClassFile(Type.Class thisType, Type.Class superType, int flags, Type.Class[] interfaces) {
76 thisType.super(flags, new AttrGen());
77 this.thisType = thisType;
78 this.superType = superType;
79 this.interfaces = interfaces;
84 /** Adds a new method to this class
85 @param name The name of the method (not the signature, just the name)
86 @param ret The return type of the method
87 @param args The arguments to the method
88 @param flags The flags for the method
89 (PUBLIC, PRIVATE, PROTECTED, STATIC, SYNCHRONIZED, NATIVE, ABSTRACT, STRICT)
90 @return A new MethodGen object for the method
91 @exception IllegalArgumentException if illegal flags are specified
95 public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
96 MethodGen mg = new MethodGen(getType().method(name, ret, args), flags);
97 methods.addElement(mg);
101 /** Adds a new field to this class
102 @param name The name of the filed (not the signature, just the name)
103 @param type The type of the field
104 @param flags The flags for the field
105 (PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, VOLATILE, TRANSIENT)
106 @return A new FieldGen object for the method
107 @exception IllegalArgumentException if illegal flags are specified
111 public final Type.Class.Field.Body addField(Type.Class.Field field, int flags) {
112 FieldGen fg = new FieldGen(field, flags);
113 fields.addElement(fg);
117 /** Sets the source value of the SourceFile attribute of this class
118 @param sourceFile The string to be uses as the SourceFile of this class
120 public void setSourceFile(String sourceFile) { attrs.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
122 /** Writes the classfile data to the file specifed
123 @see ClassFile#dump(OutputStream)
125 public void dump(String file) throws IOException { dump(new File(file)); }
127 /** Writes the classfile data to the file specified
128 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)
129 @see ClassFile#dump(OutputStream)
131 public void dump(File f) throws IOException {
132 if(f.isDirectory()) {
133 String[] a = thisType.components();
135 for(i=0;i<a.length-1;i++) {
136 f = new File(f, a[i]);
139 f = new File(f, a[i] + ".class");
141 OutputStream os = new FileOutputStream(f);
146 /** Writes the classfile data to the outputstream specified
147 @param os The stream to write the class to
148 @exception IOException if an IOException occures while writing the class data
149 @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
150 @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
152 public void dump(OutputStream os) throws IOException {
153 DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
158 private void _dump(DataOutput o) throws IOException {
159 ConstantPool cp = new ConstantPool();
162 if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
163 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish(cp);
164 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish(cp);
170 o.writeInt(0xcafebabe); // magic
171 o.writeShort(minor); // minor_version
172 o.writeShort(major); // major_version
174 cp.dump(o); // constant_pool
177 o.writeShort(cp.getIndex(thisType)); // this_class
178 o.writeShort(cp.getIndex(superType)); // super_class
180 o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
181 if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
183 o.writeShort(fields.size()); // fields_count
184 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
186 o.writeShort(methods.size()); // methods_count
187 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
189 attrs.dump(o,cp); // attributes
192 public static ClassFile read(String s) throws IOException { return read(new File(s)); }
193 public static ClassFile read(File f) throws ClassReadExn, IOException {
194 InputStream is = new FileInputStream(f);
195 ClassFile ret = read(is);
200 public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
202 return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
203 } catch(RuntimeException e) {
205 throw new ClassReadExn("invalid constant pool entry");
209 public ClassFile(DataInput i) throws IOException { this(i, false); }
210 public ClassFile(DataInput i, boolean ssa) throws IOException {
211 this(i.readInt(), i.readShort(), i.readShort(), new ConstantPool(i), i.readShort(), i, ssa);
213 private ClassFile(int magic, short minor, short major, ConstantPool cp,
214 short flags, DataInput i, boolean ssa) throws IOException {
215 this(magic, minor, major, cp, flags, (Type.Class)cp.getKeyByIndex(i.readShort()), i, ssa);
217 private ClassFile(int magic, short minor, short major, ConstantPool cp, short flags,
218 Type.Class thisType, DataInput i, boolean ssa) throws IOException {
219 thisType.super(flags, null);
220 if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
223 this.thisType = thisType;
224 superType = (Type.Class) cp.getKeyByIndex(i.readShort());
225 interfaces = new Type.Class[i.readShort()];
226 for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class) cp.getKeyByIndex(i.readShort());
227 int numFields = i.readShort();
228 for(int j=0; j<numFields; j++) fields.addElement(new FieldGen(this.getType(), i, cp));
229 int numMethods = i.readShort();
230 for(int j=0; j<numMethods; j++) methods.addElement(ssa
231 ? new JSSA(this.getType(), i, cp)
232 : new MethodGen(this.getType(), i, cp));
233 readAttributes(i, cp);
235 // FEATURE: Support these
236 // NOTE: Until we can support them properly we HAVE to delete them,
237 // they'll be incorrect after we rewrite the constant pool, etc
238 attrs.remove("InnerClasses");
241 /** Thrown when class generation fails for a reason not under the control of the user
242 (IllegalStateExceptions are thrown in those cases */
243 // FEATURE: This should probably be a checked exception
244 public static class Exn extends RuntimeException {
245 public Exn(String s) { super(s); }
248 public static class ClassReadExn extends IOException {
249 public ClassReadExn(String s) { super(s); }
252 static class AttrGen {
253 private final Hashtable ht = new Hashtable();
256 AttrGen(DataInput in, ConstantPool cp) throws IOException {
257 int size = in.readShort();
258 for(int i=0; i<size; i++) {
259 String name = cp.getUtf8KeyByIndex(in.readUnsignedShort());
260 int length = in.readInt();
261 if ((name.equals("SourceFile")||name.equals("ConstantValue")) && length == 2) {
262 ht.put(name, cp.getKeyByIndex(in.readUnsignedShort()));
264 byte[] buf = new byte[length];
271 public Object get(String s) { return ht.get(s); }
272 public void put(String s, Object data) { ht.put(s, data); }
273 public boolean contains(String s) { return ht.get(s) != null; }
274 public void remove(String s) { ht.remove(s); }
275 public int size() { return ht.size(); }
277 void finish(ConstantPool cp) {
278 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
279 String name = (String) e.nextElement();
280 Object val = ht.get(name);
282 if(!(val instanceof byte[])) cp.add(val);
286 void dump(DataOutput o, ConstantPool cp) throws IOException {
287 o.writeShort(size());
288 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
289 String name = (String) e.nextElement();
290 Object val = ht.get(name);
291 o.writeShort(cp.getUtf8Index(name));
292 if(val instanceof byte[]) {
293 byte[] buf = (byte[]) val;
294 o.writeInt(buf.length);
298 o.writeShort(cp.getIndex(val));
304 public static void main(String[] args) throws Exception {
305 if(args.length >= 2 && args[0].equals("copyto")) {
306 File dest = new File(args[1]);
308 for(int i=2;i<args.length;i++) {
309 System.err.println("Copying " + args[i]);
310 read(args[i]).dump(dest);
313 else if (args.length==1) {
314 if (args[0].endsWith(".class")) {
315 System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))).toString());
317 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
318 System.out.println(new ClassFile(new DataInputStream(is)).toString());
322 Type.Class me = new Type.Class("Test");
323 ClassFile cg = new ClassFile("Test", "java.lang.Object", PUBLIC|SUPER|FINAL);
324 FieldGen fg = cg.addField("foo", Type.INT, PUBLIC|STATIC);
326 MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, STATIC|PUBLIC);
330 mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
332 mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
334 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
335 mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
336 Type.VOID, new Type[]{Type.INT}));
337 //mg.add(IINC, new int[]{0, 1});
339 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
343 mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));
345 mg.add(IF_ICMPLT, top);
347 cg.dump("Test.class");