rename CPGen -> ConstantPool
[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 final Vector fields = new Vector();
16     private final Vector methods = new Vector();
17     
18     final ConstantPool cp;
19     private final AttrGen attributes;
20
21     public static String flagsToString(int flags) {
22         String ret = "";
23         if ((flags & ACC_PUBLIC) != 0)       ret += "public ";
24         if ((flags & ACC_PRIVATE) != 0)      ret += "private ";
25         if ((flags & ACC_PROTECTED) != 0)    ret += "protected ";
26         if ((flags & ACC_STATIC) != 0)       ret += "static ";
27         if ((flags & ACC_FINAL) != 0)        ret += "final ";
28         if ((flags & ACC_ABSTRACT) != 0)     ret += "abstract ";
29         if ((flags & ACC_SYNCHRONIZED) != 0) ret += "synchronized ";
30         if ((flags & ACC_NATIVE) != 0)       ret += "native ";
31         if ((flags & ACC_STRICT) != 0)       ret += "strictfp ";
32         if ((flags & ACC_VOLATILE) != 0)     ret += "volatile ";
33         if ((flags & ACC_TRANSIENT) != 0)    ret += "transient ";
34         return ret;
35     }
36
37     public Type.Class getType() { return thisType; }
38     public String toString() { StringBuffer sb = new StringBuffer(); toString(sb); return sb.toString(); }
39     public void   toString(StringBuffer sb) {
40         sb.append(flagsToString(flags));
41         sb.append((flags & ACC_INTERFACE) != 0 ? "interface " : "class ");
42         sb.append(thisType);
43         if (superType != null) sb.append(" extends " + superType);
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]);
46         sb.append(" {");
47         sb.append(" // [jcf v"+major+"."+minor+"]");
48         String sourceFile = (String)attributes.get("SourceFile");
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     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 & ~(ACC_PUBLIC|ACC_FINAL|ACC_SUPER|ACC_INTERFACE|ACC_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         
75         cp = new ConstantPool();
76         attributes = new AttrGen(cp);
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                      (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_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(this, 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         (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_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(this, 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.add("SourceFile", 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         cp.optimize();
155         cp.stable();
156         
157         cp.add(thisType);
158         cp.add(superType);
159         if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
160                 
161         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish();
162         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish();
163         
164         cp.seal();
165         
166         o.writeInt(0xcafebabe); // magic
167         o.writeShort(minor); // minor_version
168         o.writeShort(major); // major_version
169         
170         cp.dump(o); // constant_pool
171         
172         o.writeShort(flags);
173         o.writeShort(cp.getIndex(thisType)); // this_class
174         o.writeShort(cp.getIndex(superType)); // super_class
175         
176         o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
177         if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
178         
179         o.writeShort(fields.size()); // fields_count
180         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o); // fields
181
182         o.writeShort(methods.size()); // methods_count
183         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o); // methods
184         
185         o.writeShort(attributes.size()); // attributes_count
186         attributes.dump(o); // attributes        
187     }
188     
189     public ClassFile read(File f) throws ClassReadExn, IOException {
190         InputStream is = new FileInputStream(f);
191         ClassFile ret = read(is);
192         is.close();
193         return ret;
194     }
195     
196     public ClassFile read(InputStream is) throws ClassReadExn, IOException {
197         return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
198     }
199
200     ClassFile(DataInput i) throws ClassReadExn, IOException {
201         int magic = i.readInt();
202         if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
203         minor = i.readShort();
204         //if (minor != 3) throw new ClassReadExn("invalid minor version: " + minor);
205         major = i.readShort();
206         //if (major != 45 && major != 46) throw new ClassReadExn("invalid major version");
207         cp = new ConstantPool(i);
208         flags = i.readShort();
209         thisType = (Type.Class)cp.getType(i.readShort());
210         superType = (Type.Class)cp.getType(i.readShort());
211         interfaces = new Type.Class[i.readShort()];
212         for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class)cp.getType(i.readShort());
213         int numFields = i.readShort();
214         for(int j=0; j<numFields; j++) fields.add(new FieldGen(cp, i));
215         int numMethods = i.readShort();
216         for(int j=0; j<numMethods; j++) methods.add(new MethodGen(cp, i, this));
217         attributes = new AttrGen(cp, i);
218     }
219     
220     /** Thrown when class generation fails for a reason not under the control of the user
221         (IllegalStateExceptions are thrown in those cases */
222     public static class Exn extends RuntimeException {
223         public Exn(String s) { super(s); }
224     }
225     
226     public static class ClassReadExn extends IOException {
227         public ClassReadExn(String s) { super(s); }
228     }
229     
230     static class AttrGen {
231         private final ConstantPool cp;
232         private final Hashtable ht = new Hashtable();
233         
234         public AttrGen(ConstantPool cp) { this.cp = cp; }
235         public AttrGen(ConstantPool cp, DataInput in) throws IOException {
236             this(cp);
237             int size = in.readShort();
238             for(int i=0; i<size; i++) {
239                 String name = null;
240                 int idx = in.readShort();
241                 ConstantPool.Ent e = cp.getByIndex(idx);
242                 Object key = e.key();
243                 if (key instanceof String) name = (String)key;
244                 else name = ((Type)key).getDescriptor();
245
246                 int length = in.readInt();
247                 if (length==2) {   // FIXME might be wrong assumption
248                     ht.put(name, cp.getByIndex(in.readShort()));
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) {
258             Object ret = ht.get(s);
259             if (ret instanceof ConstantPool.Utf8Ent) return ((ConstantPool.Utf8Ent)ret).s;
260             return ret;
261         }
262         
263         public void add(String s, Object data) {
264             cp.addUtf8(s);
265             ht.put(s, data);
266         }
267         
268         public boolean contains(String s) { return ht.get(s) != null; }
269         
270         public int size() { return ht.size(); }
271         
272         public void dump(DataOutput o) throws IOException {
273             for(Enumeration e = ht.keys(); e.hasMoreElements();) {
274                 String name = (String) e.nextElement();
275                 Object val = ht.get(name);
276                 o.writeShort(cp.getUtf8Index(name));
277                 if(val instanceof byte[]) {
278                     byte[] buf = (byte[]) val;
279                     o.writeInt(buf.length);
280                     o.write(buf);
281                 } else if (val instanceof ConstantPool.Ent) {
282                     o.writeInt(2);
283                     o.writeShort(cp.getIndex((ConstantPool.Ent)val));
284                 } else {
285                     throw new Error("should never happen");
286                 }
287             }
288         }
289     }
290     
291     public static void main(String[] args) throws Exception {
292         if (args.length==1) {
293             if (args[0].endsWith(".class")) {
294                 System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))));
295             } else {
296                 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
297                 System.out.println(new ClassFile(new DataInputStream(is)));
298             }
299         } else {
300             /*
301             Type.Class me = new Type.Class("Test");
302             ClassFile cg = new ClassFile("Test", "java.lang.Object", ACC_PUBLIC|ACC_SUPER|ACC_FINAL);
303             FieldGen fg = cg.addField("foo", Type.INT, ACC_PUBLIC|ACC_STATIC);
304         
305             MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, ACC_STATIC|ACC_PUBLIC);
306             mg.setMaxLocals(1);
307             mg.addPushConst(0);
308             //mg.add(ISTORE_0);
309             mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
310             int top = mg.size();
311             mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
312             //mg.add(ILOAD_0);
313             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
314             mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
315                                                Type.VOID, new Type[]{Type.INT}));
316             //mg.add(IINC, new int[]{0, 1});
317             //mg.add(ILOAD_0);
318             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
319             mg.addPushConst(1);
320             mg.add(IADD);
321             mg.add(DUP);
322             mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));       
323             mg.addPushConst(10);
324             mg.add(IF_ICMPLT, top);
325             mg.add(RETURN);
326             cg.dump("Test.class");
327             */
328         }
329     }
330 }