version 0.2
[org.ibex.arenaj.git] / src / org / ibex / arenaj / Main.java
1 package org.ibex.arenaj;
2 import soot.*;
3 import soot.jimple.*;
4 import soot.util.*;
5 import java.io.*;
6 import java.util.*;
7
8 public class Main extends SceneTransformer {    
9
10     public static final int initialSize = 100;
11
12     private static Main instance = new Main();
13     private Main() { }
14     public static Main v() { return instance; }
15    
16     public static void main(String[] args) throws Exception {
17         if(args.length == 0) {
18             System.out.println("Syntax: java " + v().getClass().getName() + " [soot options]");
19             System.exit(0);
20         }
21         PackManager.v().getPack("wjtp").add(new Transform("wjtp.tx", Main.v()));
22         String[] args2 = new String[args.length + 11];
23         System.arraycopy(args, 0, args2, 0, args.length-1);
24         String sootcp =
25             System.getProperty("java.class.path") + 
26             File.pathSeparator +
27             System.getProperty("sun.boot.class.path");
28         if (System.getProperty("java.ext.dirs") != null) {
29             StringTokenizer st = new StringTokenizer(File.pathSeparatorChar+"", System.getProperty("java.ext.dirs"));
30             while(st.hasMoreTokens()) {
31                 File f = new File(st.nextToken());
32                 if (!f.exists() || !f.isDirectory()) continue;
33                 String[] jars = f.list();
34                 for(int i=0; i<jars.length; i++)
35                     sootcp += File.pathSeparator + jars[i];
36             }
37         }
38         args2[args.length - 1] = "-w";
39         args2[args.length + 0] = "-p";
40         args2[args.length + 1] = "cg";
41         args2[args.length + 2] = "enabled:false";
42         args2[args.length + 3] = "-p";
43         args2[args.length + 4] = "wjap";
44         args2[args.length + 5] = "enabled:false";
45         args2[args.length + 6] = "-keep-line-number";
46         args2[args.length + 7] = "-keep-line-number";
47         args2[args.length + 8] = "-cp";
48         args2[args.length + 9] = sootcp;
49         args2[args.length + 10] = args[args.length-1];
50         soot.Main.main(args2);
51     }
52
53     static int tfr = 0;
54     public static Local viaLocal(Value v, Body b, Unit u) {
55         Local l = Jimple.v().newLocal("tmpRef" + (tfr++), v.getType());
56         b.getLocals().add(l);
57         b.getUnits().insertBefore(Jimple.v().newAssignStmt(l, v), u);
58         return l;
59     }
60
61     HashMap map = new HashMap();
62     HashSet size_added = new HashSet();
63
64     public boolean isGladiator(SootClass c) { return c.implementsInterface("org.ibex.arenaj.Gladiator"); }
65     public boolean isGladiatorField(SootField f)
66         { return isGladiator(f.getDeclaringClass()) && !f.getName().equals("this") && f.getName().indexOf('$')==-1; }
67     public boolean isGladiatorFieldRef(SootFieldRef f) {
68         return isGladiator(f.declaringClass()) && !f.name().equals("this") && f.name().indexOf('$')==-1;
69     }
70     public SootField getGladiatorField(SootField f) { return getGladiatorField(f.makeRef()); }
71     public SootField getGladiatorField(SootFieldRef f) {
72         SootClass c  = f.declaringClass();
73         SootClass oc = Scene.v().getSootClass(c.getName().substring(0, c.getName().lastIndexOf('$')));
74         String sig = f.declaringClass().getName()+"."+f.name();
75         if (map.get(sig) != null) return (SootField)map.get(sig);
76         Type t = f.type();
77         if (t instanceof RefType && isGladiator(((RefType)t).getSootClass())) t = IntType.v();
78         SootField nf = new SootField(c.getShortName().substring(c.getShortName().lastIndexOf('$')+1) + "$" + f.name(),
79                                      t.makeArrayType(),
80                                      0);
81         oc.addField(nf);
82         Body body = oc.getMethod("<init>", new LinkedList()).getActiveBody();
83         Expr newArr = Jimple.v().newNewArrayExpr(t, IntConstant.v(initialSize));
84         Local newArrLocal = Jimple.v().newLocal("tmpRef" + (tfr++), f.type().makeArrayType());
85         body.getLocals().add(newArrLocal);
86         InstanceFieldRef ifr = Jimple.v().newInstanceFieldRef(body.getThisLocal(), nf.makeRef());
87         body.getUnits().addFirst(Jimple.v().newAssignStmt(ifr, newArrLocal));
88         body.getUnits().addFirst(Jimple.v().newAssignStmt(newArrLocal, newArr));
89         map.put(sig, nf);
90         return nf;
91     }
92
93     private Body body;
94     public SootFieldRef getGladiatorFieldSizeRef(SootClass c) {
95         SootClass mc = getParent(c);
96         String name = c.getShortName().substring(c.getShortName().lastIndexOf('$')+1) + "$$size";
97         if (map.get(name) == null) {
98             SootField f = new SootField(name, IntType.v());
99             mc.addField(f);
100
101             Body body = mc.getMethod("<init>", new LinkedList()).getActiveBody();
102             InstanceFieldRef ifr = Jimple.v().newInstanceFieldRef(body.getThisLocal(), f.makeRef());
103             body.getUnits().addFirst(Jimple.v().newAssignStmt(ifr, IntConstant.v(0)));
104
105             map.put(c, f);
106         }
107         return Scene.v().makeFieldRef(mc, name, IntType.v(), false);
108     }
109     public SootFieldRef getGladiatorFieldMaxRef(SootClass c) {
110         SootClass mc = getParent(c);
111         String name = c.getShortName().substring(c.getShortName().lastIndexOf('$')+1) + "$$max";
112         if (map.get(name) == null) {
113             SootField f = new SootField(name, IntType.v());
114             mc.addField(f);
115
116             Body body = mc.getMethod("<init>", new LinkedList()).getActiveBody();
117             InstanceFieldRef ifr = Jimple.v().newInstanceFieldRef(body.getThisLocal(), f.makeRef());
118             body.getUnits().addFirst(Jimple.v().newAssignStmt(ifr, IntConstant.v(initialSize)));
119
120             map.put(c, f);
121         }
122         return Scene.v().makeFieldRef(mc, name, IntType.v(), false);
123     }
124
125     public boolean isGladiatorType(Type t) {
126         return (t instanceof RefType) && isGladiator(((RefType)t).getSootClass());
127     }
128
129     public SootMethodRef convert(SootMethodRef mr) {
130         List l = mr.parameterTypes();
131         List l2 = new LinkedList();
132         for(Iterator it2 = l.iterator(); it2.hasNext();) {
133             Type t = (Type)it2.next();
134             l2.add(isGladiatorType(t) ? IntType.v() : t);
135         }
136         return Scene.v().makeMethodRef(mr.declaringClass(),
137                                        mr.name(),
138                                        l2,
139                                        isGladiatorType(mr.returnType()) ? IntType.v() : mr.returnType(),
140                                        mr.isStatic());
141     }
142
143     boolean done = false;
144     public void internalTransform(String phaseName, Map options) {
145         for(Iterator it = Scene.v().getApplicationClasses().iterator(); it.hasNext();) {
146             SootClass sc = (SootClass)it.next();
147             if (!isGladiator(sc)) continue;
148             System.out.println("fixing Gladiator class: " + sc);
149             fixClass(sc);
150         }
151         for(Iterator it = Scene.v().getApplicationClasses().iterator(); it.hasNext();) {
152             SootClass sc = (SootClass)it.next();
153             System.out.println("        updating class: " + sc);
154             nuke(sc);
155         }
156     }
157
158     public SootClass getParent(SootClass sc) {
159         return Scene.v().getSootClass(sc.getName().substring(0, sc.getName().lastIndexOf('$')));
160     }
161
162     public void fixClass(SootClass sc) {
163         SootClass mc = getParent(sc);
164         String incFuncName = sc.getShortName().substring(sc.getShortName().lastIndexOf('$')+1) + "$$inc";
165         SootMethod method = new SootMethod(incFuncName, new LinkedList(),
166                                            IntType.v(), Modifier.PRIVATE,
167                                            new LinkedList());
168         mc.addMethod(method);
169         method.setActiveBody(body = Jimple.v().newBody(method));
170         body.setMethod(method);
171         ((JimpleBody)body).insertIdentityStmts();
172         Local l = Jimple.v().newLocal("tmpRef" + (tfr++), IntType.v());
173         body.getLocals().add(l);
174         Local l2 = Jimple.v().newLocal("tmpRef" + (tfr++), IntType.v());
175         body.getLocals().add(l2);
176         Local l3 = Jimple.v().newLocal("tmpRef" + (tfr++), IntType.v());
177         body.getLocals().add(l3);
178         InstanceFieldRef sfr = Jimple.v().newInstanceFieldRef(body.getThisLocal(), getGladiatorFieldSizeRef(sc));
179         body.getUnits().add(Jimple.v().newAssignStmt(l, sfr));
180         body.getUnits().add(Jimple.v().newAssignStmt(l2, Jimple.v().newAddExpr(l, IntConstant.v(1))));
181         InstanceFieldRef maxField = Jimple.v().newInstanceFieldRef(body.getThisLocal(), getGladiatorFieldMaxRef(sc));
182         body.getUnits().add(Jimple.v().newAssignStmt(l3, maxField));
183         Stmt stmt = Jimple.v().newReturnStmt(l2);
184         body.getUnits().add(Jimple.v().newIfStmt(Jimple.v().newLtExpr(l2, l3), stmt));
185
186         Local l4 = Jimple.v().newLocal("tmpRef" + (tfr++), IntType.v());
187         body.getLocals().add(l4);
188         body.getUnits().add(Jimple.v().newAssignStmt(l4, Jimple.v().newShlExpr(l3, IntConstant.v(1))));
189         body.getUnits().add(Jimple.v().newAssignStmt(maxField, l4));
190
191         for(Iterator it = sc.getFields().iterator(); it.hasNext();) {
192             SootField f = getGladiatorField((SootField)it.next());
193             InstanceFieldRef ifr = Jimple.v().newInstanceFieldRef(body.getThisLocal(), f.makeRef());
194             Local ll0 = Jimple.v().newLocal("tmpRef" + (tfr++), f.getType());
195             body.getLocals().add(ll0);
196             body.getUnits().add(Jimple.v().newAssignStmt(ll0, ifr));
197             Local ll = Jimple.v().newLocal("tmpRef" + (tfr++), f.getType());
198             body.getLocals().add(ll);
199             body.getUnits().add(Jimple.v().newAssignStmt(ll,
200                                                          Jimple.v().newNewArrayExpr(((ArrayType)f.getType()).getElementType(),
201                                                                                     l4)));
202             Type ot = Scene.v().getSootClass("java.lang.Object").getType();
203             List types = new LinkedList();
204             types.add(ot);
205             types.add(IntType.v());
206             types.add(ot);
207             types.add(IntType.v());
208             types.add(IntType.v());
209             SootMethodRef arrayCopy =
210                 Scene.v().makeMethodRef(Scene.v().getSootClass("java.lang.System"),
211                                         "arraycopy",
212                                         types,
213                                         VoidType.v(),
214                                         true);
215             List args = new LinkedList();
216             args.add(ll0);
217             args.add(IntConstant.v(0));
218             args.add(ll);
219             args.add(IntConstant.v(0));
220             args.add(l3);
221             body.getUnits().add(Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(arrayCopy, args)));
222             body.getUnits().add(Jimple.v().newAssignStmt(ifr,ll));
223         }
224
225         body.getUnits().add(stmt);
226     }
227
228     public void nuke(SootClass c) {
229         for(Iterator it = c.getFields().iterator(); it.hasNext();) {
230             SootField f = (SootField)it.next();
231             Type t = f.getType();
232             if (t instanceof RefType) {
233                 RefType rt = (RefType)t;
234                 SootClass sc = rt.getSootClass();
235                 if (isGladiator(sc)) f.setType(IntType.v());
236             } else if (t instanceof ArrayType) {
237                 ArrayType at = (ArrayType)t;
238                 t = at.getElementType();
239                 if (!(t instanceof RefType)) continue;                
240                 RefType rt = (RefType)t;
241                 SootClass sc = rt.getSootClass();
242                 if (isGladiator(sc)) f.setType(IntType.v().makeArrayType());
243             }
244         }
245
246         List list = new LinkedList(); list.addAll(c.getMethods());
247         for(Iterator it = list.iterator(); it.hasNext();) {
248             SootMethod m = (SootMethod)it.next();
249             if (isGladiator(c) && m.getName().equals("<init>")) continue;
250             if (m.hasActiveBody() && !m.isStatic()) m.setActiveBody(fixBody(m.getActiveBody()));
251             if (m.getName().equals("<init>")) continue;
252             if (m.getName().equals("<clinit>")) continue;
253             List l2 = new LinkedList();
254             List l = m.getParameterTypes();
255             for(Iterator it2 = l.iterator(); it2.hasNext();) {
256                 Type t = (Type)it2.next();
257                 l2.add(isGladiatorType(t) ? IntType.v() : t);
258             }
259             Type t = m.getReturnType();
260             c.removeMethod(m);
261             if (isGladiatorType(t)) {
262                 t = IntType.v();
263                 Body bod = m.getActiveBody();
264                 for(Iterator stmtIt = bod.getUnits().snapshotIterator(); stmtIt.hasNext();) {
265                     Stmt s = (Stmt) stmtIt.next();
266                     if (s instanceof ReturnStmt) {
267                         if (((ReturnStmt)s).getOp().getType() instanceof NullType) {
268                             ((ReturnStmt)s).getOpBox().setValue(IntConstant.v(-1));
269                         }
270                     }
271                 }
272             }
273             SootMethod meth = new SootMethod(m.getName(), l2, t, m.getModifiers());
274             meth.setActiveBody(m.getActiveBody());
275             c.addMethod(meth);
276         }
277
278     }
279
280     protected Body fixBody(Body body) {
281         this.body = body;
282         Chain units = body.getUnits();
283         for(Iterator it = body.getLocals().snapshotIterator(); it.hasNext();) {
284             Local l = (Local)it.next();
285             if (isGladiatorType(l.getType())) l.setType(IntType.v());
286         }
287         for(int qq=0; qq<2; qq++) for(Iterator stmtIt = units.snapshotIterator(); stmtIt.hasNext();) {
288             Stmt s = (Stmt) stmtIt.next();
289             List l = s.getUseAndDefBoxes();
290             if (s instanceof DefinitionStmt) {
291                 DefinitionStmt ds = (DefinitionStmt)s;
292                 if (ds.getLeftOp().getType() instanceof PrimType && ds.getRightOp().getType() instanceof NullType) {
293                     ds.getRightOpBox().setValue(IntConstant.v(-1));
294                 }
295             }
296             for(Iterator it = l.iterator(); it.hasNext();) {
297                 Object o = it.next();
298                 if (o instanceof ValueBox) {
299                     ValueBox vb = (ValueBox)o;
300                     Value v = vb.getValue();
301                     
302                     if (v instanceof BinopExpr) {
303                         BinopExpr boe = (BinopExpr)v;
304                         if (boe.getOp1().getType() instanceof PrimType && boe.getOp2().getType() instanceof NullType) {
305                             boe.setOp2(IntConstant.v(-1));
306                         }
307                         if (boe.getOp2().getType() instanceof PrimType && boe.getOp1().getType() instanceof NullType) {
308                             boe.setOp1(IntConstant.v(-1));
309                         }
310                     }
311
312                     if (v instanceof InvokeExpr) {
313                         InvokeExpr ie = (InvokeExpr)v;
314                         SootMethodRef mr = ie.getMethodRef();
315                         if (isGladiator(mr.declaringClass())) {
316                             body.getUnits().remove(s);
317                             qq = 0;
318                             break;
319                         }
320                         mr = convert(mr);
321                         ie.setMethodRef(mr);
322                         for(int i=0; i<ie.getArgCount(); i++) {
323                             ValueBox b = ie.getArgBox(i);
324                             Value val = b.getValue();
325                             if (mr.parameterType(i) instanceof RefType && val.getType() instanceof PrimType) {
326                                 SootClass intClass = Scene.v().getSootClass("java.lang.Integer");
327                                 List typelist = new LinkedList();
328                                 typelist.add(IntType.v());
329                                 SootMethod intMethod = intClass.getMethod("<init>", typelist);
330                                 Local loc = viaLocal(Jimple.v().newNewExpr(RefType.v(intClass)), body, s);
331                                 List list = new LinkedList();
332                                 list.add(val);
333                                 units.insertBefore(Jimple.v().newInvokeStmt(Jimple.v().newSpecialInvokeExpr(loc,
334                                                                                                             intMethod.makeRef(),
335                                                                                                             list)),
336                                                    s);
337                                 b.setValue(loc);
338                             }
339                             if (val != null && val.getType() instanceof NullType && mr.parameterType(i) instanceof IntType) {
340                                 b.setValue(IntConstant.v(-1));
341                             }
342                         }
343
344                     } else if (v instanceof NewExpr) {
345                         NewExpr ne = (NewExpr)v;
346                         if (isGladiatorType(ne.getBaseType())) {
347                             SootClass sc = ((RefType)ne.getBaseType()).getSootClass();
348                             SootClass mc = getParent(sc);
349                             String incFuncName = sc.getShortName().substring(sc.getShortName().lastIndexOf('$')+1) + "$$inc";
350                             SootMethodRef smr = Scene.v().makeMethodRef(mc, incFuncName, new LinkedList(), IntType.v(), false);
351                             Expr invokeExpr = Jimple.v().newSpecialInvokeExpr(body.getThisLocal(), smr);
352                             Local ll = viaLocal(invokeExpr, body, s);
353                             vb.setValue(ll);
354                         }
355
356                     } else if (v instanceof CastExpr) {
357                         CastExpr ce = (CastExpr)v;
358                         if (isGladiatorType(ce.getCastType())) {
359                             SootClass mc = getParent(((RefType)ce.getCastType()).getSootClass());
360                             LinkedList list = new LinkedList();
361                             list.add(Scene.v().getSootClass("java.lang.Object").getType());
362                             SootMethodRef mr = Scene.v().makeMethodRef(mc, "zap", list, IntType.v(), true);
363                             Local loc = viaLocal(ce.getOp(), body, s);
364                             List list2 = new LinkedList();
365                             list2.add(loc);
366                             vb.setValue(viaLocal(Jimple.v().newStaticInvokeExpr(mr, list2), body, s));
367                         }
368
369                     } else if (v instanceof InstanceFieldRef) {
370                         InstanceFieldRef ifr = (InstanceFieldRef)v;
371                         SootFieldRef fr = ifr.getFieldRef();
372                         Type t = fr.type();
373                         if (isGladiatorFieldRef(fr)) {
374                             SootClass mc = getParent(fr.declaringClass());
375                             SootFieldRef sf = getGladiatorField(fr).makeRef();
376                             InstanceFieldRef sfr = Jimple.v().newInstanceFieldRef(body.getThisLocal(), sf);
377                             ArrayRef ar = Jimple.v().newArrayRef(viaLocal(sfr, body, s), ifr.getBase());
378                             vb.setValue(ar);
379                         }
380                         if ((t instanceof RefType) && isGladiator(((RefType)t).getSootClass())) {
381                             SootClass tc = ((RefType)t).getSootClass();
382                             SootClass mc = getParent(tc);
383                             ifr.setFieldRef(Scene.v().makeFieldRef(mc, fr.name(), IntType.v(), false));
384                         }
385                     }
386                 }
387             }
388         }
389         return body;
390     }
391 }