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;
15 private final Vector fields = new Vector();
16 public final Vector methods = new Vector();
18 private final AttrGen attributes;
20 static String flagsToString(int flags, boolean isClass) {
21 StringBuffer sb = new StringBuffer(32);
22 if ((flags & PUBLIC) != 0) sb.append("public ");
23 if ((flags & PRIVATE) != 0) sb.append("private ");
24 if ((flags & PROTECTED) != 0) sb.append("protected ");
25 if ((flags & STATIC) != 0) sb.append("static ");
26 if ((flags & FINAL) != 0) sb.append("final ");
27 if ((flags & ABSTRACT) != 0) sb.append("abstract ");
28 if (!isClass && (flags & SYNCHRONIZED) != 0) sb.append("synchronized ");
29 if (!isClass && (flags & NATIVE) != 0) sb.append("native ");
30 if (!isClass && (flags & STRICT) != 0) sb.append("strictfp ");
31 if (!isClass && (flags & VOLATILE) != 0) sb.append("volatile ");
32 if (!isClass && (flags & TRANSIENT) != 0) sb.append("transient ");
36 public Type.Class getType() { return thisType; }
37 public int getFlags() { return flags; }
39 String debugToString() { return debugToString(new StringBuffer(4096)).toString(); }
40 StringBuffer debugToString(StringBuffer sb) {
41 sb.append(flagsToString(flags,true));
42 sb.append((flags & INTERFACE) != 0 ? "interface " : "class ");
43 sb.append(thisType.debugToString());
44 if (superType != null) sb.append(" extends " + superType.debugToString());
45 if (interfaces != null && interfaces.length > 0) sb.append(" implements");
46 for(int i=0; i<interfaces.length; i++) sb.append((i==0?" ":", ")+interfaces[i].debugToString());
48 sb.append(" // v"+major+"."+minor);
49 ConstantPool.Utf8Key sourceFile = (ConstantPool.Utf8Key) attributes.get("SourceFile");
50 if (sourceFile != null) sb.append(" from " + sourceFile.s);
52 for(int i=0; i<fields.size(); i++) {
54 ((FieldGen)fields.elementAt(i)).debugToString(sb);
57 for(int i=0; i<methods.size(); i++) {
58 ((MethodGen)methods.elementAt(i)).debugToString(sb,thisType.getShortName());
65 public ClassFile(Type.Class thisType, Type.Class superType, int flags) { this(thisType, superType, flags, null); }
66 public ClassFile(Type.Class thisType, Type.Class superType, int flags, Type.Class[] interfaces) {
68 this.thisType = thisType;
69 if((flags & ~(PUBLIC|FINAL|SUPER|INTERFACE|ABSTRACT)) != 0)
70 throw new IllegalArgumentException("invalid flags");
71 this.superType = superType;
72 this.interfaces = interfaces;
76 this.attributes = new AttrGen();
79 /** Adds a new method to this class
80 @param name The name of the method (not the signature, just the name)
81 @param ret The return type of the method
82 @param args The arguments to the method
83 @param flags The flags for the method
84 (PUBLIC, PRIVATE, PROTECTED, STATIC, SYNCHRONIZED, NATIVE, ABSTRACT, STRICT)
85 @return A new MethodGen object for the method
86 @exception IllegalArgumentException if illegal flags are specified
90 public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
91 MethodGen mg = new MethodGen(getType().method(name, ret, args), flags);
92 methods.addElement(mg);
96 /** Adds a new field to this class
97 @param name The name of the filed (not the signature, just the name)
98 @param type The type of the field
99 @param flags The flags for the field
100 (PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, VOLATILE, TRANSIENT)
101 @return A new FieldGen object for the method
102 @exception IllegalArgumentException if illegal flags are specified
106 public final FieldGen addField(String name, Type type, int flags) {
107 FieldGen fg = new FieldGen(this, name, type, flags);
108 fields.addElement(fg);
112 /** Sets the source value of the SourceFile attribute of this class
113 @param sourceFile The string to be uses as the SourceFile of this class
115 public void setSourceFile(String sourceFile) { attributes.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
117 /** Writes the classfile data to the file specifed
118 @see ClassFile#dump(OutputStream)
120 public void dump(String file) throws IOException { dump(new File(file)); }
122 /** Writes the classfile data to the file specified
123 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)
124 @see ClassFile#dump(OutputStream)
126 public void dump(File f) throws IOException {
127 if(f.isDirectory()) {
128 String[] a = thisType.components();
130 for(i=0;i<a.length-1;i++) {
131 f = new File(f, a[i]);
134 f = new File(f, a[i] + ".class");
136 OutputStream os = new FileOutputStream(f);
141 /** Writes the classfile data to the outputstream specified
142 @param os The stream to write the class to
143 @exception IOException if an IOException occures while writing the class data
144 @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
145 @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
147 public void dump(OutputStream os) throws IOException {
148 DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
153 private void _dump(DataOutput o) throws IOException {
154 ConstantPool cp = new ConstantPool();
157 if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
158 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish(cp);
159 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish(cp);
160 attributes.finish(cp);
165 o.writeInt(0xcafebabe); // magic
166 o.writeShort(minor); // minor_version
167 o.writeShort(major); // major_version
169 cp.dump(o); // constant_pool
172 o.writeShort(cp.getIndex(thisType)); // this_class
173 o.writeShort(cp.getIndex(superType)); // super_class
175 o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
176 if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
178 o.writeShort(fields.size()); // fields_count
179 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
181 o.writeShort(methods.size()); // methods_count
182 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
184 attributes.dump(o,cp); // attributes
187 public static ClassFile read(String s) throws IOException { return read(new File(s)); }
188 public static ClassFile read(File f) throws ClassReadExn, IOException {
189 InputStream is = new FileInputStream(f);
190 ClassFile ret = read(is);
195 public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
197 return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
198 } catch(RuntimeException e) {
200 throw new ClassReadExn("invalid constant pool entry");
204 public ClassFile(DataInput i) throws IOException { this(i, false); }
205 public ClassFile(DataInput i, boolean ssa) throws IOException {
206 this(i.readInt(), i.readShort(), i.readShort(), new ConstantPool(i), i.readShort(), i, ssa);
208 private ClassFile(int magic, short minor, short major, ConstantPool cp,
209 short flags, DataInput i, boolean ssa) throws IOException {
210 this(magic, minor, major, cp, flags, (Type.Class)cp.getKeyByIndex(i.readShort()), i, ssa);
212 private ClassFile(int magic, short minor, short major, ConstantPool cp, short flags,
213 Type.Class thisType, DataInput i, boolean ssa) throws IOException {
215 if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
219 if((flags & ~(PUBLIC|FINAL|SUPER|INTERFACE|ABSTRACT)) != 0)
220 throw new ClassReadExn("invalid flags: " + Integer.toString(flags,16));
221 this.thisType = thisType;
222 superType = (Type.Class) cp.getKeyByIndex(i.readShort());
223 interfaces = new Type.Class[i.readShort()];
224 for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class) cp.getKeyByIndex(i.readShort());
225 int numFields = i.readShort();
226 for(int j=0; j<numFields; j++) fields.addElement(new FieldGen(i, cp));
227 int numMethods = i.readShort();
228 for(int j=0; j<numMethods; j++) methods.addElement(ssa
229 ? new JSSA(this.getType(), i, cp)
230 : new MethodGen(this.getType(), i, cp));
231 attributes = new AttrGen(i, cp);
233 // FEATURE: Support these
234 // NOTE: Until we can support them properly we HAVE to delete them,
235 // they'll be incorrect after we rewrite the constant pool, etc
236 attributes.remove("InnerClasses");
239 /** Thrown when class generation fails for a reason not under the control of the user
240 (IllegalStateExceptions are thrown in those cases */
241 // FEATURE: This should probably be a checked exception
242 public static class Exn extends RuntimeException {
243 public Exn(String s) { super(s); }
246 public static class ClassReadExn extends IOException {
247 public ClassReadExn(String s) { super(s); }
250 static class AttrGen {
251 private final Hashtable ht = new Hashtable();
254 AttrGen(DataInput in, ConstantPool cp) throws IOException {
255 int size = in.readShort();
256 for(int i=0; i<size; i++) {
257 String name = cp.getUtf8KeyByIndex(in.readUnsignedShort());
258 int length = in.readInt();
259 if ((name.equals("SourceFile")||name.equals("ConstantValue")) && length == 2) {
260 ht.put(name, cp.getKeyByIndex(in.readUnsignedShort()));
262 byte[] buf = new byte[length];
269 public Object get(String s) { return ht.get(s); }
270 public void put(String s, Object data) { ht.put(s, data); }
271 public boolean contains(String s) { return ht.get(s) != null; }
272 public void remove(String s) { ht.remove(s); }
273 public int size() { return ht.size(); }
275 void finish(ConstantPool cp) {
276 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
277 String name = (String) e.nextElement();
278 Object val = ht.get(name);
280 if(!(val instanceof byte[])) cp.add(val);
284 void dump(DataOutput o, ConstantPool cp) throws IOException {
285 o.writeShort(size());
286 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
287 String name = (String) e.nextElement();
288 Object val = ht.get(name);
289 o.writeShort(cp.getUtf8Index(name));
290 if(val instanceof byte[]) {
291 byte[] buf = (byte[]) val;
292 o.writeInt(buf.length);
296 o.writeShort(cp.getIndex(val));
302 public static void main(String[] args) throws Exception {
303 if(args.length >= 2 && args[0].equals("copyto")) {
304 File dest = new File(args[1]);
306 for(int i=2;i<args.length;i++) {
307 System.err.println("Copying " + args[i]);
308 read(args[i]).dump(dest);
311 else if (args.length==1) {
312 if (args[0].endsWith(".class")) {
313 System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))).debugToString());
315 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
316 System.out.println(new ClassFile(new DataInputStream(is)).debugToString());
320 Type.Class me = new Type.Class("Test");
321 ClassFile cg = new ClassFile("Test", "java.lang.Object", PUBLIC|SUPER|FINAL);
322 FieldGen fg = cg.addField("foo", Type.INT, PUBLIC|STATIC);
324 MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, STATIC|PUBLIC);
328 mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
330 mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
332 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
333 mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
334 Type.VOID, new Type[]{Type.INT}));
335 //mg.add(IINC, new int[]{0, 1});
337 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
341 mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));
343 mg.add(IF_ICMPLT, top);
345 cg.dump("Test.class");