ClassFile.addMethod(Method, int)
[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     final Type.Class superType;
10     final Type.Class[] interfaces;
11     private final short minor;
12     private final short major;
13     
14     private final Vector fields = new Vector();
15     private final Vector methods = new Vector();
16
17     public Type.Class.Method.Body[] methods() {
18         Type.Class.Method.Body[] ret = new Type.Class.Method.Body[methods.size()];
19         methods.copyInto(ret);
20         return ret;
21     }
22
23     public Type.Class.Field.Body[] fields() {
24         Type.Class.Field.Body[] ret = new Type.Class.Field.Body[fields.size()];
25         fields.copyInto(ret);
26         return ret;
27     }
28     
29     static String flagsToString(int flags, boolean isClass) {
30         StringBuffer sb = new StringBuffer(32);
31         if ((flags & PUBLIC) != 0)       sb.append("public ");
32         if ((flags & PRIVATE) != 0)      sb.append("private ");
33         if ((flags & PROTECTED) != 0)    sb.append("protected ");
34         if ((flags & STATIC) != 0)       sb.append("static ");
35         if ((flags & FINAL) != 0)        sb.append("final ");
36         if ((flags & ABSTRACT) != 0)     sb.append("abstract ");
37         if (!isClass && (flags & SYNCHRONIZED) != 0) sb.append("synchronized ");
38         if (!isClass && (flags & NATIVE) != 0)       sb.append("native ");
39         if (!isClass && (flags & STRICT) != 0)       sb.append("strictfp ");
40         if (!isClass && (flags & VOLATILE) != 0)     sb.append("volatile ");
41         if (!isClass && (flags & TRANSIENT) != 0)    sb.append("transient ");
42         return sb.toString();
43     }
44
45     public Type.Class getType() { return thisType; }
46     public int getFlags() { return flags; }
47     
48     public String toString() { return toString(new StringBuffer(4096)).toString(); }
49     StringBuffer toString(StringBuffer sb) {
50         sb.append(flagsToString(flags,true));
51         sb.append((flags & INTERFACE) != 0 ? "interface " : "class ");
52         sb.append(thisType.toString());
53         if (superType != null) sb.append(" extends " + superType.toString());
54         if (interfaces != null && interfaces.length > 0) sb.append(" implements");
55         for(int i=0; i<interfaces.length; i++) sb.append((i==0?" ":", ")+interfaces[i].toString());
56         sb.append(" {");
57         sb.append(" // v"+major+"."+minor);
58         ConstantPool.Utf8Key sourceFile = (ConstantPool.Utf8Key) attrs.get("SourceFile");
59         if (sourceFile != null) sb.append(" from " + sourceFile.s);
60         sb.append("\n");
61         for(int i=0; i<fields.size(); i++) {
62             sb.append("  ");
63             ((FieldGen)fields.elementAt(i)).toString(sb);
64             sb.append("\n");
65         }
66         for(int i=0; i<methods.size(); i++) {
67             ((MethodGen)methods.elementAt(i)).toString(sb,thisType.getShortName());
68             sb.append("\n");
69         }
70         sb.append("}");
71         return sb;
72     }
73
74     public ClassFile(Type.Class thisType, Type.Class superType, int flags) { this(thisType, superType, flags, null); }
75     public ClassFile(Type.Class thisType, Type.Class superType, int flags, Type.Class[] interfaces) {
76         thisType.super(flags, new AttrGen());
77         this.thisType = thisType;
78         this.superType = superType;
79         this.interfaces = interfaces;
80         this.minor = 3;
81         this.major = 45;        
82     }
83     
84     /** Adds a new method to this class 
85         @param name The name of the method (not the signature, just the name)
86         @param ret The return type of the method
87         @param args The arguments to the method
88         @param flags The flags for the method
89                      (PUBLIC, PRIVATE, PROTECTED, STATIC, SYNCHRONIZED, NATIVE, ABSTRACT, STRICT)
90         @return A new MethodGen object for the method
91         @exception IllegalArgumentException if illegal flags are specified
92         @see MethodGen
93         @see CGConst
94     */
95     public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
96         return addMethod(getType().method(name, ret, args),flags);
97     }
98     public final MethodGen addMethod(Type.Class.Method method,int flags) {
99         MethodGen mg = new MethodGen(method, flags);
100         methods.addElement(mg);
101         return mg;
102     }
103     public final MethodGen addMethod(Type.Class.Method m, int flags) {
104         MethodGen mg = new MethodGen(m, flags);
105         methods.addElement(mg);
106         return mg;
107     }
108     
109     /** Adds a new field to this class 
110         @param name The name of the filed (not the signature, just the name)
111         @param type The type of the field
112         @param flags The flags for the field
113         (PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, VOLATILE, TRANSIENT)
114         @return A new FieldGen object for the method
115         @exception IllegalArgumentException if illegal flags are specified
116         @see FieldGen
117         @see CGConst
118         */  
119     public final FieldGen addField(String name, Type type, int flags) {
120         return addField(getType().field(name,type),flags);
121     }
122     public final FieldGen addField(Type.Class.Field field, int flags) {
123         FieldGen fg = new FieldGen(field , flags);
124         fields.addElement(fg);
125         return fg;
126     }
127     
128     /** Sets the source value of the SourceFile attribute of this class 
129         @param sourceFile The string to be uses as the SourceFile of this class
130     */
131     public void setSourceFile(String sourceFile) { attrs.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
132     
133     /** Writes the classfile data to the file specifed
134         @see ClassFile#dump(OutputStream)
135     */
136     public void dump(String file) throws IOException { dump(new File(file)); }
137     
138     /** Writes the classfile data to the file specified
139         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)
140         @see ClassFile#dump(OutputStream)
141     */
142     public void dump(File f) throws IOException {
143         if(f.isDirectory()) {
144             String[] a = thisType.components();
145             int i;
146             for(i=0;i<a.length-1;i++) {
147                 f = new File(f, a[i]);
148                 f.mkdir();
149             }
150             f = new File(f, a[i] + ".class");
151         }
152         OutputStream os = new FileOutputStream(f);
153         dump(os);
154         os.close();
155     }
156    
157     /** Writes the classfile data to the outputstream specified
158         @param os The stream to write the class to
159         @exception IOException if an IOException occures while writing the class data
160         @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
161         @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
162     */
163     public void dump(OutputStream os) throws IOException {
164         DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
165         _dump(dos);
166         dos.flush();
167     }
168     
169     private void _dump(DataOutput o) throws IOException {
170         ConstantPool cp = new ConstantPool();
171         cp.add(thisType);
172         cp.add(superType);
173         if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
174         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish(cp);
175         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish(cp);
176         attrs.finish(cp);
177         
178         cp.optimize();
179         cp.seal();
180         
181         o.writeInt(0xcafebabe); // magic
182         o.writeShort(minor); // minor_version
183         o.writeShort(major); // major_version
184         
185         cp.dump(o); // constant_pool
186         
187         o.writeShort(flags);
188         o.writeShort(cp.getIndex(thisType)); // this_class
189         o.writeShort(cp.getIndex(superType)); // super_class
190         
191         o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
192         if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
193         
194         o.writeShort(fields.size()); // fields_count
195         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
196
197         o.writeShort(methods.size()); // methods_count
198         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
199         
200         attrs.dump(o,cp); // attributes        
201     }
202     
203     public static ClassFile read(String s) throws IOException { return read(new File(s)); }
204     public static ClassFile read(File f) throws ClassReadExn, IOException {
205         InputStream is = new FileInputStream(f);
206         ClassFile ret = read(is);
207         is.close();
208         return ret;
209     }
210     
211     public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
212         try {
213             return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
214         } catch(RuntimeException e) {
215             e.printStackTrace();
216             throw new ClassReadExn("invalid constant pool entry");
217         }
218     }
219
220     public ClassFile(DataInput i) throws IOException { this(i, false); }
221     public ClassFile(DataInput i, boolean ssa) throws IOException {
222         this(i.readInt(), i.readShort(), i.readShort(), new ConstantPool(i), i.readShort(), i, ssa);
223     }
224     private ClassFile(int magic, short minor, short major, ConstantPool cp,
225                       short flags, DataInput i, boolean ssa) throws IOException {
226         this(magic, minor, major, cp, flags, (Type.Class)cp.getKeyByIndex(i.readShort()), i, ssa);
227     }
228     private ClassFile(int magic, short minor, short major, ConstantPool cp, short flags,
229                       Type.Class thisType, DataInput i, boolean ssa) throws IOException {
230         thisType.super(flags, null);
231         if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
232         this.minor = minor;
233         this.major = major;
234         this.thisType = thisType;
235         superType = (Type.Class) cp.getKeyByIndex(i.readShort());
236         interfaces = new Type.Class[i.readShort()];
237         for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class) cp.getKeyByIndex(i.readShort());
238         int numFields = i.readShort();
239         for(int j=0; j<numFields; j++) fields.addElement(new FieldGen(this.getType(), i, cp));
240         int numMethods = i.readShort();
241         for(int j=0; j<numMethods; j++) methods.addElement(ssa 
242                                                            ? new JSSA(this.getType(), i, cp) 
243                                                            : new MethodGen(this.getType(), i, cp));
244         readAttributes(i, cp);
245         
246         // FEATURE: Support these
247         // NOTE: Until we can support them properly we HAVE to delete them,
248         //       they'll be incorrect after we rewrite the constant pool, etc
249         attrs.remove("InnerClasses");
250     }
251     
252     /** Thrown when class generation fails for a reason not under the control of the user
253         (IllegalStateExceptions are thrown in those cases */
254     // FEATURE: This should probably be a checked exception
255     public static class Exn extends RuntimeException {
256         public Exn(String s) { super(s); }
257     }
258     
259     public static class ClassReadExn extends IOException {
260         public ClassReadExn(String s) { super(s); }
261     }
262     
263     static class AttrGen {
264         private final Hashtable ht = new Hashtable();
265         
266         AttrGen() { }
267         AttrGen(DataInput in, ConstantPool cp) throws IOException {
268             int size = in.readShort();
269             for(int i=0; i<size; i++) {
270                 String name = cp.getUtf8KeyByIndex(in.readUnsignedShort());
271                 int length = in.readInt();
272                 if ((name.equals("SourceFile")||name.equals("ConstantValue")) && length == 2) {
273                     ht.put(name, cp.getKeyByIndex(in.readUnsignedShort()));
274                 } else {
275                     byte[] buf = new byte[length];
276                     in.readFully(buf);
277                     ht.put(name, buf);
278                 }
279             }
280         }
281
282         public Object get(String s) { return ht.get(s); }
283         public void put(String s, Object data) { ht.put(s, data); }
284         public boolean contains(String s) { return ht.get(s) != null; }
285         public void remove(String s) { ht.remove(s); }
286         public int size() { return ht.size(); }
287         
288         void finish(ConstantPool cp) {
289             for(Enumeration e = ht.keys(); e.hasMoreElements();) {
290                 String name = (String) e.nextElement();
291                 Object val = ht.get(name);
292                 cp.addUtf8(name);
293                 if(!(val instanceof byte[])) cp.add(val);
294             }
295         }
296         
297         void dump(DataOutput o, ConstantPool cp) throws IOException {
298             o.writeShort(size());
299             for(Enumeration e = ht.keys(); e.hasMoreElements();) {
300                 String name = (String) e.nextElement();
301                 Object val = ht.get(name);
302                 o.writeShort(cp.getUtf8Index(name));
303                 if(val instanceof byte[]) {
304                     byte[] buf = (byte[]) val;
305                     o.writeInt(buf.length);
306                     o.write(buf);
307                 } else {
308                     o.writeInt(2);
309                     o.writeShort(cp.getIndex(val));
310                 }
311             }
312         }
313     }
314     
315     public static void main(String[] args) throws Exception {
316         if(args.length >= 2 && args[0].equals("copyto")) {
317             File dest = new File(args[1]);
318             dest.mkdirs();
319             for(int i=2;i<args.length;i++) {
320                 System.err.println("Copying " + args[i]);
321                 read(args[i]).dump(dest);
322             }
323         }
324         else if (args.length==1) {
325             if (args[0].endsWith(".class")) {
326                 System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))).toString());
327             } else {
328                 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
329                 System.out.println(new ClassFile(new DataInputStream(is)).toString());
330             }
331         } else {
332             /*
333             Type.Class me = new Type.Class("Test");
334             ClassFile cg = new ClassFile("Test", "java.lang.Object", PUBLIC|SUPER|FINAL);
335             FieldGen fg = cg.addField("foo", Type.INT, PUBLIC|STATIC);
336         
337             MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, STATIC|PUBLIC);
338             mg.setMaxLocals(1);
339             mg.addPushConst(0);
340             //mg.add(ISTORE_0);
341             mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
342             int top = mg.size();
343             mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
344             //mg.add(ILOAD_0);
345             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
346             mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
347                                                Type.VOID, new Type[]{Type.INT}));
348             //mg.add(IINC, new int[]{0, 1});
349             //mg.add(ILOAD_0);
350             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
351             mg.addPushConst(1);
352             mg.add(IADD);
353             mg.add(DUP);
354             mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));       
355             mg.addPushConst(10);
356             mg.add(IF_ICMPLT, top);
357             mg.add(RETURN);
358             cg.dump("Test.class");
359             */
360         }
361     }
362 }