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