major updates to JSSA
[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     
38     String debugToString() { return debugToString(new StringBuffer(4096)).toString(); }
39     StringBuffer debugToString(StringBuffer sb) {
40         sb.append(flagsToString(flags,true));
41         sb.append((flags & 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());
46         sb.append(" {");
47         sb.append(" // v"+major+"."+minor);
48         ConstantPool.Utf8Key sourceFile = (ConstantPool.Utf8Key) attributes.get("SourceFile");
49         if (sourceFile != null) sb.append(" from " + sourceFile.s);
50         sb.append("\n");
51         for(int i=0; i<fields.size(); i++) {
52             sb.append("  ");
53             ((FieldGen)fields.elementAt(i)).debugToString(sb);
54             sb.append("\n");
55         }
56         for(int i=0; i<methods.size(); i++) {
57             ((MethodGen)methods.elementAt(i)).debugToString(sb,thisType.getShortName());
58             sb.append("\n");
59         }
60         sb.append("}");
61         return sb;
62     }
63
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 & ~(PUBLIC|FINAL|SUPER|INTERFACE|ABSTRACT)) != 0)
67             throw new IllegalArgumentException("invalid flags");
68         this.thisType = thisType;
69         this.superType = superType;
70         this.interfaces = interfaces;
71         this.flags = flags;
72         this.minor = 3;
73         this.major = 45;        
74         this.attributes = new AttrGen();
75     }
76     
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                      (PUBLIC, PRIVATE, PROTECTED, STATIC, SYNCHRONIZED, NATIVE, ABSTRACT, STRICT)
83         @return A new MethodGen object for the method
84         @exception IllegalArgumentException if illegal flags are specified
85         @see MethodGen
86         @see CGConst
87     */
88     public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
89         MethodGen mg = new MethodGen(getType().method(name, ret, args), flags);
90         methods.addElement(mg);
91         return mg;
92     }
93     
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         (PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, VOLATILE, TRANSIENT)
99         @return A new FieldGen object for the method
100         @exception IllegalArgumentException if illegal flags are specified
101         @see FieldGen
102         @see CGConst
103         */  
104     public final FieldGen addField(String name, Type type, int flags) {
105         FieldGen fg = new FieldGen(this, name, type, flags);
106         fields.addElement(fg);
107         return fg;
108     }
109     
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
112     */
113     public void setSourceFile(String sourceFile) { attributes.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
114     
115     /** Writes the classfile data to the file specifed
116         @see ClassFile#dump(OutputStream)
117     */
118     public void dump(String file) throws IOException { dump(new File(file)); }
119     
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)
123     */
124     public void dump(File f) throws IOException {
125         if(f.isDirectory()) {
126             String[] a = thisType.components();
127             int i;
128             for(i=0;i<a.length-1;i++) {
129                 f = new File(f, a[i]);
130                 f.mkdir();
131             }
132             f = new File(f, a[i] + ".class");
133         }
134         OutputStream os = new FileOutputStream(f);
135         dump(os);
136         os.close();
137     }
138    
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)
144     */
145     public void dump(OutputStream os) throws IOException {
146         DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
147         _dump(dos);
148         dos.flush();
149     }
150     
151     private void _dump(DataOutput o) throws IOException {
152         ConstantPool cp = new ConstantPool();
153         cp.add(thisType);
154         cp.add(superType);
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);
159         
160         cp.optimize();
161         cp.seal();
162         
163         o.writeInt(0xcafebabe); // magic
164         o.writeShort(minor); // minor_version
165         o.writeShort(major); // major_version
166         
167         cp.dump(o); // constant_pool
168         
169         o.writeShort(flags);
170         o.writeShort(cp.getIndex(thisType)); // this_class
171         o.writeShort(cp.getIndex(superType)); // super_class
172         
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
175         
176         o.writeShort(fields.size()); // fields_count
177         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
178
179         o.writeShort(methods.size()); // methods_count
180         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
181         
182         attributes.dump(o,cp); // attributes        
183     }
184     
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);
189         is.close();
190         return ret;
191     }
192     
193     public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
194         try {
195             return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
196         } catch(RuntimeException e) {
197             e.printStackTrace();
198             throw new ClassReadExn("invalid constant pool entry");
199         }
200     }
201
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 & ~(PUBLIC|FINAL|SUPER|INTERFACE|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.getType(), i, cp));
219         attributes = new AttrGen(i, cp);
220         
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");
225     }
226     
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); }
232     }
233     
234     public static class ClassReadExn extends IOException {
235         public ClassReadExn(String s) { super(s); }
236     }
237     
238     static class AttrGen {
239         private final Hashtable ht = new Hashtable();
240         
241         AttrGen() { }
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()));
249                 } else {
250                     byte[] buf = new byte[length];
251                     in.readFully(buf);
252                     ht.put(name, buf);
253                 }
254             }
255         }
256
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(); }
262         
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);
267                 cp.addUtf8(name);
268                 if(!(val instanceof byte[])) cp.add(val);
269             }
270         }
271         
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);
281                     o.write(buf);
282                 } else {
283                     o.writeInt(2);
284                     o.writeShort(cp.getIndex(val));
285                 }
286             }
287         }
288     }
289     
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]);
293             dest.mkdirs();
294             for(int i=2;i<args.length;i++) {
295                 System.err.println("Copying " + args[i]);
296                 read(args[i]).dump(dest);
297             }
298         }
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());
302             } else {
303                 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
304                 System.out.println(new ClassFile(new DataInputStream(is)).debugToString());
305             }
306         } else {
307             /*
308             Type.Class me = new Type.Class("Test");
309             ClassFile cg = new ClassFile("Test", "java.lang.Object", PUBLIC|SUPER|FINAL);
310             FieldGen fg = cg.addField("foo", Type.INT, PUBLIC|STATIC);
311         
312             MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, STATIC|PUBLIC);
313             mg.setMaxLocals(1);
314             mg.addPushConst(0);
315             //mg.add(ISTORE_0);
316             mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
317             int top = mg.size();
318             mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
319             //mg.add(ILOAD_0);
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});
324             //mg.add(ILOAD_0);
325             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
326             mg.addPushConst(1);
327             mg.add(IADD);
328             mg.add(DUP);
329             mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));       
330             mg.addPushConst(10);
331             mg.add(IF_ICMPLT, top);
332             mg.add(RETURN);
333             cg.dump("Test.class");
334             */
335         }
336     }
337 }