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;
15 private final Vector fields = new Vector();
16 private final Vector methods = new Vector();
18 final ConstantPool cp;
19 private final AttrGen attributes;
21 public static String flagsToString(int flags) {
23 if ((flags & ACC_PUBLIC) != 0) ret += "public ";
24 if ((flags & ACC_PRIVATE) != 0) ret += "private ";
25 if ((flags & ACC_PROTECTED) != 0) ret += "protected ";
26 if ((flags & ACC_STATIC) != 0) ret += "static ";
27 if ((flags & ACC_FINAL) != 0) ret += "final ";
28 if ((flags & ACC_ABSTRACT) != 0) ret += "abstract ";
29 if ((flags & ACC_SYNCHRONIZED) != 0) ret += "synchronized ";
30 if ((flags & ACC_NATIVE) != 0) ret += "native ";
31 if ((flags & ACC_STRICT) != 0) ret += "strictfp ";
32 if ((flags & ACC_VOLATILE) != 0) ret += "volatile ";
33 if ((flags & ACC_TRANSIENT) != 0) ret += "transient ";
37 public Type.Class getType() { return thisType; }
38 public String toString() { StringBuffer sb = new StringBuffer(); toString(sb); return sb.toString(); }
39 public void toString(StringBuffer sb) {
40 sb.append(flagsToString(flags));
41 sb.append((flags & ACC_INTERFACE) != 0 ? "interface " : "class ");
43 if (superType != null) sb.append(" extends " + superType);
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]);
47 sb.append(" // [jcf v"+major+"."+minor+"]");
48 String sourceFile = (String)attributes.get("SourceFile");
49 if (sourceFile != null) sb.append(" from " + sourceFile);
51 for(int i=0; i<fields.size(); i++) {
53 ((FieldGen)fields.elementAt(i)).toString(sb);
56 for(int i=0; i<methods.size(); i++) {
58 ((MethodGen)methods.elementAt(i)).toString(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;
75 cp = new ConstantPool();
76 attributes = new AttrGen(cp);
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 (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_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(this, 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 (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_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.add("SourceFile", 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 {
159 if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
161 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish();
162 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish();
166 o.writeInt(0xcafebabe); // magic
167 o.writeShort(minor); // minor_version
168 o.writeShort(major); // major_version
170 cp.dump(o); // constant_pool
173 o.writeShort(cp.getIndex(thisType)); // this_class
174 o.writeShort(cp.getIndex(superType)); // super_class
176 o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
177 if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
179 o.writeShort(fields.size()); // fields_count
180 for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o); // fields
182 o.writeShort(methods.size()); // methods_count
183 for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o); // methods
185 o.writeShort(attributes.size()); // attributes_count
186 attributes.dump(o); // attributes
189 public ClassFile read(File f) throws ClassReadExn, IOException {
190 InputStream is = new FileInputStream(f);
191 ClassFile ret = read(is);
196 public ClassFile read(InputStream is) throws ClassReadExn, IOException {
197 return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
200 ClassFile(DataInput i) throws ClassReadExn, IOException {
201 int magic = i.readInt();
202 if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
203 minor = i.readShort();
204 //if (minor != 3) throw new ClassReadExn("invalid minor version: " + minor);
205 major = i.readShort();
206 //if (major != 45 && major != 46) throw new ClassReadExn("invalid major version");
207 cp = new ConstantPool(i);
208 flags = i.readShort();
209 thisType = (Type.Class)cp.getType(i.readShort());
210 superType = (Type.Class)cp.getType(i.readShort());
211 interfaces = new Type.Class[i.readShort()];
212 for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class)cp.getType(i.readShort());
213 int numFields = i.readShort();
214 for(int j=0; j<numFields; j++) fields.add(new FieldGen(cp, i));
215 int numMethods = i.readShort();
216 for(int j=0; j<numMethods; j++) methods.add(new MethodGen(cp, i, this));
217 attributes = new AttrGen(cp, i);
220 /** Thrown when class generation fails for a reason not under the control of the user
221 (IllegalStateExceptions are thrown in those cases */
222 public static class Exn extends RuntimeException {
223 public Exn(String s) { super(s); }
226 public static class ClassReadExn extends IOException {
227 public ClassReadExn(String s) { super(s); }
230 static class AttrGen {
231 private final ConstantPool cp;
232 private final Hashtable ht = new Hashtable();
234 public AttrGen(ConstantPool cp) { this.cp = cp; }
235 public AttrGen(ConstantPool cp, DataInput in) throws IOException {
237 int size = in.readShort();
238 for(int i=0; i<size; i++) {
240 int idx = in.readShort();
241 ConstantPool.Ent e = cp.getByIndex(idx);
242 Object key = e.key();
243 if (key instanceof String) name = (String)key;
244 else name = ((Type)key).getDescriptor();
246 int length = in.readInt();
247 if (length==2) { // FIXME might be wrong assumption
248 ht.put(name, cp.getByIndex(in.readShort()));
250 byte[] buf = new byte[length];
257 public Object get(String s) {
258 Object ret = ht.get(s);
259 if (ret instanceof ConstantPool.Utf8Ent) return ((ConstantPool.Utf8Ent)ret).s;
263 public void add(String s, Object data) {
268 public boolean contains(String s) { return ht.get(s) != null; }
270 public int size() { return ht.size(); }
272 public void dump(DataOutput o) throws IOException {
273 for(Enumeration e = ht.keys(); e.hasMoreElements();) {
274 String name = (String) e.nextElement();
275 Object val = ht.get(name);
276 o.writeShort(cp.getUtf8Index(name));
277 if(val instanceof byte[]) {
278 byte[] buf = (byte[]) val;
279 o.writeInt(buf.length);
281 } else if (val instanceof ConstantPool.Ent) {
283 o.writeShort(cp.getIndex((ConstantPool.Ent)val));
285 throw new Error("should never happen");
291 public static void main(String[] args) throws Exception {
292 if (args.length==1) {
293 if (args[0].endsWith(".class")) {
294 System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))));
296 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
297 System.out.println(new ClassFile(new DataInputStream(is)));
301 Type.Class me = new Type.Class("Test");
302 ClassFile cg = new ClassFile("Test", "java.lang.Object", ACC_PUBLIC|ACC_SUPER|ACC_FINAL);
303 FieldGen fg = cg.addField("foo", Type.INT, ACC_PUBLIC|ACC_STATIC);
305 MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, ACC_STATIC|ACC_PUBLIC);
309 mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
311 mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
313 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
314 mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
315 Type.VOID, new Type[]{Type.INT}));
316 //mg.add(IINC, new int[]{0, 1});
318 mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
322 mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));
324 mg.add(IF_ICMPLT, top);
326 cg.dump("Test.class");