1 package org.ibex.classgen;
6 /** Class generation object representing the whole classfile */
7 public class ClassFile implements CGConst {
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) {
67 if((flags & ~(PUBLIC|FINAL|SUPER|INTERFACE|ABSTRACT)) != 0)
68 throw new IllegalArgumentException("invalid flags");
69 this.thisType = thisType;
70 this.superType = superType;
71 this.interfaces = interfaces;
75 this.attributes = new AttrGen();
78 /** Adds a new method to this class
79 @param name The name of the method (not the signature, just the name)
80 @param ret The return type of the method
81 @param args The arguments to the method
82 @param flags The flags for the method
83 (PUBLIC, PRIVATE, PROTECTED, STATIC, SYNCHRONIZED, NATIVE, ABSTRACT, STRICT)
84 @return A new MethodGen object for the method
85 @exception IllegalArgumentException if illegal flags are specified
89 public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
90 MethodGen mg = new MethodGen(getType().method(name, ret, args), flags);
91 methods.addElement(mg);
95 /** Adds a new field to this class
96 @param name The name of the filed (not the signature, just the name)
97 @param type The type of the field
98 @param flags The flags for the field
99 (PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, VOLATILE, TRANSIENT)
100 @return A new FieldGen object for the method
101 @exception IllegalArgumentException if illegal flags are specified
105 public final FieldGen addField(String name, Type type, int flags) {
106 FieldGen fg = new FieldGen(this, name, type, flags);
107 fields.addElement(fg);
111 /** Sets the source value of the SourceFile attribute of this class
112 @param sourceFile The string to be uses as the SourceFile of this class
114 public void setSourceFile(String sourceFile) { attributes.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
116 /** Writes the classfile data to the file specifed
117 @see ClassFile#dump(OutputStream)
119 public void dump(String file) throws IOException { dump(new File(file)); }
121 /** Writes the classfile data to the file specified
122 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)
123 @see ClassFile#dump(OutputStream)
125 public void dump(File f) throws IOException {
126 if(f.isDirectory()) {
127 String[] a = thisType.components();
129 for(i=0;i<a.length-1;i++) {
130 f = new File(f, a[i]);
133 f = new File(f, a[i] + ".class");
135 OutputStream os = new FileOutputStream(f);
140 /** Writes the classfile data to the outputstream specified
141 @param os The stream to write the class to
142 @exception IOException if an IOException occures while writing the class data
143 @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
144 @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
146 public void dump(OutputStream os) throws IOException {
147 DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
152 private void _dump(DataOutput o) throws IOException {
153 ConstantPool cp = new ConstantPool();
156 if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
157 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish(cp);
158 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish(cp);
159 attributes.finish(cp);
164 o.writeInt(0xcafebabe); // magic
165 o.writeShort(minor); // minor_version
166 o.writeShort(major); // major_version
168 cp.dump(o); // constant_pool
171 o.writeShort(cp.getIndex(thisType)); // this_class
172 o.writeShort(cp.getIndex(superType)); // super_class
174 o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
175 if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
177 o.writeShort(fields.size()); // fields_count
178 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
180 o.writeShort(methods.size()); // methods_count
181 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
183 attributes.dump(o,cp); // attributes
186 public static ClassFile read(String s) throws IOException { return read(new File(s)); }
187 public static ClassFile read(File f) throws ClassReadExn, IOException {
188 InputStream is = new FileInputStream(f);
189 ClassFile ret = read(is);
194 public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
196 return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
197 } catch(RuntimeException e) {
199 throw new ClassReadExn("invalid constant pool entry");
203 public ClassFile(DataInput i) throws IOException { this(i, false); }
204 public ClassFile(DataInput i, boolean ssa) throws IOException {
205 int magic = i.readInt();
206 if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
207 minor = i.readShort();
208 major = i.readShort();
209 ConstantPool cp = new ConstantPool(i);
210 flags = i.readShort();
211 if((flags & ~(PUBLIC|FINAL|SUPER|INTERFACE|ABSTRACT)) != 0)
212 throw new ClassReadExn("invalid flags: " + Integer.toString(flags,16));
213 thisType = (Type.Class) cp.getKeyByIndex(i.readShort());
214 superType = (Type.Class) cp.getKeyByIndex(i.readShort());
215 interfaces = new Type.Class[i.readShort()];
216 for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class) cp.getKeyByIndex(i.readShort());
217 int numFields = i.readShort();
218 for(int j=0; j<numFields; j++) fields.addElement(new FieldGen(i, cp));
219 int numMethods = i.readShort();
220 for(int j=0; j<numMethods; j++) methods.addElement(ssa
221 ? new JSSA(this.getType(), i, cp)
222 : new MethodGen(this.getType(), i, cp));
223 attributes = new AttrGen(i, cp);
225 // FEATURE: Support these
226 // NOTE: Until we can support them properly we HAVE to delete them,
227 // they'll be incorrect after we rewrite the constant pool, etc
228 attributes.remove("InnerClasses");
231 /** Thrown when class generation fails for a reason not under the control of the user
232 (IllegalStateExceptions are thrown in those cases */
233 // FEATURE: This should probably be a checked exception
234 public static class Exn extends RuntimeException {
235 public Exn(String s) { super(s); }
238 public static class ClassReadExn extends IOException {
239 public ClassReadExn(String s) { super(s); }
242 static class AttrGen {
243 private final Hashtable ht = new Hashtable();
246 AttrGen(DataInput in, ConstantPool cp) throws IOException {
247 int size = in.readShort();
248 for(int i=0; i<size; i++) {
249 String name = cp.getUtf8KeyByIndex(in.readUnsignedShort());
250 int length = in.readInt();
251 if ((name.equals("SourceFile")||name.equals("ConstantValue")) && length == 2) {
252 ht.put(name, cp.getKeyByIndex(in.readUnsignedShort()));
254 byte[] buf = new byte[length];
261 public Object get(String s) { return ht.get(s); }
262 public void put(String s, Object data) { ht.put(s, data); }
263 public boolean contains(String s) { return ht.get(s) != null; }
264 public void remove(String s) { ht.remove(s); }
265 public int size() { return ht.size(); }
267 void finish(ConstantPool cp) {
268 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
269 String name = (String) e.nextElement();
270 Object val = ht.get(name);
272 if(!(val instanceof byte[])) cp.add(val);
276 void dump(DataOutput o, ConstantPool cp) throws IOException {
277 o.writeShort(size());
278 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
279 String name = (String) e.nextElement();
280 Object val = ht.get(name);
281 o.writeShort(cp.getUtf8Index(name));
282 if(val instanceof byte[]) {
283 byte[] buf = (byte[]) val;
284 o.writeInt(buf.length);
288 o.writeShort(cp.getIndex(val));
294 public static void main(String[] args) throws Exception {
295 if(args.length >= 2 && args[0].equals("copyto")) {
296 File dest = new File(args[1]);
298 for(int i=2;i<args.length;i++) {
299 System.err.println("Copying " + args[i]);
300 read(args[i]).dump(dest);
303 else if (args.length==1) {
304 if (args[0].endsWith(".class")) {
305 System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))).debugToString());
307 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
308 System.out.println(new ClassFile(new DataInputStream(is)).debugToString());
312 Type.Class me = new Type.Class("Test");
313 ClassFile cg = new ClassFile("Test", "java.lang.Object", PUBLIC|SUPER|FINAL);
314 FieldGen fg = cg.addField("foo", Type.INT, PUBLIC|STATIC);
316 MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, STATIC|PUBLIC);
320 mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
322 mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
324 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
325 mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
326 Type.VOID, new Type[]{Type.INT}));
327 //mg.add(IINC, new int[]{0, 1});
329 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
333 mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));
335 mg.add(IF_ICMPLT, top);
337 cg.dump("Test.class");