29b8d7f2e7f6e132b0c47f44b170945f10493014
[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 short minor;
12     private short major;
13     final int flags;
14     
15     private String sourceFile; 
16     private final Vector fields = new Vector();
17     private final Vector methods = new Vector();
18     
19     final CPGen cp;
20     private final AttrGen attributes;
21
22     public static String flagsToString(int flags) {
23         String ret = "";
24         if ((flags & ACC_PUBLIC) != 0)       ret += "public ";
25         if ((flags & ACC_PRIVATE) != 0)      ret += "private ";
26         if ((flags & ACC_PROTECTED) != 0)    ret += "protected ";
27         if ((flags & ACC_STATIC) != 0)       ret += "static ";
28         if ((flags & ACC_FINAL) != 0)        ret += "final ";
29         if ((flags & ACC_ABSTRACT) != 0)     ret += "abstract ";
30         if ((flags & ACC_SYNCHRONIZED) != 0) ret += "synchronized ";
31         if ((flags & ACC_NATIVE) != 0)       ret += "native ";
32         if ((flags & ACC_STRICT) != 0)       ret += "strictfp ";
33         if ((flags & ACC_VOLATILE) != 0)     ret += "volatile ";
34         if ((flags & ACC_TRANSIENT) != 0)    ret += "transient ";
35         return ret;
36     }
37
38     public Type.Class getType() { return thisType; }
39     public String toString() { StringBuffer sb = new StringBuffer(); toString(sb); return sb.toString(); }
40     public void   toString(StringBuffer sb) {
41         sb.append(flagsToString(flags));
42         sb.append((flags & ACC_INTERFACE) != 0 ? "interface " : "class ");
43         sb.append(thisType);
44         if (superType != null) sb.append(" extends " + superType);
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]);
47         sb.append(" {");
48         sb.append(" // [jcf v"+major+"."+minor+"]");
49         if (sourceFile != null) sb.append(" from " + sourceFile);
50         sb.append("\n");
51         for(int i=0; i<fields.size(); i++) {
52             sb.append("  ");
53             ((FieldGen)fields.elementAt(i)).toString(sb);
54             sb.append("\n");
55         }
56         for(int i=0; i<methods.size(); i++) {
57             sb.append("  ");
58             ((MethodGen)methods.elementAt(i)).toString(sb, thisType.getShortName());
59             sb.append("\n");
60         }
61         sb.append("}");
62     }
63
64     /** @see #ClassFile(Type.Class, Type.Class, int) */
65     public ClassFile(String name, String superName, int flags) {
66         this(Type.instance(name).asClass(), Type.instance(superName).asClass(), flags);
67     }
68
69     /** @see #ClassFile(Type.Class, Type.Class, int, Type.Class[]) */
70     public ClassFile(Type.Class thisType, Type.Class superType, int flags) {
71         this(thisType, superType, flags, null);
72     }
73     
74     /** Creates a new ClassFile object 
75         @param thisType The type of the class to generate
76         @param superType The superclass of the generated class (commonly Type.OBJECT) 
77         @param flags The access flags for this class (ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_INTERFACE, and ACC_ABSTRACT)
78     */
79     public ClassFile(Type.Class thisType, Type.Class superType, int flags, Type.Class[] interfaces) {
80         if((flags & ~(ACC_PUBLIC|ACC_FINAL|ACC_SUPER|ACC_INTERFACE|ACC_ABSTRACT)) != 0)
81             throw new IllegalArgumentException("invalid flags");
82         this.thisType = thisType;
83         this.superType = superType;
84         this.interfaces = interfaces;
85         this.flags = flags;
86         this.minor = 3;
87         this.major = 45;
88         
89         cp = new CPGen();
90         attributes = new AttrGen(cp);
91     }
92     
93     /** Adds a new method to this class 
94         @param name The name of the method (not the signature, just the name)
95         @param ret The return type of the method
96         @param args The arguments to the method
97         @param flags The flags for the method
98                      (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT)
99         @return A new MethodGen object for the method
100         @exception IllegalArgumentException if illegal flags are specified
101         @see MethodGen
102         @see CGConst
103     */
104     public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
105         MethodGen mg = new MethodGen(this, name, ret, args, flags);
106         methods.addElement(mg);
107         return mg;
108     }
109     
110     /** Adds a new field to this class 
111         @param name The name of the filed (not the signature, just the name)
112         @param type The type of the field
113         @param flags The flags for the field
114         (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_TRANSIENT)
115         @return A new FieldGen object for the method
116         @exception IllegalArgumentException if illegal flags are specified
117         @see FieldGen
118         @see CGConst
119         */  
120     public final FieldGen addField(String name, Type type, int flags) {
121         FieldGen fg = new FieldGen(this, name, type, flags);
122         fields.addElement(fg);
123         return fg;
124     }
125     
126     /** Sets the source value of the SourceFile attribute of this class 
127         @param sourceFile The string to be uses as the SourceFile of this class
128     */
129     public void setSourceFile(String sourceFile) { this.sourceFile = sourceFile; }
130     
131     /** Writes the classfile data to the file specifed
132         @see ClassFile#dump(OutputStream)
133     */
134     public void dump(String file) throws IOException { dump(new File(file)); }
135     
136     /** Writes the classfile data to the file specified
137         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)
138         @see ClassFile#dump(OutputStream)
139     */
140     public void dump(File f) throws IOException {
141         if(f.isDirectory()) {
142             String[] a = thisType.components();
143             int i;
144             for(i=0;i<a.length-1;i++) {
145                 f = new File(f, a[i]);
146                 f.mkdir();
147             }
148             f = new File(f, a[i] + ".class");
149         }
150         OutputStream os = new FileOutputStream(f);
151         dump(os);
152         os.close();
153     }
154    
155     /** Writes the classfile data to the outputstream specified
156         @param os The stream to write the class to
157         @exception IOException if an IOException occures while writing the class data
158         @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
159         @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
160     */
161     public void dump(OutputStream os) throws IOException {
162         DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
163         _dump(dos);
164         dos.flush();
165     }
166     
167     private void _dump(DataOutput o) throws IOException {
168         cp.optimize();
169         cp.stable();
170         
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         if(sourceFile != null && !attributes.contains("SourceFile")) attributes.add("SourceFile", cp.addUtf8(sourceFile));
175                 
176         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish();
177         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish();
178         
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); // fields
196
197         o.writeShort(methods.size()); // methods_count
198         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o); // methods
199         
200         o.writeShort(attributes.size()); // attributes_count
201         attributes.dump(o); // attributes        
202     }
203     
204     public 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 ClassFile read(InputStream is) throws ClassReadExn, IOException {
212         return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
213     }
214
215     ClassFile(DataInput i) throws ClassReadExn, IOException {
216         int magic = i.readInt();
217         if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
218         minor = i.readShort();
219         //if (minor != 3) throw new ClassReadExn("invalid minor version: " + minor);
220         major = i.readShort();
221         //if (major != 45 && major != 46) throw new ClassReadExn("invalid major version");
222         cp = new CPGen(i);
223         flags = i.readShort();
224         thisType = (Type.Class)cp.getType(i.readShort());
225         superType = (Type.Class)cp.getType(i.readShort());
226         interfaces = new Type.Class[i.readShort()];
227         for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class)cp.getType(i.readShort());
228         int numFields = i.readShort();
229         for(int j=0; j<numFields; j++) fields.add(new FieldGen(cp, i));
230         int numMethods = i.readShort();
231         for(int j=0; j<numMethods; j++) methods.add(new MethodGen(cp, i, this));
232         attributes = new AttrGen(cp, i);
233         sourceFile = (String)attributes.get("SourceFile");
234     }
235     
236     /** Thrown when class generation fails for a reason not under the control of the user
237         (IllegalStateExceptions are thrown in those cases */
238     public static class Exn extends RuntimeException {
239         public Exn(String s) { super(s); }
240     }
241     
242     public static class ClassReadExn extends IOException {
243         public ClassReadExn(String s) { super(s); }
244     }
245     
246     static class AttrGen {
247         private final CPGen cp;
248         private final Hashtable ht = new Hashtable();
249         
250         public AttrGen(CPGen cp) { this.cp = cp; }
251         public AttrGen(CPGen cp, DataInput in) throws IOException {
252             this(cp);
253             int size = in.readShort();
254             for(int i=0; i<size; i++) {
255                 String name = null;
256                 int idx = in.readShort();
257                 CPGen.Ent e = cp.getByIndex(idx);
258                 Object key = e.key();
259                 if (key instanceof String) name = (String)key;
260                 else name = ((Type)key).getDescriptor();
261
262                 int length = in.readInt();
263                 if (length==2) {   // FIXME might be wrong assumption
264                     ht.put(name, cp.getByIndex(in.readShort()));
265                 } else {
266                     byte[] buf = new byte[length];
267                     in.readFully(buf);
268                     ht.put(name, buf);
269                 }
270             }
271         }
272
273         public Object get(String s) {
274             Object ret = ht.get(s);
275             if (ret instanceof CPGen.Utf8Ent) return ((CPGen.Utf8Ent)ret).s;
276             return ret;
277         }
278         
279         public void add(String s, Object data) {
280             cp.addUtf8(s);
281             ht.put(s, data);
282         }
283         
284         public boolean contains(String s) { return ht.get(s) != null; }
285         
286         public int size() { return ht.size(); }
287         
288         public void dump(DataOutput o) throws IOException {
289             for(Enumeration e = ht.keys(); e.hasMoreElements();) {
290                 String name = (String) e.nextElement();
291                 Object val = ht.get(name);
292                 o.writeShort(cp.getUtf8Index(name));
293                 if(val instanceof byte[]) {
294                     byte[] buf = (byte[]) val;
295                     o.writeInt(buf.length);
296                     o.write(buf);
297                 } else if(val instanceof CPGen.Ent) {
298                     o.writeInt(2);
299                     o.writeShort(cp.getIndex((CPGen.Ent)val));
300                 } else {
301                     throw new Error("should never happen");
302                 }
303             }
304         }
305     }
306     
307     public static void main(String[] args) throws Exception {
308         if (args.length==1) {
309             if (args[0].endsWith(".class")) {
310                 System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))));
311             } else {
312                 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
313                 System.out.println(new ClassFile(new DataInputStream(is)));
314             }
315         } else {
316             /*
317             Type.Class me = new Type.Class("Test");
318             ClassFile cg = new ClassFile("Test", "java.lang.Object", ACC_PUBLIC|ACC_SUPER|ACC_FINAL);
319             FieldGen fg = cg.addField("foo", Type.INT, ACC_PUBLIC|ACC_STATIC);
320         
321             MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, ACC_STATIC|ACC_PUBLIC);
322             mg.setMaxLocals(1);
323             mg.addPushConst(0);
324             //mg.add(ISTORE_0);
325             mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
326             int top = mg.size();
327             mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
328             //mg.add(ILOAD_0);
329             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
330             mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
331                                                Type.VOID, new Type[]{Type.INT}));
332             //mg.add(IINC, new int[]{0, 1});
333             //mg.add(ILOAD_0);
334             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
335             mg.addPushConst(1);
336             mg.add(IADD);
337             mg.add(DUP);
338             mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));       
339             mg.addPushConst(10);
340             mg.add(IF_ICMPLT, top);
341             mg.add(RETURN);
342             cg.dump("Test.class");
343             */
344         }
345     }
346 }