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 private 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 & ACC_PUBLIC) != 0) sb.append("public ");
23 if ((flags & ACC_PRIVATE) != 0) sb.append("private ");
24 if ((flags & ACC_PROTECTED) != 0) sb.append("protected ");
25 if ((flags & ACC_STATIC) != 0) sb.append("static ");
26 if ((flags & ACC_FINAL) != 0) sb.append("final ");
27 if ((flags & ACC_ABSTRACT) != 0) sb.append("abstract ");
28 if (!isClass && (flags & ACC_SYNCHRONIZED) != 0) sb.append("synchronized ");
29 if (!isClass && (flags & ACC_NATIVE) != 0) sb.append("native ");
30 if (!isClass && (flags & ACC_STRICT) != 0) sb.append("strictfp ");
31 if (!isClass && (flags & ACC_VOLATILE) != 0) sb.append("volatile ");
32 if (!isClass && (flags & ACC_TRANSIENT) != 0) sb.append("transient ");
36 public Type.Class getType() { return thisType; }
38 String debugToString() { return debugToString(new StringBuffer(4096)).toString(); }
39 StringBuffer debugToString(StringBuffer sb) {
40 sb.append(flagsToString(flags,true));
41 sb.append((flags & ACC_INTERFACE) != 0 ? "interface " : "class ");
42 sb.append(thisType.debugToString());
43 if (superType != null) sb.append(" extends " + superType.debugToString());
44 if (interfaces != null && interfaces.length > 0) sb.append(" implements");
45 for(int i=0; i<interfaces.length; i++) sb.append((i==0?" ":", ")+interfaces[i].debugToString());
47 sb.append(" // v"+major+"."+minor);
48 ConstantPool.Utf8Key sourceFile = (ConstantPool.Utf8Key) attributes.get("SourceFile");
49 if (sourceFile != null) sb.append(" from " + sourceFile.s);
51 for(int i=0; i<fields.size(); i++) {
53 ((FieldGen)fields.elementAt(i)).debugToString(sb);
56 for(int i=0; i<methods.size(); i++) {
57 ((MethodGen)methods.elementAt(i)).debugToString(sb,thisType.getShortName());
64 public ClassFile(Type.Class thisType, Type.Class superType, int flags) { this(thisType, superType, flags, null); }
65 public ClassFile(Type.Class thisType, Type.Class superType, int flags, Type.Class[] interfaces) {
66 if((flags & ~(ACC_PUBLIC|ACC_FINAL|ACC_SUPER|ACC_INTERFACE|ACC_ABSTRACT)) != 0)
67 throw new IllegalArgumentException("invalid flags");
68 this.thisType = thisType;
69 this.superType = superType;
70 this.interfaces = interfaces;
74 this.attributes = new AttrGen();
77 /** Adds a new method to this class
78 @param name The name of the method (not the signature, just the name)
79 @param ret The return type of the method
80 @param args The arguments to the method
81 @param flags The flags for the method
82 (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT)
83 @return A new MethodGen object for the method
84 @exception IllegalArgumentException if illegal flags are specified
88 public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
89 MethodGen mg = new MethodGen(this, name, ret, args, flags, (this.flags & ACC_INTERFACE) != 0);
90 methods.addElement(mg);
94 /** Adds a new field to this class
95 @param name The name of the filed (not the signature, just the name)
96 @param type The type of the field
97 @param flags The flags for the field
98 (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_TRANSIENT)
99 @return A new FieldGen object for the method
100 @exception IllegalArgumentException if illegal flags are specified
104 public final FieldGen addField(String name, Type type, int flags) {
105 FieldGen fg = new FieldGen(this, name, type, flags);
106 fields.addElement(fg);
110 /** Sets the source value of the SourceFile attribute of this class
111 @param sourceFile The string to be uses as the SourceFile of this class
113 public void setSourceFile(String sourceFile) { attributes.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
115 /** Writes the classfile data to the file specifed
116 @see ClassFile#dump(OutputStream)
118 public void dump(String file) throws IOException { dump(new File(file)); }
120 /** Writes the classfile data to the file specified
121 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)
122 @see ClassFile#dump(OutputStream)
124 public void dump(File f) throws IOException {
125 if(f.isDirectory()) {
126 String[] a = thisType.components();
128 for(i=0;i<a.length-1;i++) {
129 f = new File(f, a[i]);
132 f = new File(f, a[i] + ".class");
134 OutputStream os = new FileOutputStream(f);
139 /** Writes the classfile data to the outputstream specified
140 @param os The stream to write the class to
141 @exception IOException if an IOException occures while writing the class data
142 @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
143 @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
145 public void dump(OutputStream os) throws IOException {
146 DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
151 private void _dump(DataOutput o) throws IOException {
152 ConstantPool cp = new ConstantPool();
155 if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
156 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish(cp);
157 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish(cp);
158 attributes.finish(cp);
163 o.writeInt(0xcafebabe); // magic
164 o.writeShort(minor); // minor_version
165 o.writeShort(major); // major_version
167 cp.dump(o); // constant_pool
170 o.writeShort(cp.getIndex(thisType)); // this_class
171 o.writeShort(cp.getIndex(superType)); // super_class
173 o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
174 if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
176 o.writeShort(fields.size()); // fields_count
177 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
179 o.writeShort(methods.size()); // methods_count
180 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
182 attributes.dump(o,cp); // attributes
185 public static ClassFile read(String s) throws IOException { return read(new File(s)); }
186 public static ClassFile read(File f) throws ClassReadExn, IOException {
187 InputStream is = new FileInputStream(f);
188 ClassFile ret = read(is);
193 public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
195 return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
196 } catch(RuntimeException e) {
198 throw new ClassReadExn("invalid constant pool entry");
202 ClassFile(DataInput i) throws IOException {
203 int magic = i.readInt();
204 if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
205 minor = i.readShort();
206 major = i.readShort();
207 ConstantPool cp = new ConstantPool(i);
208 flags = i.readShort();
209 if((flags & ~(ACC_PUBLIC|ACC_FINAL|ACC_SUPER|ACC_INTERFACE|ACC_ABSTRACT)) != 0)
210 throw new ClassReadExn("invalid flags: " + Integer.toString(flags,16));
211 thisType = (Type.Class) cp.getKeyByIndex(i.readShort());
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(i, cp));
217 int numMethods = i.readShort();
218 for(int j=0; j<numMethods; j++) methods.addElement(new MethodGen(this, i, cp, (this.flags & ACC_INTERFACE) != 0));
219 attributes = new AttrGen(i, cp);
221 // FEATURE: Support these
222 // NOTE: Until we can support them properly we HAVE to delete them,
223 // they'll be incorrect after we rewrite the constant pool, etc
224 attributes.remove("InnerClasses");
227 /** Thrown when class generation fails for a reason not under the control of the user
228 (IllegalStateExceptions are thrown in those cases */
229 // FEATURE: This should probably be a checked exception
230 public static class Exn extends RuntimeException {
231 public Exn(String s) { super(s); }
234 public static class ClassReadExn extends IOException {
235 public ClassReadExn(String s) { super(s); }
238 static class AttrGen {
239 private final Hashtable ht = new Hashtable();
242 AttrGen(DataInput in, ConstantPool cp) throws IOException {
243 int size = in.readShort();
244 for(int i=0; i<size; i++) {
245 String name = cp.getUtf8KeyByIndex(in.readUnsignedShort());
246 int length = in.readInt();
247 if ((name.equals("SourceFile")||name.equals("ConstantValue")) && length == 2) {
248 ht.put(name, cp.getKeyByIndex(in.readUnsignedShort()));
250 byte[] buf = new byte[length];
257 public Object get(String s) { return ht.get(s); }
258 public void put(String s, Object data) { ht.put(s, data); }
259 public boolean contains(String s) { return ht.get(s) != null; }
260 public void remove(String s) { ht.remove(s); }
261 public int size() { return ht.size(); }
263 void finish(ConstantPool cp) {
264 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
265 String name = (String) e.nextElement();
266 Object val = ht.get(name);
268 if(!(val instanceof byte[])) cp.add(val);
272 void dump(DataOutput o, ConstantPool cp) throws IOException {
273 o.writeShort(size());
274 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
275 String name = (String) e.nextElement();
276 Object val = ht.get(name);
277 o.writeShort(cp.getUtf8Index(name));
278 if(val instanceof byte[]) {
279 byte[] buf = (byte[]) val;
280 o.writeInt(buf.length);
284 o.writeShort(cp.getIndex(val));
290 public static void main(String[] args) throws Exception {
291 if(args.length >= 2 && args[0].equals("copyto")) {
292 File dest = new File(args[1]);
294 for(int i=2;i<args.length;i++) {
295 System.err.println("Copying " + args[i]);
296 read(args[i]).dump(dest);
299 else if (args.length==1) {
300 if (args[0].endsWith(".class")) {
301 System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))).debugToString());
303 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
304 System.out.println(new ClassFile(new DataInputStream(is)).debugToString());
308 Type.Class me = new Type.Class("Test");
309 ClassFile cg = new ClassFile("Test", "java.lang.Object", ACC_PUBLIC|ACC_SUPER|ACC_FINAL);
310 FieldGen fg = cg.addField("foo", Type.INT, ACC_PUBLIC|ACC_STATIC);
312 MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, ACC_STATIC|ACC_PUBLIC);
316 mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
318 mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
320 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
321 mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
322 Type.VOID, new Type[]{Type.INT}));
323 //mg.add(IINC, new int[]{0, 1});
325 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
329 mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));
331 mg.add(IF_ICMPLT, top);
333 cg.dump("Test.class");