refactored functionality out of FieldGen into Type.Class.Field
[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 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;
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         thisType.super();
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;
73         this.flags = flags;
74         this.minor = 3;
75         this.major = 45;        
76         this.attributes = new AttrGen();
77     }
78     
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
87         @see MethodGen
88         @see CGConst
89     */
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);
93         return mg;
94     }
95     
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
103         @see FieldGen
104         @see CGConst
105         */  
106     public final FieldGen addField(String name, Type type, int flags) {
107         FieldGen fg = new FieldGen(getType().field(name, type), flags);
108         fields.addElement(fg);
109         return fg;
110     }
111     
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
114     */
115     public void setSourceFile(String sourceFile) { attributes.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
116     
117     /** Writes the classfile data to the file specifed
118         @see ClassFile#dump(OutputStream)
119     */
120     public void dump(String file) throws IOException { dump(new File(file)); }
121     
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)
125     */
126     public void dump(File f) throws IOException {
127         if(f.isDirectory()) {
128             String[] a = thisType.components();
129             int i;
130             for(i=0;i<a.length-1;i++) {
131                 f = new File(f, a[i]);
132                 f.mkdir();
133             }
134             f = new File(f, a[i] + ".class");
135         }
136         OutputStream os = new FileOutputStream(f);
137         dump(os);
138         os.close();
139     }
140    
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)
146     */
147     public void dump(OutputStream os) throws IOException {
148         DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
149         _dump(dos);
150         dos.flush();
151     }
152     
153     private void _dump(DataOutput o) throws IOException {
154         ConstantPool cp = new ConstantPool();
155         cp.add(thisType);
156         cp.add(superType);
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);
161         
162         cp.optimize();
163         cp.seal();
164         
165         o.writeInt(0xcafebabe); // magic
166         o.writeShort(minor); // minor_version
167         o.writeShort(major); // major_version
168         
169         cp.dump(o); // constant_pool
170         
171         o.writeShort(flags);
172         o.writeShort(cp.getIndex(thisType)); // this_class
173         o.writeShort(cp.getIndex(superType)); // super_class
174         
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
177         
178         o.writeShort(fields.size()); // fields_count
179         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
180
181         o.writeShort(methods.size()); // methods_count
182         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
183         
184         attributes.dump(o,cp); // attributes        
185     }
186     
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);
191         is.close();
192         return ret;
193     }
194     
195     public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
196         try {
197             return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
198         } catch(RuntimeException e) {
199             e.printStackTrace();
200             throw new ClassReadExn("invalid constant pool entry");
201         }
202     }
203
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);
207     }
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);
211     }
212     private ClassFile(int magic, short minor, short major, ConstantPool cp, short flags,
213                       Type.Class thisType, DataInput i, boolean ssa) throws IOException {
214         thisType.super();
215         if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
216         this.minor = minor;
217         this.major = major;
218         this.flags = flags;
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(this, 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);
232         
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");
237     }
238     
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); }
244     }
245     
246     public static class ClassReadExn extends IOException {
247         public ClassReadExn(String s) { super(s); }
248     }
249     
250     static class AttrGen {
251         private final Hashtable ht = new Hashtable();
252         
253         AttrGen() { }
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()));
261                 } else {
262                     byte[] buf = new byte[length];
263                     in.readFully(buf);
264                     ht.put(name, buf);
265                 }
266             }
267         }
268
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(); }
274         
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);
279                 cp.addUtf8(name);
280                 if(!(val instanceof byte[])) cp.add(val);
281             }
282         }
283         
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);
293                     o.write(buf);
294                 } else {
295                     o.writeInt(2);
296                     o.writeShort(cp.getIndex(val));
297                 }
298             }
299         }
300     }
301     
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]);
305             dest.mkdirs();
306             for(int i=2;i<args.length;i++) {
307                 System.err.println("Copying " + args[i]);
308                 read(args[i]).dump(dest);
309             }
310         }
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());
314             } else {
315                 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
316                 System.out.println(new ClassFile(new DataInputStream(is)).debugToString());
317             }
318         } else {
319             /*
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);
323         
324             MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, STATIC|PUBLIC);
325             mg.setMaxLocals(1);
326             mg.addPushConst(0);
327             //mg.add(ISTORE_0);
328             mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
329             int top = mg.size();
330             mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
331             //mg.add(ILOAD_0);
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});
336             //mg.add(ILOAD_0);
337             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
338             mg.addPushConst(1);
339             mg.add(IADD);
340             mg.add(DUP);
341             mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));       
342             mg.addPushConst(10);
343             mg.add(IF_ICMPLT, top);
344             mg.add(RETURN);
345             cg.dump("Test.class");
346             */
347         }
348     }
349 }