added convenience methods to HasFlags
[org.ibex.classgen.git] / src / org / ibex / classgen / ClassFile.java
1 package org.ibex.classgen;
2
3 import java.util.*;
4 import java.io.*;
5
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;
13     final int flags;
14     
15     private final Vector fields = new Vector();
16     public final Vector methods = new Vector();
17     
18     private final AttrGen attributes;
19
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 ");
33         return sb.toString();
34     }
35
36     public Type.Class getType() { return thisType; }
37     public int getFlags() { return flags; }
38     
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());
47         sb.append(" {");
48         sb.append(" // v"+major+"."+minor);
49         ConstantPool.Utf8Key sourceFile = (ConstantPool.Utf8Key) attributes.get("SourceFile");
50         if (sourceFile != null) sb.append(" from " + sourceFile.s);
51         sb.append("\n");
52         for(int i=0; i<fields.size(); i++) {
53             sb.append("  ");
54             ((FieldGen)fields.elementAt(i)).debugToString(sb);
55             sb.append("\n");
56         }
57         for(int i=0; i<methods.size(); i++) {
58             ((MethodGen)methods.elementAt(i)).debugToString(sb,thisType.getShortName());
59             sb.append("\n");
60         }
61         sb.append("}");
62         return sb;
63     }
64
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;
72         this.flags = flags;
73         this.minor = 3;
74         this.major = 45;        
75         this.attributes = new AttrGen();
76     }
77     
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
86         @see MethodGen
87         @see CGConst
88     */
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);
92         return mg;
93     }
94     
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
102         @see FieldGen
103         @see CGConst
104         */  
105     public final FieldGen addField(String name, Type type, int flags) {
106         FieldGen fg = new FieldGen(this, name, type, flags);
107         fields.addElement(fg);
108         return fg;
109     }
110     
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
113     */
114     public void setSourceFile(String sourceFile) { attributes.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
115     
116     /** Writes the classfile data to the file specifed
117         @see ClassFile#dump(OutputStream)
118     */
119     public void dump(String file) throws IOException { dump(new File(file)); }
120     
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)
124     */
125     public void dump(File f) throws IOException {
126         if(f.isDirectory()) {
127             String[] a = thisType.components();
128             int i;
129             for(i=0;i<a.length-1;i++) {
130                 f = new File(f, a[i]);
131                 f.mkdir();
132             }
133             f = new File(f, a[i] + ".class");
134         }
135         OutputStream os = new FileOutputStream(f);
136         dump(os);
137         os.close();
138     }
139    
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)
145     */
146     public void dump(OutputStream os) throws IOException {
147         DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
148         _dump(dos);
149         dos.flush();
150     }
151     
152     private void _dump(DataOutput o) throws IOException {
153         ConstantPool cp = new ConstantPool();
154         cp.add(thisType);
155         cp.add(superType);
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);
160         
161         cp.optimize();
162         cp.seal();
163         
164         o.writeInt(0xcafebabe); // magic
165         o.writeShort(minor); // minor_version
166         o.writeShort(major); // major_version
167         
168         cp.dump(o); // constant_pool
169         
170         o.writeShort(flags);
171         o.writeShort(cp.getIndex(thisType)); // this_class
172         o.writeShort(cp.getIndex(superType)); // super_class
173         
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
176         
177         o.writeShort(fields.size()); // fields_count
178         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
179
180         o.writeShort(methods.size()); // methods_count
181         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
182         
183         attributes.dump(o,cp); // attributes        
184     }
185     
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);
190         is.close();
191         return ret;
192     }
193     
194     public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
195         try {
196             return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
197         } catch(RuntimeException e) {
198             e.printStackTrace();
199             throw new ClassReadExn("invalid constant pool entry");
200         }
201     }
202
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);
224         
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");
229     }
230     
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); }
236     }
237     
238     public static class ClassReadExn extends IOException {
239         public ClassReadExn(String s) { super(s); }
240     }
241     
242     static class AttrGen {
243         private final Hashtable ht = new Hashtable();
244         
245         AttrGen() { }
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()));
253                 } else {
254                     byte[] buf = new byte[length];
255                     in.readFully(buf);
256                     ht.put(name, buf);
257                 }
258             }
259         }
260
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(); }
266         
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);
271                 cp.addUtf8(name);
272                 if(!(val instanceof byte[])) cp.add(val);
273             }
274         }
275         
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);
285                     o.write(buf);
286                 } else {
287                     o.writeInt(2);
288                     o.writeShort(cp.getIndex(val));
289                 }
290             }
291         }
292     }
293     
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]);
297             dest.mkdirs();
298             for(int i=2;i<args.length;i++) {
299                 System.err.println("Copying " + args[i]);
300                 read(args[i]).dump(dest);
301             }
302         }
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());
306             } else {
307                 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
308                 System.out.println(new ClassFile(new DataInputStream(is)).debugToString());
309             }
310         } else {
311             /*
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);
315         
316             MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, STATIC|PUBLIC);
317             mg.setMaxLocals(1);
318             mg.addPushConst(0);
319             //mg.add(ISTORE_0);
320             mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
321             int top = mg.size();
322             mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
323             //mg.add(ILOAD_0);
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});
328             //mg.add(ILOAD_0);
329             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
330             mg.addPushConst(1);
331             mg.add(IADD);
332             mg.add(DUP);
333             mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));       
334             mg.addPushConst(10);
335             mg.add(IF_ICMPLT, top);
336             mg.add(RETURN);
337             cg.dump("Test.class");
338             */
339         }
340     }
341 }