repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
soot
soot-master/src/main/java/soot/grimp/internal/GNewInvokeExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import soot.RefType; import soot.SootMethodRef; import soot.Type; import soot.UnitPrinter; import soot.Value; import soot.grimp.Grimp; import soot.grimp.GrimpValueSwitch; import soot.grimp.NewInvokeExpr; import soot.grimp.Precedence; import soot.jimple.internal.AbstractInvokeExpr; import soot.util.Switch; public class GNewInvokeExpr extends AbstractInvokeExpr implements NewInvokeExpr, Precedence { protected RefType type; public GNewInvokeExpr(RefType type, SootMethodRef methodRef, List<? extends Value> args) { super(methodRef, new ExprBox[args.size()]); if (methodRef != null && methodRef.isStatic()) { throw new RuntimeException("wrong static-ness"); } this.type = type; final Grimp grmp = Grimp.v(); for (ListIterator<? extends Value> it = args.listIterator(); it.hasNext();) { Value v = it.next(); this.argBoxes[it.previousIndex()] = grmp.newExprBox(v); } } @Override public RefType getBaseType() { return type; } @Override public void setBaseType(RefType type) { this.type = type; } @Override public Type getType() { return type; } @Override public int getPrecedence() { return 850; } @Override public String toString() { StringBuilder buf = new StringBuilder("new "); buf.append(type.toString()).append('('); if (argBoxes != null) { for (int i = 0, e = argBoxes.length; i < e; i++) { if (i != 0) { buf.append(", "); } buf.append(argBoxes[i].getValue().toString()); } } buf.append(')'); return buf.toString(); } @Override public void toString(UnitPrinter up) { up.literal("new "); up.type(type); up.literal("("); if (argBoxes != null) { for (int i = 0, e = argBoxes.length; i < e; i++) { if (i != 0) { up.literal(", "); } argBoxes[i].toString(up); } } up.literal(")"); } @Override public void apply(Switch sw) { ((GrimpValueSwitch) sw).caseNewInvokeExpr(this); } @Override public Object clone() { final int count = getArgCount(); List<Value> clonedArgs = new ArrayList<Value>(count); for (int i = 0; i < count; i++) { clonedArgs.add(Grimp.cloneIfNecessary(getArg(i))); } return new GNewInvokeExpr(getBaseType(), methodRef, clonedArgs); } @Override public boolean equivTo(Object o) { if (o instanceof GNewInvokeExpr) { GNewInvokeExpr ie = (GNewInvokeExpr) o; if ((this.argBoxes == null ? 0 : this.argBoxes.length) != (ie.argBoxes == null ? 0 : ie.argBoxes.length) || !this.getMethod().equals(ie.getMethod()) || !this.type.equals(ie.type)) { return false; } if (this.argBoxes != null) { for (int i = 0, e = this.argBoxes.length; i < e; i++) { if (!this.argBoxes[i].getValue().equivTo(ie.argBoxes[i].getValue())) { return false; } } } return true; } return false; } /** Returns a hash code for this object, consistent with structural equality. */ @Override public int equivHashCode() { return getMethod().equivHashCode(); } }
4,114
25.210191
110
java
soot
soot-master/src/main/java/soot/grimp/internal/GNewMultiArrayExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import soot.ArrayType; import soot.Value; import soot.ValueBox; import soot.grimp.Grimp; import soot.jimple.internal.AbstractNewMultiArrayExpr; public class GNewMultiArrayExpr extends AbstractNewMultiArrayExpr { public GNewMultiArrayExpr(ArrayType type, List<? extends Value> sizes) { super(type, new ValueBox[sizes.size()]); final Grimp grmp = Grimp.v(); for (ListIterator<? extends Value> it = sizes.listIterator(); it.hasNext();) { Value v = it.next(); sizeBoxes[it.previousIndex()] = grmp.newExprBox(v); } } @Override public Object clone() { final ValueBox[] boxes = this.sizeBoxes; List<Value> clonedSizes = new ArrayList<Value>(boxes.length); for (ValueBox vb : boxes) { clonedSizes.add(Grimp.cloneIfNecessary(vb.getValue())); } return new GNewMultiArrayExpr(getBaseType(), clonedSizes); } }
1,775
30.157895
82
java
soot
soot-master/src/main/java/soot/grimp/internal/GOrExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Value; import soot.grimp.Grimp; import soot.jimple.ExprSwitch; import soot.jimple.OrExpr; import soot.util.Switch; public class GOrExpr extends AbstractGrimpIntLongBinopExpr implements OrExpr { public GOrExpr(Value op1, Value op2) { super(op1, op2); } @Override public String getSymbol() { return " | "; } @Override public int getPrecedence() { return 350; } @Override public void apply(Switch sw) { ((ExprSwitch) sw).caseOrExpr(this); } @Override public Object clone() { return new GOrExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2())); } }
1,456
24.561404
91
java
soot
soot-master/src/main/java/soot/grimp/internal/GRValueBox.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.AbstractValueBox; import soot.Local; import soot.Value; import soot.jimple.ConcreteRef; import soot.jimple.Constant; import soot.jimple.Expr; public class GRValueBox extends AbstractValueBox { public GRValueBox(Value value) { setValue(value); } @Override public boolean canContainValue(Value value) { return value instanceof Local || value instanceof Constant || value instanceof ConcreteRef || value instanceof Expr; } @Override public Object clone() { throw new RuntimeException(); } }
1,358
27.3125
120
java
soot
soot-master/src/main/java/soot/grimp/internal/GRemExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Value; import soot.grimp.Grimp; import soot.jimple.ExprSwitch; import soot.jimple.RemExpr; import soot.util.Switch; public class GRemExpr extends AbstractGrimpFloatBinopExpr implements RemExpr { public GRemExpr(Value op1, Value op2) { super(op1, op2); } @Override public final String getSymbol() { return " % "; } @Override public final int getPrecedence() { return 800; } @Override public void apply(Switch sw) { ((ExprSwitch) sw).caseRemExpr(this); } @Override public Object clone() { return new GRemExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2())); } }
1,472
24.842105
92
java
soot
soot-master/src/main/java/soot/grimp/internal/GReturnStmt.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Value; import soot.grimp.Grimp; import soot.jimple.internal.JReturnStmt; public class GReturnStmt extends JReturnStmt { public GReturnStmt(Value returnValue) { super(Grimp.v().newExprBox(returnValue)); } @Override public Object clone() { return new GReturnStmt(Grimp.cloneIfNecessary(getOp())); } }
1,158
27.975
71
java
soot
soot-master/src/main/java/soot/grimp/internal/GShlExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.IntType; import soot.LongType; import soot.Type; import soot.UnknownType; import soot.Value; import soot.grimp.Grimp; import soot.jimple.ExprSwitch; import soot.jimple.ShlExpr; import soot.util.Switch; public class GShlExpr extends AbstractGrimpIntLongBinopExpr implements ShlExpr { public GShlExpr(Value op1, Value op2) { super(op1, op2); } @Override public String getSymbol() { return " << "; } @Override public int getPrecedence() { return 650; } @Override public void apply(Switch sw) { ((ExprSwitch) sw).caseShlExpr(this); } @Override public Type getType() { if (isIntLikeType(op2Box.getValue().getType())) { final Type t1 = op1Box.getValue().getType(); if (isIntLikeType(t1)) { return IntType.v(); } final LongType tyLong = LongType.v(); if (tyLong.equals(t1)) { return tyLong; } } return UnknownType.v(); } @Override public Object clone() { return new GShlExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2())); } }
1,904
24.065789
92
java
soot
soot-master/src/main/java/soot/grimp/internal/GShrExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.IntType; import soot.LongType; import soot.Type; import soot.UnknownType; import soot.Value; import soot.grimp.Grimp; import soot.jimple.ExprSwitch; import soot.jimple.ShrExpr; import soot.util.Switch; public class GShrExpr extends AbstractGrimpIntLongBinopExpr implements ShrExpr { public GShrExpr(Value op1, Value op2) { super(op1, op2); } @Override public String getSymbol() { return " >> "; } @Override public int getPrecedence() { return 650; } @Override public void apply(Switch sw) { ((ExprSwitch) sw).caseShrExpr(this); } @Override public Type getType() { if (isIntLikeType(op2Box.getValue().getType())) { final Type t1 = op1Box.getValue().getType(); if (isIntLikeType(t1)) { return IntType.v(); } final LongType tyLong = LongType.v(); if (tyLong.equals(t1)) { return tyLong; } } return UnknownType.v(); } @Override public Object clone() { return new GShrExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2())); } }
1,904
24.065789
92
java
soot
soot-master/src/main/java/soot/grimp/internal/GSpecialInvokeExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import soot.SootMethodRef; import soot.UnitPrinter; import soot.Value; import soot.grimp.Grimp; import soot.grimp.Precedence; import soot.grimp.PrecedenceTest; import soot.jimple.internal.AbstractSpecialInvokeExpr; public class GSpecialInvokeExpr extends AbstractSpecialInvokeExpr implements Precedence { public GSpecialInvokeExpr(Value base, SootMethodRef methodRef, List<? extends Value> args) { super(Grimp.v().newObjExprBox(base), methodRef, new ExprBox[args.size()]); final Grimp grmp = Grimp.v(); for (ListIterator<? extends Value> it = args.listIterator(); it.hasNext();) { Value v = it.next(); this.argBoxes[it.previousIndex()] = grmp.newExprBox(v); } } @Override public int getPrecedence() { return 950; } @Override public String toString() { final Value base = getBase(); String baseString = base.toString(); if (base instanceof Precedence && ((Precedence) base).getPrecedence() < getPrecedence()) { baseString = "(" + baseString + ")"; } StringBuilder buf = new StringBuilder(baseString); buf.append('.').append(methodRef.getSignature()).append('('); if (argBoxes != null) { for (int i = 0, e = argBoxes.length; i < e; i++) { if (i != 0) { buf.append(", "); } buf.append(argBoxes[i].getValue().toString()); } } buf.append(')'); return buf.toString(); } @Override public void toString(UnitPrinter up) { final boolean needsBrackets = PrecedenceTest.needsBrackets(baseBox, this); if (needsBrackets) { up.literal("("); } baseBox.toString(up); if (needsBrackets) { up.literal(")"); } up.literal("."); up.methodRef(methodRef); up.literal("("); if (argBoxes != null) { for (int i = 0, e = argBoxes.length; i < e; i++) { if (i != 0) { up.literal(", "); } argBoxes[i].toString(up); } } up.literal(")"); } @Override public Object clone() { final int count = getArgCount(); List<Value> clonedArgs = new ArrayList<Value>(count); for (int i = 0; i < count; i++) { clonedArgs.add(Grimp.cloneIfNecessary(getArg(i))); } return new GSpecialInvokeExpr(Grimp.cloneIfNecessary(getBase()), methodRef, clonedArgs); } }
3,247
27.743363
94
java
soot
soot-master/src/main/java/soot/grimp/internal/GStaticInvokeExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import soot.SootMethodRef; import soot.Value; import soot.ValueBox; import soot.grimp.Grimp; import soot.jimple.internal.AbstractStaticInvokeExpr; public class GStaticInvokeExpr extends AbstractStaticInvokeExpr { public GStaticInvokeExpr(SootMethodRef methodRef, List<? extends Value> args) { super(methodRef, new ValueBox[args.size()]); final Grimp grmp = Grimp.v(); for (ListIterator<? extends Value> it = args.listIterator(); it.hasNext();) { Value v = it.next(); this.argBoxes[it.previousIndex()] = grmp.newExprBox(v); } } @Override public Object clone() { final int count = getArgCount(); List<Value> clonedArgs = new ArrayList<Value>(count); for (int i = 0; i < count; i++) { clonedArgs.add(Grimp.cloneIfNecessary(getArg(i))); } return new GStaticInvokeExpr(methodRef, clonedArgs); } }
1,805
30.137931
81
java
soot
soot-master/src/main/java/soot/grimp/internal/GSubExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Value; import soot.grimp.Grimp; import soot.jimple.ExprSwitch; import soot.jimple.SubExpr; import soot.util.Switch; public class GSubExpr extends AbstractGrimpFloatBinopExpr implements SubExpr { public GSubExpr(Value op1, Value op2) { super(op1, op2); } @Override public final String getSymbol() { return " - "; } @Override public final int getPrecedence() { return 700; } @Override public void apply(Switch sw) { ((ExprSwitch) sw).caseSubExpr(this); } @Override public Object clone() { return new GSubExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2())); } }
1,472
24.842105
92
java
soot
soot-master/src/main/java/soot/grimp/internal/GTableSwitchStmt.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.Unit; import soot.Value; import soot.grimp.Grimp; import soot.jimple.internal.JTableSwitchStmt; public class GTableSwitchStmt extends JTableSwitchStmt { public GTableSwitchStmt(Value key, int lowIndex, int highIndex, List<? extends Unit> targets, Unit defaultTarget) { super(Grimp.v().newExprBox(key), lowIndex, highIndex, getTargetBoxesArray(targets, Grimp.v()::newStmtBox), Grimp.v().newStmtBox(defaultTarget)); } @Override public Object clone() { return new GTableSwitchStmt(Grimp.cloneIfNecessary(getKey()), getLowIndex(), getHighIndex(), getTargets(), getDefaultTarget()); } }
1,481
31.933333
117
java
soot
soot-master/src/main/java/soot/grimp/internal/GThrowStmt.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Value; import soot.grimp.Grimp; import soot.jimple.internal.JThrowStmt; public class GThrowStmt extends JThrowStmt { public GThrowStmt(Value op) { super(Grimp.v().newExprBox(op)); } @Override public Object clone() { return new GThrowStmt(Grimp.cloneIfNecessary(getOp())); } }
1,135
27.4
71
java
soot
soot-master/src/main/java/soot/grimp/internal/GTrap.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.AbstractTrap; import soot.SootClass; import soot.Unit; import soot.grimp.Grimp; public class GTrap extends AbstractTrap { public GTrap(SootClass exception, Unit beginStmt, Unit endStmt, Unit handlerStmt) { super(exception, Grimp.v().newStmtBox(beginStmt), Grimp.v().newStmtBox(endStmt), Grimp.v().newStmtBox(handlerStmt)); } @Override public Object clone() { return new GTrap(exception, getBeginUnit(), getEndUnit(), getHandlerUnit()); } }
1,299
30.707317
120
java
soot
soot-master/src/main/java/soot/grimp/internal/GUshrExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.IntType; import soot.LongType; import soot.Type; import soot.UnknownType; import soot.Value; import soot.grimp.Grimp; import soot.jimple.ExprSwitch; import soot.jimple.UshrExpr; import soot.util.Switch; public class GUshrExpr extends AbstractGrimpIntLongBinopExpr implements UshrExpr { public GUshrExpr(Value op1, Value op2) { super(op1, op2); } @Override public String getSymbol() { return " >>> "; } @Override public int getPrecedence() { return 650; } @Override public void apply(Switch sw) { ((ExprSwitch) sw).caseUshrExpr(this); } @Override public Type getType() { if (isIntLikeType(op2Box.getValue().getType())) { final Type t1 = op1Box.getValue().getType(); if (isIntLikeType(t1)) { return IntType.v(); } final LongType tyLong = LongType.v(); if (tyLong.equals(t1)) { return LongType.v(); } } return UnknownType.v(); } @Override public Object clone() { return new GUshrExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2())); } }
1,917
24.236842
93
java
soot
soot-master/src/main/java/soot/grimp/internal/GVirtualInvokeExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import soot.SootMethodRef; import soot.UnitPrinter; import soot.Value; import soot.ValueBox; import soot.grimp.Grimp; import soot.grimp.Precedence; import soot.grimp.PrecedenceTest; import soot.jimple.internal.AbstractVirtualInvokeExpr; public class GVirtualInvokeExpr extends AbstractVirtualInvokeExpr implements Precedence { public GVirtualInvokeExpr(Value base, SootMethodRef methodRef, List<? extends Value> args) { super(Grimp.v().newObjExprBox(base), methodRef, new ValueBox[args.size()]); final Grimp grmp = Grimp.v(); for (ListIterator<? extends Value> it = args.listIterator(); it.hasNext();) { Value v = it.next(); this.argBoxes[it.previousIndex()] = grmp.newExprBox(v); } } @Override public int getPrecedence() { return 950; } @Override public String toString() { final Value base = getBase(); String baseString = base.toString(); if (base instanceof Precedence && ((Precedence) base).getPrecedence() < getPrecedence()) { baseString = "(" + baseString + ")"; } StringBuilder buf = new StringBuilder(baseString); buf.append('.').append(methodRef.getSignature()).append('('); if (argBoxes != null) { for (int i = 0, e = argBoxes.length; i < e; i++) { if (i != 0) { buf.append(", "); } buf.append(argBoxes[i].getValue().toString()); } } buf.append(')'); return buf.toString(); } @Override public void toString(UnitPrinter up) { final boolean needsBrackets = PrecedenceTest.needsBrackets(baseBox, this); if (needsBrackets) { up.literal("("); } baseBox.toString(up); if (needsBrackets) { up.literal(")"); } up.literal("."); up.methodRef(methodRef); up.literal("("); if (argBoxes != null) { for (int i = 0, e = argBoxes.length; i < e; i++) { if (i != 0) { up.literal(", "); } argBoxes[i].toString(up); } } up.literal(")"); } @Override public Object clone() { final int count = getArgCount(); List<Value> clonedArgs = new ArrayList<Value>(count); for (int i = 0; i < count; i++) { clonedArgs.add(Grimp.cloneIfNecessary(getArg(i))); } return new GVirtualInvokeExpr(Grimp.cloneIfNecessary(getBase()), methodRef, clonedArgs); } }
3,269
27.938053
94
java
soot
soot-master/src/main/java/soot/grimp/internal/GXorExpr.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Value; import soot.grimp.Grimp; import soot.jimple.ExprSwitch; import soot.jimple.XorExpr; import soot.util.Switch; public class GXorExpr extends AbstractGrimpIntLongBinopExpr implements XorExpr { public GXorExpr(Value op1, Value op2) { super(op1, op2); } @Override public final String getSymbol() { return " ^ "; } @Override public final int getPrecedence() { return 450; } @Override public void apply(Switch sw) { ((ExprSwitch) sw).caseXorExpr(this); } @Override public Object clone() { return new GXorExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2())); } }
1,474
24.877193
92
java
soot
soot-master/src/main/java/soot/grimp/internal/ObjExprBox.java
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Local; import soot.Value; import soot.jimple.CastExpr; import soot.jimple.ClassConstant; import soot.jimple.ConcreteRef; import soot.jimple.InvokeExpr; import soot.jimple.NewArrayExpr; import soot.jimple.NewMultiArrayExpr; import soot.jimple.NullConstant; import soot.jimple.StringConstant; /** an ExprBox which can only contain object-looking references */ public class ObjExprBox extends ExprBox { public ObjExprBox(Value value) { super(value); } @Override public boolean canContainValue(Value value) { return value instanceof ConcreteRef || value instanceof InvokeExpr || value instanceof NewArrayExpr || value instanceof NewMultiArrayExpr || value instanceof Local || value instanceof NullConstant || value instanceof StringConstant || value instanceof ClassConstant || (value instanceof CastExpr && canContainValue(((CastExpr) value).getOp())); } }
1,737
33.078431
104
java
soot
soot-master/src/main/java/soot/grimp/toolkits/base/ConstructorFolder.java
package soot.grimp.toolkits.base; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.Local; import soot.Singletons; import soot.Unit; import soot.Value; import soot.grimp.Grimp; import soot.grimp.GrimpBody; import soot.jimple.AssignStmt; import soot.jimple.InvokeStmt; import soot.jimple.NewExpr; import soot.jimple.SpecialInvokeExpr; import soot.jimple.Stmt; import soot.options.Options; import soot.toolkits.scalar.LocalUses; import soot.toolkits.scalar.UnitValueBoxPair; import soot.util.Chain; public class ConstructorFolder extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(ConstructorFolder.class); public ConstructorFolder(Singletons.Global g) { } public static ConstructorFolder v() { return G.v().soot_grimp_toolkits_base_ConstructorFolder(); } /** This method change all new Obj/<init>(args) pairs to new Obj(args) idioms. */ protected void internalTransform(Body b, String phaseName, Map options) { GrimpBody body = (GrimpBody) b; if (Options.v().verbose()) { logger.debug("[" + body.getMethod().getName() + "] Folding constructors..."); } Chain units = body.getUnits(); List<Unit> stmtList = new ArrayList<Unit>(); stmtList.addAll(units); Iterator<Unit> it = stmtList.iterator(); LocalUses localUses = LocalUses.Factory.newLocalUses(b); /* fold in NewExpr's with specialinvoke's */ while (it.hasNext()) { Stmt s = (Stmt) it.next(); if (!(s instanceof AssignStmt)) { continue; } /* this should be generalized to ArrayRefs */ Value lhs = ((AssignStmt) s).getLeftOp(); if (!(lhs instanceof Local)) { continue; } Value rhs = ((AssignStmt) s).getRightOp(); if (!(rhs instanceof NewExpr)) { continue; } /* * TO BE IMPLEMENTED LATER: move any copy of the object reference for lhs down beyond the NewInvokeExpr, with the * rationale being that you can't modify the object before the constructor call in any case. * * Also, do note that any new's (object creation) without corresponding constructors must be dead. */ List lu = localUses.getUsesOf(s); Iterator luIter = lu.iterator(); boolean MadeNewInvokeExpr = false; while (luIter.hasNext()) { Unit use = ((UnitValueBoxPair) (luIter.next())).unit; if (!(use instanceof InvokeStmt)) { continue; } InvokeStmt is = (InvokeStmt) use; if (!(is.getInvokeExpr() instanceof SpecialInvokeExpr) || lhs != ((SpecialInvokeExpr) is.getInvokeExpr()).getBase()) { continue; } SpecialInvokeExpr oldInvoke = ((SpecialInvokeExpr) is.getInvokeExpr()); LinkedList invokeArgs = new LinkedList(); for (int i = 0; i < oldInvoke.getArgCount(); i++) { invokeArgs.add(oldInvoke.getArg(i)); } AssignStmt constructStmt = Grimp.v().newAssignStmt((AssignStmt) s); constructStmt .setRightOp(Grimp.v().newNewInvokeExpr(((NewExpr) rhs).getBaseType(), oldInvoke.getMethodRef(), invokeArgs)); MadeNewInvokeExpr = true; use.redirectJumpsToThisTo(constructStmt); units.insertBefore(constructStmt, use); units.remove(use); } if (MadeNewInvokeExpr) { units.remove(s); } } } }
4,382
30.085106
121
java
soot
soot-master/src/main/java/soot/javaToJimple/AbstractJBBFactory.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public abstract class AbstractJBBFactory { protected abstract AbstractJimpleBodyBuilder createJimpleBodyBuilder(); }
949
30.666667
73
java
soot
soot-master/src/main/java/soot/javaToJimple/AbstractJimpleBodyBuilder.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; public abstract class AbstractJimpleBodyBuilder { protected soot.jimple.JimpleBody body; public void ext(AbstractJimpleBodyBuilder ext) { this.ext = ext; if (ext.ext != null) { throw new RuntimeException("Extensions created in wrong order."); } ext.base = this.base; } public AbstractJimpleBodyBuilder ext() { if (ext == null) { return this; } return ext; } private AbstractJimpleBodyBuilder ext = null; public void base(AbstractJimpleBodyBuilder base) { this.base = base; } public AbstractJimpleBodyBuilder base() { return base; } private AbstractJimpleBodyBuilder base = this; protected soot.jimple.JimpleBody createJimpleBody(polyglot.ast.Block block, List formals, soot.SootMethod sootMethod) { return ext().createJimpleBody(block, formals, sootMethod); } /* * protected soot.Value createExpr(polyglot.ast.Expr expr){ return ext().createExpr(expr); } */ protected soot.Value createAggressiveExpr(polyglot.ast.Expr expr, boolean reduceAggressively, boolean reverseCondIfNec) { // System.out.println("in abstract"); return ext().createAggressiveExpr(expr, reduceAggressively, reverseCondIfNec); } protected void createStmt(polyglot.ast.Stmt stmt) { ext().createStmt(stmt); } protected boolean needsAccessor(polyglot.ast.Expr expr) { return ext().needsAccessor(expr); } protected soot.Local handlePrivateFieldAssignSet(polyglot.ast.Assign assign) { return ext().handlePrivateFieldAssignSet(assign); } protected soot.Local handlePrivateFieldUnarySet(polyglot.ast.Unary unary) { return ext().handlePrivateFieldUnarySet(unary); } protected soot.Value getAssignRightLocal(polyglot.ast.Assign assign, soot.Local leftLocal) { return ext().getAssignRightLocal(assign, leftLocal); } protected soot.Value getSimpleAssignRightLocal(polyglot.ast.Assign assign) { return ext().getSimpleAssignRightLocal(assign); } protected soot.Local handlePrivateFieldSet(polyglot.ast.Expr expr, soot.Value right, soot.Value base) { return ext().handlePrivateFieldSet(expr, right, base); } protected soot.SootMethodRef getSootMethodRef(polyglot.ast.Call call) { return ext().getSootMethodRef(call); } protected soot.Local generateLocal(soot.Type sootType) { return ext().generateLocal(sootType); } protected soot.Local generateLocal(polyglot.types.Type polyglotType) { return ext().generateLocal(polyglotType); } protected soot.Local getThis(soot.Type sootType) { return ext().getThis(sootType); } protected soot.Value getBaseLocal(polyglot.ast.Receiver receiver) { return ext().getBaseLocal(receiver); } protected soot.Value createLHS(polyglot.ast.Expr expr) { return ext().createLHS(expr); } protected soot.jimple.FieldRef getFieldRef(polyglot.ast.Field field) { return ext().getFieldRef(field); } protected soot.jimple.Constant getConstant(soot.Type sootType, int val) { return ext().getConstant(sootType, val); } }
3,888
28.687023
123
java
soot
soot-master/src/main/java/soot/javaToJimple/AccessFieldJBB.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; public class AccessFieldJBB extends AbstractJimpleBodyBuilder { public AccessFieldJBB() { // ext(null); // base(this); } protected boolean needsAccessor(polyglot.ast.Expr expr) { if (expr instanceof soot.javaToJimple.jj.ast.JjAccessField_c) { return true; } else { return ext().needsAccessor(expr); } } protected soot.Local handlePrivateFieldUnarySet(polyglot.ast.Unary unary) { if (unary.expr() instanceof soot.javaToJimple.jj.ast.JjAccessField_c) { // not sure about strings here but... soot.javaToJimple.jj.ast.JjAccessField_c accessField = (soot.javaToJimple.jj.ast.JjAccessField_c) unary.expr(); // create field target soot.Local baseLocal = (soot.Local) base().getBaseLocal(accessField.field().target()); // soot.Value fieldGetLocal = getPrivateAccessFieldLocal(accessField, base); soot.Local fieldGetLocal = handleCall(accessField.field(), accessField.getMeth(), null, baseLocal); soot.Local tmp = base().generateLocal(accessField.field().type()); soot.jimple.AssignStmt stmt1 = soot.jimple.Jimple.v().newAssignStmt(tmp, fieldGetLocal); ext().body.getUnits().add(stmt1); Util.addLnPosTags(stmt1, unary.position()); soot.Value incVal = base().getConstant(Util.getSootType(accessField.field().type()), 1); soot.jimple.BinopExpr binExpr; if (unary.operator() == polyglot.ast.Unary.PRE_INC || unary.operator() == polyglot.ast.Unary.POST_INC) { binExpr = soot.jimple.Jimple.v().newAddExpr(tmp, incVal); } else { binExpr = soot.jimple.Jimple.v().newSubExpr(tmp, incVal); } soot.Local tmp2 = generateLocal(accessField.field().type()); soot.jimple.AssignStmt assign = soot.jimple.Jimple.v().newAssignStmt(tmp2, binExpr); ext().body.getUnits().add(assign); if (unary.operator() == polyglot.ast.Unary.PRE_INC || unary.operator() == polyglot.ast.Unary.PRE_DEC) { return base().handlePrivateFieldSet(accessField, tmp2, baseLocal); } else { base().handlePrivateFieldSet(accessField, tmp2, baseLocal); return tmp; } } else { return ext().handlePrivateFieldUnarySet(unary); } } protected soot.Local handlePrivateFieldAssignSet(polyglot.ast.Assign assign) { if (assign.left() instanceof soot.javaToJimple.jj.ast.JjAccessField_c) { // not sure about strings here but... soot.javaToJimple.jj.ast.JjAccessField_c accessField = (soot.javaToJimple.jj.ast.JjAccessField_c) assign.left(); // create field target soot.Local baseLocal = (soot.Local) base().getBaseLocal(accessField.field().target()); if (assign.operator() == polyglot.ast.Assign.ASSIGN) { soot.Value right = base().getSimpleAssignRightLocal(assign); return base().handlePrivateFieldSet(accessField, right, baseLocal); } else { // create field get using target soot.Local leftLocal = handleCall(accessField.field(), accessField.getMeth(), null, baseLocal); // handle field set using same target // soot.Local leftLocal = (soot.Local)base().createExpr(accessField); soot.Value right = base().getAssignRightLocal(assign, leftLocal); return handleFieldSet(accessField, right, baseLocal); } } else { return ext().handlePrivateFieldAssignSet(assign); } } private soot.Local handleCall(polyglot.ast.Field field, polyglot.ast.Call call, soot.Value param, soot.Local base) { soot.Type sootRecType = Util.getSootType(call.target().type()); soot.SootClass receiverTypeClass = soot.Scene.v().getSootClass("java.lang.Object"); if (sootRecType instanceof soot.RefType) { receiverTypeClass = ((soot.RefType) sootRecType).getSootClass(); } soot.SootMethodRef methToCall = base().getSootMethodRef(call); List<soot.Value> params = new ArrayList<soot.Value>(); /* * if (!field.flags().isStatic()){ //params.add(base().getThis(Util.getSootType(field.target().type()))); * params.add((soot.Local)ext().getBaseLocal(field.target())); } */ if (param != null) { params.add(param); } soot.jimple.InvokeExpr invoke; soot.Local baseLocal = base; if (base == null) { baseLocal = (soot.Local) ext().getBaseLocal(call.target()); } if (methToCall.isStatic()) { invoke = soot.jimple.Jimple.v().newStaticInvokeExpr(methToCall, params); } else if (soot.Modifier.isInterface(receiverTypeClass.getModifiers()) && call.methodInstance().flags().isAbstract()) { invoke = soot.jimple.Jimple.v().newInterfaceInvokeExpr(baseLocal, methToCall, params); } else { invoke = soot.jimple.Jimple.v().newVirtualInvokeExpr(baseLocal, methToCall, params); } soot.Local retLocal = base().generateLocal(field.type()); soot.jimple.AssignStmt assignStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, invoke); ext().body.getUnits().add(assignStmt); return retLocal; } protected soot.Local handlePrivateFieldSet(polyglot.ast.Expr expr, soot.Value right, soot.Value baseLocal) { if (expr instanceof soot.javaToJimple.jj.ast.JjAccessField_c) { soot.javaToJimple.jj.ast.JjAccessField_c accessField = (soot.javaToJimple.jj.ast.JjAccessField_c) expr; return handleCall(accessField.field(), accessField.setMeth(), right, null); } else { return ext().handlePrivateFieldSet(expr, right, baseLocal); } } private soot.Local handleFieldSet(soot.javaToJimple.jj.ast.JjAccessField_c accessField, soot.Value right, soot.Local base) { return handleCall(accessField.field(), accessField.setMeth(), right, base); } /* * protected soot.Value createExpr(polyglot.ast.Expr expr){ if (expr instanceof soot.javaToJimple.jj.ast.JjAccessField_c){ * soot.javaToJimple.jj.ast.JjAccessField_c accessField = (soot.javaToJimple.jj.ast.JjAccessField_c)expr; * * * // here is where we need to return the field using get method return handleCall(accessField.field(), * accessField.getMeth(), null, null); // return ext().createExpr(accessField.field()); } else { return * ext().createExpr(expr); } } */ protected soot.Value createAggressiveExpr(polyglot.ast.Expr expr, boolean redAgg, boolean revIfNec) { if (expr instanceof soot.javaToJimple.jj.ast.JjAccessField_c) { soot.javaToJimple.jj.ast.JjAccessField_c accessField = (soot.javaToJimple.jj.ast.JjAccessField_c) expr; // here is where we need to return the field using get method return handleCall(accessField.field(), accessField.getMeth(), null, null); // return ext().createExpr(accessField.field()); } else { return ext().createAggressiveExpr(expr, redAgg, revIfNec); } } protected soot.Value createLHS(polyglot.ast.Expr expr) { if (expr instanceof soot.javaToJimple.jj.ast.JjAccessField_c) { soot.javaToJimple.jj.ast.JjAccessField_c accessField = (soot.javaToJimple.jj.ast.JjAccessField_c) expr; return handleCall(accessField.field(), accessField.getMeth(), null, null);// base().getFieldRef(accessField.field()); } else { return ext().createLHS(expr); } } }
8,031
42.182796
124
java
soot
soot-master/src/main/java/soot/javaToJimple/AnonClassInitMethodSource.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.PackManager; public class AnonClassInitMethodSource extends soot.javaToJimple.PolyglotMethodSource { private boolean hasOuterRef; public void hasOuterRef(boolean b) { hasOuterRef = b; } public boolean hasOuterRef() { return hasOuterRef; } private boolean hasQualifier; public void hasQualifier(boolean b) { hasQualifier = b; } public boolean hasQualifier() { return hasQualifier; } private boolean inStaticMethod; public void inStaticMethod(boolean b) { inStaticMethod = b; } public boolean inStaticMethod() { return inStaticMethod; } private boolean isSubType = false; public void isSubType(boolean b) { isSubType = b; } public boolean isSubType() { return isSubType; } private soot.Type superOuterType = null; private soot.Type thisOuterType = null; public void superOuterType(soot.Type t) { superOuterType = t; } public soot.Type superOuterType() { return superOuterType; } public void thisOuterType(soot.Type t) { thisOuterType = t; } public soot.Type thisOuterType() { return thisOuterType; } private polyglot.types.ClassType polyglotType; public void polyglotType(polyglot.types.ClassType type) { polyglotType = type; } public polyglot.types.ClassType polyglotType() { return polyglotType; } private polyglot.types.ClassType anonType; public void anonType(polyglot.types.ClassType type) { anonType = type; } public polyglot.types.ClassType anonType() { return anonType; } public soot.Body getBody(soot.SootMethod sootMethod, String phaseName) { AnonInitBodyBuilder aibb = new AnonInitBodyBuilder(); soot.jimple.JimpleBody body = aibb.createBody(sootMethod); PackManager.v().getPack("jj").apply(body); return body; } private soot.Type outerClassType; public soot.Type outerClassType() { return outerClassType; } public void outerClassType(soot.Type type) { outerClassType = type; } }
2,841
21.377953
87
java
soot
soot-master/src/main/java/soot/javaToJimple/AnonConstructorFinder.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import polyglot.types.Type; public class AnonConstructorFinder extends polyglot.visit.ContextVisitor { private static final Logger logger = LoggerFactory.getLogger(AnonConstructorFinder.class); public AnonConstructorFinder(polyglot.frontend.Job job, polyglot.types.TypeSystem ts, polyglot.ast.NodeFactory nf) { super(job, ts, nf); } public polyglot.visit.NodeVisitor enter(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.New && ((polyglot.ast.New) n).anonType() != null) { try { List<Type> argTypes = new ArrayList<Type>(); for (Iterator it = ((polyglot.ast.New) n).arguments().iterator(); it.hasNext();) { argTypes.add(((polyglot.ast.Expr) it.next()).type()); } polyglot.types.ConstructorInstance ci = typeSystem().findConstructor(((polyglot.ast.New) n).anonType().superType().toClass(), argTypes, ((polyglot.ast.New) n).anonType().superType().toClass()); InitialResolver.v().addToAnonConstructorMap((polyglot.ast.New) n, ci); } catch (polyglot.types.SemanticException e) { System.out.println(e.getMessage()); logger.error(e.getMessage(), e); } } return this; } }
2,221
35.42623
118
java
soot
soot-master/src/main/java/soot/javaToJimple/AnonInitBodyBuilder.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import polyglot.ast.Block; import polyglot.ast.FieldDecl; import soot.Scene; import soot.SootClass; import soot.SootField; import soot.SootMethodRef; import soot.VoidType; public class AnonInitBodyBuilder extends JimpleBodyBuilder { public soot.jimple.JimpleBody createBody(soot.SootMethod sootMethod) { body = soot.jimple.Jimple.v().newBody(sootMethod); lg = Scene.v().createLocalGenerator(body); AnonClassInitMethodSource acims = (AnonClassInitMethodSource) body.getMethod().getSource(); ArrayList<SootField> fields = acims.getFinalsList(); boolean inStaticMethod = acims.inStaticMethod(); boolean isSubType = acims.isSubType(); soot.Type superOuterType = acims.superOuterType(); soot.Type thisOuterType = acims.thisOuterType(); ArrayList<FieldDecl> fieldInits = acims.getFieldInits(); soot.Type outerClassType = acims.outerClassType(); polyglot.types.ClassType polyglotType = acims.polyglotType(); polyglot.types.ClassType anonType = acims.anonType(); boolean hasOuterRef = ((AnonClassInitMethodSource) body.getMethod().getSource()).hasOuterRef(); boolean hasQualifier = ((AnonClassInitMethodSource) body.getMethod().getSource()).hasQualifier(); // this formal needed soot.RefType type = sootMethod.getDeclaringClass().getType(); specialThisLocal = soot.jimple.Jimple.v().newLocal("this", type); body.getLocals().add(specialThisLocal); soot.jimple.ThisRef thisRef = soot.jimple.Jimple.v().newThisRef(type); soot.jimple.Stmt thisStmt = soot.jimple.Jimple.v().newIdentityStmt(specialThisLocal, thisRef); body.getUnits().add(thisStmt); ArrayList invokeList = new ArrayList(); ArrayList invokeTypeList = new ArrayList(); int numParams = sootMethod.getParameterCount(); int numFinals = 0; if (fields != null) { numFinals = fields.size(); } int startFinals = numParams - numFinals; ArrayList paramsForFinals = new ArrayList(); soot.Local outerLocal = null; soot.Local qualifierLocal = null; // param Iterator fIt = sootMethod.getParameterTypes().iterator(); int counter = 0; while (fIt.hasNext()) { soot.Type fType = (soot.Type) fIt.next(); soot.Local local = soot.jimple.Jimple.v().newLocal("r" + counter, fType); body.getLocals().add(local); soot.jimple.ParameterRef paramRef = soot.jimple.Jimple.v().newParameterRef(fType, counter); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(local, paramRef); int realArgs = 0; if ((hasOuterRef) && (counter == 0)) { // in a non static method the first param is the outer ref outerLocal = local; realArgs = 1; stmt.addTag(new soot.tagkit.EnclosingTag()); } if ((hasOuterRef) && (hasQualifier) && (counter == 1)) { // here second param is qualifier if there is one qualifierLocal = local; realArgs = 2; invokeList.add(qualifierLocal); stmt.addTag(new soot.tagkit.QualifyingTag()); } else if ((!hasOuterRef) && (hasQualifier) && (counter == 0)) { qualifierLocal = local; realArgs = 1; invokeList.add(qualifierLocal); stmt.addTag(new soot.tagkit.QualifyingTag()); } if ((counter >= realArgs) && (counter < startFinals)) { invokeTypeList.add(fType); invokeList.add(local); } else if (counter >= startFinals) { paramsForFinals.add(local); } body.getUnits().add(stmt); counter++; } SootClass superClass = sootMethod.getDeclaringClass().getSuperclass(); // ArrayList needsRef = // needsOuterClassRef(polyglotOuterType);//soot.javaToJimple.InitialResolver.v().getHasOuterRefInInit(); if (needsOuterClassRef(polyglotType)) { // if ((needsRef != null) && (needsRef.contains(superClass.getType())) ){ invokeTypeList.add(0, superOuterType); } SootMethodRef callMethod = Scene.v().makeMethodRef(sootMethod.getDeclaringClass().getSuperclass(), "<init>", invokeTypeList, VoidType.v(), false); if ((!hasQualifier) && (needsOuterClassRef(polyglotType))) { // && (needsRef.contains(superClass.getType()))){ if (isSubType) { invokeList.add(0, outerLocal); } else { invokeList.add(0, Util.getThisGivenOuter(superOuterType, new HashMap(), body, Scene.v().createLocalGenerator(body), outerLocal)); } } soot.jimple.InvokeExpr invoke = soot.jimple.Jimple.v().newSpecialInvokeExpr(specialThisLocal, callMethod, invokeList); soot.jimple.Stmt invokeStmt = soot.jimple.Jimple.v().newInvokeStmt(invoke); body.getUnits().add(invokeStmt); // System.out.println("polyglotType: "+polyglotType+" needs ref: "+needsOuterClassRef(polyglotType)); // field assign if (!inStaticMethod && needsOuterClassRef(anonType)) { soot.SootFieldRef field = Scene.v().makeFieldRef(sootMethod.getDeclaringClass(), "this$0", outerClassType, false); soot.jimple.InstanceFieldRef ref = soot.jimple.Jimple.v().newInstanceFieldRef(specialThisLocal, field); soot.jimple.AssignStmt assign = soot.jimple.Jimple.v().newAssignStmt(ref, outerLocal); body.getUnits().add(assign); } if (fields != null) { Iterator finalsIt = paramsForFinals.iterator(); Iterator<SootField> fieldsIt = fields.iterator(); while (finalsIt.hasNext() && fieldsIt.hasNext()) { soot.Local pLocal = (soot.Local) finalsIt.next(); soot.SootField pField = fieldsIt.next(); soot.jimple.FieldRef pRef = soot.jimple.Jimple.v().newInstanceFieldRef(specialThisLocal, pField.makeRef()); soot.jimple.AssignStmt pAssign = soot.jimple.Jimple.v().newAssignStmt(pRef, pLocal); body.getUnits().add(pAssign); } } // need to be able to handle any kind of field inits -> make this class // extend JimpleBodyBuilder to have access to everything if (fieldInits != null) { handleFieldInits(fieldInits); } ArrayList<Block> staticBlocks = ((AnonClassInitMethodSource) body.getMethod().getSource()).getInitializerBlocks(); if (staticBlocks != null) { handleStaticBlocks(staticBlocks); } // return soot.jimple.ReturnVoidStmt retStmt = soot.jimple.Jimple.v().newReturnVoidStmt(); body.getUnits().add(retStmt); return body; } }
7,263
36.637306
123
java
soot
soot-master/src/main/java/soot/javaToJimple/AnonLocalClassInfo.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import polyglot.util.IdentityKey; public class AnonLocalClassInfo { private boolean inStaticMethod; private ArrayList<IdentityKey> finalLocalsAvail; private ArrayList<IdentityKey> finalLocalsUsed; public boolean inStaticMethod() { return inStaticMethod; } public void inStaticMethod(boolean b) { inStaticMethod = b; } public ArrayList<IdentityKey> finalLocalsAvail() { return finalLocalsAvail; } public void finalLocalsAvail(ArrayList<IdentityKey> list) { finalLocalsAvail = list; } public ArrayList<IdentityKey> finalLocalsUsed() { return finalLocalsUsed; } public void finalLocalsUsed(ArrayList<IdentityKey> list) { finalLocalsUsed = list; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("static: "); sb.append(inStaticMethod); sb.append(" finalLocalsAvail: "); sb.append(finalLocalsAvail); sb.append(" finalLocalsUsed: "); sb.append(finalLocalsUsed); return sb.toString(); } }
1,865
25.657143
71
java
soot
soot-master/src/main/java/soot/javaToJimple/AssertClassMethodSource.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; public class AssertClassMethodSource implements soot.MethodSource { public soot.Body getBody(soot.SootMethod sootMethod, String phaseName) { soot.Body classBody = soot.jimple.Jimple.v().newBody(sootMethod); // static invoke of forName soot.jimple.ParameterRef paramRef = soot.jimple.Jimple.v().newParameterRef(soot.RefType.v("java.lang.String"), 0); soot.Local paramLocal = soot.jimple.Jimple.v().newLocal("$r0", soot.RefType.v("java.lang.String")); classBody.getLocals().add(paramLocal); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(paramLocal, paramRef); classBody.getUnits().add(stmt); ArrayList paramTypes = new ArrayList(); paramTypes.add(soot.RefType.v("java.lang.String")); soot.SootMethodRef methodToInvoke = soot.Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.Class"), "forName", paramTypes, soot.RefType.v("java.lang.Class"), true); soot.Local invokeLocal = soot.jimple.Jimple.v().newLocal("$r1", soot.RefType.v("java.lang.Class")); classBody.getLocals().add(invokeLocal); ArrayList params = new ArrayList(); params.add(paramLocal); soot.jimple.Expr invokeExpr = soot.jimple.Jimple.v().newStaticInvokeExpr(methodToInvoke, params); soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, invokeExpr); classBody.getUnits().add(assign); // return soot.jimple.Stmt retStmt = soot.jimple.Jimple.v().newReturnStmt(invokeLocal); classBody.getUnits().add(retStmt); // catch soot.Local catchRefLocal = soot.jimple.Jimple.v().newLocal("$r2", soot.RefType.v("java.lang.ClassNotFoundException")); classBody.getLocals().add(catchRefLocal); soot.jimple.CaughtExceptionRef caughtRef = soot.jimple.Jimple.v().newCaughtExceptionRef(); soot.jimple.Stmt caughtIdentity = soot.jimple.Jimple.v().newIdentityStmt(catchRefLocal, caughtRef); classBody.getUnits().add(caughtIdentity); // new no class def found error soot.Local noClassDefLocal = soot.jimple.Jimple.v().newLocal("$r3", soot.RefType.v("java.lang.NoClassDefFoundError")); classBody.getLocals().add(noClassDefLocal); soot.jimple.Expr newExpr = soot.jimple.Jimple.v().newNewExpr(soot.RefType.v("java.lang.NoClassDefFoundError")); soot.jimple.Stmt noClassDefAssign = soot.jimple.Jimple.v().newAssignStmt(noClassDefLocal, newExpr); classBody.getUnits().add(noClassDefAssign); // no class def found invoke paramTypes = new ArrayList(); soot.SootMethodRef initMethToInvoke = soot.Scene.v().makeMethodRef( soot.Scene.v().getSootClass("java.lang.NoClassDefFoundError"), "<init>", paramTypes, soot.VoidType.v(), false); params = new ArrayList(); soot.jimple.Expr initInvoke = soot.jimple.Jimple.v().newSpecialInvokeExpr(noClassDefLocal, initMethToInvoke, params); soot.jimple.Stmt initStmt = soot.jimple.Jimple.v().newInvokeStmt(initInvoke); classBody.getUnits().add(initStmt); // get exception message soot.Local throwLocal = soot.jimple.Jimple.v().newLocal("$r4", soot.RefType.v("java.lang.Throwable")); classBody.getLocals().add(throwLocal); paramTypes = new ArrayList(); paramTypes.add(soot.RefType.v("java.lang.Throwable")); params = new ArrayList(); params.add(catchRefLocal); soot.SootMethodRef messageMethToInvoke = soot.Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.Throwable"), "initCause", paramTypes, soot.RefType.v("java.lang.Throwable"), false); soot.jimple.Expr messageInvoke = soot.jimple.Jimple.v().newVirtualInvokeExpr(noClassDefLocal, messageMethToInvoke, params); soot.jimple.Stmt messageAssign = soot.jimple.Jimple.v().newAssignStmt(throwLocal, messageInvoke); classBody.getUnits().add(messageAssign); // throw soot.jimple.Stmt throwStmt = soot.jimple.Jimple.v().newThrowStmt(throwLocal); throwStmt.addTag(new soot.tagkit.ThrowCreatedByCompilerTag()); classBody.getUnits().add(throwStmt); // trap soot.Trap trap = soot.jimple.Jimple.v().newTrap(soot.Scene.v().getSootClass("java.lang.ClassNotFoundException"), assign, retStmt, caughtIdentity); classBody.getTraps().add(trap); return classBody; } }
5,078
45.59633
125
java
soot
soot-master/src/main/java/soot/javaToJimple/AssertStmtChecker.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class AssertStmtChecker extends polyglot.visit.NodeVisitor { private boolean hasAssert = false; public boolean isHasAssert() { return hasAssert; } public AssertStmtChecker() { } public polyglot.ast.Node override(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.ClassDecl) { return n; } if ((n instanceof polyglot.ast.New) && (((polyglot.ast.New) n).anonType() != null)) { return n; } return null; } public polyglot.visit.NodeVisitor enter(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.Assert) { hasAssert = true; } return enter(n); } }
1,512
27.018519
90
java
soot
soot-master/src/main/java/soot/javaToJimple/BiMap.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashMap; public class BiMap { HashMap<Object, Object> keyVal; HashMap<Object, Object> valKey; public BiMap() { } public void put(Object key, Object val) { if (keyVal == null) { keyVal = new HashMap<Object, Object>(); } if (valKey == null) { valKey = new HashMap<Object, Object>(); } keyVal.put(key, val); valKey.put(val, key); } public Object getKey(Object val) { if (valKey == null) { return null; } return valKey.get(val); } public Object getVal(Object key) { if (keyVal == null) { return null; } return keyVal.get(key); } public boolean containsKey(Object key) { if (keyVal == null) { return false; } return keyVal.containsKey(key); } public boolean containsVal(Object val) { if (valKey == null) { return false; } return valKey.containsKey(val); } }
1,744
21.960526
71
java
soot
soot-master/src/main/java/soot/javaToJimple/CastInsertionVisitor.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class CastInsertionVisitor extends polyglot.visit.AscriptionVisitor { public CastInsertionVisitor(polyglot.frontend.Job job, polyglot.types.TypeSystem ts, polyglot.ast.NodeFactory nf) { super(job, ts, nf); } public polyglot.ast.Expr ascribe(polyglot.ast.Expr e, polyglot.types.Type toType) { // System.out.println("expr: "+e); // System.out.println("expr: "+e.getClass()); // System.out.println("to type: "+toType); polyglot.types.Type fromType = e.type(); // System.out.println("from type: "+fromType); if (toType == null) { return e; } if (toType.isVoid()) { return e; } polyglot.util.Position p = e.position(); if (toType.equals(fromType)) { return e; } /* * double -> (int, long, float) float -> (int, long, double) long -> (int, double, float) int (byte, char, short, * boolean) -> (byte, char, short, long, double, float) ie double to short goes through int etc. */ if (toType.isPrimitive() && fromType.isPrimitive()) { polyglot.ast.Expr newExpr; // System.out.println("from type: "+fromType); // System.out.println("to type: "+toType); if (fromType.isFloat() || fromType.isLong() || fromType.isDouble()) { if (toType.isFloat() || toType.isLong() || toType.isDouble() || toType.isInt()) { newExpr = nf.Cast(p, nf.CanonicalTypeNode(p, toType), e).type(toType); } else { newExpr = nf.Cast(p, nf.CanonicalTypeNode(p, toType), nf.Cast(p, nf.CanonicalTypeNode(p, ts.Int()), e).type(ts.Int())) .type(toType); } } else { newExpr = nf.Cast(p, nf.CanonicalTypeNode(p, toType), e).type(toType); } return newExpr; } return e; } public polyglot.ast.Node leaveCall(polyglot.ast.Node old, polyglot.ast.Node n, polyglot.visit.NodeVisitor v) throws polyglot.types.SemanticException { n = super.leaveCall(old, n, v); return n; } }
2,822
31.079545
124
java
soot
soot-master/src/main/java/soot/javaToJimple/ClassDeclFinder.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import polyglot.ast.ClassDecl; public class ClassDeclFinder extends polyglot.visit.NodeVisitor { private final ArrayList<ClassDecl> declsFound; public ArrayList<ClassDecl> declsFound() { return declsFound; } public ClassDeclFinder() { declsFound = new ArrayList<ClassDecl>(); } public polyglot.visit.NodeVisitor enter(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.ClassDecl) { declsFound.add((polyglot.ast.ClassDecl) n); } return enter(n); } }
1,380
27.183673
90
java
soot
soot-master/src/main/java/soot/javaToJimple/ClassLiteralChecker.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import polyglot.ast.Node; public class ClassLiteralChecker extends polyglot.visit.NodeVisitor { private final ArrayList<Node> list; public ArrayList<Node> getList() { return list; } public ClassLiteralChecker() { list = new ArrayList<Node>(); } public polyglot.ast.Node override(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.ClassDecl) { return n; } if ((n instanceof polyglot.ast.New) && (((polyglot.ast.New) n).anonType() != null)) { return n; } return null; } public polyglot.visit.NodeVisitor enter(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.ClassLit) { polyglot.ast.ClassLit lit = (polyglot.ast.ClassLit) n; // only find ones where type is not primitive if (!lit.typeNode().type().isPrimitive()) { list.add(n); } } return enter(n); } }
1,776
27.206349
90
java
soot
soot-master/src/main/java/soot/javaToJimple/ClassLiteralMethodSource.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; public class ClassLiteralMethodSource implements soot.MethodSource { public soot.Body getBody(soot.SootMethod sootMethod, String phaseName) { soot.Body classBody = soot.jimple.Jimple.v().newBody(sootMethod); // static invoke of forName soot.jimple.ParameterRef paramRef = soot.jimple.Jimple.v().newParameterRef(soot.RefType.v("java.lang.String"), 0); soot.Local paramLocal = soot.jimple.Jimple.v().newLocal("$r0", soot.RefType.v("java.lang.String")); classBody.getLocals().add(paramLocal); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(paramLocal, paramRef); classBody.getUnits().add(stmt); ArrayList paramTypes = new ArrayList(); paramTypes.add(soot.RefType.v("java.lang.String")); soot.SootMethodRef methodToInvoke = soot.Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.Class"), "forName", paramTypes, soot.RefType.v("java.lang.Class"), true); soot.Local invokeLocal = soot.jimple.Jimple.v().newLocal("$r1", soot.RefType.v("java.lang.Class")); classBody.getLocals().add(invokeLocal); ArrayList params = new ArrayList(); params.add(paramLocal); soot.jimple.Expr invokeExpr = soot.jimple.Jimple.v().newStaticInvokeExpr(methodToInvoke, params); soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, invokeExpr); classBody.getUnits().add(assign); // return soot.jimple.Stmt retStmt = soot.jimple.Jimple.v().newReturnStmt(invokeLocal); classBody.getUnits().add(retStmt); // catch soot.Local catchRefLocal = soot.jimple.Jimple.v().newLocal("$r2", soot.RefType.v("java.lang.ClassNotFoundException")); classBody.getLocals().add(catchRefLocal); soot.jimple.CaughtExceptionRef caughtRef = soot.jimple.Jimple.v().newCaughtExceptionRef(); soot.jimple.Stmt caughtIdentity = soot.jimple.Jimple.v().newIdentityStmt(catchRefLocal, caughtRef); classBody.getUnits().add(caughtIdentity); // new no class def found error soot.Local throwLocal = soot.jimple.Jimple.v().newLocal("$r3", soot.RefType.v("java.lang.NoClassDefFoundError")); classBody.getLocals().add(throwLocal); soot.jimple.Expr newExpr = soot.jimple.Jimple.v().newNewExpr(soot.RefType.v("java.lang.NoClassDefFoundError")); soot.jimple.Stmt throwAssign = soot.jimple.Jimple.v().newAssignStmt(throwLocal, newExpr); classBody.getUnits().add(throwAssign); // get exception message soot.Local messageLocal = soot.jimple.Jimple.v().newLocal("$r4", soot.RefType.v("java.lang.String")); classBody.getLocals().add(messageLocal); // params = new ArrayList(); // params.add(catchRefLocal); soot.SootMethodRef messageMethToInvoke = soot.Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.Throwable"), "getMessage", new ArrayList(), soot.RefType.v("java.lang.String"), false); soot.jimple.Expr messageInvoke = soot.jimple.Jimple.v().newVirtualInvokeExpr(catchRefLocal, messageMethToInvoke, new ArrayList()); soot.jimple.Stmt messageAssign = soot.jimple.Jimple.v().newAssignStmt(messageLocal, messageInvoke); classBody.getUnits().add(messageAssign); // no class def found init paramTypes = new ArrayList(); paramTypes.add(soot.RefType.v("java.lang.String")); soot.SootMethodRef initMethToInvoke = soot.Scene.v().makeMethodRef( soot.Scene.v().getSootClass("java.lang.NoClassDefFoundError"), "<init>", paramTypes, soot.VoidType.v(), false); params = new ArrayList(); params.add(messageLocal); soot.jimple.Expr initInvoke = soot.jimple.Jimple.v().newSpecialInvokeExpr(throwLocal, initMethToInvoke, params); soot.jimple.Stmt initStmt = soot.jimple.Jimple.v().newInvokeStmt(initInvoke); classBody.getUnits().add(initStmt); // throw soot.jimple.Stmt throwStmt = soot.jimple.Jimple.v().newThrowStmt(throwLocal); throwStmt.addTag(new soot.tagkit.ThrowCreatedByCompilerTag()); classBody.getUnits().add(throwStmt); // trap soot.Trap trap = soot.jimple.Jimple.v().newTrap(soot.Scene.v().getSootClass("java.lang.ClassNotFoundException"), assign, retStmt, caughtIdentity); classBody.getTraps().add(trap); return classBody; } }
5,059
45.422018
125
java
soot
soot-master/src/main/java/soot/javaToJimple/ClassResolver.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import polyglot.ast.Block; import polyglot.ast.FieldDecl; import polyglot.ast.Node; import polyglot.types.Type; import polyglot.util.IdentityKey; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.options.Options; import soot.tagkit.DoubleConstantValueTag; import soot.tagkit.EnclosingTag; import soot.tagkit.FloatConstantValueTag; import soot.tagkit.IntegerConstantValueTag; import soot.tagkit.LongConstantValueTag; import soot.tagkit.QualifyingTag; import soot.tagkit.SourceFileTag; import soot.tagkit.StringConstantValueTag; import soot.tagkit.SyntheticTag; public class ClassResolver { private static final Logger logger = LoggerFactory.getLogger(ClassResolver.class); private ArrayList<FieldDecl> staticFieldInits; private ArrayList<FieldDecl> fieldInits; private ArrayList<Block> initializerBlocks; private ArrayList<Block> staticInitializerBlocks; /** * adds source file tag to each sootclass */ protected void addSourceFileTag(soot.SootClass sc) { SourceFileTag tag = (SourceFileTag) sc.getTag(SourceFileTag.NAME); if (tag == null) { tag = new SourceFileTag(); sc.addTag(tag); } String name = Util.getSourceFileOfClass(sc); if (InitialResolver.v().classToSourceMap() != null) { if (InitialResolver.v().classToSourceMap().containsKey(name)) { name = InitialResolver.v().classToSourceMap().get(name); } } // the pkg is not included in the tag for some unknown reason // I think in this case windows uses the same slash - may cause // windows problems though int slashIndex = name.lastIndexOf('/'); if (slashIndex != -1) { name = name.substring(slashIndex + 1); } tag.setSourceFile(name); // sc.addTag(new SourceFileTag(name)); } /** * Class Declaration Creation */ private void createClassDecl(polyglot.ast.ClassDecl cDecl) { // add outer class tag if neccessary (if class is not top-level) if (!cDecl.type().isTopLevel()) { SootClass outerClass = ((soot.RefType) Util.getSootType(cDecl.type().outer())).getSootClass(); if (InitialResolver.v().getInnerClassInfoMap() == null) { InitialResolver.v().setInnerClassInfoMap(new HashMap<SootClass, InnerClassInfo>()); } InitialResolver.v().getInnerClassInfoMap().put(sootClass, new InnerClassInfo(outerClass, cDecl.name(), InnerClassInfo.NESTED)); sootClass.setOuterClass(outerClass); } // modifiers polyglot.types.Flags flags = cDecl.flags(); addModifiers(flags, cDecl); // super class if (cDecl.superClass() == null) { soot.SootClass superClass = soot.Scene.v().getSootClass("java.lang.Object"); sootClass.setSuperclass(superClass); } else { sootClass.setSuperclass(((soot.RefType) Util.getSootType(cDecl.superClass().type())).getSootClass()); if (((polyglot.types.ClassType) cDecl.superClass().type()).isNested()) { polyglot.types.ClassType superType = (polyglot.types.ClassType) cDecl.superClass().type(); // add inner clas tag Util.addInnerClassTag(sootClass, sootClass.getName(), ((soot.RefType) Util.getSootType(superType.outer())).toString(), superType.name(), Util.getModifier(superType.flags())); } } // implements for (Iterator interfacesIt = cDecl.interfaces().iterator(); interfacesIt.hasNext();) { polyglot.ast.TypeNode next = (polyglot.ast.TypeNode) interfacesIt.next(); sootClass.addInterface(((soot.RefType) Util.getSootType(next.type())).getSootClass()); } findReferences(cDecl); createClassBody(cDecl.body()); // handle initialization of fields // static fields init in clinit // other fields init in init handleFieldInits(); if ((staticFieldInits != null) || (staticInitializerBlocks != null)) { soot.SootMethod clinitMethod; if (!sootClass.declaresMethod("<clinit>", new ArrayList(), soot.VoidType.v())) { clinitMethod = Scene.v().makeSootMethod("<clinit>", new ArrayList(), soot.VoidType.v(), soot.Modifier.STATIC, new ArrayList<SootClass>()); sootClass.addMethod(clinitMethod); PolyglotMethodSource mSource = new PolyglotMethodSource(); mSource.setJBB(InitialResolver.v().getJBBFactory().createJimpleBodyBuilder()); clinitMethod.setSource(mSource); } else { clinitMethod = sootClass.getMethod("<clinit>", new ArrayList(), soot.VoidType.v()); } ((PolyglotMethodSource) clinitMethod.getSource()).setStaticFieldInits(staticFieldInits); ((PolyglotMethodSource) clinitMethod.getSource()).setStaticInitializerBlocks(staticInitializerBlocks); } // add final locals to local inner classes inits if (cDecl.type().isLocal()) { AnonLocalClassInfo info = InitialResolver.v().finalLocalInfo().get(new polyglot.util.IdentityKey(cDecl.type())); ArrayList<SootField> finalsList = addFinalLocals(cDecl.body(), info.finalLocalsAvail(), cDecl.type(), info); for (soot.SootMethod meth : sootClass.getMethods()) { if (meth.getName().equals("<init>")) { ((PolyglotMethodSource) meth.getSource()).setFinalsList(finalsList); } } if (!info.inStaticMethod()) { polyglot.types.ClassType outerType = cDecl.type().outer(); addOuterClassThisRefToInit(outerType); addOuterClassThisRefField(outerType); } } // add outer class ref to constructors of inner classes // and out class field ref (only for non-static inner classes else if (cDecl.type().isNested() && !cDecl.flags().isStatic()) { polyglot.types.ClassType outerType = cDecl.type().outer(); addOuterClassThisRefToInit(outerType); addOuterClassThisRefField(outerType); } Util.addLnPosTags(sootClass, cDecl.position()); } private void findReferences(polyglot.ast.Node node) { TypeListBuilder typeListBuilder = new TypeListBuilder(); node.visit(typeListBuilder); for (Type type : typeListBuilder.getList()) { if (type.isPrimitive()) { continue; } if (!type.isClass()) { continue; } polyglot.types.ClassType classType = (polyglot.types.ClassType) type; soot.Type sootClassType = Util.getSootType(classType); references.add(sootClassType); } } /** * Class Body Creation */ private void createClassBody(polyglot.ast.ClassBody classBody) { // reinit static lists staticFieldInits = null; fieldInits = null; initializerBlocks = null; staticInitializerBlocks = null; // handle members for (Iterator it = classBody.members().iterator(); it.hasNext();) { Object next = it.next(); if (next instanceof polyglot.ast.MethodDecl) { createMethodDecl((polyglot.ast.MethodDecl) next); } else if (next instanceof polyglot.ast.FieldDecl) { createFieldDecl((polyglot.ast.FieldDecl) next); } else if (next instanceof polyglot.ast.ConstructorDecl) { createConstructorDecl((polyglot.ast.ConstructorDecl) next); } else if (next instanceof polyglot.ast.ClassDecl) { // this handles inner class tags for immediately enclosed // normal nested classes Util.addInnerClassTag(sootClass, Util.getSootType(((polyglot.ast.ClassDecl) next).type()).toString(), sootClass.getName(), ((polyglot.ast.ClassDecl) next).name().toString(), Util.getModifier(((polyglot.ast.ClassDecl) next).flags())); } else if (next instanceof polyglot.ast.Initializer) { createInitializer((polyglot.ast.Initializer) next); } else if (Options.v().verbose()) { logger.debug("Class Body Member not implemented for type " + next.getClass().getName()); } } handleInnerClassTags(classBody); handleClassLiteral(classBody); handleAssert(classBody); } private void addOuterClassThisRefField(polyglot.types.Type outerType) { soot.Type outerSootType = Util.getSootType(outerType); soot.SootField field = Scene.v().makeSootField("this$0", outerSootType, soot.Modifier.PRIVATE | soot.Modifier.FINAL); sootClass.addField(field); field.addTag(new SyntheticTag()); } private void addOuterClassThisRefToInit(polyglot.types.Type outerType) { soot.Type outerSootType = Util.getSootType(outerType); for (soot.SootMethod meth : sootClass.getMethods()) { if (meth.getName().equals("<init>")) { List<soot.Type> newParams = new ArrayList<soot.Type>(); newParams.add(outerSootType); newParams.addAll(meth.getParameterTypes()); meth.setParameterTypes(newParams); meth.addTag(new EnclosingTag()); if (InitialResolver.v().getHasOuterRefInInit() == null) { InitialResolver.v().setHasOuterRefInInit(new ArrayList()); } InitialResolver.v().getHasOuterRefInInit().add(meth.getDeclaringClass().getType()); } } } private void addFinals(polyglot.types.LocalInstance li, ArrayList<SootField> finalFields) { // add as param for init for (SootMethod meth : sootClass.getMethods()) { if (meth.getName().equals("<init>")) { List<soot.Type> newParams = new ArrayList<soot.Type>(); newParams.addAll(meth.getParameterTypes()); newParams.add(Util.getSootType(li.type())); meth.setParameterTypes(newParams); } } // add field soot.SootField sf = Scene.v().makeSootField("val$" + li.name(), Util.getSootType(li.type()), soot.Modifier.FINAL | soot.Modifier.PRIVATE); sootClass.addField(sf); finalFields.add(sf); sf.addTag(new SyntheticTag()); } private ArrayList<SootField> addFinalLocals(polyglot.ast.ClassBody cBody, ArrayList<IdentityKey> finalLocalsAvail, polyglot.types.ClassType nodeKeyType, AnonLocalClassInfo info) { ArrayList<SootField> finalFields = new ArrayList<SootField>(); LocalUsesChecker luc = new LocalUsesChecker(); cBody.visit(luc); /* Iterator localsNeededIt = luc.getLocals().iterator(); */ ArrayList<IdentityKey> localsUsed = new ArrayList<IdentityKey>(); /* * while (localsNeededIt.hasNext()){ polyglot.types.LocalInstance li = * (polyglot.types.LocalInstance)((polyglot.util.IdentityKey) localsNeededIt.next()).object(); //if * (luc.getLocalDecls().contains(new polyglot.util.IdentityKey(li))){ //} //else { //} if (finalLocalsAvail.contains(new * polyglot.util.IdentityKey(li)) && !luc.getLocalDecls().contains(new polyglot.util.IdentityKey(li))){ * * addFinals(li,finalFields); * * localsUsed.add(new polyglot.util.IdentityKey(li)); } } */ for (IdentityKey next : finalLocalsAvail) { polyglot.types.LocalInstance li = (polyglot.types.LocalInstance) next.object(); if (!luc.getLocalDecls().contains(new polyglot.util.IdentityKey(li))) { localsUsed.add(new polyglot.util.IdentityKey(li)); addFinals(li, finalFields); } } // this part is broken it adds all final locals available for the new // not just the ones used (which is a problem) for (Node next : luc.getNews()) { polyglot.ast.New tempNew = (polyglot.ast.New) next; polyglot.types.ClassType tempNewType = (polyglot.types.ClassType) tempNew.objectType().type(); if (InitialResolver.v().finalLocalInfo().containsKey(new polyglot.util.IdentityKey(tempNewType))) { AnonLocalClassInfo lInfo = InitialResolver.v().finalLocalInfo().get(new polyglot.util.IdentityKey(tempNewType)); for (Iterator<IdentityKey> it = lInfo.finalLocalsAvail().iterator(); it.hasNext();) { polyglot.types.LocalInstance li2 = (polyglot.types.LocalInstance) it.next().object(); if (!sootClass.declaresField("val$" + li2.name(), Util.getSootType(li2.type()))) { if (!luc.getLocalDecls().contains(new polyglot.util.IdentityKey(li2))) { addFinals(li2, finalFields); localsUsed.add(new polyglot.util.IdentityKey(li2)); } } } } } // also need to add them if any super class all the way up needs one // because the super() will be made in init and it will require // possibly eventually to send in the finals polyglot.types.ClassType superType = (polyglot.types.ClassType) nodeKeyType.superType(); while (!Util.getSootType(superType).equals(soot.Scene.v().getSootClass("java.lang.Object").getType())) { if (InitialResolver.v().finalLocalInfo().containsKey(new polyglot.util.IdentityKey(superType))) { AnonLocalClassInfo lInfo = InitialResolver.v().finalLocalInfo().get(new polyglot.util.IdentityKey(superType)); for (IdentityKey next : lInfo.finalLocalsAvail()) { polyglot.types.LocalInstance li2 = (polyglot.types.LocalInstance) next.object(); if (!sootClass.declaresField("val$" + li2.name(), Util.getSootType(li2.type()))) { if (!luc.getLocalDecls().contains(new polyglot.util.IdentityKey(li2))) { addFinals(li2, finalFields); localsUsed.add(new polyglot.util.IdentityKey(li2)); } } } } superType = (polyglot.types.ClassType) superType.superType(); } info.finalLocalsUsed(localsUsed); InitialResolver.v().finalLocalInfo().put(new polyglot.util.IdentityKey(nodeKeyType), info); return finalFields; } /** * creates the Jimple for an anon class - in the AST there is no class decl for anon classes - the revelant fields and * methods are created */ private void createAnonClassDecl(polyglot.ast.New aNew) { SootClass outerClass = ((soot.RefType) Util.getSootType(aNew.anonType().outer())).getSootClass(); if (InitialResolver.v().getInnerClassInfoMap() == null) { InitialResolver.v().setInnerClassInfoMap(new HashMap<SootClass, InnerClassInfo>()); } InitialResolver.v().getInnerClassInfoMap().put(sootClass, new InnerClassInfo(outerClass, "0", InnerClassInfo.ANON)); sootClass.setOuterClass(outerClass); soot.SootClass typeClass = ((soot.RefType) Util.getSootType(aNew.objectType().type())).getSootClass(); // set superclass if (((polyglot.types.ClassType) aNew.objectType().type()).flags().isInterface()) { sootClass.addInterface(typeClass); sootClass.setSuperclass(soot.Scene.v().getSootClass("java.lang.Object")); } else { sootClass.setSuperclass(typeClass); if (((polyglot.types.ClassType) aNew.objectType().type()).isNested()) { polyglot.types.ClassType superType = (polyglot.types.ClassType) aNew.objectType().type(); // add inner clas tag Util.addInnerClassTag(sootClass, typeClass.getName(), ((soot.RefType) Util.getSootType(superType.outer())).toString(), superType.name(), Util.getModifier(superType.flags())); } } // needs to be done for local also ArrayList params = new ArrayList(); soot.SootMethod method; // if interface there are no extra params if (((polyglot.types.ClassType) aNew.objectType().type()).flags().isInterface()) { method = Scene.v().makeSootMethod("<init>", params, soot.VoidType.v()); } else { if (!aNew.arguments().isEmpty()) { polyglot.types.ConstructorInstance ci = InitialResolver.v().getConstructorForAnon(aNew); for (Iterator aIt = ci.formalTypes().iterator(); aIt.hasNext();) { polyglot.types.Type pType = (polyglot.types.Type) aIt.next(); params.add(Util.getSootType(pType)); } } /* * Iterator aIt = aNew.arguments().iterator(); while (aIt.hasNext()){ polyglot.types.Type pType = * ((polyglot.ast.Expr)aIt.next()).type(); params.add(Util.getSootType(pType)); } */ method = Scene.v().makeSootMethod("<init>", params, soot.VoidType.v()); } AnonClassInitMethodSource src = new AnonClassInitMethodSource(); method.setSource(src); sootClass.addMethod(method); AnonLocalClassInfo info = InitialResolver.v().finalLocalInfo().get(new polyglot.util.IdentityKey(aNew.anonType())); if (aNew.qualifier() != null) { // && (!(aNew.qualifier() instanceof // polyglot.ast.Special && // ((polyglot.ast.Special)aNew.qualifier()).kind() // == polyglot.ast.Special.THIS)) ){ // if (aNew.qualifier() != null ) { // add qualifier ref - do this first to get right order addQualifierRefToInit(aNew.qualifier().type()); src.hasQualifier(true); } if (info != null) { src.inStaticMethod(info.inStaticMethod()); if (!info.inStaticMethod()) { if (!InitialResolver.v().isAnonInCCall(aNew.anonType())) { addOuterClassThisRefToInit(aNew.anonType().outer()); addOuterClassThisRefField(aNew.anonType().outer()); src.thisOuterType(Util.getSootType(aNew.anonType().outer())); src.hasOuterRef(true); } } } src.polyglotType((polyglot.types.ClassType) aNew.anonType().superType()); src.anonType(aNew.anonType()); if (info != null) { src.setFinalsList(addFinalLocals(aNew.body(), info.finalLocalsAvail(), aNew.anonType(), info)); } src.outerClassType(Util.getSootType(aNew.anonType().outer())); if (((polyglot.types.ClassType) aNew.objectType().type()).isNested()) { src.superOuterType(Util.getSootType(((polyglot.types.ClassType) aNew.objectType().type()).outer())); src.isSubType(Util.isSubType(aNew.anonType().outer(), ((polyglot.types.ClassType) aNew.objectType().type()).outer())); } Util.addLnPosTags(sootClass, aNew.position().line(), aNew.body().position().endLine(), aNew.position().column(), aNew.body().position().endColumn()); } public int getModifiers(polyglot.types.Flags flags) { return Util.getModifier(flags); } /** * adds modifiers */ private void addModifiers(polyglot.types.Flags flags, polyglot.ast.ClassDecl cDecl) { int modifiers = 0; if (cDecl.type().isNested()) { if (flags.isPublic() || flags.isProtected() || flags.isPrivate()) { modifiers = soot.Modifier.PUBLIC; } if (flags.isInterface()) { modifiers = modifiers | soot.Modifier.INTERFACE; } if (flags.isAbstract()) { modifiers = modifiers | soot.Modifier.ABSTRACT; } // if inner classes are declared in an interface they need to be // given public access but I have no idea why // if inner classes are declared in an interface the are // implicitly static and public (jls9.5) if (cDecl.type().outer().flags().isInterface()) { modifiers = modifiers | soot.Modifier.PUBLIC; } } else { modifiers = getModifiers(flags); } sootClass.setModifiers(modifiers); } private soot.SootClass getSpecialInterfaceAnonClass(soot.SootClass addToClass) { // check to see if there is already a special anon class for this // interface if ((InitialResolver.v().specialAnonMap() != null) && (InitialResolver.v().specialAnonMap().containsKey(addToClass))) { return InitialResolver.v().specialAnonMap().get(addToClass); } else { String specialClassName = addToClass.getName() + "$" + InitialResolver.v().getNextAnonNum(); // add class to scene and other maps and lists as needed soot.SootClass specialClass = new soot.SootClass(specialClassName); soot.Scene.v().addClass(specialClass); specialClass.setApplicationClass(); specialClass.addTag(new SyntheticTag()); specialClass.setSuperclass(soot.Scene.v().getSootClass("java.lang.Object")); Util.addInnerClassTag(addToClass, specialClass.getName(), addToClass.getName(), null, soot.Modifier.STATIC); Util.addInnerClassTag(specialClass, specialClass.getName(), addToClass.getName(), null, soot.Modifier.STATIC); InitialResolver.v().addNameToAST(specialClassName); references.add(RefType.v(specialClassName)); if (InitialResolver.v().specialAnonMap() == null) { InitialResolver.v().setSpecialAnonMap(new HashMap<SootClass, SootClass>()); } InitialResolver.v().specialAnonMap().put(addToClass, specialClass); return specialClass; } } /** * Handling for assert stmts - extra fields and methods are needed in the Jimple */ private void handleAssert(polyglot.ast.ClassBody cBody) { // find any asserts in class body but not in inner class bodies AssertStmtChecker asc = new AssertStmtChecker(); cBody.visit(asc); if (!asc.isHasAssert()) { return; } // two extra fields // $assertionsDisabled field is added to the actual class where the // assert is found (even if its an inner class - interfaces cannot // have asserts stmts directly contained within them) String fieldName = "$assertionsDisabled"; soot.Type fieldType = soot.BooleanType.v(); if (!sootClass.declaresField(fieldName, fieldType)) { soot.SootField assertionsDisabledField = Scene.v().makeSootField(fieldName, fieldType, soot.Modifier.STATIC | soot.Modifier.FINAL); sootClass.addField(assertionsDisabledField); assertionsDisabledField.addTag(new SyntheticTag()); } // class$ field is added to the outer most class if sootClass // containing the assert is inner - if the outer most class is // an interface - add instead to special interface anon class soot.SootClass addToClass = sootClass; while ((InitialResolver.v().getInnerClassInfoMap() != null) && (InitialResolver.v().getInnerClassInfoMap().containsKey(addToClass))) { addToClass = InitialResolver.v().getInnerClassInfoMap().get(addToClass).getOuterClass(); } // this field is named after the outer class even if the outer // class is an interface and will be actually added to the // special interface anon class fieldName = "class$" + addToClass.getName().replaceAll(".", "$"); if ((InitialResolver.v().getInterfacesList() != null) && (InitialResolver.v().getInterfacesList().contains(addToClass.getName()))) { addToClass = getSpecialInterfaceAnonClass(addToClass); } fieldType = soot.RefType.v("java.lang.Class"); if (!addToClass.declaresField(fieldName, fieldType)) { soot.SootField classField = Scene.v().makeSootField(fieldName, fieldType, soot.Modifier.STATIC); addToClass.addField(classField); classField.addTag(new SyntheticTag()); } // two extra methods // class$ method is added to the outer most class if sootClass // containing the assert is inner - if the outer most class is // an interface - add instead to special interface anon class String methodName = "class$"; soot.Type methodRetType = soot.RefType.v("java.lang.Class"); ArrayList paramTypes = new ArrayList(); paramTypes.add(soot.RefType.v("java.lang.String")); // make meth soot.SootMethod sootMethod = Scene.v().makeSootMethod(methodName, paramTypes, methodRetType, soot.Modifier.STATIC); AssertClassMethodSource assertMSrc = new AssertClassMethodSource(); sootMethod.setSource(assertMSrc); if (!addToClass.declaresMethod(methodName, paramTypes, methodRetType)) { addToClass.addMethod(sootMethod); sootMethod.addTag(new SyntheticTag()); } // clinit method is added to actual class where assert is found // if the class already has a clinit method its method source is // informed of an assert methodName = "<clinit>"; methodRetType = soot.VoidType.v(); paramTypes = new ArrayList(); // make meth sootMethod = Scene.v().makeSootMethod(methodName, paramTypes, methodRetType, soot.Modifier.STATIC); PolyglotMethodSource mSrc = new PolyglotMethodSource(); mSrc.setJBB(InitialResolver.v().getJBBFactory().createJimpleBodyBuilder()); mSrc.hasAssert(true); sootMethod.setSource(mSrc); if (!sootClass.declaresMethod(methodName, paramTypes, methodRetType)) { sootClass.addMethod(sootMethod); } else { ((soot.javaToJimple.PolyglotMethodSource) sootClass.getMethod(methodName, paramTypes, methodRetType).getSource()) .hasAssert(true); } } /** * Constructor Declaration Creation */ private void createConstructorDecl(polyglot.ast.ConstructorDecl constructor) { String name = "<init>"; ArrayList parameters = createParameters(constructor); ArrayList<SootClass> exceptions = createExceptions(constructor); soot.SootMethod sootMethod = createSootConstructor(name, constructor.flags(), parameters, exceptions); finishProcedure(constructor, sootMethod); } /** * Method Declaration Creation */ private void createMethodDecl(polyglot.ast.MethodDecl method) { String name = createName(method); // parameters ArrayList parameters = createParameters(method); // exceptions ArrayList<SootClass> exceptions = createExceptions(method); soot.SootMethod sootMethod = createSootMethod(name, method.flags(), method.returnType().type(), parameters, exceptions); finishProcedure(method, sootMethod); } /** * looks after pos tags for methods and constructors */ private void finishProcedure(polyglot.ast.ProcedureDecl procedure, soot.SootMethod sootMethod) { addProcedureToClass(sootMethod); if (procedure.position() != null) { Util.addLnPosTags(sootMethod, procedure.position()); } PolyglotMethodSource mSrc = new PolyglotMethodSource(procedure.body(), procedure.formals()); mSrc.setJBB(InitialResolver.v().getJBBFactory().createJimpleBodyBuilder()); sootMethod.setSource(mSrc); } private void handleFieldInits() { if ((fieldInits != null) || (initializerBlocks != null)) { for (soot.SootMethod next : sootClass.getMethods()) { if (next.getName().equals("<init>")) { soot.javaToJimple.PolyglotMethodSource src = (soot.javaToJimple.PolyglotMethodSource) next.getSource(); src.setInitializerBlocks(initializerBlocks); src.setFieldInits(fieldInits); } } } } private void handleClassLiteral(polyglot.ast.ClassBody cBody) { // check for class lits whose type is not primitive ClassLiteralChecker classLitChecker = new ClassLiteralChecker(); cBody.visit(classLitChecker); ArrayList<Node> classLitList = classLitChecker.getList(); if (!classLitList.isEmpty()) { soot.SootClass addToClass = sootClass; if (addToClass.isInterface()) { addToClass = getSpecialInterfaceAnonClass(addToClass); } // add class$ meth String methodName = "class$"; soot.Type methodRetType = soot.RefType.v("java.lang.Class"); ArrayList paramTypes = new ArrayList(); paramTypes.add(soot.RefType.v("java.lang.String")); soot.SootMethod sootMethod = Scene.v().makeSootMethod(methodName, paramTypes, methodRetType, soot.Modifier.STATIC); ClassLiteralMethodSource mSrc = new ClassLiteralMethodSource(); sootMethod.setSource(mSrc); if (!addToClass.declaresMethod(methodName, paramTypes, methodRetType)) { addToClass.addMethod(sootMethod); sootMethod.addTag(new SyntheticTag()); } // add fields for all non prim class lits for (Iterator<Node> classLitIt = classLitList.iterator(); classLitIt.hasNext();) { polyglot.ast.ClassLit classLit = (polyglot.ast.ClassLit) classLitIt.next(); // field String fieldName = Util.getFieldNameForClassLit(classLit.typeNode().type()); soot.Type fieldType = soot.RefType.v("java.lang.Class"); soot.SootField sootField = Scene.v().makeSootField(fieldName, fieldType, soot.Modifier.STATIC); if (!addToClass.declaresField(fieldName, fieldType)) { addToClass.addField(sootField); sootField.addTag(new SyntheticTag()); } } } } /** * Source Creation */ protected void createSource(polyglot.ast.SourceFile source) { // add absolute path to sourceFileTag SourceFileTag t = (SourceFileTag) sootClass.getTag(SourceFileTag.NAME); if (t != null) { /* * System.out.println("source: "+source); System.out.println("source.source(): "+source.source()); System.out.println( * "source path: "+source.source().path()); System.out.println("source name: "+source.source().name()); */ t.setAbsolutePath(source.source().path()); } else { t = new SourceFileTag(); /* * System.out.println("source: "+source); System.out.println("source.source(): "+source.source()); System.out.println( * "source path: "+source.source().path()); System.out.println("source name: "+source.source().name()); */ t.setAbsolutePath(source.source().path()); sootClass.addTag(t); } String simpleName = sootClass.getName(); boolean found = false; // first look in top-level decls for (Iterator declsIt = source.decls().iterator(); declsIt.hasNext();) { Object next = declsIt.next(); if (next instanceof polyglot.ast.ClassDecl) { polyglot.types.ClassType nextType = ((polyglot.ast.ClassDecl) next).type(); if (Util.getSootType(nextType).equals(sootClass.getType())) { createClassDecl((polyglot.ast.ClassDecl) next); found = true; } } } // if the class wasn't a top level then its nested, local or anon if (!found) { NestedClassListBuilder nestedClassBuilder = new NestedClassListBuilder(); source.visit(nestedClassBuilder); Iterator<Node> nestedDeclsIt = nestedClassBuilder.getClassDeclsList().iterator(); while (nestedDeclsIt.hasNext() && !found) { polyglot.ast.ClassDecl nextDecl = (polyglot.ast.ClassDecl) nestedDeclsIt.next(); polyglot.types.ClassType type = nextDecl.type(); if (type.isLocal() && !type.isAnonymous()) { if (InitialResolver.v().getLocalClassMap().containsVal(simpleName)) { createClassDecl( ((polyglot.ast.LocalClassDecl) InitialResolver.v().getLocalClassMap().getKey(simpleName)).decl()); found = true; } } else { if (Util.getSootType(type).equals(sootClass.getType())) { createClassDecl(nextDecl); found = true; } } } if (!found) { // assume its anon class (only option left) // if ((InitialResolver.v().getAnonClassMap() != null) && InitialResolver.v().getAnonClassMap().containsVal(simpleName)) { polyglot.ast.New aNew = (polyglot.ast.New) InitialResolver.v().getAnonClassMap().getKey(simpleName); if (aNew == null) { throw new RuntimeException("Could resolve class: " + simpleName); } createAnonClassDecl(aNew); findReferences(aNew.body()); createClassBody(aNew.body()); handleFieldInits(); } else { // could be an anon class that was created out of thin air // for handling class lits (and asserts) in interfaces // this is now done on creation of this special class // sootClass.setSuperclass(soot.Scene.v().getSootClass("java.lang.Object")); } } } } private void handleInnerClassTags(polyglot.ast.ClassBody classBody) { // if this class is an inner class add self if ((InitialResolver.v().getInnerClassInfoMap() != null) && (InitialResolver.v().getInnerClassInfoMap().containsKey(sootClass))) { // hasTag(OuterClassTag.NAME)){ InnerClassInfo tag = InitialResolver.v().getInnerClassInfoMap().get(sootClass); Util.addInnerClassTag(sootClass, sootClass.getName(), tag.getInnerType() == InnerClassInfo.ANON ? null : tag.getOuterClass().getName(), tag.getInnerType() == InnerClassInfo.ANON ? null : tag.getSimpleName(), soot.Modifier.isInterface(tag.getOuterClass().getModifiers()) ? soot.Modifier.STATIC | soot.Modifier.PUBLIC : sootClass.getModifiers()); // if this class is an inner class and enclosing class is also // an inner class add enclsing class SootClass outerClass = tag.getOuterClass(); while (InitialResolver.v().getInnerClassInfoMap().containsKey(outerClass)) { InnerClassInfo tag2 = InitialResolver.v().getInnerClassInfoMap().get(outerClass); Util.addInnerClassTag(sootClass, outerClass.getName(), tag2.getInnerType() == InnerClassInfo.ANON ? null : tag2.getOuterClass().getName(), tag2.getInnerType() == InnerClassInfo.ANON ? null : tag2.getSimpleName(), tag2.getInnerType() == InnerClassInfo.ANON && soot.Modifier.isInterface(tag2.getOuterClass().getModifiers()) ? soot.Modifier.STATIC | soot.Modifier.PUBLIC : outerClass.getModifiers()); outerClass = tag2.getOuterClass(); } } } private void addQualifierRefToInit(polyglot.types.Type type) { soot.Type sootType = Util.getSootType(type); for (soot.SootMethod meth : sootClass.getMethods()) { if (meth.getName().equals("<init>")) { List<soot.Type> newParams = new ArrayList<soot.Type>(); newParams.add(sootType); newParams.addAll(meth.getParameterTypes()); meth.setParameterTypes(newParams); meth.addTag(new QualifyingTag()); } } } private void addProcedureToClass(soot.SootMethod method) { sootClass.addMethod(method); } private void addConstValTag(polyglot.ast.FieldDecl field, soot.SootField sootField) { // logger.debug("adding constantval tag to field: "+field); if (field.fieldInstance().constantValue() instanceof Integer) { sootField.addTag(new IntegerConstantValueTag(((Integer) field.fieldInstance().constantValue()))); } else if (field.fieldInstance().constantValue() instanceof Character) { sootField.addTag(new IntegerConstantValueTag(((Character) field.fieldInstance().constantValue()))); } else if (field.fieldInstance().constantValue() instanceof Short) { sootField.addTag(new IntegerConstantValueTag(((Short) field.fieldInstance().constantValue()))); } else if (field.fieldInstance().constantValue() instanceof Byte) { sootField.addTag(new IntegerConstantValueTag(((Byte) field.fieldInstance().constantValue()))); } else if (field.fieldInstance().constantValue() instanceof Boolean) { boolean b = ((Boolean) field.fieldInstance().constantValue()); sootField.addTag(new IntegerConstantValueTag(b ? 1 : 0)); } else if (field.fieldInstance().constantValue() instanceof Long) { sootField.addTag(new LongConstantValueTag(((Long) field.fieldInstance().constantValue()))); } else if (field.fieldInstance().constantValue() instanceof Double) { // System.out.println("const val: // "+field.fieldInstance().constantValue()); sootField.addTag(new DoubleConstantValueTag((long) ((Double) field.fieldInstance().constantValue()).doubleValue())); // System.out.println(((Double)field.fieldInstance().constantValue()).doubleValue()); DoubleConstantValueTag tag = (DoubleConstantValueTag) sootField.getTag(DoubleConstantValueTag.NAME); // System.out.println("tag: "+tag); } else if (field.fieldInstance().constantValue() instanceof Float) { sootField.addTag(new FloatConstantValueTag(((Float) field.fieldInstance().constantValue()))); } else if (field.fieldInstance().constantValue() instanceof String) { sootField.addTag(new StringConstantValueTag((String) field.fieldInstance().constantValue())); } else { throw new RuntimeException("Expecting static final field to have a constant value! For field: " + field + " of type: " + field.fieldInstance().constantValue().getClass()); } } /** * Field Declaration Creation */ private void createFieldDecl(polyglot.ast.FieldDecl field) { // System.out.println("field decl: "+field); int modifiers = Util.getModifier(field.fieldInstance().flags()); String name = field.fieldInstance().name(); soot.Type sootType = Util.getSootType(field.fieldInstance().type()); soot.SootField sootField = Scene.v().makeSootField(name, sootType, modifiers); sootClass.addField(sootField); if (field.fieldInstance().flags().isStatic()) { if (field.init() != null) { if (field.flags().isFinal() && (field.type().type().isPrimitive() || (field.type().type().toString().equals("java.lang.String"))) && field.fieldInstance().isConstant()) { // System.out.println("adding constantValtag: to field: // "+sootField); addConstValTag(field, sootField); } else { if (staticFieldInits == null) { staticFieldInits = new ArrayList<FieldDecl>(); } staticFieldInits.add(field); } } } else { if (field.init() != null) { if (fieldInits == null) { fieldInits = new ArrayList<FieldDecl>(); } fieldInits.add(field); } } Util.addLnPosTags(sootField, field.position()); } public ClassResolver(SootClass sootClass, Set<soot.Type> set) { this.sootClass = sootClass; this.references = set; } private final SootClass sootClass; private final Collection<soot.Type> references; /** * Procedure Declaration Helper Methods creates procedure name */ private String createName(polyglot.ast.ProcedureDecl procedure) { return procedure.name(); } /** * creates soot params from polyglot formals */ private ArrayList createParameters(polyglot.ast.ProcedureDecl procedure) { ArrayList parameters = new ArrayList(); for (Iterator formalsIt = procedure.formals().iterator(); formalsIt.hasNext();) { polyglot.ast.Formal next = (polyglot.ast.Formal) formalsIt.next(); parameters.add(Util.getSootType(next.type().type())); } return parameters; } /** * creates soot exceptions from polyglot throws */ private ArrayList<SootClass> createExceptions(polyglot.ast.ProcedureDecl procedure) { ArrayList<SootClass> exceptions = new ArrayList<SootClass>(); for (Iterator throwsIt = procedure.throwTypes().iterator(); throwsIt.hasNext();) { polyglot.types.Type throwType = ((polyglot.ast.TypeNode) throwsIt.next()).type(); exceptions.add(((soot.RefType) Util.getSootType(throwType)).getSootClass()); } return exceptions; } private soot.SootMethod createSootMethod(String name, polyglot.types.Flags flags, polyglot.types.Type returnType, ArrayList parameters, ArrayList<SootClass> exceptions) { int modifier = Util.getModifier(flags); soot.Type sootReturnType = Util.getSootType(returnType); return Scene.v().makeSootMethod(name, parameters, sootReturnType, modifier, exceptions); } /** * Initializer Creation */ private void createInitializer(polyglot.ast.Initializer initializer) { if (initializer.flags().isStatic()) { if (staticInitializerBlocks == null) { staticInitializerBlocks = new ArrayList<Block>(); } staticInitializerBlocks.add(initializer.body()); } else { if (initializerBlocks == null) { initializerBlocks = new ArrayList<Block>(); } initializerBlocks.add(initializer.body()); } } private soot.SootMethod createSootConstructor(String name, polyglot.types.Flags flags, ArrayList parameters, ArrayList<SootClass> exceptions) { int modifier = Util.getModifier(flags); return Scene.v().makeSootMethod(name, parameters, soot.VoidType.v(), modifier, exceptions); } }
40,670
40.123357
124
java
soot
soot-master/src/main/java/soot/javaToJimple/CommaJBB.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class CommaJBB extends AbstractJimpleBodyBuilder { public CommaJBB() { // ext(null); // base(this); } /* * protected soot.Value createExpr(polyglot.ast.Expr expr){ if (expr instanceof soot.javaToJimple.jj.ast.JjComma_c){ return * getCommaLocal((soot.javaToJimple.jj.ast.JjComma_c)expr); } else { return ext().createExpr(expr); } } */ protected soot.Value createAggressiveExpr(polyglot.ast.Expr expr, boolean redAggr, boolean revIfNec) { if (expr instanceof soot.javaToJimple.jj.ast.JjComma_c) { return getCommaLocal((soot.javaToJimple.jj.ast.JjComma_c) expr); } else { return ext().createAggressiveExpr(expr, redAggr, revIfNec); } } private soot.Value getCommaLocal(soot.javaToJimple.jj.ast.JjComma_c comma) { base().createAggressiveExpr(comma.first(), false, false); soot.Value val = base().createAggressiveExpr(comma.second(), false, false); return val; } }
1,767
33
125
java
soot
soot-master/src/main/java/soot/javaToJimple/DefaultLocalGenerator.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashSet; import java.util.Set; import java.util.function.Supplier; import soot.Body; import soot.BooleanType; import soot.ByteType; import soot.CharType; import soot.DoubleType; import soot.FloatType; import soot.IntType; import soot.Local; import soot.LocalGenerator; import soot.LongType; import soot.RefLikeType; import soot.ShortType; import soot.Type; import soot.UnknownType; import soot.VoidType; import soot.jimple.Jimple; import soot.jimple.toolkits.typing.fast.Integer127Type; import soot.jimple.toolkits.typing.fast.Integer1Type; import soot.jimple.toolkits.typing.fast.Integer32767Type; import soot.util.Chain; public class DefaultLocalGenerator extends LocalGenerator { protected final Chain<Local> locals; protected Set<String> names; protected long expectedModCount; private int tempInt = -1; private int tempVoid = -1; private int tempBoolean = -1; private int tempLong = -1; private int tempDouble = -1; private int tempFloat = -1; private int tempRefLikeType = -1; private int tempByte = -1; private int tempShort = -1; private int tempChar = -1; private int tempUnknownType = -1; public DefaultLocalGenerator(Body b) { this.locals = b.getLocals(); this.names = null; this.expectedModCount = -1;// init with invalid mod count } public Local generateLocal(Type type) { Supplier<String> nameGen; if (type instanceof IntType || type instanceof Integer1Type || type instanceof Integer127Type || type instanceof Integer32767Type) { nameGen = this::nextIntName; } else if (type instanceof ByteType) { nameGen = this::nextByteName; } else if (type instanceof ShortType) { nameGen = this::nextShortName; } else if (type instanceof BooleanType) { nameGen = this::nextBooleanName; } else if (type instanceof VoidType) { nameGen = this::nextVoidName; } else if (type instanceof CharType) { nameGen = this::nextCharName; } else if (type instanceof DoubleType) { nameGen = this::nextDoubleName; } else if (type instanceof FloatType) { nameGen = this::nextFloatName; } else if (type instanceof LongType) { nameGen = this::nextLongName; } else if (type instanceof RefLikeType) { nameGen = this::nextRefLikeTypeName; } else if (type instanceof UnknownType) { nameGen = this::nextUnknownTypeName; } else { throw new RuntimeException( String.format("Unhandled Type %s of Local variable to Generate - Not Implemented", type.getClass().getName())); } // Ensure the 'names' set is up to date with the local chain. Set<String> localNames = this.names; { Chain<Local> locs = this.locals; long modCount = locs.getModificationCount(); if (this.expectedModCount != modCount) { this.expectedModCount = modCount; this.names = localNames = new HashSet<>(locs.size()); for (Local l : locs) { localNames.add(l.getName()); } } assert (localNames != null); } String name; do { name = nameGen.get(); } while (localNames.contains(name)); return createLocal(name, type); } private String nextIntName() { return "$i" + (++tempInt); } private String nextCharName() { return "$c" + (++tempChar); } private String nextVoidName() { return "$v" + (++tempVoid); } private String nextByteName() { return "$b" + (++tempByte); } private String nextShortName() { return "$s" + (++tempShort); } private String nextBooleanName() { return "$z" + (++tempBoolean); } private String nextDoubleName() { return "$d" + (++tempDouble); } private String nextFloatName() { return "$f" + (++tempFloat); } private String nextLongName() { return "$l" + (++tempLong); } private String nextRefLikeTypeName() { return "$r" + (++tempRefLikeType); } private String nextUnknownTypeName() { return "$u" + (++tempUnknownType); } // this should be used for generated locals only protected Local createLocal(String name, Type sootType) { assert (expectedModCount == locals.getModificationCount());// pre-condition assert (!names.contains(name));// pre-condition Local sootLocal = Jimple.v().newLocal(name, sootType); locals.add(sootLocal); expectedModCount++; names.add(name); assert (expectedModCount == locals.getModificationCount());// post-condition assert (names.contains(name));// post-condition return sootLocal; } }
5,371
27.727273
121
java
soot
soot-master/src/main/java/soot/javaToJimple/IInitialResolver.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2008 Eric Bodden * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashSet; import java.util.List; import java.util.Set; import soot.SootClass; import soot.Type; public interface IInitialResolver { public void formAst(String fullPath, List<String> locations, String className); public Dependencies resolveFromJavaFile(SootClass sc); public class Dependencies { public final Set<Type> typesToHierarchy, typesToSignature; public Dependencies() { typesToHierarchy = new HashSet<>(); typesToSignature = new HashSet<>(); } public Dependencies(Set<Type> typesToHierarchy, Set<Type> typesToSignature) { this.typesToHierarchy = typesToHierarchy == null ? new HashSet<>() : typesToHierarchy; this.typesToSignature = typesToSignature == null ? new HashSet<>() : typesToSignature; } } }
1,609
29.961538
92
java
soot
soot-master/src/main/java/soot/javaToJimple/InitialResolver.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import polyglot.ast.ClassDecl; import polyglot.ast.New; import polyglot.ast.Node; import polyglot.types.ConstructorInstance; import polyglot.util.IdentityKey; import soot.FastHierarchy; import soot.SootClass; import soot.SootMethod; public class InitialResolver implements IInitialResolver { private polyglot.ast.Node astNode; // source node private polyglot.frontend.Compiler compiler; private BiMap anonClassMap; // maps New to SootClass (name) private HashMap<IdentityKey, String> anonTypeMap; // maps polyglot types to soot types private BiMap localClassMap; // maps LocalClassDecl to SootClass (name) private HashMap<IdentityKey, String> localTypeMap; // maps polyglot types to soot types private int privateAccessCounter = 0; // global for whole program because // the methods created are static private HashMap<IdentityKey, AnonLocalClassInfo> finalLocalInfo; // new or lcd mapped to list of final locals avail in // current meth and the whether // its static private HashMap<String, Node> sootNameToAST = null; private ArrayList hasOuterRefInInit; // list of sootclass types that need an outer class this param in for init private HashMap<String, String> classToSourceMap; private HashMap<SootClass, SootClass> specialAnonMap; private HashMap<IdentityKey, SootMethod> privateFieldGetAccessMap; private HashMap<IdentityKey, SootMethod> privateFieldSetAccessMap; private HashMap<IdentityKey, SootMethod> privateMethodGetAccessMap; private ArrayList<String> interfacesList; private ArrayList<Node> cCallList; private HashMap<New, ConstructorInstance> anonConstructorMap; public void addToAnonConstructorMap(polyglot.ast.New anonNew, polyglot.types.ConstructorInstance ci) { if (anonConstructorMap == null) { anonConstructorMap = new HashMap<New, ConstructorInstance>(); } anonConstructorMap.put(anonNew, ci); } public polyglot.types.ConstructorInstance getConstructorForAnon(polyglot.ast.New anonNew) { if (anonConstructorMap == null) { return null; } return anonConstructorMap.get(anonNew); } private FastHierarchy hierarchy; private AbstractJBBFactory jbbFactory = new JimpleBodyBuilderFactory(); public void setJBBFactory(AbstractJBBFactory jbbFactory) { this.jbbFactory = jbbFactory; } public AbstractJBBFactory getJBBFactory() { return jbbFactory; } /** * returns true if there is an AST avail for given soot class */ public boolean hasASTForSootName(String name) { if (sootNameToAST == null) { return false; } if (sootNameToAST.containsKey(name)) { return true; } return false; } /** * sets AST for given soot class if possible */ public void setASTForSootName(String name) { if (!hasASTForSootName(name)) { throw new RuntimeException("Can only set AST for name if it exists." + "You should probably not be calling this method unless you know what you're doing!"); } setAst(sootNameToAST.get(name)); } public InitialResolver(soot.Singletons.Global g) { } public static InitialResolver v() { return soot.G.v().soot_javaToJimple_InitialResolver(); } /** * Invokes polyglot and gets the AST for the source given in fullPath */ public void formAst(String fullPath, List<String> locations, String className) { JavaToJimple jtj = new JavaToJimple(); polyglot.frontend.ExtensionInfo extInfo = jtj.initExtInfo(fullPath, locations); // only have one compiler - for memory issues if (compiler == null) { compiler = new polyglot.frontend.Compiler(extInfo); } // build ast astNode = jtj.compile(compiler, fullPath, extInfo); resolveAST(); } /** * if you have a special AST set it here then call resolveFormJavaFile on the soot class */ public void setAst(polyglot.ast.Node ast) { astNode = ast; } /* * March 2nd, 2006 Nomair Is it okkay get the ast and send it to the ASTMetrics package???? */ public polyglot.ast.Node getAst() { return astNode; } private void makeASTMap() { ClassDeclFinder finder = new ClassDeclFinder(); astNode.visit(finder); Iterator<ClassDecl> it = finder.declsFound().iterator(); while (it.hasNext()) { polyglot.ast.ClassDecl decl = it.next(); polyglot.types.ClassType type = decl.type(); if (type.flags().isInterface()) { if (interfacesList == null) { interfacesList = new ArrayList<String>(); } interfacesList.add(Util.getSootType(type).toString()); } addNameToAST(Util.getSootType(type).toString()); } } /** * add name to AST to map - used mostly for inner and non public top-level classes */ protected void addNameToAST(String name) { if (sootNameToAST == null) { sootNameToAST = new HashMap<String, Node>(); } sootNameToAST.put(name, astNode); } public void resolveAST() { buildInnerClassInfo(); if (astNode instanceof polyglot.ast.SourceFile) { createClassToSourceMap((polyglot.ast.SourceFile) astNode); } } // resolves all types and deals with .class literals and asserts public Dependencies resolveFromJavaFile(soot.SootClass sc) { Dependencies dependencies = new Dependencies(); // conservatively load all to signatures ClassResolver cr = new ClassResolver(sc, dependencies.typesToSignature); // create class to source map first // create source file if (astNode instanceof polyglot.ast.SourceFile) { cr.createSource((polyglot.ast.SourceFile) astNode); } cr.addSourceFileTag(sc); makeASTMap(); return dependencies; } private void createClassToSourceMap(polyglot.ast.SourceFile src) { String srcName = src.source().path(); String srcFileName = null; if (src.package_() != null) { String slashedPkg = src.package_().package_().fullName().replaceAll(".", System.getProperty("file.separator")); srcFileName = srcName.substring(srcName.lastIndexOf(slashedPkg)); } else { srcFileName = srcName.substring(srcName.lastIndexOf(System.getProperty("file.separator")) + 1); } ArrayList list = new ArrayList(); Iterator it = src.decls().iterator(); while (it.hasNext()) { polyglot.ast.ClassDecl nextDecl = (polyglot.ast.ClassDecl) it.next(); addToClassToSourceMap(Util.getSootType(nextDecl.type()).toString(), srcFileName); } } private void createLocalAndAnonClassNames(ArrayList<Node> anonBodyList, ArrayList<Node> localClassDeclList) { Iterator<Node> anonBodyIt = anonBodyList.iterator(); while (anonBodyIt.hasNext()) { createAnonClassName((polyglot.ast.New) anonBodyIt.next()); } Iterator<Node> localClassDeclIt = localClassDeclList.iterator(); while (localClassDeclIt.hasNext()) { createLocalClassName((polyglot.ast.LocalClassDecl) localClassDeclIt.next()); } } protected int getNextAnonNum() { if (anonTypeMap == null) { return 1; } else { return anonTypeMap.size() + 1; } } private void createAnonClassName(polyglot.ast.New nextNew) { // maybe this anon has already been resolved if (anonClassMap == null) { anonClassMap = new BiMap(); } if (anonTypeMap == null) { anonTypeMap = new HashMap<IdentityKey, String>(); } if (!anonClassMap.containsKey(nextNew)) { int nextAvailNum = 1; polyglot.types.ClassType outerToMatch = nextNew.anonType().outer(); while (outerToMatch.isNested()) { outerToMatch = outerToMatch.outer(); } if (!anonTypeMap.isEmpty()) { Iterator<IdentityKey> matchIt = anonTypeMap.keySet().iterator(); while (matchIt.hasNext()) { polyglot.types.ClassType pType = (polyglot.types.ClassType) matchIt.next().object(); polyglot.types.ClassType outerMatch = pType.outer(); while (outerMatch.isNested()) { outerMatch = outerMatch.outer(); } if (outerMatch.equals(outerToMatch)) { int numFound = getAnonClassNum(anonTypeMap.get(new polyglot.util.IdentityKey(pType))); if (numFound >= nextAvailNum) { nextAvailNum = numFound + 1; } } } } String realName = outerToMatch.fullName() + "$" + nextAvailNum; anonClassMap.put(nextNew, realName); anonTypeMap.put(new polyglot.util.IdentityKey(nextNew.anonType()), realName); addNameToAST(realName); } } private void createLocalClassName(polyglot.ast.LocalClassDecl lcd) { // maybe this localdecl has already been resolved if (localClassMap == null) { localClassMap = new BiMap(); } if (localTypeMap == null) { localTypeMap = new HashMap<IdentityKey, String>(); } if (!localClassMap.containsKey(lcd)) { int nextAvailNum = 1; polyglot.types.ClassType outerToMatch = lcd.decl().type().outer(); while (outerToMatch.isNested()) { outerToMatch = outerToMatch.outer(); } if (!localTypeMap.isEmpty()) { Iterator<IdentityKey> matchIt = localTypeMap.keySet().iterator(); while (matchIt.hasNext()) { polyglot.types.ClassType pType = (polyglot.types.ClassType) matchIt.next().object(); polyglot.types.ClassType outerMatch = pType.outer(); while (outerMatch.isNested()) { outerMatch = outerMatch.outer(); } if (outerMatch.equals(outerToMatch)) { int numFound = getLocalClassNum(localTypeMap.get(new polyglot.util.IdentityKey(pType)), lcd.decl().name()); if (numFound >= nextAvailNum) { nextAvailNum = numFound + 1; } } } } String realName = outerToMatch.fullName() + "$" + nextAvailNum + lcd.decl().name(); localClassMap.put(lcd, realName); localTypeMap.put(new polyglot.util.IdentityKey(lcd.decl().type()), realName); addNameToAST(realName); } } private static final int NO_MATCH = 0; private int getLocalClassNum(String realName, String simpleName) { // a local inner class is named outer$NsimpleName where outer // is the very outer most class int dIndex = realName.indexOf("$"); int nIndex = realName.indexOf(simpleName, dIndex); if (nIndex == -1) { return NO_MATCH; } if (dIndex == -1) { throw new RuntimeException("Matching an incorrectly named local inner class: " + realName); } String numString = realName.substring(dIndex + 1, nIndex); for (int i = 0; i < numString.length(); i++) { if (!Character.isDigit(numString.charAt(i))) { return NO_MATCH; } } return (new Integer(numString)).intValue(); } private int getAnonClassNum(String realName) { // a anon inner class is named outer$N where outer // is the very outer most class int dIndex = realName.indexOf("$"); if (dIndex == -1) { throw new RuntimeException("Matching an incorrectly named anon inner class: " + realName); } return (new Integer(realName.substring(dIndex + 1))).intValue(); } /** * ClassToSourceMap is for classes whos names don't match the source file name - ex: multiple top level classes in a single * file */ private void addToClassToSourceMap(String className, String sourceName) { if (classToSourceMap == null) { classToSourceMap = new HashMap<String, String>(); } classToSourceMap.put(className, sourceName); } public boolean hasClassInnerTag(soot.SootClass sc, String innerName) { Iterator it = sc.getTags().iterator(); while (it.hasNext()) { soot.tagkit.Tag t = (soot.tagkit.Tag) it.next(); if (t instanceof soot.tagkit.InnerClassTag) { soot.tagkit.InnerClassTag tag = (soot.tagkit.InnerClassTag) t; if (tag.getInnerClass().equals(innerName)) { return true; } } } return false; } private void buildInnerClassInfo() { InnerClassInfoFinder icif = new InnerClassInfoFinder(); astNode.visit(icif); createLocalAndAnonClassNames(icif.anonBodyList(), icif.localClassDeclList()); buildFinalLocalMap(icif.memberList()); } private void buildFinalLocalMap(ArrayList<Node> memberList) { Iterator<Node> it = memberList.iterator(); while (it.hasNext()) { handleFinalLocals((polyglot.ast.ClassMember) it.next()); } } private void handleFinalLocals(polyglot.ast.ClassMember member) { MethodFinalsChecker mfc = new MethodFinalsChecker(); member.visit(mfc); // System.out.println("member: "+member); // System.out.println("mcf final locals avail: "+mfc.finalLocals()); // System.out.println("mcf locals used: "+mfc.typeToLocalsUsed()); // System.out.println("mfc inners: "+mfc.inners()); if (cCallList == null) { cCallList = new ArrayList<Node>(); } cCallList.addAll(mfc.ccallList()); // System.out.println("cCallList: "+cCallList); AnonLocalClassInfo alci = new AnonLocalClassInfo(); if (member instanceof polyglot.ast.ProcedureDecl) { polyglot.ast.ProcedureDecl procedure = (polyglot.ast.ProcedureDecl) member; // not sure if this will break deep nesting alci.finalLocalsAvail(mfc.finalLocals()); if (procedure.flags().isStatic()) { alci.inStaticMethod(true); } } else if (member instanceof polyglot.ast.FieldDecl) { alci.finalLocalsAvail(new ArrayList<IdentityKey>()); if (((polyglot.ast.FieldDecl) member).flags().isStatic()) { alci.inStaticMethod(true); } } else if (member instanceof polyglot.ast.Initializer) { // for now don't make final locals avail in init blocks // need to test this alci.finalLocalsAvail(mfc.finalLocals()); if (((polyglot.ast.Initializer) member).flags().isStatic()) { alci.inStaticMethod(true); } } if (finalLocalInfo == null) { finalLocalInfo = new HashMap<IdentityKey, AnonLocalClassInfo>(); } Iterator<IdentityKey> it = mfc.inners().iterator(); while (it.hasNext()) { polyglot.types.ClassType cType = (polyglot.types.ClassType) it.next().object(); // do the comparison about locals avail and locals used here HashMap<IdentityKey, ArrayList<IdentityKey>> typeToLocalUsed = mfc.typeToLocalsUsed(); ArrayList<IdentityKey> localsUsed = new ArrayList<IdentityKey>(); if (typeToLocalUsed.containsKey(new polyglot.util.IdentityKey(cType))) { ArrayList localsNeeded = typeToLocalUsed.get(new polyglot.util.IdentityKey(cType)); Iterator usesIt = localsNeeded.iterator(); while (usesIt.hasNext()) { polyglot.types.LocalInstance li = (polyglot.types.LocalInstance) ((polyglot.util.IdentityKey) usesIt.next()).object(); if (alci.finalLocalsAvail().contains(new polyglot.util.IdentityKey(li))) { localsUsed.add(new polyglot.util.IdentityKey(li)); } } } AnonLocalClassInfo info = new AnonLocalClassInfo(); info.inStaticMethod(alci.inStaticMethod()); info.finalLocalsAvail(localsUsed); if (!finalLocalInfo.containsKey(new polyglot.util.IdentityKey(cType))) { finalLocalInfo.put(new polyglot.util.IdentityKey(cType), info); } } } public boolean isAnonInCCall(polyglot.types.ClassType anonType) { // System.out.println("checking type: "+anonType); Iterator<Node> it = cCallList.iterator(); while (it.hasNext()) { polyglot.ast.ConstructorCall cCall = (polyglot.ast.ConstructorCall) it.next(); // System.out.println("cCall params: "+cCall.arguments()); Iterator argsIt = cCall.arguments().iterator(); while (argsIt.hasNext()) { Object next = argsIt.next(); if (next instanceof polyglot.ast.New && ((polyglot.ast.New) next).anonType() != null) { // System.out.println("comparing: "+((polyglot.ast.New)next).anonType()); if (((polyglot.ast.New) next).anonType().equals(anonType)) { return true; } } } } return false; } public BiMap getAnonClassMap() { return anonClassMap; } public BiMap getLocalClassMap() { return localClassMap; } public HashMap<IdentityKey, String> getAnonTypeMap() { return anonTypeMap; } public HashMap<IdentityKey, String> getLocalTypeMap() { return localTypeMap; } public HashMap<IdentityKey, AnonLocalClassInfo> finalLocalInfo() { return finalLocalInfo; } public int getNextPrivateAccessCounter() { int res = privateAccessCounter; privateAccessCounter++; return res; } public ArrayList getHasOuterRefInInit() { return hasOuterRefInInit; } public void setHasOuterRefInInit(ArrayList list) { hasOuterRefInInit = list; } public HashMap<SootClass, SootClass> specialAnonMap() { return specialAnonMap; } public void setSpecialAnonMap(HashMap<SootClass, SootClass> map) { specialAnonMap = map; } public void hierarchy(soot.FastHierarchy fh) { hierarchy = fh; } public soot.FastHierarchy hierarchy() { return hierarchy; } private HashMap<SootClass, InnerClassInfo> innerClassInfoMap; public HashMap<SootClass, InnerClassInfo> getInnerClassInfoMap() { return innerClassInfoMap; } public void setInnerClassInfoMap(HashMap<SootClass, InnerClassInfo> map) { innerClassInfoMap = map; } protected HashMap<String, String> classToSourceMap() { return classToSourceMap; } public void addToPrivateFieldGetAccessMap(polyglot.ast.Field field, soot.SootMethod meth) { if (privateFieldGetAccessMap == null) { privateFieldGetAccessMap = new HashMap<IdentityKey, SootMethod>(); } privateFieldGetAccessMap.put(new polyglot.util.IdentityKey(field.fieldInstance()), meth); } public HashMap<IdentityKey, SootMethod> getPrivateFieldGetAccessMap() { return privateFieldGetAccessMap; } public void addToPrivateFieldSetAccessMap(polyglot.ast.Field field, soot.SootMethod meth) { if (privateFieldSetAccessMap == null) { privateFieldSetAccessMap = new HashMap<IdentityKey, SootMethod>(); } privateFieldSetAccessMap.put(new polyglot.util.IdentityKey(field.fieldInstance()), meth); } public HashMap<IdentityKey, SootMethod> getPrivateFieldSetAccessMap() { return privateFieldSetAccessMap; } public void addToPrivateMethodGetAccessMap(polyglot.ast.Call call, soot.SootMethod meth) { if (privateMethodGetAccessMap == null) { privateMethodGetAccessMap = new HashMap<IdentityKey, SootMethod>(); } privateMethodGetAccessMap.put(new polyglot.util.IdentityKey(call.methodInstance()), meth); } public HashMap<IdentityKey, SootMethod> getPrivateMethodGetAccessMap() { return privateMethodGetAccessMap; } public ArrayList<String> getInterfacesList() { return interfacesList; } }
19,985
33.222603
125
java
soot
soot-master/src/main/java/soot/javaToJimple/InnerClassInfo.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class InnerClassInfo { public static final int NESTED = 0; public static final int STATIC = 1; public static final int LOCAL = 2; public static final int ANON = 3; private soot.SootClass outerClass; public soot.SootClass getOuterClass() { return outerClass; } private String simpleName; public String getSimpleName() { return simpleName; } private int innerType; public int getInnerType() { return innerType; } public InnerClassInfo(soot.SootClass outerClass, String simpleName, int innerType) { this.outerClass = outerClass; this.simpleName = simpleName; this.innerType = innerType; } }
1,485
25.535714
86
java
soot
soot-master/src/main/java/soot/javaToJimple/InnerClassInfoFinder.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import polyglot.ast.Node; public class InnerClassInfoFinder extends polyglot.visit.NodeVisitor { private final ArrayList<Node> localClassDeclList; private final ArrayList<Node> anonBodyList; private final ArrayList<Node> memberList; // private ArrayList declaredInstList; // private ArrayList usedInstList; public ArrayList<Node> memberList() { return memberList; } /* * public ArrayList declaredInstList(){ return declaredInstList; } * * public ArrayList usedInstList(){ return usedInstList; } */ public ArrayList<Node> localClassDeclList() { return localClassDeclList; } public ArrayList<Node> anonBodyList() { return anonBodyList; } public InnerClassInfoFinder() { // declFound = null; localClassDeclList = new ArrayList<Node>(); anonBodyList = new ArrayList<Node>(); memberList = new ArrayList<Node>(); // declaredInstList = new ArrayList(); // usedInstList = new ArrayList(); } public polyglot.visit.NodeVisitor enter(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.LocalClassDecl) { localClassDeclList.add(n); } if (n instanceof polyglot.ast.New) { if (((polyglot.ast.New) n).anonType() != null) { anonBodyList.add(n); } /* * polyglot.types.ProcedureInstance pi = ((polyglot.ast.New)n).constructorInstance(); if (pi.isPrivate()){ * usedInstList.add(new polyglot.util.IdentityKey(pi)); } */ } if (n instanceof polyglot.ast.ProcedureDecl) { memberList.add(n); /* * polyglot.types.ProcedureInstance pi = ((polyglot.ast.ProcedureDecl)n).procedureInstance(); if * (pi.flags().isPrivate()){ declaredInstList.add(new polyglot.util.IdentityKey(pi)); } */ } if (n instanceof polyglot.ast.FieldDecl) { memberList.add(n); /* * polyglot.types.FieldInstance fi = ((polyglot.ast.FieldDecl)n).fieldInstance(); if (fi.flags().isPrivate()){ * declaredInstList.add(new polyglot.util.IdentityKey(fi)); } */ } if (n instanceof polyglot.ast.Initializer) { memberList.add(n); } /* * if (n instanceof polyglot.ast.Field) { polyglot.types.FieldInstance fi = ((polyglot.ast.Field)n).fieldInstance(); if * (fi.isPrivate()){ usedInstList.add(new polyglot.util.IdentityKey(fi)); } } if (n instanceof polyglot.ast.Call){ * polyglot.types.ProcedureInst pi = ((polyglot.ast.Call)n).methodInstance(); if (pi.isPrivate()){ usedInstList.add(new * polyglot.util.IdentityKey(pi)); } } if (n instanceof polyglot.ast.ConstructorCall){ polyglot.types.ProcedureInstance * pi = ((polyglot.ast.ConstructorCall)n).constructorInstance(); if (pi.isPrivate()){ usedInstList.add(new * polyglot.util.IdentityKey(pi)); } } */ return enter(n); } }
3,692
32.880734
123
java
soot
soot-master/src/main/java/soot/javaToJimple/JavaToJimple.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import polyglot.frontend.ExtensionInfo; import polyglot.frontend.FileSource; import polyglot.frontend.Job; import polyglot.frontend.Pass; import polyglot.frontend.SourceJob; import polyglot.frontend.SourceLoader; import polyglot.frontend.VisitorPass; public class JavaToJimple { public static final polyglot.frontend.Pass.ID CAST_INSERTION = new polyglot.frontend.Pass.ID("cast-insertion"); public static final polyglot.frontend.Pass.ID STRICTFP_PROP = new polyglot.frontend.Pass.ID("strictfp-prop"); public static final polyglot.frontend.Pass.ID ANON_CONSTR_FINDER = new polyglot.frontend.Pass.ID("anon-constr-finder"); public static final polyglot.frontend.Pass.ID SAVE_AST = new polyglot.frontend.Pass.ID("save-ast"); /** * sets up the info needed to invoke polyglot */ public polyglot.frontend.ExtensionInfo initExtInfo(String fileName, List<String> sourceLocations) { Set<String> source = new HashSet<String>(); ExtensionInfo extInfo = new soot.javaToJimple.jj.ExtensionInfo() { public List passes(Job job) { List passes = super.passes(job); // beforePass(passes, Pass.EXIT_CHECK, new VisitorPass(polyglot.frontend.Pass.FOLD, job, new // polyglot.visit.ConstantFolder(ts, nf))); beforePass(passes, Pass.EXIT_CHECK, new VisitorPass(CAST_INSERTION, job, new CastInsertionVisitor(job, ts, nf))); beforePass(passes, Pass.EXIT_CHECK, new VisitorPass(STRICTFP_PROP, job, new StrictFPPropagator(false))); beforePass(passes, Pass.EXIT_CHECK, new VisitorPass(ANON_CONSTR_FINDER, job, new AnonConstructorFinder(job, ts, nf))); afterPass(passes, Pass.PRE_OUTPUT_ALL, new SaveASTVisitor(SAVE_AST, job, this)); removePass(passes, Pass.OUTPUT); return passes; } }; polyglot.main.Options options = extInfo.getOptions(); options.assertions = true; options.source_path = new LinkedList<File>(); Iterator<String> it = sourceLocations.iterator(); while (it.hasNext()) { Object next = it.next(); // System.out.println("adding src loc: "+next.toString()); options.source_path.add(new File(next.toString())); } options.source_ext = new String[] { "java" }; options.serialize_type_info = false; source.add(fileName); options.source_path.add(new File(fileName).getParentFile()); polyglot.main.Options.global = options; return extInfo; } /** * uses polyglot to compile source and build AST */ public polyglot.ast.Node compile(polyglot.frontend.Compiler compiler, String fileName, polyglot.frontend.ExtensionInfo extInfo) { SourceLoader source_loader = compiler.sourceExtension().sourceLoader(); try { FileSource source = new FileSource(new File(fileName)); // This hack is to stop the catch block at the bottom causing an error // with versions of Polyglot where the constructor above can't throw IOException // It should be removed as soon as Polyglot 1.3 is no longer supported. if (false) { throw new IOException("Bogus exception"); } SourceJob job = null; if (compiler.sourceExtension() instanceof soot.javaToJimple.jj.ExtensionInfo) { soot.javaToJimple.jj.ExtensionInfo jjInfo = (soot.javaToJimple.jj.ExtensionInfo) compiler.sourceExtension(); if (jjInfo.sourceJobMap() != null) { job = (SourceJob) jjInfo.sourceJobMap().get(source); } } if (job == null) { job = compiler.sourceExtension().addJob(source); } boolean result = false; result = compiler.sourceExtension().runToCompletion(); if (!result) { throw new soot.CompilationDeathException(0, "Could not compile"); } polyglot.ast.Node node = job.ast(); return node; } catch (IOException e) { return null; } } }
4,871
34.05036
121
java
soot
soot-master/src/main/java/soot/javaToJimple/JimpleBodyBuilder.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Stack; import polyglot.ast.Block; import polyglot.ast.FieldDecl; import polyglot.ast.Try; import polyglot.util.IdentityKey; import soot.Local; import soot.LocalGenerator; import soot.Scene; import soot.SootClass; import soot.SootField; import soot.Trap; import soot.Value; import soot.jimple.IntConstant; import soot.jimple.Jimple; import soot.jimple.Stmt; public class JimpleBodyBuilder extends AbstractJimpleBodyBuilder { public JimpleBodyBuilder() { // ext(null); // base(this); } protected List<List<Stmt>> beforeReturn; // list used to exclude return // stmts from synch try blocks protected List<List<Stmt>> afterReturn; // list used to exclude return stmts // from synch try blocks protected ArrayList<Trap> exceptionTable; // list of exceptions protected Stack<Stmt> endControlNoop = new Stack<Stmt>(); // for break protected Stack<Stmt> condControlNoop = new Stack<Stmt>(); // continue protected Stack<Value> monitorStack; // for synchronized blocks protected Stack<Try> tryStack; // for try stmts in case of returns protected Stack<Try> catchStack; // for catch stmts in case of returns protected Stack<Stmt> trueNoop = new Stack<Stmt>(); protected Stack<Stmt> falseNoop = new Stack<Stmt>(); protected HashMap<String, Stmt> labelBreakMap; // for break label --> nop to // jump to protected HashMap<String, Stmt> labelContinueMap; // for continue label --> // nop to jump to protected HashMap<polyglot.ast.Stmt, Stmt> labelMap; protected HashMap<IdentityKey, Local> localsMap = new HashMap<IdentityKey, Local>(); // localInst // --> // soot // local protected HashMap getThisMap = new HashMap(); // type --> local to ret protected Local specialThisLocal; // === body.getThisLocal(); protected Local outerClassParamLocal; // outer class this protected int paramRefCount = 0; // counter for param ref stmts protected LocalGenerator lg; // for generated locals not in orig src /** * Jimple Body Creation */ @Override public soot.jimple.JimpleBody createJimpleBody(polyglot.ast.Block block, List formals, soot.SootMethod sootMethod) { createBody(sootMethod); lg = Scene.v().createLocalGenerator(body); // create this formal except for static methods if (!soot.Modifier.isStatic(sootMethod.getModifiers())) { soot.RefType type = sootMethod.getDeclaringClass().getType(); specialThisLocal = soot.jimple.Jimple.v().newLocal("this", type); body.getLocals().add(specialThisLocal); soot.jimple.ThisRef thisRef = soot.jimple.Jimple.v().newThisRef(type); soot.jimple.Stmt thisStmt = soot.jimple.Jimple.v().newIdentityStmt(specialThisLocal, thisRef); body.getUnits().add(thisStmt); // this is causing problems - no this in java code -> no tags // Util.addLineTag(thisStmt, block); } int formalsCounter = 0; // create outer class this param ref for inner classes except for static // inner classes - this is not needed int outerIndex = sootMethod.getDeclaringClass().getName().lastIndexOf("$"); if ((outerIndex != -1) && (sootMethod.getName().equals("<init>"))) { SootField this0Field = sootMethod.getDeclaringClass().getFieldByNameUnsafe("this$0"); if (this0Field != null) { // we know its an inner non static class can get outer class // from field ref of the this$0 field soot.SootClass outerClass = ((soot.RefType) this0Field.getType()).getSootClass(); soot.Local outerLocal = lg.generateLocal(outerClass.getType()); soot.jimple.ParameterRef paramRef = soot.jimple.Jimple.v().newParameterRef(outerClass.getType(), formalsCounter); paramRefCount++; soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(outerLocal, paramRef); stmt.addTag(new soot.tagkit.EnclosingTag()); body.getUnits().add(stmt); ((soot.javaToJimple.PolyglotMethodSource) sootMethod.getSource()).setOuterClassThisInit(outerLocal); outerClassParamLocal = outerLocal; formalsCounter++; } } // handle formals if (formals != null) { String[] formalNames = new String[formals.size()]; Iterator formalsIt = formals.iterator(); while (formalsIt.hasNext()) { polyglot.ast.Formal formal = (polyglot.ast.Formal) formalsIt.next(); createFormal(formal, formalsCounter); formalNames[formalsCounter] = formal.name(); formalsCounter++; } body.getMethod().addTag(new soot.tagkit.ParamNamesTag(formalNames)); } // handle final local params ArrayList<SootField> finalsList = ((PolyglotMethodSource) body.getMethod().getSource()).getFinalsList(); if (finalsList != null) { Iterator<SootField> finalsIt = finalsList.iterator(); while (finalsIt.hasNext()) { soot.SootField sf = finalsIt.next(); soot.jimple.ParameterRef paramRef = soot.jimple.Jimple.v().newParameterRef(sf.getType(), formalsCounter); paramRefCount++; soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(lg.generateLocal(sf.getType()), paramRef); body.getUnits().add(stmt); formalsCounter++; } } createBlock(block); // if method is <clinit> handle static field inits if (sootMethod.getName().equals("<clinit>")) { handleAssert(sootMethod); handleStaticFieldInits(sootMethod); handleStaticInitializerBlocks(sootMethod); } // determine if body has a return stmt boolean hasReturn = false; if (block != null) { Iterator it = block.statements().iterator(); while (it.hasNext()) { Object next = it.next(); if (next instanceof polyglot.ast.Return) { hasReturn = true; } } } soot.Type retType = body.getMethod().getReturnType(); // only do this if noexplicit return if ((!hasReturn) && (retType instanceof soot.VoidType)) { soot.jimple.Stmt retStmt = soot.jimple.Jimple.v().newReturnVoidStmt(); body.getUnits().add(retStmt); } // add exceptions from exceptionTable if (exceptionTable != null) { Iterator<Trap> trapsIt = exceptionTable.iterator(); while (trapsIt.hasNext()) { body.getTraps().add(trapsIt.next()); } } return body; } private void handleAssert(soot.SootMethod sootMethod) { if (!((soot.javaToJimple.PolyglotMethodSource) sootMethod.getSource()).hasAssert()) { return; } ((soot.javaToJimple.PolyglotMethodSource) sootMethod.getSource()).addAssertInits(body); } /** * adds any needed field inits */ private void handleFieldInits(soot.SootMethod sootMethod) { ArrayList<FieldDecl> fieldInits = ((soot.javaToJimple.PolyglotMethodSource) sootMethod.getSource()).getFieldInits(); if (fieldInits != null) { handleFieldInits(fieldInits); } } protected void handleFieldInits(ArrayList<FieldDecl> fieldInits) { Iterator<FieldDecl> fieldInitsIt = fieldInits.iterator(); while (fieldInitsIt.hasNext()) { polyglot.ast.FieldDecl field = fieldInitsIt.next(); String fieldName = field.name(); polyglot.ast.Expr initExpr = field.init(); soot.SootClass currentClass = body.getMethod().getDeclaringClass(); soot.SootFieldRef sootField = soot.Scene.v().makeFieldRef(currentClass, fieldName, Util.getSootType(field.type().type()), field.flags().isStatic()); soot.Local base = specialThisLocal; soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newInstanceFieldRef(base, sootField); soot.Value sootExpr; if (initExpr instanceof polyglot.ast.ArrayInit) { sootExpr = getArrayInitLocal((polyglot.ast.ArrayInit) initExpr, field.type().type()); } else { // System.out.println("field init expr: "+initExpr); sootExpr = base().createAggressiveExpr(initExpr, false, false); // System.out.println("soot expr: "+sootExpr); } if (sootExpr instanceof soot.jimple.ConditionExpr) { sootExpr = handleCondBinExpr((soot.jimple.ConditionExpr) sootExpr); } soot.jimple.AssignStmt assign; if (sootExpr instanceof soot.Local) { assign = soot.jimple.Jimple.v().newAssignStmt(fieldRef, sootExpr); } else if (sootExpr instanceof soot.jimple.Constant) { assign = soot.jimple.Jimple.v().newAssignStmt(fieldRef, sootExpr); } else { throw new RuntimeException("fields must assign to local or constant only"); } body.getUnits().add(assign); Util.addLnPosTags(assign, initExpr.position()); Util.addLnPosTags(assign.getRightOpBox(), initExpr.position()); } } /** * adds this field for the outer class */ private void handleOuterClassThisInit(soot.SootMethod sootMethod) { // static inner classes are different SootField this0Field = body.getMethod().getDeclaringClass().getFieldByNameUnsafe("this$0"); if (this0Field != null) { soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newInstanceFieldRef(specialThisLocal, this0Field.makeRef()); soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(fieldRef, outerClassParamLocal); body.getUnits().add(stmt); } } /** * adds any needed static field inits */ private void handleStaticFieldInits(soot.SootMethod sootMethod) { ArrayList<FieldDecl> staticFieldInits = ((soot.javaToJimple.PolyglotMethodSource) sootMethod.getSource()).getStaticFieldInits(); if (staticFieldInits != null) { Iterator<FieldDecl> staticFieldInitsIt = staticFieldInits.iterator(); while (staticFieldInitsIt.hasNext()) { polyglot.ast.FieldDecl field = staticFieldInitsIt.next(); String fieldName = field.name(); polyglot.ast.Expr initExpr = field.init(); soot.SootClass currentClass = body.getMethod().getDeclaringClass(); soot.SootFieldRef sootField = soot.Scene.v().makeFieldRef(currentClass, fieldName, Util.getSootType(field.type().type()), field.flags().isStatic()); soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(sootField); // System.out.println("initExpr: "+initExpr); soot.Value sootExpr; if (initExpr instanceof polyglot.ast.ArrayInit) { sootExpr = getArrayInitLocal((polyglot.ast.ArrayInit) initExpr, field.type().type()); } else { // System.out.println("field init expr: "+initExpr); sootExpr = base().createAggressiveExpr(initExpr, false, false); // System.out.println("soot expr: "+sootExpr); if (sootExpr instanceof soot.jimple.ConditionExpr) { sootExpr = handleCondBinExpr((soot.jimple.ConditionExpr) sootExpr); } } soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(fieldRef, sootExpr); body.getUnits().add(assign); Util.addLnPosTags(assign, initExpr.position()); } } } /** * init blocks get created within init methods in Jimple */ private void handleInitializerBlocks(soot.SootMethod sootMethod) { ArrayList<Block> initializerBlocks = ((soot.javaToJimple.PolyglotMethodSource) sootMethod.getSource()).getInitializerBlocks(); if (initializerBlocks != null) { handleStaticBlocks(initializerBlocks); } } protected void handleStaticBlocks(ArrayList<Block> initializerBlocks) { Iterator<Block> initBlocksIt = initializerBlocks.iterator(); while (initBlocksIt.hasNext()) { createBlock(initBlocksIt.next()); } } /** * static init blocks get created in clinit methods in Jimple */ private void handleStaticInitializerBlocks(soot.SootMethod sootMethod) { ArrayList<Block> staticInitializerBlocks = ((soot.javaToJimple.PolyglotMethodSource) sootMethod.getSource()).getStaticInitializerBlocks(); if (staticInitializerBlocks != null) { Iterator<Block> staticInitBlocksIt = staticInitializerBlocks.iterator(); while (staticInitBlocksIt.hasNext()) { createBlock(staticInitBlocksIt.next()); } } } /** * create body and make it be active */ private void createBody(soot.SootMethod sootMethod) { body = soot.jimple.Jimple.v().newBody(sootMethod); sootMethod.setActiveBody(body); } /** * Block creation */ private void createBlock(polyglot.ast.Block block) { if (block == null) { return; } // handle stmts Iterator it = block.statements().iterator(); while (it.hasNext()) { Object next = it.next(); if (next instanceof polyglot.ast.Stmt) { createStmt((polyglot.ast.Stmt) next); } else { throw new RuntimeException("Unexpected - Unhandled Node"); } } } /** * Catch Formal creation - method parameters */ private soot.Local createCatchFormal(polyglot.ast.Formal formal) { soot.Type sootType = Util.getSootType(formal.type().type()); soot.Local formalLocal = createLocal(formal.localInstance()); soot.jimple.CaughtExceptionRef exceptRef = soot.jimple.Jimple.v().newCaughtExceptionRef(); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(formalLocal, exceptRef); body.getUnits().add(stmt); Util.addLnPosTags(stmt, formal.position()); Util.addLnPosTags(((soot.jimple.IdentityStmt) stmt).getRightOpBox(), formal.position()); String[] names = new String[] { formal.name() }; stmt.addTag(new soot.tagkit.ParamNamesTag(names)); return formalLocal; } /** * Formal creation - method parameters */ private void createFormal(polyglot.ast.Formal formal, int counter) { soot.Type sootType = Util.getSootType(formal.type().type()); soot.Local formalLocal = createLocal(formal.localInstance()); soot.jimple.ParameterRef paramRef = soot.jimple.Jimple.v().newParameterRef(sootType, counter); paramRefCount++; soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(formalLocal, paramRef); body.getUnits().add(stmt); Util.addLnPosTags(((soot.jimple.IdentityStmt) stmt).getRightOpBox(), formal.position()); Util.addLnPosTags(stmt, formal.position()); } /** * Literal Creation */ private soot.Value createLiteral(polyglot.ast.Lit lit) { if (lit instanceof polyglot.ast.IntLit) { polyglot.ast.IntLit intLit = (polyglot.ast.IntLit) lit; long litValue = intLit.value(); if (intLit.kind() == polyglot.ast.IntLit.INT) { return soot.jimple.IntConstant.v((int) litValue); } else { // System.out.println(litValue); return soot.jimple.LongConstant.v(litValue); } } else if (lit instanceof polyglot.ast.StringLit) { String litValue = ((polyglot.ast.StringLit) lit).value(); return soot.jimple.StringConstant.v(litValue); } else if (lit instanceof polyglot.ast.NullLit) { return soot.jimple.NullConstant.v(); } else if (lit instanceof polyglot.ast.FloatLit) { polyglot.ast.FloatLit floatLit = (polyglot.ast.FloatLit) lit; double litValue = floatLit.value(); if (floatLit.kind() == polyglot.ast.FloatLit.DOUBLE) { return soot.jimple.DoubleConstant.v(floatLit.value()); } else { return soot.jimple.FloatConstant.v((float) (floatLit.value())); } } else if (lit instanceof polyglot.ast.CharLit) { char litValue = ((polyglot.ast.CharLit) lit).value(); return soot.jimple.IntConstant.v(litValue); } else if (lit instanceof polyglot.ast.BooleanLit) { boolean litValue = ((polyglot.ast.BooleanLit) lit).value(); if (litValue) { return soot.jimple.IntConstant.v(1); } else { return soot.jimple.IntConstant.v(0); } } else if (lit instanceof polyglot.ast.ClassLit) { return getSpecialClassLitLocal((polyglot.ast.ClassLit) lit); } else { throw new RuntimeException("Unknown Literal - Unhandled: " + lit.getClass()); } } /** * Local Creation */ // this should be used for polyglot locals and formals private soot.Local createLocal(polyglot.types.LocalInstance localInst) { soot.Type sootType = Util.getSootType(localInst.type()); String name = localInst.name(); soot.Local sootLocal = createLocal(name, sootType); localsMap.put(new polyglot.util.IdentityKey(localInst), sootLocal); return sootLocal; } // this should be used for generated locals only private soot.Local createLocal(String name, soot.Type sootType) { soot.Local sootLocal = soot.jimple.Jimple.v().newLocal(name, sootType); body.getLocals().add(sootLocal); return sootLocal; } /** * Local Retreival */ private soot.Local getLocal(polyglot.ast.Local local) { return getLocal(local.localInstance()); } /** * Local Retreival */ private soot.Local getLocal(polyglot.types.LocalInstance li) { if (localsMap.containsKey(new polyglot.util.IdentityKey(li))) { soot.Local sootLocal = localsMap.get(new polyglot.util.IdentityKey(li)); return sootLocal; } else if (body.getMethod().getDeclaringClass().declaresField("val$" + li.name(), Util.getSootType(li.type()))) { soot.Local fieldLocal = generateLocal(li.type()); soot.SootFieldRef field = soot.Scene.v().makeFieldRef(body.getMethod().getDeclaringClass(), "val$" + li.name(), Util.getSootType(li.type()), false); soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newInstanceFieldRef(specialThisLocal, field); soot.jimple.AssignStmt assign = soot.jimple.Jimple.v().newAssignStmt(fieldLocal, fieldRef); body.getUnits().add(assign); return fieldLocal; } /* * else { throw new RuntimeException("Trying unsuccessfully to get local: "+li.name()); } */ else { // else create access meth in outer for val$fieldname // get the this$0 field to find the type of an outer class - has // to have one because local/anon inner can't declare static // memebers so for deepnesting not in static context for these // cases soot.SootClass currentClass = body.getMethod().getDeclaringClass(); boolean fieldFound = false; while (!fieldFound) { if (!currentClass.declaresFieldByName("this$0")) { throw new RuntimeException( "Trying to get field val$" + li.name() + " from some outer class but can't access the outer class of: " + currentClass.getName() + "!" + " current class contains fields: " + currentClass.getFields()); } soot.SootClass outerClass = ((soot.RefType) currentClass.getFieldByName("this$0").getType()).getSootClass(); // look for field of type li.type and name val$li.name in outer // class if (outerClass.declaresField("val$" + li.name(), Util.getSootType(li.type()))) { fieldFound = true; } currentClass = outerClass; // repeat until found in some outer class } // create and add accessor to that outer class (indic as current) soot.SootMethod methToInvoke = makeLiFieldAccessMethod(currentClass, li); // invoke and return // generate a local that corresponds to the invoke of that meth ArrayList methParams = new ArrayList(); methParams.add(getThis(currentClass.getType())); soot.Local res = Util.getPrivateAccessFieldInvoke(methToInvoke.makeRef(), methParams, body, lg); return res; } } private soot.SootMethod makeLiFieldAccessMethod(soot.SootClass classToInvoke, polyglot.types.LocalInstance li) { String name = "access$" + soot.javaToJimple.InitialResolver.v().getNextPrivateAccessCounter() + "00"; ArrayList paramTypes = new ArrayList(); paramTypes.add(classToInvoke.getType()); soot.SootMethod meth = Scene.v().makeSootMethod(name, paramTypes, Util.getSootType(li.type()), soot.Modifier.STATIC); classToInvoke.addMethod(meth); PrivateFieldAccMethodSource src = new PrivateFieldAccMethodSource(Util.getSootType(li.type()), "val$" + li.name(), false, classToInvoke); meth.setActiveBody(src.getBody(meth, null)); meth.addTag(new soot.tagkit.SyntheticTag()); return meth; } /** * Stmt creation */ @Override protected void createStmt(polyglot.ast.Stmt stmt) { // System.out.println("stmt: "+stmt.getClass()); if (stmt instanceof polyglot.ast.Eval) { base().createAggressiveExpr(((polyglot.ast.Eval) stmt).expr(), false, false); } else if (stmt instanceof polyglot.ast.If) { createIf2((polyglot.ast.If) stmt); } else if (stmt instanceof polyglot.ast.LocalDecl) { createLocalDecl((polyglot.ast.LocalDecl) stmt); } else if (stmt instanceof polyglot.ast.Block) { createBlock((polyglot.ast.Block) stmt); } else if (stmt instanceof polyglot.ast.While) { createWhile2((polyglot.ast.While) stmt); } else if (stmt instanceof polyglot.ast.Do) { createDo2((polyglot.ast.Do) stmt); } else if (stmt instanceof polyglot.ast.For) { createForLoop2((polyglot.ast.For) stmt); } else if (stmt instanceof polyglot.ast.Switch) { createSwitch((polyglot.ast.Switch) stmt); } else if (stmt instanceof polyglot.ast.Return) { createReturn((polyglot.ast.Return) stmt); } else if (stmt instanceof polyglot.ast.Branch) { createBranch((polyglot.ast.Branch) stmt); } else if (stmt instanceof polyglot.ast.ConstructorCall) { createConstructorCall((polyglot.ast.ConstructorCall) stmt); } else if (stmt instanceof polyglot.ast.Empty) { // do nothing empty stmt } else if (stmt instanceof polyglot.ast.Throw) { createThrow((polyglot.ast.Throw) stmt); } else if (stmt instanceof polyglot.ast.Try) { createTry((polyglot.ast.Try) stmt); } else if (stmt instanceof polyglot.ast.Labeled) { createLabeled((polyglot.ast.Labeled) stmt); } else if (stmt instanceof polyglot.ast.Synchronized) { createSynchronized((polyglot.ast.Synchronized) stmt); } else if (stmt instanceof polyglot.ast.Assert) { createAssert((polyglot.ast.Assert) stmt); } else if (stmt instanceof polyglot.ast.LocalClassDecl) { createLocalClassDecl((polyglot.ast.LocalClassDecl) stmt); } else { throw new RuntimeException("Unhandled Stmt: " + stmt.getClass()); } } private boolean needSootIf(soot.Value sootCond) { if (sootCond instanceof soot.jimple.IntConstant) { if (((soot.jimple.IntConstant) sootCond).value == 1) { return false; } } return true; } /** * If Stmts Creation - only add line-number tags to if (the other stmts needing tags are created elsewhere */ /* * private void createIf(polyglot.ast.If ifExpr){ * * // create true/false noops to handle cond and/or trueNoop.push(soot.jimple.Jimple.v().newNopStmt()); * falseNoop.push(soot.jimple.Jimple.v().newNopStmt()); * * // handle cond polyglot.ast.Expr condition = ifExpr.cond(); soot.Value sootCond = base().createExpr(condition); * * // pop true false noops right away soot.jimple.Stmt tNoop = (soot.jimple.Stmt)trueNoop.pop(); soot.jimple.Stmt fNoop = * (soot.jimple.Stmt)falseNoop.pop(); * * boolean needIf = needSootIf(sootCond); if (!(sootCond instanceof soot.jimple.ConditionExpr)) { sootCond = * soot.jimple.Jimple.v().newEqExpr(sootCond, soot.jimple.IntConstant.v(0)); } else { sootCond = * reverseCondition((soot.jimple.ConditionExpr)sootCond); sootCond = handleDFLCond((soot.jimple.ConditionExpr)sootCond); } * * // add if soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); * * if (needIf) { soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(sootCond, noop1); * body.getUnits().add(ifStmt); // add line and pos tags Util.addLnPosTags(ifStmt.getConditionBox(), condition.position()); * Util.addLnPosTags(ifStmt, condition.position()); } * * // add true nop body.getUnits().add(tNoop); * * // add consequence polyglot.ast.Stmt consequence = ifExpr.consequent(); createStmt(consequence); * * soot.jimple.Stmt noop2 = null; if (ifExpr.alternative() != null){ noop2 = soot.jimple.Jimple.v().newNopStmt(); * soot.jimple.Stmt goto1 = soot.jimple.Jimple.v().newGotoStmt(noop2); body.getUnits().add(goto1); } * * body.getUnits().add(noop1); * * // add false nop body.getUnits().add(fNoop); * * * // handle alternative polyglot.ast.Stmt alternative = ifExpr.alternative(); if (alternative != null){ * createStmt(alternative); body.getUnits().add(noop2); } * * * } */ /** * If Stmts Creation - only add line-number tags to if (the other stmts needing tags are created elsewhere */ private void createIf2(polyglot.ast.If ifExpr) { soot.jimple.NopStmt endTgt = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.NopStmt brchTgt = soot.jimple.Jimple.v().newNopStmt(); // handle cond polyglot.ast.Expr condition = ifExpr.cond(); createBranchingExpr(condition, brchTgt, false); // add consequence polyglot.ast.Stmt consequence = ifExpr.consequent(); createStmt(consequence); soot.jimple.Stmt goto1 = soot.jimple.Jimple.v().newGotoStmt(endTgt); body.getUnits().add(goto1); body.getUnits().add(brchTgt); // handle alternative polyglot.ast.Stmt alternative = ifExpr.alternative(); if (alternative != null) { createStmt(alternative); } body.getUnits().add(endTgt); } private void createBranchingExpr(polyglot.ast.Expr expr, soot.jimple.Stmt tgt, boolean boto) { if (expr instanceof polyglot.ast.Binary && ((polyglot.ast.Binary) expr).operator() == polyglot.ast.Binary.COND_AND) { polyglot.ast.Binary cond_and = (polyglot.ast.Binary) expr; if (boto) { soot.jimple.Stmt t1 = soot.jimple.Jimple.v().newNopStmt(); createBranchingExpr(cond_and.left(), t1, false); createBranchingExpr(cond_and.right(), tgt, true); body.getUnits().add(t1); } else { createBranchingExpr(cond_and.left(), tgt, false); createBranchingExpr(cond_and.right(), tgt, false); } } else if (expr instanceof polyglot.ast.Binary && ((polyglot.ast.Binary) expr).operator() == polyglot.ast.Binary.COND_OR) { polyglot.ast.Binary cond_or = (polyglot.ast.Binary) expr; if (boto) { createBranchingExpr(cond_or.left(), tgt, true); createBranchingExpr(cond_or.right(), tgt, true); } else { soot.jimple.Stmt t1 = soot.jimple.Jimple.v().newNopStmt(); createBranchingExpr(cond_or.left(), t1, true); createBranchingExpr(cond_or.right(), tgt, false); body.getUnits().add(t1); } } else if (expr instanceof polyglot.ast.Unary && ((polyglot.ast.Unary) expr).operator() == polyglot.ast.Unary.NOT) { polyglot.ast.Unary not = (polyglot.ast.Unary) expr; createBranchingExpr(not.expr(), tgt, !boto); } else { soot.Value sootCond = base().createAggressiveExpr(expr, false, false); boolean needIf = needSootIf(sootCond); if (needIf) { if (!(sootCond instanceof soot.jimple.ConditionExpr)) { if (!boto) { sootCond = soot.jimple.Jimple.v().newEqExpr(sootCond, soot.jimple.IntConstant.v(0)); } else { sootCond = soot.jimple.Jimple.v().newNeExpr(sootCond, soot.jimple.IntConstant.v(0)); } } else { sootCond = handleDFLCond((soot.jimple.ConditionExpr) sootCond); if (!boto) { sootCond = reverseCondition((soot.jimple.ConditionExpr) sootCond); } } soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(sootCond, tgt); body.getUnits().add(ifStmt); // add line and pos tags Util.addLnPosTags(ifStmt.getConditionBox(), expr.position()); Util.addLnPosTags(ifStmt, expr.position()); } // for an "if(true) goto tgt" we have to branch always; for an // "if(true) goto tgt" we just // do nothing at all // (if boto is false then we have to reverse the meaning) else if (sootCond instanceof IntConstant && (((IntConstant) sootCond).value == 1) == boto) { soot.jimple.GotoStmt gotoStmt = soot.jimple.Jimple.v().newGotoStmt(tgt); body.getUnits().add(gotoStmt); // add line and pos tags Util.addLnPosTags(gotoStmt, expr.position()); } } } /** * While Stmts Creation */ /* * private void createWhile(polyglot.ast.While whileStmt){ * * // create true/false noops to handle cond and/or trueNoop.push(soot.jimple.Jimple.v().newNopStmt()); * falseNoop.push(soot.jimple.Jimple.v().newNopStmt()); * * soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt noop2 = * soot.jimple.Jimple.v().newNopStmt(); * * // these are for break and continue endControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); * condControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); * * body.getUnits().add(noop2); * * // handle cond soot.jimple.Stmt continueStmt = (soot.jimple.Stmt)condControlNoop.pop(); * body.getUnits().add(continueStmt); condControlNoop.push(continueStmt); * * polyglot.ast.Expr condition = whileStmt.cond(); soot.Value sootCond = base().createExpr(condition); soot.jimple.Stmt * tNoop = (soot.jimple.Stmt)trueNoop.pop(); soot.jimple.Stmt fNoop = (soot.jimple.Stmt)falseNoop.pop(); boolean needIf = * needSootIf(sootCond); if (!(sootCond instanceof soot.jimple.ConditionExpr)) { sootCond = * soot.jimple.Jimple.v().newEqExpr(sootCond, soot.jimple.IntConstant.v(0)); } else { sootCond = * reverseCondition((soot.jimple.ConditionExpr)sootCond); sootCond = handleDFLCond((soot.jimple.ConditionExpr)sootCond); } * * if (needIf){ soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(sootCond, noop1); * * body.getUnits().add(ifStmt); Util.addLnPosTags(ifStmt.getConditionBox(), condition.position()); * Util.addLnPosTags(ifStmt, condition.position()); } * * body.getUnits().add(tNoop); createStmt(whileStmt.body()); soot.jimple.GotoStmt gotoLoop = * soot.jimple.Jimple.v().newGotoStmt(noop2); body.getUnits().add(gotoLoop); * * body.getUnits().add((soot.jimple.Stmt)(endControlNoop.pop())); body.getUnits().add(noop1); body.getUnits().add(fNoop); * condControlNoop.pop(); } */ /** * While Stmts Creation */ private void createWhile2(polyglot.ast.While whileStmt) { soot.jimple.Stmt brchTgt = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt beginTgt = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(beginTgt); // these are for break and continue endControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); condControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); // handle cond soot.jimple.Stmt continueStmt = condControlNoop.pop(); body.getUnits().add(continueStmt); condControlNoop.push(continueStmt); polyglot.ast.Expr condition = whileStmt.cond(); createBranchingExpr(condition, brchTgt, false); createStmt(whileStmt.body()); soot.jimple.GotoStmt gotoLoop = soot.jimple.Jimple.v().newGotoStmt(beginTgt); body.getUnits().add(gotoLoop); body.getUnits().add((endControlNoop.pop())); body.getUnits().add(brchTgt); condControlNoop.pop(); } /** * DoWhile Stmts Creation */ /* * private void createDo(polyglot.ast.Do doStmt){ * * // create true/false noops to handle cond and/or soot.jimple.Stmt tNoop = soot.jimple.Jimple.v().newNopStmt(); * soot.jimple.Stmt fNoop = soot.jimple.Jimple.v().newNopStmt(); * * soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(noop1); * * // add true noop - for cond and/or body.getUnits().add(tNoop); * * // these are for break and continue endControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); * condControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); * * // handle body createStmt(doStmt.body()); * * // handle cond soot.jimple.Stmt continueStmt = (soot.jimple.Stmt)condControlNoop.pop(); * body.getUnits().add(continueStmt); condControlNoop.push(continueStmt); * * // handle label continue //if ((labelContinueMap != null) && (labelContinueMap.containsKey(lastLabel))){ if (labelMap != * null && labelMap.containsKey(doStmt)){ body.getUnits().add((soot.jimple.Stmt)labelMap.get(doStmt)); } /*if * ((labelContinueMap != null) && (labelStack != null) && (!labelStack.isEmpty()) && * (labelContinueMap.containsKey(((LabelKey)labelStack.peek()).label()))){ * body.getUnits().add((soot.jimple.Stmt)labelContinueMap.get(((LabelKey) labelStack.peek()).label())); } */ /* * trueNoop.push(tNoop); falseNoop.push(fNoop); * * polyglot.ast.Expr condition = doStmt.cond(); soot.Value sootCond = base().createExpr(condition); * * trueNoop.pop(); * * boolean needIf = needSootIf(sootCond); if (!(sootCond instanceof soot.jimple.ConditionExpr)) { sootCond = * soot.jimple.Jimple.v().newNeExpr(sootCond, soot.jimple.IntConstant.v(0)); } else { sootCond = * handleDFLCond((soot.jimple.ConditionExpr)sootCond); } if (needIf){ soot.jimple.IfStmt ifStmt = * soot.jimple.Jimple.v().newIfStmt(sootCond, noop1); body.getUnits().add(ifStmt); Util.addPosTag(ifStmt.getConditionBox(), * condition.position()); Util.addLnPosTags(ifStmt, condition.position()); } else { soot.jimple.GotoStmt gotoIf = * soot.jimple.Jimple.v().newGotoStmt(noop1); body.getUnits().add(gotoIf); } * body.getUnits().add((soot.jimple.Stmt)(endControlNoop.pop())); condControlNoop.pop(); * body.getUnits().add(falseNoop.pop()); } */ /** * DoWhile Stmts Creation */ private void createDo2(polyglot.ast.Do doStmt) { soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(noop1); // these are for break and continue endControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); condControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); // handle body createStmt(doStmt.body()); // handle cond soot.jimple.Stmt continueStmt = condControlNoop.pop(); body.getUnits().add(continueStmt); condControlNoop.push(continueStmt); if (labelMap != null && labelMap.containsKey(doStmt)) { body.getUnits().add(labelMap.get(doStmt)); } polyglot.ast.Expr condition = doStmt.cond(); createBranchingExpr(condition, noop1, true); body.getUnits().add((endControlNoop.pop())); condControlNoop.pop(); } /** * For Loop Stmts Creation */ /* * private void createForLoop(polyglot.ast.For forStmt){ * * // create true/false noops to handle cond and/or soot.jimple.Stmt tNoop = soot.jimple.Jimple.v().newNopStmt(); * soot.jimple.Stmt fNoop = soot.jimple.Jimple.v().newNopStmt(); * * // these ()are for break and continue endControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); * condControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); * * // handle for inits Iterator initsIt = forStmt.inits().iterator(); while (initsIt.hasNext()){ * createStmt((polyglot.ast.Stmt)initsIt.next()); } soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); * soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); * * body.getUnits().add(noop2); * * // handle cond * * polyglot.ast.Expr condition = forStmt.cond(); if (condition != null) { trueNoop.push(tNoop); falseNoop.push(fNoop); * soot.Value sootCond = base().createExpr(condition); trueNoop.pop(); falseNoop.pop(); * * boolean needIf = needSootIf(sootCond); if (!(sootCond instanceof soot.jimple.ConditionExpr)) { sootCond = * soot.jimple.Jimple.v().newEqExpr(sootCond, soot.jimple.IntConstant.v(0)); } else { sootCond = * reverseCondition((soot.jimple.ConditionExpr)sootCond); sootCond = handleDFLCond((soot.jimple.ConditionExpr)sootCond); } * if (needIf){ soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(sootCond, noop1); * * // add cond body.getUnits().add(ifStmt); * * // add line and pos tags Util.addLnPosTags(ifStmt.getConditionBox(), condition.position()); Util.addLnPosTags(ifStmt, * condition.position()); } //else { // soot.jimple.GotoStmt gotoIf = soot.jimple.Jimple.v().newGotoStmt(noop1); // * body.getUnits().add(gotoIf); //} * * } //else { // soot.jimple.Stmt goto2 = soot.jimple.Jimple.v().newGotoStmt(noop1); // body.getUnits().add(goto2); * * //} * * * // handle body //soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); //soot.jimple.Stmt goto1 = * soot.jimple.Jimple.v().newGotoStmt(noop2); //body.getUnits().add(goto1); //body.getUnits().add(noop1); * body.getUnits().add(tNoop); createStmt(forStmt.body()); * * // handle continue body.getUnits().add((soot.jimple.Stmt)(condControlNoop.pop())); * * // handle label continue //if ((labelContinueMap != null) && (labelContinueMap.containsKey(lastLabel))){ if (labelMap != * null && labelMap.containsKey(forStmt)){ body.getUnits().add((soot.jimple.Stmt)labelMap.get(forStmt)); } * * /*if ((labelContinueMap != null) && (labelStack != null) && (!labelStack.isEmpty()) && * (labelContinueMap.containsKey(((LabelKey)labelStack.peek()).label()))){ * body.getUnits().add((soot.jimple.Stmt)labelContinueMap.get(((LabelKey) labelStack.peek()).label())); * //System.out.println("lastLabel: "+lastLabel); //if (!body.getUnits().contains((soot.jimple.Stmt)labelContinueMap.get( * lastLabel))){ // body.getUnits().add((soot.jimple.Stmt)labelContinueMap.get(lastLabel)); //} } */ // handle iters /* * Iterator itersIt = forStmt.iters().iterator(); //System.out.println("for iters: "+forStmt.iters()); while * (itersIt.hasNext()){ createStmt((polyglot.ast.Stmt)itersIt.next()); } soot.jimple.Stmt goto1 = * soot.jimple.Jimple.v().newGotoStmt(noop2); body.getUnits().add(goto1); //body.getUnits().add(noop2); * * // handle cond * * /*polyglot.ast.Expr condition = forStmt.cond(); if (condition != null) { soot.Value sootCond = * base().createExpr(condition); boolean needIf = needSootIf(sootCond); if (!(sootCond instanceof * soot.jimple.ConditionExpr)) { sootCond = soot.jimple.Jimple.v().newNeExpr(sootCond, soot.jimple.IntConstant.v(0)); } * else { sootCond = handleDFLCond((soot.jimple.ConditionExpr)sootCond); } if (needIf){ soot.jimple.IfStmt ifStmt = * soot.jimple.Jimple.v().newIfStmt(sootCond, noop1); * * // add cond body.getUnits().add(ifStmt); * * // add line and pos tags Util.addLnPosTags(ifStmt.getConditionBox(), condition.position()); Util.addLnPosTags(ifStmt, * condition.position()); } else { soot.jimple.GotoStmt gotoIf = soot.jimple.Jimple.v().newGotoStmt(noop1); * body.getUnits().add(gotoIf); } * * } else { soot.jimple.Stmt goto2 = soot.jimple.Jimple.v().newGotoStmt(noop1); body.getUnits().add(goto2); * * } */ /* * body.getUnits().add(noop1); body.getUnits().add((soot.jimple.Stmt)(endControlNoop.pop())); body.getUnits().add(fNoop); * * } */ /** * For Loop Stmts Creation */ private void createForLoop2(polyglot.ast.For forStmt) { // these ()are for break and continue endControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); condControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); // handle for inits Iterator initsIt = forStmt.inits().iterator(); while (initsIt.hasNext()) { createStmt((polyglot.ast.Stmt) initsIt.next()); } soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(noop2); // handle cond polyglot.ast.Expr condition = forStmt.cond(); if (condition != null) { createBranchingExpr(condition, noop1, false); } createStmt(forStmt.body()); // handle continue body.getUnits().add((condControlNoop.pop())); if (labelMap != null && labelMap.containsKey(forStmt)) { body.getUnits().add(labelMap.get(forStmt)); } // handle iters Iterator itersIt = forStmt.iters().iterator(); while (itersIt.hasNext()) { createStmt((polyglot.ast.Stmt) itersIt.next()); } soot.jimple.Stmt goto1 = soot.jimple.Jimple.v().newGotoStmt(noop2); body.getUnits().add(goto1); body.getUnits().add(noop1); body.getUnits().add((endControlNoop.pop())); } /** * Local Decl Creation */ private void createLocalDecl(polyglot.ast.LocalDecl localDecl) { // System.out.println("local decl: "+localDecl); String name = localDecl.name(); polyglot.types.LocalInstance localInst = localDecl.localInstance(); soot.Value lhs = createLocal(localInst); polyglot.ast.Expr expr = localDecl.init(); if (expr != null) { // System.out.println("expr: "+expr+" get type: "+expr.getClass()); soot.Value rhs; if (expr instanceof polyglot.ast.ArrayInit) { // System.out.println("creating array from localdecl: // "+localInst.type()); rhs = getArrayInitLocal((polyglot.ast.ArrayInit) expr, localInst.type()); } else { // System.out.println("create local decl: "+expr+" is a: // "+expr.getClass()); rhs = base().createAggressiveExpr(expr, false, false); // System.out.println("rhs is: "+rhs+" is a: "+rhs.getClass()); } if (rhs instanceof soot.jimple.ConditionExpr) { rhs = handleCondBinExpr((soot.jimple.ConditionExpr) rhs); } // System.out.println("rhs: "+rhs); soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(lhs, rhs); body.getUnits().add(stmt); // Util.addLineTag(stmt, localDecl); Util.addLnPosTags(stmt, localDecl.position()); // this is a special case for position tags if (localDecl.position() != null) { Util.addLnPosTags(stmt.getLeftOpBox(), localDecl.position().line(), localDecl.position().endLine(), localDecl.position().endColumn() - name.length(), localDecl.position().endColumn()); if (expr != null) { Util.addLnPosTags(stmt, localDecl.position().line(), expr.position().endLine(), localDecl.position().column(), expr.position().endColumn()); } else { Util.addLnPosTags(stmt, localDecl.position().line(), localDecl.position().endLine(), localDecl.position().column(), localDecl.position().endColumn()); } } else { } if (expr != null) { Util.addLnPosTags(stmt.getRightOpBox(), expr.position()); } } } /** * Switch Stmts Creation */ private void createSwitch(polyglot.ast.Switch switchStmt) { polyglot.ast.Expr value = switchStmt.expr(); soot.Value sootValue = base().createAggressiveExpr(value, false, false); if (switchStmt.elements().size() == 0) { return; } soot.jimple.Stmt defaultTarget = null; polyglot.ast.Case[] caseArray = new polyglot.ast.Case[switchStmt.elements().size()]; soot.jimple.Stmt[] targetsArray = new soot.jimple.Stmt[switchStmt.elements().size()]; ArrayList<Stmt> targets = new ArrayList<Stmt>(); HashMap<Object, Stmt> targetsMap = new HashMap<Object, Stmt>(); int counter = 0; Iterator it = switchStmt.elements().iterator(); while (it.hasNext()) { Object next = it.next(); if (next instanceof polyglot.ast.Case) { soot.jimple.Stmt noop = soot.jimple.Jimple.v().newNopStmt(); if (!((polyglot.ast.Case) next).isDefault()) { targets.add(noop); caseArray[counter] = (polyglot.ast.Case) next; targetsArray[counter] = noop; counter++; targetsMap.put(next, noop); } else { defaultTarget = noop; } } } // sort targets map int lowIndex = 0; int highIndex = 0; for (int i = 0; i < counter; i++) { for (int j = i + 1; j < counter; j++) { if (caseArray[j].value() < caseArray[i].value()) { polyglot.ast.Case tempCase = caseArray[i]; soot.jimple.Stmt tempTarget = targetsArray[i]; caseArray[i] = caseArray[j]; targetsArray[i] = targetsArray[j]; caseArray[j] = tempCase; targetsArray[j] = tempTarget; } } } ArrayList sortedTargets = new ArrayList(); for (int i = 0; i < counter; i++) { sortedTargets.add(targetsArray[i]); } // deal with default boolean hasDefaultTarget = true; if (defaultTarget == null) { soot.jimple.Stmt noop = soot.jimple.Jimple.v().newNopStmt(); defaultTarget = noop; hasDefaultTarget = false; } // lookup or tableswitch soot.jimple.Stmt sootSwitchStmt; if (isLookupSwitch(switchStmt)) { ArrayList values = new ArrayList(); for (int i = 0; i < counter; i++) { if (!caseArray[i].isDefault()) { values.add(soot.jimple.IntConstant.v((int) caseArray[i].value())); } } soot.jimple.LookupSwitchStmt lookupStmt = soot.jimple.Jimple.v().newLookupSwitchStmt(sootValue, values, sortedTargets, defaultTarget); Util.addLnPosTags(lookupStmt.getKeyBox(), value.position()); sootSwitchStmt = lookupStmt; } else { long lowVal = 0; long highVal = 0; boolean unknown = true; it = switchStmt.elements().iterator(); while (it.hasNext()) { Object next = it.next(); if (next instanceof polyglot.ast.Case) { if (!((polyglot.ast.Case) next).isDefault()) { long temp = ((polyglot.ast.Case) next).value(); if (unknown) { highVal = temp; lowVal = temp; unknown = false; } if (temp > highVal) { highVal = temp; } if (temp < lowVal) { lowVal = temp; } } } } soot.jimple.TableSwitchStmt tableStmt = soot.jimple.Jimple.v().newTableSwitchStmt(sootValue, (int) lowVal, (int) highVal, sortedTargets, defaultTarget); Util.addLnPosTags(tableStmt.getKeyBox(), value.position()); sootSwitchStmt = tableStmt; } body.getUnits().add(sootSwitchStmt); Util.addLnPosTags(sootSwitchStmt, switchStmt.position()); endControlNoop.push(soot.jimple.Jimple.v().newNopStmt()); it = switchStmt.elements().iterator(); Iterator<Stmt> targetsIt = targets.iterator(); while (it.hasNext()) { Object next = it.next(); if (next instanceof polyglot.ast.Case) { if (!((polyglot.ast.Case) next).isDefault()) { body.getUnits().add(targetsMap.get(next)); } else { body.getUnits().add(defaultTarget); } } else { polyglot.ast.SwitchBlock blockStmt = (polyglot.ast.SwitchBlock) next; createBlock(blockStmt); } } if (!hasDefaultTarget) { body.getUnits().add(defaultTarget); } body.getUnits().add((endControlNoop.pop())); } /** * Determine if switch should be lookup or table - this doesn't always get the same result as javac lookup: non-table * table: sequential (no gaps) */ private boolean isLookupSwitch(polyglot.ast.Switch switchStmt) { int lowest = 0; int highest = 0; int counter = 0; Iterator it = switchStmt.elements().iterator(); while (it.hasNext()) { Object next = it.next(); if (next instanceof polyglot.ast.Case) { polyglot.ast.Case caseStmt = (polyglot.ast.Case) next; if (caseStmt.isDefault()) { continue; } int caseValue = (int) caseStmt.value(); if (caseValue <= lowest || counter == 0) { lowest = caseValue; } if (caseValue >= highest || counter == 0) { highest = caseValue; } counter++; } } if ((counter - 1) == (highest - lowest)) { return false; } return true; } /** * Branch Stmts Creation */ private void createBranch(polyglot.ast.Branch branchStmt) { // handle finally blocks before branch if inside try block if (tryStack != null && !tryStack.isEmpty()) { polyglot.ast.Try currentTry = tryStack.pop(); if (currentTry.finallyBlock() != null) { createBlock(currentTry.finallyBlock()); tryStack.push(currentTry); } else { tryStack.push(currentTry); } } // handle finally blocks before branch if inside catch block if (catchStack != null && !catchStack.isEmpty()) { polyglot.ast.Try currentTry = catchStack.pop(); if (currentTry.finallyBlock() != null) { createBlock(currentTry.finallyBlock()); catchStack.push(currentTry); } else { catchStack.push(currentTry); } } body.getUnits().add(soot.jimple.Jimple.v().newNopStmt()); if (branchStmt.kind() == polyglot.ast.Branch.BREAK) { if (branchStmt.label() == null) { soot.jimple.Stmt gotoEndNoop = endControlNoop.pop(); // handle monitor exits before break if necessary if (monitorStack != null) { Stack<Local> putBack = new Stack<Local>(); while (!monitorStack.isEmpty()) { soot.Local exitVal = (soot.Local) monitorStack.pop(); putBack.push(exitVal); soot.jimple.ExitMonitorStmt emStmt = soot.jimple.Jimple.v().newExitMonitorStmt(exitVal); body.getUnits().add(emStmt); } while (!putBack.isEmpty()) { monitorStack.push(putBack.pop()); } } soot.jimple.Stmt gotoEnd = soot.jimple.Jimple.v().newGotoStmt(gotoEndNoop); endControlNoop.push(gotoEndNoop); body.getUnits().add(gotoEnd); Util.addLnPosTags(gotoEnd, branchStmt.position()); } else { soot.jimple.Stmt gotoLabel = soot.jimple.Jimple.v().newGotoStmt(labelBreakMap.get(branchStmt.label())); body.getUnits().add(gotoLabel); Util.addLnPosTags(gotoLabel, branchStmt.position()); } } else if (branchStmt.kind() == polyglot.ast.Branch.CONTINUE) { if (branchStmt.label() == null) { soot.jimple.Stmt gotoCondNoop = condControlNoop.pop(); // handle monitor exits before continue if necessary if (monitorStack != null) { Stack<Local> putBack = new Stack<Local>(); while (!monitorStack.isEmpty()) { soot.Local exitVal = (soot.Local) monitorStack.pop(); putBack.push(exitVal); soot.jimple.ExitMonitorStmt emStmt = soot.jimple.Jimple.v().newExitMonitorStmt(exitVal); body.getUnits().add(emStmt); } while (!putBack.isEmpty()) { monitorStack.push(putBack.pop()); } } soot.jimple.Stmt gotoCond = soot.jimple.Jimple.v().newGotoStmt(gotoCondNoop); condControlNoop.push(gotoCondNoop); body.getUnits().add(gotoCond); Util.addLnPosTags(gotoCond, branchStmt.position()); } else { soot.jimple.Stmt gotoLabel = soot.jimple.Jimple.v().newGotoStmt(labelContinueMap.get(branchStmt.label())); body.getUnits().add(gotoLabel); Util.addLnPosTags(gotoLabel, branchStmt.position()); } } } /** * Labeled Stmt Creation */ private void createLabeled(polyglot.ast.Labeled labeledStmt) { String label = labeledStmt.label(); // lastLabel = label; polyglot.ast.Stmt stmt = labeledStmt.statement(); soot.jimple.Stmt noop = soot.jimple.Jimple.v().newNopStmt(); // System.out.println("labeled stmt type: "+stmt.getClass()); if (!(stmt instanceof polyglot.ast.For) && !(stmt instanceof polyglot.ast.Do)) { body.getUnits().add(noop); } /* * else { if (labelStack == null){ labelStack = new Stack(); } labelStack.push(new LabelKey(label, noop)); } */ if (labelMap == null) { labelMap = new HashMap<polyglot.ast.Stmt, Stmt>(); } labelMap.put(stmt, noop); if (labelBreakMap == null) { labelBreakMap = new HashMap<String, Stmt>(); } if (labelContinueMap == null) { labelContinueMap = new HashMap<String, Stmt>(); } labelContinueMap.put(label, noop); soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); labelBreakMap.put(label, noop2); createStmt(stmt); /* * if (labelStack != null && !labelStack.isEmpty() && (stmt instanceof polyglot.ast.For || stmt instanceof * polyglot.ast.Do)){ labelStack.pop(); } */ body.getUnits().add(noop2); // the idea here is to make a map of labels to the first // jimple stmt of the stmt (a noop) to be created - so // there is something to look up for breaks and continues // with labels } /* * class LabelKey{ * * public LabelKey(String label, soot.jimple.Stmt noop){ this.label = label; this.noop = noop; } private String label; * public String label(){ return label; } private soot.jimple.Stmt noop; public soot.jimple.Stmt noop(){ return noop; } } */ /** * Assert Stmt Creation */ private void createAssert(polyglot.ast.Assert assertStmt) { // check if assertions are disabled soot.Local testLocal = lg.generateLocal(soot.BooleanType.v()); soot.SootFieldRef assertField = soot.Scene.v().makeFieldRef(body.getMethod().getDeclaringClass(), "$assertionsDisabled", soot.BooleanType.v(), true); soot.jimple.FieldRef assertFieldRef = soot.jimple.Jimple.v().newStaticFieldRef(assertField); soot.jimple.AssignStmt fieldAssign = soot.jimple.Jimple.v().newAssignStmt(testLocal, assertFieldRef); body.getUnits().add(fieldAssign); soot.jimple.NopStmt nop1 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.ConditionExpr cond1 = soot.jimple.Jimple.v().newNeExpr(testLocal, soot.jimple.IntConstant.v(0)); soot.jimple.IfStmt testIf = soot.jimple.Jimple.v().newIfStmt(cond1, nop1); body.getUnits().add(testIf); // actual cond test if ((assertStmt.cond() instanceof polyglot.ast.BooleanLit) && (!((polyglot.ast.BooleanLit) assertStmt.cond()).value())) { // don't makeif } else { soot.Value sootCond = base().createAggressiveExpr(assertStmt.cond(), false, false); boolean needIf = needSootIf(sootCond); if (!(sootCond instanceof soot.jimple.ConditionExpr)) { sootCond = soot.jimple.Jimple.v().newEqExpr(sootCond, soot.jimple.IntConstant.v(1)); } else { sootCond = handleDFLCond((soot.jimple.ConditionExpr) sootCond); } if (needIf) { // add if soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(sootCond, nop1); body.getUnits().add(ifStmt); Util.addLnPosTags(ifStmt.getConditionBox(), assertStmt.cond().position()); Util.addLnPosTags(ifStmt, assertStmt.position()); } } // assertion failure code soot.Local failureLocal = lg.generateLocal(soot.RefType.v("java.lang.AssertionError")); soot.jimple.NewExpr newExpr = soot.jimple.Jimple.v().newNewExpr(soot.RefType.v("java.lang.AssertionError")); soot.jimple.AssignStmt newAssign = soot.jimple.Jimple.v().newAssignStmt(failureLocal, newExpr); body.getUnits().add(newAssign); soot.SootMethodRef methToInvoke; ArrayList paramTypes = new ArrayList(); ArrayList params = new ArrayList(); if (assertStmt.errorMessage() != null) { soot.Value errorExpr = base().createAggressiveExpr(assertStmt.errorMessage(), false, false); if (errorExpr instanceof soot.jimple.ConditionExpr) { errorExpr = handleCondBinExpr((soot.jimple.ConditionExpr) errorExpr); } soot.Type errorType = errorExpr.getType(); if (assertStmt.errorMessage().type().isChar()) { errorType = soot.CharType.v(); } if (errorType instanceof soot.IntType) { paramTypes.add(soot.IntType.v()); } else if (errorType instanceof soot.LongType) { paramTypes.add(soot.LongType.v()); } else if (errorType instanceof soot.FloatType) { paramTypes.add(soot.FloatType.v()); } else if (errorType instanceof soot.DoubleType) { paramTypes.add(soot.DoubleType.v()); } else if (errorType instanceof soot.CharType) { paramTypes.add(soot.CharType.v()); } else if (errorType instanceof soot.BooleanType) { paramTypes.add(soot.BooleanType.v()); } else if (errorType instanceof soot.ShortType) { paramTypes.add(soot.IntType.v()); } else if (errorType instanceof soot.ByteType) { paramTypes.add(soot.IntType.v()); } else { paramTypes.add(soot.Scene.v().getSootClass("java.lang.Object").getType()); } params.add(errorExpr); } methToInvoke = soot.Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.AssertionError"), "<init>", paramTypes, soot.VoidType.v(), false); soot.jimple.SpecialInvokeExpr invokeExpr = soot.jimple.Jimple.v().newSpecialInvokeExpr(failureLocal, methToInvoke, params); soot.jimple.InvokeStmt invokeStmt = soot.jimple.Jimple.v().newInvokeStmt(invokeExpr); body.getUnits().add(invokeStmt); if (assertStmt.errorMessage() != null) { Util.addLnPosTags(invokeExpr.getArgBox(0), assertStmt.errorMessage().position()); } soot.jimple.ThrowStmt throwStmt = soot.jimple.Jimple.v().newThrowStmt(failureLocal); body.getUnits().add(throwStmt); // end body.getUnits().add(nop1); } /** * Synchronized Stmt Creation */ private void createSynchronized(polyglot.ast.Synchronized synchStmt) { soot.Value sootExpr = base().createAggressiveExpr(synchStmt.expr(), false, false); soot.jimple.EnterMonitorStmt enterMon = soot.jimple.Jimple.v().newEnterMonitorStmt(sootExpr); body.getUnits().add(enterMon); if (beforeReturn == null) { beforeReturn = new ArrayList<List<Stmt>>(); } if (afterReturn == null) { afterReturn = new ArrayList<List<Stmt>>(); } beforeReturn.add(new ArrayList<Stmt>()); afterReturn.add(new ArrayList<Stmt>()); if (monitorStack == null) { monitorStack = new Stack<Value>(); } monitorStack.push(sootExpr); Util.addLnPosTags(enterMon.getOpBox(), synchStmt.expr().position()); Util.addLnPosTags(enterMon, synchStmt.expr().position()); soot.jimple.Stmt startNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(startNoop); createBlock(synchStmt.body()); soot.jimple.ExitMonitorStmt exitMon = soot.jimple.Jimple.v().newExitMonitorStmt(sootExpr); body.getUnits().add(exitMon); monitorStack.pop(); Util.addLnPosTags(exitMon.getOpBox(), synchStmt.expr().position()); Util.addLnPosTags(exitMon, synchStmt.expr().position()); soot.jimple.Stmt endSynchNoop = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt gotoEnd = soot.jimple.Jimple.v().newGotoStmt(endSynchNoop); soot.jimple.Stmt endNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(endNoop); body.getUnits().add(gotoEnd); soot.jimple.Stmt catchAllBeforeNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(catchAllBeforeNoop); // catch all soot.Local formalLocal = lg.generateLocal(soot.RefType.v("java.lang.Throwable")); soot.jimple.CaughtExceptionRef exceptRef = soot.jimple.Jimple.v().newCaughtExceptionRef(); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(formalLocal, exceptRef); body.getUnits().add(stmt); // catch soot.jimple.Stmt catchBeforeNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(catchBeforeNoop); soot.Local local = lg.generateLocal(soot.RefType.v("java.lang.Throwable")); soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(local, formalLocal); body.getUnits().add(assign); soot.jimple.ExitMonitorStmt catchExitMon = soot.jimple.Jimple.v().newExitMonitorStmt(sootExpr); body.getUnits().add(catchExitMon); Util.addLnPosTags(catchExitMon.getOpBox(), synchStmt.expr().position()); soot.jimple.Stmt catchAfterNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(catchAfterNoop); // throw soot.jimple.Stmt throwStmt = soot.jimple.Jimple.v().newThrowStmt(local); body.getUnits().add(throwStmt); body.getUnits().add(endSynchNoop); /* * add to the exceptionList all the ranges dictated by the returns found (the problem is that return statements are not * within the traps because just before the return all locks have already been released) */ List<Stmt> before = beforeReturn.get(beforeReturn.size() - 1); // last // element List<Stmt> after = afterReturn.get(afterReturn.size() - 1); // last // element if (before.size() > 0) { addToExceptionList(startNoop, before.get(0), catchAllBeforeNoop, soot.Scene.v().getSootClass("java.lang.Throwable")); for (int i = 1; i < before.size(); i++) { addToExceptionList(after.get(i - 1), before.get(i), catchAllBeforeNoop, soot.Scene.v().getSootClass("java.lang.Throwable")); } addToExceptionList(after.get(after.size() - 1), endNoop, catchAllBeforeNoop, soot.Scene.v().getSootClass("java.lang.Throwable")); } else { addToExceptionList(startNoop, endNoop, catchAllBeforeNoop, soot.Scene.v().getSootClass("java.lang.Throwable")); } beforeReturn.remove(before); afterReturn.remove(after); addToExceptionList(catchBeforeNoop, catchAfterNoop, catchAllBeforeNoop, soot.Scene.v().getSootClass("java.lang.Throwable")); } /** * Return Stmts Creation */ private void createReturn(polyglot.ast.Return retStmt) { polyglot.ast.Expr expr = retStmt.expr(); soot.Value sootLocal = null; if (expr != null) { sootLocal = base().createAggressiveExpr(expr, false, false); } // handle monitor exits before return if necessary if (monitorStack != null) { Stack<Local> putBack = new Stack<Local>(); while (!monitorStack.isEmpty()) { soot.Local exitVal = (soot.Local) monitorStack.pop(); putBack.push(exitVal); soot.jimple.ExitMonitorStmt emStmt = soot.jimple.Jimple.v().newExitMonitorStmt(exitVal); body.getUnits().add(emStmt); } while (!putBack.isEmpty()) { monitorStack.push(putBack.pop()); } // put label after exitmonitor(s) to mark where to stop the synch // try block soot.jimple.Stmt stopNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(stopNoop); if (beforeReturn != null) // add to the list(s) of returns to be // handled in the createSynch method { for (List<Stmt> v : beforeReturn) { v.add(stopNoop); } } } // handle finally blocks before return if inside try block if (tryStack != null && !tryStack.isEmpty()) { polyglot.ast.Try currentTry = tryStack.pop(); if (currentTry.finallyBlock() != null) { createBlock(currentTry.finallyBlock()); tryStack.push(currentTry); // if return stmt contains a return don't create the other // return // ReturnStmtChecker rsc = new ReturnStmtChecker(); // currentTry.finallyBlock().visit(rsc); // if (rsc.hasRet()){ // return; // } } else { tryStack.push(currentTry); } } // handle finally blocks before return if inside catch block if (catchStack != null && !catchStack.isEmpty()) { polyglot.ast.Try currentTry = catchStack.pop(); if (currentTry.finallyBlock() != null) { createBlock(currentTry.finallyBlock()); catchStack.push(currentTry); // if return stmt contains a return don't create the other // return // extra return remove with some Soot phase // ReturnStmtChecker rsc = new ReturnStmtChecker(); // currentTry.finallyBlock().visit(rsc); // if (rsc.hasRet()){ // return; // } } else { catchStack.push(currentTry); } } // return if (expr == null) { soot.jimple.Stmt retStmtVoid = soot.jimple.Jimple.v().newReturnVoidStmt(); body.getUnits().add(retStmtVoid); Util.addLnPosTags(retStmtVoid, retStmt.position()); } else { // soot.Value sootLocal = createExpr(expr); if (sootLocal instanceof soot.jimple.ConditionExpr) { sootLocal = handleCondBinExpr((soot.jimple.ConditionExpr) sootLocal); } soot.jimple.ReturnStmt retStmtLocal = soot.jimple.Jimple.v().newReturnStmt(sootLocal); body.getUnits().add(retStmtLocal); Util.addLnPosTags(retStmtLocal.getOpBox(), expr.position()); Util.addLnPosTags(retStmtLocal, retStmt.position()); } // after the return is handled, put another label to show the new start // point of the synch try block soot.jimple.Stmt startNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(startNoop); if (afterReturn != null) // add to the list(s) of returns to be handled // in the createSynch method { for (List<Stmt> v : afterReturn) { v.add(startNoop); } } } /** * Throw Stmt Creation */ private void createThrow(polyglot.ast.Throw throwStmt) { soot.Value toThrow = base().createAggressiveExpr(throwStmt.expr(), false, false); soot.jimple.ThrowStmt throwSt = soot.jimple.Jimple.v().newThrowStmt(toThrow); body.getUnits().add(throwSt); Util.addLnPosTags(throwSt, throwStmt.position()); Util.addLnPosTags(throwSt.getOpBox(), throwStmt.expr().position()); } /** * Try Stmt Creation */ private void createTry(polyglot.ast.Try tryStmt) { polyglot.ast.Block finallyBlock = tryStmt.finallyBlock(); if (finallyBlock == null) { createTryCatch(tryStmt); } else { createTryCatchFinally(tryStmt); } } /** * handles try/catch (try/catch/finally is separate for simplicity) */ private void createTryCatch(polyglot.ast.Try tryStmt) { // try polyglot.ast.Block tryBlock = tryStmt.tryBlock(); // this nop is for the fromStmt of try soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(noop1); if (tryStack == null) { tryStack = new Stack<Try>(); } tryStack.push(tryStmt); createBlock(tryBlock); tryStack.pop(); // this nop is for the toStmt of try soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(noop2); // create end nop for after entire try/catch soot.jimple.Stmt endNoop = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt tryEndGoto = soot.jimple.Jimple.v().newGotoStmt(endNoop); body.getUnits().add(tryEndGoto); Iterator it = tryStmt.catchBlocks().iterator(); while (it.hasNext()) { soot.jimple.Stmt noop3 = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(noop3); // create catch stmts polyglot.ast.Catch catchBlock = (polyglot.ast.Catch) it.next(); // create catch ref createCatchFormal(catchBlock.formal()); if (catchStack == null) { catchStack = new Stack<Try>(); } catchStack.push(tryStmt); createBlock(catchBlock.body()); catchStack.pop(); soot.jimple.Stmt catchEndGoto = soot.jimple.Jimple.v().newGotoStmt(endNoop); body.getUnits().add(catchEndGoto); soot.Type sootType = Util.getSootType(catchBlock.catchType()); addToExceptionList(noop1, noop2, noop3, soot.Scene.v().getSootClass(sootType.toString())); } body.getUnits().add(endNoop); } /** * handles try/catch/finally (try/catch is separate for simplicity) */ private void createTryCatchFinally(polyglot.ast.Try tryStmt) { HashMap<Stmt, Stmt> gotoMap = new HashMap<Stmt, Stmt>(); // try polyglot.ast.Block tryBlock = tryStmt.tryBlock(); // this nop is for the fromStmt of try soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(noop1); if (tryStack == null) { tryStack = new Stack<Try>(); } tryStack.push(tryStmt); createBlock(tryBlock); tryStack.pop(); // this nop is for the toStmt of try soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(noop2); // create end nop for after entire try/catch soot.jimple.Stmt endNoop = soot.jimple.Jimple.v().newNopStmt(); // to finally soot.jimple.Stmt tryGotoFinallyNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(tryGotoFinallyNoop); soot.jimple.Stmt tryFinallyNoop = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt tryGotoFinally = soot.jimple.Jimple.v().newGotoStmt(tryFinallyNoop); body.getUnits().add(tryGotoFinally); // goto end stmts soot.jimple.Stmt beforeEndGotoNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(beforeEndGotoNoop); soot.jimple.Stmt tryEndGoto = soot.jimple.Jimple.v().newGotoStmt(endNoop); body.getUnits().add(tryEndGoto); gotoMap.put(tryFinallyNoop, beforeEndGotoNoop); // catch section soot.jimple.Stmt catchAllBeforeNoop = soot.jimple.Jimple.v().newNopStmt(); Iterator it = tryStmt.catchBlocks().iterator(); while (it.hasNext()) { soot.jimple.Stmt noop3 = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(noop3); // create catch stmts polyglot.ast.Catch catchBlock = (polyglot.ast.Catch) it.next(); // create catch ref soot.jimple.Stmt catchRefNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(catchRefNoop); createCatchFormal(catchBlock.formal()); soot.jimple.Stmt catchStmtsNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(catchStmtsNoop); if (catchStack == null) { catchStack = new Stack<Try>(); } catchStack.push(tryStmt); createBlock(catchBlock.body()); catchStack.pop(); // to finally soot.jimple.Stmt catchGotoFinallyNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(catchGotoFinallyNoop); soot.jimple.Stmt catchFinallyNoop = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt catchGotoFinally = soot.jimple.Jimple.v().newGotoStmt(catchFinallyNoop); body.getUnits().add(catchGotoFinally); // goto end stmts soot.jimple.Stmt beforeCatchEndGotoNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(beforeCatchEndGotoNoop); soot.jimple.Stmt catchEndGoto = soot.jimple.Jimple.v().newGotoStmt(endNoop); body.getUnits().add(catchEndGoto); gotoMap.put(catchFinallyNoop, beforeCatchEndGotoNoop); soot.Type sootType = Util.getSootType(catchBlock.catchType()); addToExceptionList(noop1, noop2, noop3, soot.Scene.v().getSootClass(sootType.toString())); addToExceptionList(catchStmtsNoop, beforeCatchEndGotoNoop, catchAllBeforeNoop, soot.Scene.v().getSootClass("java.lang.Throwable")); } // catch all ref soot.Local formalLocal = lg.generateLocal(soot.RefType.v("java.lang.Throwable")); body.getUnits().add(catchAllBeforeNoop); soot.jimple.CaughtExceptionRef exceptRef = soot.jimple.Jimple.v().newCaughtExceptionRef(); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(formalLocal, exceptRef); body.getUnits().add(stmt); // catch all assign soot.jimple.Stmt beforeCatchAllAssignNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(beforeCatchAllAssignNoop); soot.Local catchAllAssignLocal = lg.generateLocal(soot.RefType.v("java.lang.Throwable")); soot.jimple.Stmt catchAllAssign = soot.jimple.Jimple.v().newAssignStmt(catchAllAssignLocal, formalLocal); body.getUnits().add(catchAllAssign); // catch all finally soot.jimple.Stmt catchAllFinallyNoop = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt catchAllGotoFinally = soot.jimple.Jimple.v().newGotoStmt(catchAllFinallyNoop); body.getUnits().add(catchAllGotoFinally); // catch all throw soot.jimple.Stmt catchAllBeforeThrowNoop = soot.jimple.Jimple.v().newNopStmt(); body.getUnits().add(catchAllBeforeThrowNoop); soot.jimple.Stmt throwStmt = soot.jimple.Jimple.v().newThrowStmt(catchAllAssignLocal); throwStmt.addTag(new soot.tagkit.ThrowCreatedByCompilerTag()); body.getUnits().add(throwStmt); gotoMap.put(catchAllFinallyNoop, catchAllBeforeThrowNoop); // catch all goto end soot.jimple.Stmt catchAllGotoEnd = soot.jimple.Jimple.v().newGotoStmt(endNoop); body.getUnits().add(catchAllGotoEnd); addToExceptionList(beforeCatchAllAssignNoop, catchAllBeforeThrowNoop, catchAllBeforeNoop, soot.Scene.v().getSootClass("java.lang.Throwable")); // create finally's Iterator<Stmt> finallyIt = gotoMap.keySet().iterator(); while (finallyIt.hasNext()) { soot.jimple.Stmt noopStmt = finallyIt.next(); body.getUnits().add(noopStmt); createBlock(tryStmt.finallyBlock()); soot.jimple.Stmt backToStmt = gotoMap.get(noopStmt); soot.jimple.Stmt backToGoto = soot.jimple.Jimple.v().newGotoStmt(backToStmt); body.getUnits().add(backToGoto); } body.getUnits().add(endNoop); addToExceptionList(noop1, beforeEndGotoNoop, catchAllBeforeNoop, soot.Scene.v().getSootClass("java.lang.Throwable")); } /** * add exceptions to a list that gets added at end of method */ private void addToExceptionList(soot.jimple.Stmt from, soot.jimple.Stmt to, soot.jimple.Stmt with, soot.SootClass exceptionClass) { if (exceptionTable == null) { exceptionTable = new ArrayList<Trap>(); } soot.Trap trap = soot.jimple.Jimple.v().newTrap(exceptionClass, from, to, with); exceptionTable.add(trap); } public soot.jimple.Constant createConstant(polyglot.ast.Expr expr) { Object constantVal = expr.constantValue(); // System.out.println("expr: "+expr); return getConstant(constantVal, expr.type()); } /** * Expression Creation */ /* * protected soot.Value createExpr(polyglot.ast.Expr expr){ * //System.out.println("create expr: "+expr+" type: "+expr.getClass()); // maybe right here check if expr has constant val * and return that // instead if (expr.isConstant() && expr.constantValue() != null && expr.type() != null && !(expr * instanceof polyglot.ast.Binary && expr.type().toString().equals("java.lang.String")) ){ return createConstant(expr); } * if (expr instanceof polyglot.ast.Assign) { return getAssignLocal((polyglot.ast.Assign)expr); } else if (expr instanceof * polyglot.ast.Lit) { return createLiteral((polyglot.ast.Lit)expr); } else if (expr instanceof polyglot.ast.Local) { * return getLocal((polyglot.ast.Local)expr); } else if (expr instanceof polyglot.ast.Binary) { return * getBinaryLocal((polyglot.ast.Binary)expr); } else if (expr instanceof polyglot.ast.Unary) { return * getUnaryLocal((polyglot.ast.Unary)expr); } else if (expr instanceof polyglot.ast.Cast) { return * getCastLocal((polyglot.ast.Cast)expr); } //else if (expr instanceof polyglot.ast.ArrayInit) { // array init are special * and get created elsewhere //} else if (expr instanceof polyglot.ast.ArrayAccess) { return * getArrayRefLocal((polyglot.ast.ArrayAccess)expr); } else if (expr instanceof polyglot.ast.NewArray) { return * getNewArrayLocal((polyglot.ast.NewArray)expr); } else if (expr instanceof polyglot.ast.Call) { return * getCallLocal((polyglot.ast.Call)expr); } else if (expr instanceof polyglot.ast.New) { return * getNewLocal((polyglot.ast.New)expr); } else if (expr instanceof polyglot.ast.Special) { return * getSpecialLocal((polyglot.ast.Special)expr); } else if (expr instanceof polyglot.ast.Instanceof) { return * getInstanceOfLocal((polyglot.ast.Instanceof)expr); } else if (expr instanceof polyglot.ast.Conditional) { return * getConditionalLocal((polyglot.ast.Conditional)expr); } else if (expr instanceof polyglot.ast.Field) { return * getFieldLocal((polyglot.ast.Field)expr); } else { throw new RuntimeException("Unhandled Expression: "+expr); } * * } */ /** * Aggressive Expression Creation make reduceAggressively true to not reduce all the way to a local */ @Override protected soot.Value createAggressiveExpr(polyglot.ast.Expr expr, boolean reduceAggressively, boolean reverseCondIfNec) { // System.out.println("create expr: "+expr+" type: "+expr.getClass()); // maybe right here check if expr has constant val and return that // instead if (expr.isConstant() && expr.constantValue() != null && expr.type() != null && !(expr instanceof polyglot.ast.Binary && expr.type().toString().equals("java.lang.String"))) { return createConstant(expr); } if (expr instanceof polyglot.ast.Assign) { return getAssignLocal((polyglot.ast.Assign) expr); } else if (expr instanceof polyglot.ast.Lit) { return createLiteral((polyglot.ast.Lit) expr); } else if (expr instanceof polyglot.ast.Local) { return getLocal((polyglot.ast.Local) expr); } else if (expr instanceof polyglot.ast.Binary) { return getBinaryLocal2((polyglot.ast.Binary) expr, reduceAggressively); } else if (expr instanceof polyglot.ast.Unary) { return getUnaryLocal((polyglot.ast.Unary) expr); } else if (expr instanceof polyglot.ast.Cast) { return getCastLocal((polyglot.ast.Cast) expr); } // else if (expr instanceof polyglot.ast.ArrayInit) { // array init are special and get created elsewhere // } else if (expr instanceof polyglot.ast.ArrayAccess) { return getArrayRefLocal((polyglot.ast.ArrayAccess) expr); } else if (expr instanceof polyglot.ast.NewArray) { return getNewArrayLocal((polyglot.ast.NewArray) expr); } else if (expr instanceof polyglot.ast.Call) { return getCallLocal((polyglot.ast.Call) expr); } else if (expr instanceof polyglot.ast.New) { return getNewLocal((polyglot.ast.New) expr); } else if (expr instanceof polyglot.ast.Special) { return getSpecialLocal((polyglot.ast.Special) expr); } else if (expr instanceof polyglot.ast.Instanceof) { return getInstanceOfLocal((polyglot.ast.Instanceof) expr); } else if (expr instanceof polyglot.ast.Conditional) { return getConditionalLocal((polyglot.ast.Conditional) expr); } else if (expr instanceof polyglot.ast.Field) { return getFieldLocal((polyglot.ast.Field) expr); } else { throw new RuntimeException("Unhandled Expression: " + expr); } } @Override protected soot.Local handlePrivateFieldUnarySet(polyglot.ast.Unary unary) { polyglot.ast.Field fLeft = (polyglot.ast.Field) unary.expr(); soot.Value base = base().getBaseLocal(fLeft.target()); soot.Value fieldGetLocal = getPrivateAccessFieldLocal(fLeft, base); soot.Local tmp = generateLocal(fLeft.type()); soot.jimple.AssignStmt stmt1 = soot.jimple.Jimple.v().newAssignStmt(tmp, fieldGetLocal); body.getUnits().add(stmt1); Util.addLnPosTags(stmt1, unary.position()); soot.Value incVal = base().getConstant(Util.getSootType(fLeft.type()), 1); soot.jimple.BinopExpr binExpr; if (unary.operator() == polyglot.ast.Unary.PRE_INC || unary.operator() == polyglot.ast.Unary.POST_INC) { binExpr = soot.jimple.Jimple.v().newAddExpr(tmp, incVal); } else { binExpr = soot.jimple.Jimple.v().newSubExpr(tmp, incVal); } soot.Local tmp2 = generateLocal(fLeft.type()); soot.jimple.AssignStmt assign = soot.jimple.Jimple.v().newAssignStmt(tmp2, binExpr); body.getUnits().add(assign); if (unary.operator() == polyglot.ast.Unary.PRE_INC || unary.operator() == polyglot.ast.Unary.PRE_DEC) { return base().handlePrivateFieldSet(fLeft, tmp2, base); } else { base().handlePrivateFieldSet(fLeft, tmp2, base); return tmp; } } @Override protected soot.Local handlePrivateFieldAssignSet(polyglot.ast.Assign assign) { polyglot.ast.Field fLeft = (polyglot.ast.Field) assign.left(); // soot.Value right = createExpr(assign.right()); // if assign is not = but +=, -=, *=, /=, >>=, >>>-, <<=, %=, // |= &= or ^= then compute it all into a local first // if (assign.operator() != polyglot.ast.Assign.ASSIGN){ // in this cas can cast to local (never a string const here // as it has to be a lhs soot.Value right; soot.Value fieldBase = base().getBaseLocal(fLeft.target()); if (assign.operator() == polyglot.ast.Assign.ASSIGN) { right = base().getSimpleAssignRightLocal(assign); } else if ((assign.operator() == polyglot.ast.Assign.ADD_ASSIGN) && assign.type().toString().equals("java.lang.String")) { right = getStringConcatAssignRightLocal(assign); } else { // here the lhs is a private field and needs to use get call soot.Local leftLocal = getPrivateAccessFieldLocal(fLeft, fieldBase); // soot.Local leftLocal = (soot.Local)base().createExpr(fLeft); right = base().getAssignRightLocal(assign, leftLocal); } return handlePrivateFieldSet(fLeft, right, fieldBase); } @Override protected soot.Local handlePrivateFieldSet(polyglot.ast.Expr expr, soot.Value right, soot.Value base) { // in normal j2j its always a field (and checked before call) // only has an expr for param for extensibility polyglot.ast.Field fLeft = (polyglot.ast.Field) expr; soot.SootClass containClass = ((soot.RefType) Util.getSootType(fLeft.target().type())).getSootClass(); soot.SootMethod methToUse = addSetAccessMeth(containClass, fLeft, right); ArrayList params = new ArrayList(); if (!fLeft.flags().isStatic()) { // this is the this ref if needed // params.add(getThis(Util.getSootType(fLeft.target().type()))); params.add(base); } params.add(right); soot.jimple.InvokeExpr invoke = soot.jimple.Jimple.v().newStaticInvokeExpr(methToUse.makeRef(), params); soot.Local retLocal = lg.generateLocal(right.getType()); soot.jimple.AssignStmt assignStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, invoke); body.getUnits().add(assignStmt); return retLocal; } private soot.SootMethod addSetAccessMeth(soot.SootClass conClass, polyglot.ast.Field field, soot.Value param) { if ((InitialResolver.v().getPrivateFieldSetAccessMap() != null) && (InitialResolver.v().getPrivateFieldSetAccessMap() .containsKey(new polyglot.util.IdentityKey(field.fieldInstance())))) { return InitialResolver.v().getPrivateFieldSetAccessMap().get(new polyglot.util.IdentityKey(field.fieldInstance())); } String name = "access$" + soot.javaToJimple.InitialResolver.v().getNextPrivateAccessCounter() + "00"; ArrayList paramTypes = new ArrayList(); if (!field.flags().isStatic()) { // add this param type paramTypes.add(conClass.getType()); // paramTypes.add(Util.getSootType(field.target().type())); } soot.Type retType; paramTypes.add(Util.getSootType(field.type())); retType = Util.getSootType(field.type()); /* * if (param.getType() instanceof soot.NullType){ paramTypes.add(soot.RefType.v("java.lang.Object")); retType = * soot.RefType.v("java.lang.Object"); } else { paramTypes.add(param.getType()); retType = param.getType(); } */ soot.SootMethod meth = Scene.v().makeSootMethod(name, paramTypes, retType, soot.Modifier.STATIC); PrivateFieldSetMethodSource pfsms = new PrivateFieldSetMethodSource(Util.getSootType(field.type()), field.name(), field.flags().isStatic()); conClass.addMethod(meth); meth.setActiveBody(pfsms.getBody(meth, null)); InitialResolver.v().addToPrivateFieldSetAccessMap(field, meth); meth.addTag(new soot.tagkit.SyntheticTag()); return meth; } private soot.SootMethod addGetFieldAccessMeth(soot.SootClass conClass, polyglot.ast.Field field) { if ((InitialResolver.v().getPrivateFieldGetAccessMap() != null) && (InitialResolver.v().getPrivateFieldGetAccessMap() .containsKey(new polyglot.util.IdentityKey(field.fieldInstance())))) { return InitialResolver.v().getPrivateFieldGetAccessMap().get(new polyglot.util.IdentityKey(field.fieldInstance())); } String name = "access$" + soot.javaToJimple.InitialResolver.v().getNextPrivateAccessCounter() + "00"; ArrayList paramTypes = new ArrayList(); if (!field.flags().isStatic()) { // add this param type paramTypes.add(conClass.getType());// (soot.Local)getBaseLocal(field.target())); // paramTypes.add(Util.getSootType(field.target().type())); } soot.SootMethod meth = Scene.v().makeSootMethod(name, paramTypes, Util.getSootType(field.type()), soot.Modifier.STATIC); PrivateFieldAccMethodSource pfams = new PrivateFieldAccMethodSource(Util.getSootType(field.type()), field.name(), field.flags().isStatic(), conClass); conClass.addMethod(meth); meth.setActiveBody(pfams.getBody(meth, null)); InitialResolver.v().addToPrivateFieldGetAccessMap(field, meth); meth.addTag(new soot.tagkit.SyntheticTag()); return meth; } private soot.SootMethod addGetMethodAccessMeth(soot.SootClass conClass, polyglot.ast.Call call) { if ((InitialResolver.v().getPrivateMethodGetAccessMap() != null) && (InitialResolver.v().getPrivateMethodGetAccessMap() .containsKey(new polyglot.util.IdentityKey(call.methodInstance())))) { return InitialResolver.v().getPrivateMethodGetAccessMap().get(new polyglot.util.IdentityKey(call.methodInstance())); } String name = "access$" + soot.javaToJimple.InitialResolver.v().getNextPrivateAccessCounter() + "00"; ArrayList paramTypes = new ArrayList(); if (!call.methodInstance().flags().isStatic()) { // add this param type // paramTypes.add(Util.getSootType(call.methodInstance().container())); paramTypes.add(conClass.getType()); } ArrayList sootParamsTypes = getSootParamsTypes(call); paramTypes.addAll(sootParamsTypes); soot.SootMethod meth = Scene.v().makeSootMethod(name, paramTypes, Util.getSootType(call.methodInstance().returnType()), soot.Modifier.STATIC); PrivateMethodAccMethodSource pmams = new PrivateMethodAccMethodSource(call.methodInstance()); conClass.addMethod(meth); meth.setActiveBody(pmams.getBody(meth, null)); InitialResolver.v().addToPrivateMethodGetAccessMap(call, meth); meth.addTag(new soot.tagkit.SyntheticTag()); return meth; } @Override protected soot.Value getAssignRightLocal(polyglot.ast.Assign assign, soot.Local leftLocal) { if (assign.operator() == polyglot.ast.Assign.ASSIGN) { return base().getSimpleAssignRightLocal(assign); } else if (assign.operator() == polyglot.ast.Assign.ADD_ASSIGN && assign.type().toString().equals("java.lang.String")) { return getStringConcatAssignRightLocal(assign); } else { return getComplexAssignRightLocal(assign, leftLocal); } } @Override protected soot.Value getSimpleAssignRightLocal(polyglot.ast.Assign assign) { boolean repush = false; soot.jimple.Stmt tNoop = null; soot.jimple.Stmt fNoop = null; if (!trueNoop.empty() && !falseNoop.empty()) { tNoop = trueNoop.pop(); fNoop = falseNoop.pop(); repush = true; } soot.Value right = base().createAggressiveExpr(assign.right(), false, false); if (repush) { trueNoop.push(tNoop); falseNoop.push(fNoop); } if (right instanceof soot.jimple.ConditionExpr) { right = handleCondBinExpr((soot.jimple.ConditionExpr) right); } return right; } private soot.Local getStringConcatAssignRightLocal(polyglot.ast.Assign assign) { soot.Local sb = createStringBuffer(assign); sb = generateAppends(assign.left(), sb); sb = generateAppends(assign.right(), sb); soot.Local rLocal = createToString(sb, assign); return rLocal; } private soot.Local getComplexAssignRightLocal(polyglot.ast.Assign assign, soot.Local leftLocal) { soot.Value right = base().createAggressiveExpr(assign.right(), false, false); if (right instanceof soot.jimple.ConditionExpr) { right = handleCondBinExpr((soot.jimple.ConditionExpr) right); } soot.jimple.BinopExpr binop = null; if (assign.operator() == polyglot.ast.Assign.ADD_ASSIGN) { binop = soot.jimple.Jimple.v().newAddExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.SUB_ASSIGN) { binop = soot.jimple.Jimple.v().newSubExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.MUL_ASSIGN) { binop = soot.jimple.Jimple.v().newMulExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.DIV_ASSIGN) { binop = soot.jimple.Jimple.v().newDivExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.MOD_ASSIGN) { binop = soot.jimple.Jimple.v().newRemExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.SHL_ASSIGN) { binop = soot.jimple.Jimple.v().newShlExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.SHR_ASSIGN) { binop = soot.jimple.Jimple.v().newShrExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.USHR_ASSIGN) { binop = soot.jimple.Jimple.v().newUshrExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.BIT_AND_ASSIGN) { binop = soot.jimple.Jimple.v().newAndExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.BIT_OR_ASSIGN) { binop = soot.jimple.Jimple.v().newOrExpr(leftLocal, right); } else if (assign.operator() == polyglot.ast.Assign.BIT_XOR_ASSIGN) { binop = soot.jimple.Jimple.v().newXorExpr(leftLocal, right); } soot.Local retLocal = lg.generateLocal(leftLocal.getType()); soot.jimple.AssignStmt assignStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, binop); body.getUnits().add(assignStmt); Util.addLnPosTags(binop.getOp1Box(), assign.left().position()); Util.addLnPosTags(binop.getOp2Box(), assign.right().position()); return retLocal; } private soot.Value getSimpleAssignLocal(polyglot.ast.Assign assign) { soot.jimple.AssignStmt stmt; soot.Value left = base().createLHS(assign.left()); soot.Value right = base().getSimpleAssignRightLocal(assign); stmt = soot.jimple.Jimple.v().newAssignStmt(left, right); body.getUnits().add(stmt); Util.addLnPosTags(stmt, assign.position()); Util.addLnPosTags(stmt.getRightOpBox(), assign.right().position()); Util.addLnPosTags(stmt.getLeftOpBox(), assign.left().position()); if (left instanceof soot.Local) { return left; } else { return right; } } private soot.Value getStrConAssignLocal(polyglot.ast.Assign assign) { soot.jimple.AssignStmt stmt; soot.Value left = base().createLHS(assign.left()); soot.Value right = getStringConcatAssignRightLocal(assign); stmt = soot.jimple.Jimple.v().newAssignStmt(left, right); body.getUnits().add(stmt); Util.addLnPosTags(stmt, assign.position()); Util.addLnPosTags(stmt.getRightOpBox(), assign.right().position()); Util.addLnPosTags(stmt.getLeftOpBox(), assign.left().position()); if (left instanceof soot.Local) { return left; } else { return right; } } /** * Assign Expression Creation */ protected soot.Value getAssignLocal(polyglot.ast.Assign assign) { // handle private access field assigns // HashMap accessMap = // ((PolyglotMethodSource)body.getMethod().getSource()).getPrivateAccessMap(); // if assigning to a field and the field is private and its not in // this class (then it had better be in some outer class and will // be handled as such) if (base().needsAccessor(assign.left())) { // if ((assign.left() instanceof polyglot.ast.Field) && // (needsPrivateAccessor((polyglot.ast.Field)assign.left()) || // needsProtectedAccessor((polyglot.ast.Field)assign.left()))){ // ((polyglot.ast.Field)assign.left()).fieldInstance().flags().isPrivate() // && // !Util.getSootType(((polyglot.ast.Field)assign.left()).fieldInstance() // .container()).equals(body.getMethod().getDeclaringClass().getType())){ return base().handlePrivateFieldAssignSet(assign); } if (assign.operator() == polyglot.ast.Assign.ASSIGN) { return getSimpleAssignLocal(assign); } if ((assign.operator() == polyglot.ast.Assign.ADD_ASSIGN) && assign.type().toString().equals("java.lang.String")) { return getStrConAssignLocal(assign); } soot.jimple.AssignStmt stmt; soot.Value left = base().createLHS(assign.left()); soot.Value left2 = (soot.Value) left.clone(); soot.Local leftLocal; if (left instanceof soot.Local) { leftLocal = (soot.Local) left; } else { leftLocal = lg.generateLocal(left.getType()); soot.jimple.AssignStmt stmt1 = soot.jimple.Jimple.v().newAssignStmt(leftLocal, left); body.getUnits().add(stmt1); Util.addLnPosTags(stmt1, assign.position()); } soot.Value right = base().getAssignRightLocal(assign, leftLocal); soot.jimple.AssignStmt stmt2 = soot.jimple.Jimple.v().newAssignStmt(leftLocal, right); body.getUnits().add(stmt2); Util.addLnPosTags(stmt2, assign.position()); Util.addLnPosTags(stmt2.getRightOpBox(), assign.right().position()); Util.addLnPosTags(stmt2.getLeftOpBox(), assign.left().position()); if (!(left instanceof soot.Local)) { soot.jimple.AssignStmt stmt3 = soot.jimple.Jimple.v().newAssignStmt(left2, leftLocal); body.getUnits().add(stmt3); Util.addLnPosTags(stmt3, assign.position()); Util.addLnPosTags(stmt3.getRightOpBox(), assign.right().position()); Util.addLnPosTags(stmt3.getLeftOpBox(), assign.left().position()); } return leftLocal; } /** * Field Expression Creation - LHS */ private soot.Value getFieldLocalLeft(polyglot.ast.Field field) { polyglot.ast.Receiver receiver = field.target(); if ((field.name().equals("length")) && (receiver.type() instanceof polyglot.types.ArrayType)) { return getSpecialArrayLengthLocal(field); } else { return getFieldRef(field); } } /** * Field Expression Creation */ private soot.Value getFieldLocal(polyglot.ast.Field field) { polyglot.ast.Receiver receiver = field.target(); soot.javaToJimple.PolyglotMethodSource ms = (soot.javaToJimple.PolyglotMethodSource) body.getMethod().getSource(); if ((field.name().equals("length")) && (receiver.type() instanceof polyglot.types.ArrayType)) { return getSpecialArrayLengthLocal(field); } else if (field.name().equals("class")) { throw new RuntimeException("Should go through ClassLit"); } else if (base().needsAccessor(field)) { // else if (needsPrivateAccessor(field) || // needsProtectedAccessor(field)){ // ((field.fieldInstance().flags().isPrivate() && // !Util.getSootType(field.fieldInstance().container()).equals(body.getMethod().getDeclaringClass().getType())) // ||()){ soot.Value base = base().getBaseLocal(field.target()); return getPrivateAccessFieldLocal(field, base); } if ((field.target() instanceof polyglot.ast.Special) && (((polyglot.ast.Special) field.target()).kind() == polyglot.ast.Special.SUPER) && (((polyglot.ast.Special) field.target()).qualifier() != null)) { return getSpecialSuperQualifierLocal(field); } else if (shouldReturnConstant(field)) { return getReturnConstant(field); // in this case don't return fieldRef but a string constant } else { soot.jimple.FieldRef fieldRef = getFieldRef(field); soot.Local baseLocal = generateLocal(field.type()); soot.jimple.AssignStmt fieldAssignStmt = soot.jimple.Jimple.v().newAssignStmt(baseLocal, fieldRef); body.getUnits().add(fieldAssignStmt); Util.addLnPosTags(fieldAssignStmt, field.position()); Util.addLnPosTags(fieldAssignStmt.getRightOpBox(), field.position()); return baseLocal; } } @Override protected boolean needsAccessor(polyglot.ast.Expr expr) { if (!(expr instanceof polyglot.ast.Field) && !(expr instanceof polyglot.ast.Call)) { return false; } else { if (expr instanceof polyglot.ast.Field) { return needsAccessor(((polyglot.ast.Field) expr).fieldInstance()); } else { return needsAccessor(((polyglot.ast.Call) expr).methodInstance()); } } } /** * needs accessors: when field or meth is private and in some other class when field or meth is protected and in */ protected boolean needsAccessor(polyglot.types.MemberInstance inst) { if (inst.flags().isPrivate()) { if (!Util.getSootType(inst.container()).equals(body.getMethod().getDeclaringClass().getType())) { return true; } } else if (inst.flags().isProtected()) { if (Util.getSootType(inst.container()).equals(body.getMethod().getDeclaringClass().getType())) { return false; } soot.SootClass currentClass = body.getMethod().getDeclaringClass(); if (currentClass.getSuperclass().getType().equals(Util.getSootType(inst.container()))) { return false; } while (currentClass.hasOuterClass()) { currentClass = currentClass.getOuterClass(); if (Util.getSootType(inst.container()).equals(currentClass.getType())) { return false; } else if (Util.getSootType(inst.container()).equals(currentClass.getSuperclass().getType())) { return true; } } return false; } return false; } /** * needs a private access method if field is private and in some other class */ /* * protected boolean needsPrivateAccessor(polyglot.ast.Field field){ if (field.fieldInstance().flags().isPrivate()){ if * (!Util.getSootType(field.fieldInstance().container()).equals(body. getMethod().getDeclaringClass().getType())){ return * true; } } return false; } */ /** * needs a protected access method if field is protected and in a super class of the outer class of the innerclass trying * to access the field (ie not in self or in outer of self) */ /* * protected boolean needsProtectedAccessor(polyglot.ast.Field field){ //return false; if * (field.fieldInstance().flags().isProtected()){ if (Util.getSootType(field.fieldInstance().container()).equals(body. * getMethod().getDeclaringClass().getType())){ return false; } soot.SootClass currentClass = * body.getMethod().getDeclaringClass(); while (currentClass.hasOuterClass()){ currentClass = currentClass.getOuterClass(); * if (Util.getSootType(field.fieldInstance().container()).equals(currentClass. getType())){ return false; } else if * (Util.getSootType(field.fieldInstance().container()).equals(currentClass. getSuperclass().getType())){ return true; } } * return false; } return false; /* if (field.fieldInstance().flags().isProtected()){ if * (!Util.getSootType(field.fieldInstance().container()).equals(body. getMethod().getDeclaringClass().getType())){ * soot.SootClass checkClass = body.getMethod().getDeclaringClass(); while (checkClass.hasOuterClass()){ checkClass = * checkClass.getOuterClass(); if (Util.getSootType(field.fieldInstance().container()).equals(checkClass. getType())){ * return false; } * * } return true; } } return false; */ // } private soot.jimple.Constant getReturnConstant(polyglot.ast.Field field) { return getConstant(field.constantValue(), field.type()); } private soot.jimple.Constant getConstant(Object constVal, polyglot.types.Type type) { // System.out.println("getConstant: "+constVal); if (constVal instanceof String) { return soot.jimple.StringConstant.v((String) constVal); } else if (constVal instanceof Boolean) { boolean val = ((Boolean) constVal).booleanValue(); return soot.jimple.IntConstant.v(val ? 1 : 0); } else if (type.isChar()) { char val; if (constVal instanceof Integer) { val = (char) ((Integer) constVal).intValue(); } else { val = ((Character) constVal).charValue(); } // System.out.println("val: "+val); return soot.jimple.IntConstant.v(val); } else { Number num = (Number) constVal; // System.out.println("num: "+num); num = createConstantCast(type, num); // System.out.println("num: "+num); if (num instanceof Long) { // System.out.println(((Long)num).longValue()); return soot.jimple.LongConstant.v(((Long) num).longValue()); } else if (num instanceof Double) { return soot.jimple.DoubleConstant.v(((Double) num).doubleValue()); } else if (num instanceof Float) { return soot.jimple.FloatConstant.v(((Float) num).floatValue()); } else if (num instanceof Byte) { return soot.jimple.IntConstant.v(((Byte) num).byteValue()); } else if (num instanceof Short) { return soot.jimple.IntConstant.v(((Short) num).shortValue()); } else { return soot.jimple.IntConstant.v(((Integer) num).intValue()); } } } private Number createConstantCast(polyglot.types.Type fieldType, Number constant) { if (constant instanceof Integer) { if (fieldType.isDouble()) { return new Double(((Integer) constant).intValue()); } else if (fieldType.isFloat()) { return new Float(((Integer) constant).intValue()); } else if (fieldType.isLong()) { return new Long(((Integer) constant).intValue()); } } return constant; } private boolean shouldReturnConstant(polyglot.ast.Field field) { if (field.isConstant() && field.constantValue() != null) { return true; } return false; } /** * creates a field ref */ @Override protected soot.jimple.FieldRef getFieldRef(polyglot.ast.Field field) { soot.SootClass receiverClass = ((soot.RefType) Util.getSootType(field.target().type())).getSootClass(); soot.SootFieldRef receiverField = soot.Scene.v().makeFieldRef(receiverClass, field.name(), Util.getSootType(field.type()), field.flags().isStatic()); soot.jimple.FieldRef fieldRef; if (field.fieldInstance().flags().isStatic()) { fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(receiverField); } else { soot.Local base; base = (soot.Local) base().getBaseLocal(field.target()); fieldRef = soot.jimple.Jimple.v().newInstanceFieldRef(base, receiverField); } if (field.target() instanceof polyglot.ast.Local && fieldRef instanceof soot.jimple.InstanceFieldRef) { Util.addLnPosTags(((soot.jimple.InstanceFieldRef) fieldRef).getBaseBox(), field.target().position()); } return fieldRef; } /** * For Inner Classes - to access private fields of their outer class */ private soot.Local getPrivateAccessFieldLocal(polyglot.ast.Field field, soot.Value base) { // need to add access method // if private add to the containing class // but if its protected then add to outer class - not containing // class because in this case the containing class is the super class soot.SootMethod toInvoke; soot.SootClass invokeClass; if (field.fieldInstance().flags().isPrivate()) { toInvoke = addGetFieldAccessMeth(((soot.RefType) Util.getSootType(field.fieldInstance().container())).getSootClass(), field); invokeClass = ((soot.RefType) Util.getSootType(field.fieldInstance().container())).getSootClass(); } else { if (InitialResolver.v().hierarchy() == null) { InitialResolver.v().hierarchy(new soot.FastHierarchy()); } soot.SootClass containingClass = ((soot.RefType) Util.getSootType(field.fieldInstance().container())).getSootClass(); soot.SootClass addToClass; if (body.getMethod().getDeclaringClass().hasOuterClass()) { addToClass = body.getMethod().getDeclaringClass().getOuterClass(); while (!InitialResolver.v().hierarchy().canStoreType(containingClass.getType(), addToClass.getType())) { if (addToClass.hasOuterClass()) { addToClass = addToClass.getOuterClass(); } else { break; } } } else { addToClass = containingClass; } invokeClass = addToClass; toInvoke = addGetFieldAccessMeth(addToClass, field); } ArrayList params = new ArrayList(); if (!field.fieldInstance().flags().isStatic()) { params.add(base); /* * if (field.target() instanceof polyglot.ast.Expr){ params.add((soot.Local)base().getBaseLocal(field.target())); } * else if (body.getMethod().getDeclaringClass().declaresFieldByName( "this$0")){ * params.add(getThis(invokeClass.getType())); } else { soot.Local local = * (soot.Local)base().getBaseLocal(field.target()); params.add(local); } */ // (soot.Local)getBaseLocal(field.target())); /* * if (Util.getSootType(field.target().type()).equals(invokeClass. getType())){ */ // params.add(getThis(invokeClass.getType()));//(soot.Local)getBaseLocal(field.target())); // } /* else { */ // soot.Local local = (soot.Local)getBaseLocal(field.target()); // params.add(getThis(invokeClass.getType()));//(soot.Local)getBaseLocal(field.target())); // soot.Local local = (soot.Local)getBaseLocal(field.target()); // params.add(local); // } } return Util.getPrivateAccessFieldInvoke(toInvoke.makeRef(), params, body, lg); } /** * To get the local for the special .class literal */ private soot.Local getSpecialClassLitLocal(polyglot.ast.ClassLit lit) { if (lit.typeNode().type().isPrimitive()) { polyglot.types.PrimitiveType primType = (polyglot.types.PrimitiveType) lit.typeNode().type(); soot.Local retLocal = lg.generateLocal(soot.RefType.v("java.lang.Class")); soot.SootFieldRef primField = null; if (primType.isBoolean()) { primField = soot.Scene.v().makeFieldRef(soot.Scene.v().getSootClass("java.lang.Boolean"), "TYPE", soot.RefType.v("java.lang.Class"), true); } else if (primType.isByte()) { primField = soot.Scene.v().makeFieldRef(soot.Scene.v().getSootClass("java.lang.Byte"), "TYPE", soot.RefType.v("java.lang.Class"), true); } else if (primType.isChar()) { primField = soot.Scene.v().makeFieldRef(soot.Scene.v().getSootClass("java.lang.Character"), "TYPE", soot.RefType.v("java.lang.Class"), true); } else if (primType.isDouble()) { primField = soot.Scene.v().makeFieldRef(soot.Scene.v().getSootClass("java.lang.Double"), "TYPE", soot.RefType.v("java.lang.Class"), true); } else if (primType.isFloat()) { primField = soot.Scene.v().makeFieldRef(soot.Scene.v().getSootClass("java.lang.Float"), "TYPE", soot.RefType.v("java.lang.Class"), true); } else if (primType.isInt()) { primField = soot.Scene.v().makeFieldRef(soot.Scene.v().getSootClass("java.lang.Integer"), "TYPE", soot.RefType.v("java.lang.Class"), true); } else if (primType.isLong()) { primField = soot.Scene.v().makeFieldRef(soot.Scene.v().getSootClass("java.lang.Long"), "TYPE", soot.RefType.v("java.lang.Class"), true); } else if (primType.isShort()) { primField = soot.Scene.v().makeFieldRef(soot.Scene.v().getSootClass("java.lang.Short"), "TYPE", soot.RefType.v("java.lang.Class"), true); } else if (primType.isVoid()) { primField = soot.Scene.v().makeFieldRef(soot.Scene.v().getSootClass("java.lang.Void"), "TYPE", soot.RefType.v("java.lang.Class"), true); } soot.jimple.StaticFieldRef fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(primField); soot.jimple.AssignStmt assignStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, fieldRef); body.getUnits().add(assignStmt); return retLocal; } else { // this class soot.SootClass thisClass = body.getMethod().getDeclaringClass(); String fieldName = Util.getFieldNameForClassLit(lit.typeNode().type()); soot.Type fieldType = soot.RefType.v("java.lang.Class"); soot.Local fieldLocal = lg.generateLocal(soot.RefType.v("java.lang.Class")); soot.SootFieldRef sootField = null; if (thisClass.isInterface()) { HashMap<SootClass, SootClass> specialAnonMap = InitialResolver.v().specialAnonMap(); if ((specialAnonMap != null) && (specialAnonMap.containsKey(thisClass))) { soot.SootClass specialClass = specialAnonMap.get(thisClass); sootField = soot.Scene.v().makeFieldRef(specialClass, fieldName, fieldType, true); } else { throw new RuntimeException( "Class is interface so it must have an anon class to handle class lits but its anon class cannot be found."); } } else { sootField = soot.Scene.v().makeFieldRef(thisClass, fieldName, fieldType, true); } soot.jimple.StaticFieldRef fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(sootField); soot.jimple.Stmt fieldAssign = soot.jimple.Jimple.v().newAssignStmt(fieldLocal, fieldRef); body.getUnits().add(fieldAssign); soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Expr neExpr = soot.jimple.Jimple.v().newNeExpr(fieldLocal, soot.jimple.NullConstant.v()); soot.jimple.Stmt ifStmt = soot.jimple.Jimple.v().newIfStmt(neExpr, noop1); body.getUnits().add(ifStmt); ArrayList paramTypes = new ArrayList(); paramTypes.add(soot.RefType.v("java.lang.String")); soot.SootMethodRef invokeMeth = null; if (thisClass.isInterface()) { HashMap<SootClass, SootClass> specialAnonMap = InitialResolver.v().specialAnonMap(); if ((specialAnonMap != null) && (specialAnonMap.containsKey(thisClass))) { soot.SootClass specialClass = specialAnonMap.get(thisClass); invokeMeth = soot.Scene.v().makeMethodRef(specialClass, "class$", paramTypes, soot.RefType.v("java.lang.Class"), true); } else { throw new RuntimeException( "Class is interface so it must have an anon class to handle class lits but its anon class cannot be found."); } } else { invokeMeth = soot.Scene.v().makeMethodRef(thisClass, "class$", paramTypes, soot.RefType.v("java.lang.Class"), true); } ArrayList params = new ArrayList(); params.add(soot.jimple.StringConstant.v(Util.getParamNameForClassLit(lit.typeNode().type()))); soot.jimple.Expr classInvoke = soot.jimple.Jimple.v().newStaticInvokeExpr(invokeMeth, params); soot.Local methLocal = lg.generateLocal(soot.RefType.v("java.lang.Class")); soot.jimple.Stmt invokeAssign = soot.jimple.Jimple.v().newAssignStmt(methLocal, classInvoke); body.getUnits().add(invokeAssign); soot.jimple.Stmt assignField = soot.jimple.Jimple.v().newAssignStmt(fieldRef, methLocal); body.getUnits().add(assignField); soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt goto1 = soot.jimple.Jimple.v().newGotoStmt(noop2); body.getUnits().add(goto1); body.getUnits().add(noop1); fieldAssign = soot.jimple.Jimple.v().newAssignStmt(methLocal, fieldRef); body.getUnits().add(fieldAssign); body.getUnits().add(noop2); return methLocal; } } /** * Array Length local for example a.length w/o brackets gets length of array */ private soot.Local getSpecialArrayLengthLocal(polyglot.ast.Field field) { soot.Local localField; polyglot.ast.Receiver receiver = field.target(); if (receiver instanceof polyglot.ast.Local) { localField = getLocal((polyglot.ast.Local) receiver); } else if (receiver instanceof polyglot.ast.Expr) { localField = (soot.Local) base().createAggressiveExpr((polyglot.ast.Expr) receiver, false, false); } else { localField = generateLocal(receiver.type()); } soot.jimple.LengthExpr lengthExpr = soot.jimple.Jimple.v().newLengthExpr(localField); soot.Local retLocal = lg.generateLocal(soot.IntType.v()); soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(retLocal, lengthExpr); body.getUnits().add(assign); Util.addLnPosTags(assign, field.position()); Util.addLnPosTags(lengthExpr.getOpBox(), field.target().position()); return retLocal; } /** * Binary Expression Creation */ private soot.Value getBinaryLocal2(polyglot.ast.Binary binary, boolean reduceAggressively) { // System.out.println("binary: "+binary+" class: "+binary.getClass()); soot.Value rhs; if (binary.operator() == polyglot.ast.Binary.COND_AND) { return createCondAnd(binary); } if (binary.operator() == polyglot.ast.Binary.COND_OR) { return createCondOr(binary); } if (binary.type().toString().equals("java.lang.String")) { // System.out.println("binary: "+binary); if (areAllStringLits(binary)) { String result = createStringConstant(binary); // System.out.println("created string constant: "+result); return soot.jimple.StringConstant.v(result); } else { soot.Local sb = createStringBuffer(binary); sb = generateAppends(binary.left(), sb); sb = generateAppends(binary.right(), sb); return createToString(sb, binary); } } // System.out.println("bin exp left: "+binary.left()); // System.out.println("bin exp right: "+binary.right()); soot.Value lVal = base().createAggressiveExpr(binary.left(), true, false); soot.Value rVal = base().createAggressiveExpr(binary.right(), true, false); if (isComparisonBinary(binary.operator())) { // System.out.println("bin exp: "+binary); rhs = getBinaryComparisonExpr(lVal, rVal, binary.operator()); } else { rhs = getBinaryExpr(lVal, rVal, binary.operator()); } if (rhs instanceof soot.jimple.BinopExpr) { Util.addLnPosTags(((soot.jimple.BinopExpr) rhs).getOp1Box(), binary.left().position()); Util.addLnPosTags(((soot.jimple.BinopExpr) rhs).getOp2Box(), binary.right().position()); } if (rhs instanceof soot.jimple.ConditionExpr && !reduceAggressively) { return rhs; } else if (rhs instanceof soot.jimple.ConditionExpr) { rhs = handleCondBinExpr((soot.jimple.ConditionExpr) rhs, true); } soot.Local lhs = generateLocal(binary.type()); soot.jimple.AssignStmt assignStmt = soot.jimple.Jimple.v().newAssignStmt(lhs, rhs); body.getUnits().add(assignStmt); // System.out.println("binary pos: "+binary.position()); Util.addLnPosTags(assignStmt.getRightOpBox(), binary.position()); Util.addLnPosTags(assignStmt, binary.position()); return lhs; } private boolean areAllStringLits(polyglot.ast.Node node) { // System.out.println("node in is string lit: "+node+" kind: // "+node.getClass()); if (node instanceof polyglot.ast.StringLit) { return true; } else if (node instanceof polyglot.ast.Field) { if (shouldReturnConstant((polyglot.ast.Field) node)) { return true; } else { return false; } } else if (node instanceof polyglot.ast.Binary) { if (areAllStringLitsBinary((polyglot.ast.Binary) node)) { return true; } return false; } else if (node instanceof polyglot.ast.Unary) { polyglot.ast.Unary unary = (polyglot.ast.Unary) node; if (unary.isConstant()) { return true; } return false; } else if (node instanceof polyglot.ast.Cast) { polyglot.ast.Cast cast = (polyglot.ast.Cast) node; if (cast.isConstant()) { return true; } return false; } else if (node instanceof polyglot.ast.Lit) { polyglot.ast.Lit lit = (polyglot.ast.Lit) node; // System.out.println("lit: "+lit+" is constant: // "+(lit.isConstant()?true:false)); if (lit.isConstant()) { return true; } return false; } return false; } private boolean areAllStringLitsBinary(polyglot.ast.Binary binary) { if (areAllStringLits(binary.left()) && areAllStringLits(binary.right())) { return true; } else { return false; } } private String createStringConstant(polyglot.ast.Node node) { // System.out.println("creatinf string constant: // "+createConstant((polyglot.ast.Expr)node)); String s = null; if (node instanceof polyglot.ast.StringLit) { s = ((polyglot.ast.StringLit) node).value(); } else if (node instanceof polyglot.ast.Cast) { polyglot.ast.Cast cast = (polyglot.ast.Cast) node; if (cast.type().isChar()) { s = "" + ((Character) cast.constantValue()).charValue(); } else { s = "" + cast.constantValue(); } } else if (node instanceof polyglot.ast.Unary) { polyglot.ast.Unary unary = (polyglot.ast.Unary) node; s = "" + unary.constantValue(); } else if (node instanceof polyglot.ast.CharLit) { s = "" + ((polyglot.ast.CharLit) node).value(); } else if (node instanceof polyglot.ast.BooleanLit) { s = "" + ((polyglot.ast.BooleanLit) node).value(); } else if (node instanceof polyglot.ast.IntLit) { s = "" + ((polyglot.ast.IntLit) node).value(); } else if (node instanceof polyglot.ast.FloatLit) { s = "" + ((polyglot.ast.FloatLit) node).value(); } else if (node instanceof polyglot.ast.NullLit) { s = "null"; } else if (node instanceof polyglot.ast.Field) { polyglot.ast.Field field = (polyglot.ast.Field) node; if (field.fieldInstance().constantValue() instanceof String) { s = (String) field.constantValue(); } else if (field.fieldInstance().constantValue() instanceof Boolean) { boolean val = ((Boolean) field.constantValue()).booleanValue(); int temp = val ? 1 : 0; s = "" + temp; } else if (field.type().isChar()) { char val = (char) ((Integer) field.constantValue()).intValue(); s = "" + val; } else { Number num = (Number) field.fieldInstance().constantValue(); num = createConstantCast(field.type(), num); if (num instanceof Long) { s = "" + ((Long) num).longValue(); } else if (num instanceof Double) { s = "" + ((Double) num).doubleValue(); } else if (num instanceof Float) { s = "" + ((Float) num).floatValue(); } else if (num instanceof Byte) { s = "" + ((Byte) num).byteValue(); } else if (num instanceof Short) { s = "" + ((Short) num).shortValue(); } else { s = "" + ((Integer) num).intValue(); } } } else if (node instanceof polyglot.ast.Binary) { s = createStringConstantBinary((polyglot.ast.Binary) node); } else { throw new RuntimeException("No other string constant folding done"); } return s; } private String createStringConstantBinary(polyglot.ast.Binary binary) { // System.out.println("create string binary: type"+binary.type()); String s = null; if (Util.getSootType(binary.type()).toString().equals("java.lang.String")) { // here if type is a string return string constant s = createStringConstant(binary.left()) + createStringConstant(binary.right()); } else { // else eval and return string of the eval result s = binary.constantValue().toString(); } return s; } private boolean isComparisonBinary(polyglot.ast.Binary.Operator op) { if ((op == polyglot.ast.Binary.EQ) || (op == polyglot.ast.Binary.NE) || (op == polyglot.ast.Binary.GE) || (op == polyglot.ast.Binary.GT) || (op == polyglot.ast.Binary.LE) || (op == polyglot.ast.Binary.LT)) { return true; } else { return false; } } /** * Creates a binary expression that is not a comparison */ private soot.Value getBinaryExpr(soot.Value lVal, soot.Value rVal, polyglot.ast.Binary.Operator operator) { soot.Value rValue = null; if (lVal instanceof soot.jimple.ConditionExpr) { lVal = handleCondBinExpr((soot.jimple.ConditionExpr) lVal); } if (rVal instanceof soot.jimple.ConditionExpr) { rVal = handleCondBinExpr((soot.jimple.ConditionExpr) rVal); } if (operator == polyglot.ast.Binary.ADD) { rValue = soot.jimple.Jimple.v().newAddExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.SUB) { rValue = soot.jimple.Jimple.v().newSubExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.MUL) { rValue = soot.jimple.Jimple.v().newMulExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.DIV) { rValue = soot.jimple.Jimple.v().newDivExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.SHR) { if (rVal.getType().equals(soot.LongType.v())) { soot.Local intVal = lg.generateLocal(soot.IntType.v()); soot.jimple.CastExpr castExpr = soot.jimple.Jimple.v().newCastExpr(rVal, soot.IntType.v()); soot.jimple.AssignStmt assignStmt = soot.jimple.Jimple.v().newAssignStmt(intVal, castExpr); body.getUnits().add(assignStmt); rValue = soot.jimple.Jimple.v().newShrExpr(lVal, intVal); } else { rValue = soot.jimple.Jimple.v().newShrExpr(lVal, rVal); } } else if (operator == polyglot.ast.Binary.USHR) { if (rVal.getType().equals(soot.LongType.v())) { soot.Local intVal = lg.generateLocal(soot.IntType.v()); soot.jimple.CastExpr castExpr = soot.jimple.Jimple.v().newCastExpr(rVal, soot.IntType.v()); soot.jimple.AssignStmt assignStmt = soot.jimple.Jimple.v().newAssignStmt(intVal, castExpr); body.getUnits().add(assignStmt); rValue = soot.jimple.Jimple.v().newUshrExpr(lVal, intVal); } else { rValue = soot.jimple.Jimple.v().newUshrExpr(lVal, rVal); } } else if (operator == polyglot.ast.Binary.SHL) { if (rVal.getType().equals(soot.LongType.v())) { soot.Local intVal = lg.generateLocal(soot.IntType.v()); soot.jimple.CastExpr castExpr = soot.jimple.Jimple.v().newCastExpr(rVal, soot.IntType.v()); soot.jimple.AssignStmt assignStmt = soot.jimple.Jimple.v().newAssignStmt(intVal, castExpr); body.getUnits().add(assignStmt); rValue = soot.jimple.Jimple.v().newShlExpr(lVal, intVal); } else { rValue = soot.jimple.Jimple.v().newShlExpr(lVal, rVal); } } else if (operator == polyglot.ast.Binary.BIT_AND) { rValue = soot.jimple.Jimple.v().newAndExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.BIT_OR) { rValue = soot.jimple.Jimple.v().newOrExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.BIT_XOR) { rValue = soot.jimple.Jimple.v().newXorExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.MOD) { rValue = soot.jimple.Jimple.v().newRemExpr(lVal, rVal); } else { throw new RuntimeException("Binary not yet handled!"); } return rValue; } /** * Creates a binary expr that is a comparison */ private soot.Value getBinaryComparisonExpr(soot.Value lVal, soot.Value rVal, polyglot.ast.Binary.Operator operator) { soot.Value rValue; if (operator == polyglot.ast.Binary.EQ) { // System.out.println("processing: // "+body.getMethod().getDeclaringClass()); // System.out.println("lval: "+lVal+" rval: "+rVal); rValue = soot.jimple.Jimple.v().newEqExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.GE) { rValue = soot.jimple.Jimple.v().newGeExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.GT) { rValue = soot.jimple.Jimple.v().newGtExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.LE) { rValue = soot.jimple.Jimple.v().newLeExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.LT) { rValue = soot.jimple.Jimple.v().newLtExpr(lVal, rVal); } else if (operator == polyglot.ast.Binary.NE) { rValue = soot.jimple.Jimple.v().newNeExpr(lVal, rVal); } else { throw new RuntimeException("Unknown Comparison Expr"); } return rValue; } /** * in bytecode and Jimple the conditions in conditional binary expressions are often reversed */ private soot.Value reverseCondition(soot.jimple.ConditionExpr cond) { soot.jimple.ConditionExpr newExpr; if (cond instanceof soot.jimple.EqExpr) { newExpr = soot.jimple.Jimple.v().newNeExpr(cond.getOp1(), cond.getOp2()); } else if (cond instanceof soot.jimple.NeExpr) { newExpr = soot.jimple.Jimple.v().newEqExpr(cond.getOp1(), cond.getOp2()); } else if (cond instanceof soot.jimple.GtExpr) { newExpr = soot.jimple.Jimple.v().newLeExpr(cond.getOp1(), cond.getOp2()); } else if (cond instanceof soot.jimple.GeExpr) { newExpr = soot.jimple.Jimple.v().newLtExpr(cond.getOp1(), cond.getOp2()); } else if (cond instanceof soot.jimple.LtExpr) { newExpr = soot.jimple.Jimple.v().newGeExpr(cond.getOp1(), cond.getOp2()); } else if (cond instanceof soot.jimple.LeExpr) { newExpr = soot.jimple.Jimple.v().newGtExpr(cond.getOp1(), cond.getOp2()); } else { throw new RuntimeException("Unknown Condition Expr"); } newExpr.getOp1Box().addAllTagsOf(cond.getOp1Box()); newExpr.getOp2Box().addAllTagsOf(cond.getOp2Box()); return newExpr; } /** * Special conditions for doubles and floats and longs */ private soot.Value handleDFLCond(soot.jimple.ConditionExpr cond) { soot.Local result = lg.generateLocal(soot.ByteType.v()); soot.jimple.Expr cmExpr = null; if (isDouble(cond.getOp1()) || isDouble(cond.getOp2()) || isFloat(cond.getOp1()) || isFloat(cond.getOp2())) { // use cmpg and cmpl if ((cond instanceof soot.jimple.GeExpr) || (cond instanceof soot.jimple.GtExpr)) { // use cmpg cmExpr = soot.jimple.Jimple.v().newCmpgExpr(cond.getOp1(), cond.getOp2()); } else { // use cmpl cmExpr = soot.jimple.Jimple.v().newCmplExpr(cond.getOp1(), cond.getOp2()); } } else if (isLong(cond.getOp1()) || isLong(cond.getOp2())) { // use cmp cmExpr = soot.jimple.Jimple.v().newCmpExpr(cond.getOp1(), cond.getOp2()); } else { return cond; } soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(result, cmExpr); body.getUnits().add(assign); if (cond instanceof soot.jimple.EqExpr) { cond = soot.jimple.Jimple.v().newEqExpr(result, soot.jimple.IntConstant.v(0)); } else if (cond instanceof soot.jimple.GeExpr) { cond = soot.jimple.Jimple.v().newGeExpr(result, soot.jimple.IntConstant.v(0)); } else if (cond instanceof soot.jimple.GtExpr) { cond = soot.jimple.Jimple.v().newGtExpr(result, soot.jimple.IntConstant.v(0)); } else if (cond instanceof soot.jimple.LeExpr) { cond = soot.jimple.Jimple.v().newLeExpr(result, soot.jimple.IntConstant.v(0)); } else if (cond instanceof soot.jimple.LtExpr) { cond = soot.jimple.Jimple.v().newLtExpr(result, soot.jimple.IntConstant.v(0)); } else if (cond instanceof soot.jimple.NeExpr) { cond = soot.jimple.Jimple.v().newNeExpr(result, soot.jimple.IntConstant.v(0)); } else { throw new RuntimeException("Unknown Comparison Expr"); } return cond; } private boolean isDouble(soot.Value val) { if (val.getType() instanceof soot.DoubleType) { return true; } return false; } private boolean isFloat(soot.Value val) { if (val.getType() instanceof soot.FloatType) { return true; } return false; } private boolean isLong(soot.Value val) { if (val.getType() instanceof soot.LongType) { return true; } return false; } /** * Creates a conitional AND expr */ private soot.Value createCondAnd(polyglot.ast.Binary binary) { soot.Local retLocal = lg.generateLocal(soot.BooleanType.v()); soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); soot.Value lVal = base().createAggressiveExpr(binary.left(), false, false); boolean leftNeedIf = needSootIf(lVal); if (!(lVal instanceof soot.jimple.ConditionExpr)) { lVal = soot.jimple.Jimple.v().newEqExpr(lVal, soot.jimple.IntConstant.v(0)); } else { lVal = reverseCondition((soot.jimple.ConditionExpr) lVal); lVal = handleDFLCond((soot.jimple.ConditionExpr) lVal); } if (leftNeedIf) { soot.jimple.IfStmt ifLeft; /* * if (!falseNoop.empty()){ soot.jimple.Stmt fNoop = (soot.jimple.Stmt)falseNoop.peek(); ifLeft = * soot.jimple.Jimple.v().newIfStmt(lVal, fNoop); } else { */ ifLeft = soot.jimple.Jimple.v().newIfStmt(lVal, noop1); // } body.getUnits().add(ifLeft); Util.addLnPosTags(ifLeft.getConditionBox(), binary.left().position()); Util.addLnPosTags(ifLeft, binary.left().position()); } soot.jimple.Stmt endNoop = soot.jimple.Jimple.v().newNopStmt(); soot.Value rVal = base().createAggressiveExpr(binary.right(), false, false); boolean rightNeedIf = needSootIf(rVal); if (!(rVal instanceof soot.jimple.ConditionExpr)) { rVal = soot.jimple.Jimple.v().newEqExpr(rVal, soot.jimple.IntConstant.v(0)); } else { rVal = reverseCondition((soot.jimple.ConditionExpr) rVal); rVal = handleDFLCond((soot.jimple.ConditionExpr) rVal); } if (rightNeedIf) { soot.jimple.IfStmt ifRight; /* * if (!falseNoop.empty()){ soot.jimple.Stmt fNoop = (soot.jimple.Stmt)falseNoop.peek(); ifRight = * soot.jimple.Jimple.v().newIfStmt(rVal, fNoop); } else { */ ifRight = soot.jimple.Jimple.v().newIfStmt(rVal, noop1); // } body.getUnits().add(ifRight); Util.addLnPosTags(ifRight.getConditionBox(), binary.right().position()); Util.addLnPosTags(ifRight, binary.right().position()); } // return if cond will be used in if /* * if (!falseNoop.empty()){ return soot.jimple.IntConstant.v(1); } */ soot.jimple.Stmt assign1 = soot.jimple.Jimple.v().newAssignStmt(retLocal, soot.jimple.IntConstant.v(1)); body.getUnits().add(assign1); soot.jimple.Stmt gotoEnd1 = soot.jimple.Jimple.v().newGotoStmt(endNoop); body.getUnits().add(gotoEnd1); body.getUnits().add(noop1); soot.jimple.Stmt assign2 = soot.jimple.Jimple.v().newAssignStmt(retLocal, soot.jimple.IntConstant.v(0)); body.getUnits().add(assign2); body.getUnits().add(endNoop); Util.addLnPosTags(assign1, binary.position()); Util.addLnPosTags(assign2, binary.position()); return retLocal; } int inLeftOr = 0; /** * Creates a conditional OR expr */ private soot.Value createCondOr(polyglot.ast.Binary binary) { // System.out.println("cond or binary: "+binary); soot.Local retLocal = lg.generateLocal(soot.BooleanType.v()); // end soot.jimple.Stmt endNoop = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); // inLeftOr++; soot.Value lVal = base().createAggressiveExpr(binary.left(), false, false); // inLeftOr--; // System.out.println("leftval : "+lVal); boolean leftNeedIf = needSootIf(lVal); if (!(lVal instanceof soot.jimple.ConditionExpr)) { lVal = soot.jimple.Jimple.v().newNeExpr(lVal, soot.jimple.IntConstant.v(0)); } else { // no reversing of condition needed for first expr in conditional // or expression lVal = handleDFLCond((soot.jimple.ConditionExpr) lVal); } if (leftNeedIf) { soot.jimple.IfStmt ifLeft; /* * if (!trueNoop.empty()){ ifLeft = soot.jimple.Jimple.v().newIfStmt(lVal, (soot.jimple.Stmt)trueNoop.peek()); } else { */ ifLeft = soot.jimple.Jimple.v().newIfStmt(lVal, noop1); // } body.getUnits().add(ifLeft); Util.addLnPosTags(ifLeft, binary.left().position()); Util.addLnPosTags(ifLeft.getConditionBox(), binary.left().position()); } soot.Value rVal = base().createAggressiveExpr(binary.right(), false, false); boolean rightNeedIf = needSootIf(rVal); if (!(rVal instanceof soot.jimple.ConditionExpr)) { rVal = soot.jimple.Jimple.v().newEqExpr(rVal, soot.jimple.IntConstant.v(0)); } else { // need to reverse right part of conditional or expr if (/* !trueNoop.empty() && */ inLeftOr == 0) { rVal = reverseCondition((soot.jimple.ConditionExpr) rVal); } rVal = handleDFLCond((soot.jimple.ConditionExpr) rVal); } if (rightNeedIf) { soot.jimple.IfStmt ifRight; /* * if (!trueNoop.empty()){ if (inLeftOr == 0){ ifRight = soot.jimple.Jimple.v().newIfStmt(rVal, * (soot.jimple.Stmt)falseNoop.peek()); } else { ifRight = soot.jimple.Jimple.v().newIfStmt(rVal, * (soot.jimple.Stmt)trueNoop.peek()); } } else { */ ifRight = soot.jimple.Jimple.v().newIfStmt(rVal, noop2); // } body.getUnits().add(ifRight); Util.addLnPosTags(ifRight, binary.right().position()); Util.addLnPosTags(ifRight.getConditionBox(), binary.right().position()); } // return if cond will be used in if /* * if (!trueNoop.empty()){ return soot.jimple.IntConstant.v(1); } */ body.getUnits().add(noop1); soot.jimple.Stmt assign2 = soot.jimple.Jimple.v().newAssignStmt(retLocal, soot.jimple.IntConstant.v(1)); body.getUnits().add(assign2); Util.addLnPosTags(assign2, binary.position()); soot.jimple.Stmt gotoEnd2 = soot.jimple.Jimple.v().newGotoStmt(endNoop); body.getUnits().add(gotoEnd2); body.getUnits().add(noop2); soot.jimple.Stmt assign3 = soot.jimple.Jimple.v().newAssignStmt(retLocal, soot.jimple.IntConstant.v(0)); body.getUnits().add(assign3); Util.addLnPosTags(assign3, binary.position()); body.getUnits().add(endNoop); Util.addLnPosTags(assign2, binary.position()); Util.addLnPosTags(assign3, binary.position()); return retLocal; } private soot.Local handleCondBinExpr(soot.jimple.ConditionExpr condExpr) { soot.Local boolLocal = lg.generateLocal(soot.BooleanType.v()); soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); soot.Value newVal; newVal = reverseCondition(condExpr); newVal = handleDFLCond((soot.jimple.ConditionExpr) newVal); soot.jimple.Stmt ifStmt = soot.jimple.Jimple.v().newIfStmt(newVal, noop1); body.getUnits().add(ifStmt); body.getUnits().add(soot.jimple.Jimple.v().newAssignStmt(boolLocal, soot.jimple.IntConstant.v(1))); soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt goto1 = soot.jimple.Jimple.v().newGotoStmt(noop2); body.getUnits().add(goto1); body.getUnits().add(noop1); body.getUnits().add(soot.jimple.Jimple.v().newAssignStmt(boolLocal, soot.jimple.IntConstant.v(0))); body.getUnits().add(noop2); return boolLocal; } private soot.Local handleCondBinExpr(soot.jimple.ConditionExpr condExpr, boolean reverse) { soot.Local boolLocal = lg.generateLocal(soot.BooleanType.v()); soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); soot.Value newVal = condExpr; if (reverse) { newVal = reverseCondition(condExpr); } newVal = handleDFLCond((soot.jimple.ConditionExpr) newVal); soot.jimple.Stmt ifStmt = soot.jimple.Jimple.v().newIfStmt(newVal, noop1); body.getUnits().add(ifStmt); body.getUnits().add(soot.jimple.Jimple.v().newAssignStmt(boolLocal, soot.jimple.IntConstant.v(1))); soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt goto1 = soot.jimple.Jimple.v().newGotoStmt(noop2); body.getUnits().add(goto1); body.getUnits().add(noop1); body.getUnits().add(soot.jimple.Jimple.v().newAssignStmt(boolLocal, soot.jimple.IntConstant.v(0))); body.getUnits().add(noop2); return boolLocal; } private soot.Local createStringBuffer(polyglot.ast.Expr expr) { // create and add one string buffer soot.Local local = lg.generateLocal(soot.RefType.v("java.lang.StringBuffer")); soot.jimple.NewExpr newExpr = soot.jimple.Jimple.v().newNewExpr(soot.RefType.v("java.lang.StringBuffer")); soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(local, newExpr); body.getUnits().add(assign); Util.addLnPosTags(assign, expr.position()); soot.SootClass classToInvoke1 = soot.Scene.v().getSootClass("java.lang.StringBuffer"); soot.SootMethodRef methodToInvoke1 = soot.Scene.v().makeMethodRef(classToInvoke1, "<init>", new ArrayList(), soot.VoidType.v(), false); soot.jimple.SpecialInvokeExpr invoke = soot.jimple.Jimple.v().newSpecialInvokeExpr(local, methodToInvoke1); soot.jimple.Stmt invokeStmt = soot.jimple.Jimple.v().newInvokeStmt(invoke); body.getUnits().add(invokeStmt); Util.addLnPosTags(invokeStmt, expr.position()); return local; } private soot.Local createToString(soot.Local sb, polyglot.ast.Expr expr) { // invoke toString on local (type StringBuffer) soot.Local newString = lg.generateLocal(soot.RefType.v("java.lang.String")); soot.SootClass classToInvoke2 = soot.Scene.v().getSootClass("java.lang.StringBuffer"); soot.SootMethodRef methodToInvoke2 = soot.Scene.v().makeMethodRef(classToInvoke2, "toString", new ArrayList(), soot.RefType.v("java.lang.String"), false); soot.jimple.VirtualInvokeExpr toStringInvoke = soot.jimple.Jimple.v().newVirtualInvokeExpr(sb, methodToInvoke2); soot.jimple.Stmt lastAssign = soot.jimple.Jimple.v().newAssignStmt(newString, toStringInvoke); body.getUnits().add(lastAssign); Util.addLnPosTags(lastAssign, expr.position()); return newString; } private boolean isStringConcat(polyglot.ast.Expr expr) { if (expr instanceof polyglot.ast.Binary) { polyglot.ast.Binary bin = (polyglot.ast.Binary) expr; if (bin.operator() == polyglot.ast.Binary.ADD) { if (bin.type().toString().equals("java.lang.String")) { return true; } return false; } return false; } else if (expr instanceof polyglot.ast.Assign) { polyglot.ast.Assign assign = (polyglot.ast.Assign) expr; if (assign.operator() == polyglot.ast.Assign.ADD_ASSIGN) { if (assign.type().toString().equals("java.lang.String")) { return true; } return false; } return false; } return false; } /** * Generates one part of a concatenation String */ private soot.Local generateAppends(polyglot.ast.Expr expr, soot.Local sb) { // System.out.println("generate appends for expr: "+expr); if (isStringConcat(expr)) { if (expr instanceof polyglot.ast.Binary) { sb = generateAppends(((polyglot.ast.Binary) expr).left(), sb); sb = generateAppends(((polyglot.ast.Binary) expr).right(), sb); } else { sb = generateAppends(((polyglot.ast.Assign) expr).left(), sb); sb = generateAppends(((polyglot.ast.Assign) expr).right(), sb); } } else { soot.Value toApp = base().createAggressiveExpr(expr, false, false); // System.out.println("toApp: "+toApp+" type: "+toApp.getType()); soot.Type appendType = null; if (toApp instanceof soot.jimple.StringConstant) { appendType = soot.RefType.v("java.lang.String"); } else if (toApp instanceof soot.jimple.NullConstant) { appendType = soot.RefType.v("java.lang.Object"); } else if (toApp instanceof soot.jimple.Constant) { appendType = toApp.getType(); } else if (toApp instanceof soot.Local) { if (((soot.Local) toApp).getType() instanceof soot.PrimType) { appendType = ((soot.Local) toApp).getType(); } else if (((soot.Local) toApp).getType() instanceof soot.RefType) { if (((soot.Local) toApp).getType().toString().equals("java.lang.String")) { appendType = soot.RefType.v("java.lang.String"); } else if (((soot.Local) toApp).getType().toString().equals("java.lang.StringBuffer")) { appendType = soot.RefType.v("java.lang.StringBuffer"); } else { appendType = soot.RefType.v("java.lang.Object"); } } else { // this is for arrays appendType = soot.RefType.v("java.lang.Object"); } } else if (toApp instanceof soot.jimple.ConditionExpr) { toApp = handleCondBinExpr((soot.jimple.ConditionExpr) toApp); appendType = soot.BooleanType.v(); } // handle shorts if (appendType instanceof soot.ShortType || appendType instanceof soot.ByteType) { soot.Local intLocal = lg.generateLocal(soot.IntType.v()); soot.jimple.Expr cast = soot.jimple.Jimple.v().newCastExpr(toApp, soot.IntType.v()); soot.jimple.Stmt castAssign = soot.jimple.Jimple.v().newAssignStmt(intLocal, cast); body.getUnits().add(castAssign); toApp = intLocal; appendType = soot.IntType.v(); } ArrayList paramsTypes = new ArrayList(); paramsTypes.add(appendType); ArrayList params = new ArrayList(); params.add(toApp); soot.SootClass classToInvoke = soot.Scene.v().getSootClass("java.lang.StringBuffer"); soot.SootMethodRef methodToInvoke = soot.Scene.v().makeMethodRef(classToInvoke, "append", paramsTypes, soot.RefType.v("java.lang.StringBuffer"), false); soot.jimple.VirtualInvokeExpr appendInvoke = soot.jimple.Jimple.v().newVirtualInvokeExpr(sb, methodToInvoke, params); Util.addLnPosTags(appendInvoke.getArgBox(0), expr.position()); soot.Local tmp = lg.generateLocal(soot.RefType.v("java.lang.StringBuffer")); soot.jimple.Stmt appendStmt = soot.jimple.Jimple.v().newAssignStmt(tmp, appendInvoke); sb = tmp; body.getUnits().add(appendStmt); Util.addLnPosTags(appendStmt, expr.position()); } return sb; } /** * Unary Expression Creation */ private soot.Value getUnaryLocal(polyglot.ast.Unary unary) { polyglot.ast.Expr expr = unary.expr(); polyglot.ast.Unary.Operator op = unary.operator(); if (op == polyglot.ast.Unary.POST_INC || op == polyglot.ast.Unary.PRE_INC || op == polyglot.ast.Unary.POST_DEC || op == polyglot.ast.Unary.PRE_DEC) { if (base().needsAccessor(unary.expr())) { return base().handlePrivateFieldUnarySet(unary); } soot.Value left = base().createLHS(unary.expr()); // do necessary cloning soot.Value leftClone = Jimple.cloneIfNecessary(left); soot.Local tmp = lg.generateLocal(left.getType()); soot.jimple.AssignStmt stmt1 = soot.jimple.Jimple.v().newAssignStmt(tmp, left); body.getUnits().add(stmt1); Util.addLnPosTags(stmt1, unary.position()); soot.Value incVal = base().getConstant(left.getType(), 1); soot.jimple.BinopExpr binExpr; if (unary.operator() == polyglot.ast.Unary.PRE_INC || unary.operator() == polyglot.ast.Unary.POST_INC) { binExpr = soot.jimple.Jimple.v().newAddExpr(tmp, incVal); } else { binExpr = soot.jimple.Jimple.v().newSubExpr(tmp, incVal); } soot.Local tmp2 = lg.generateLocal(left.getType()); soot.jimple.AssignStmt assign = soot.jimple.Jimple.v().newAssignStmt(tmp2, binExpr); body.getUnits().add(assign); // if (base().needsAccessor(unary.expr())){ // base().handlePrivateFieldSet(unary.expr(), tmp2); // } // else { soot.jimple.AssignStmt stmt3 = soot.jimple.Jimple.v().newAssignStmt(leftClone, tmp2); body.getUnits().add(stmt3); // } if (unary.operator() == polyglot.ast.Unary.POST_DEC || unary.operator() == polyglot.ast.Unary.POST_INC) { return tmp; } else { return tmp2; } } /* * if (op == polyglot.ast.Unary.POST_INC){ soot.Local retLocal = generateLocal(expr.type()); soot.Value sootExpr = * base().createExpr(expr); soot.jimple.AssignStmt preStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, sootExpr); * body.getUnits().add(preStmt); * * soot.jimple.AddExpr addExpr = soot.jimple.Jimple.v().newAddExpr(sootExpr, getConstant(retLocal.getType(), 1)); * * Util.addLnPosTags(addExpr.getOp1Box(), expr.position()); * * soot.Local local = generateLocal(expr.type()); soot.jimple.AssignStmt stmt = * soot.jimple.Jimple.v().newAssignStmt(local, addExpr); body.getUnits().add(stmt); * * Util.addLnPosTags(stmt, expr.position()); soot.jimple.AssignStmt aStmt = * soot.jimple.Jimple.v().newAssignStmt(sootExpr, local); body.getUnits().add(aStmt); * * Util.addLnPosTags(aStmt, expr.position()); Util.addLnPosTags(aStmt, unary.position()); * * if ((expr instanceof polyglot.ast.Field) || (expr instanceof polyglot.ast.ArrayAccess)) { //if ((expr instanceof * polyglot.ast.Field) && (needsPrivateAccessor((polyglot.ast.Field)expr) || * needsProtectedAccessor((polyglot.ast.Field)expr))){ if (base().needsAccessor(expr)){ handlePrivateFieldSet(expr, * local); } else { soot.Value actualUnaryExpr = createLHS(expr); soot.jimple.AssignStmt s = * soot.jimple.Jimple.v().newAssignStmt(actualUnaryExpr, local); body.getUnits().add(s); Util.addLnPosTags(s, * expr.position()); Util.addLnPosTags(s.getLeftOpBox(), expr.position()); } * * } return retLocal; * * } else if (op == polyglot.ast.Unary.POST_DEC) { soot.Local retLocal = generateLocal(expr.type()); * * soot.Value sootExpr = base().createExpr(expr); * * soot.jimple.AssignStmt preStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, sootExpr); * body.getUnits().add(preStmt); * * soot.jimple.SubExpr subExpr = soot.jimple.Jimple.v().newSubExpr(sootExpr, getConstant(retLocal.getType(), 1)); * Util.addLnPosTags(subExpr.getOp1Box(), expr.position()); * * soot.Local local = generateLocal(expr.type()); soot.jimple.AssignStmt stmt = * soot.jimple.Jimple.v().newAssignStmt(local, subExpr); body.getUnits().add(stmt); Util.addLnPosTags(stmt, * expr.position()); * * soot.jimple.AssignStmt aStmt = soot.jimple.Jimple.v().newAssignStmt(sootExpr, local); body.getUnits().add(aStmt); * * Util.addLnPosTags(aStmt, expr.position()); Util.addLnPosTags(aStmt, unary.position()); * * if ((expr instanceof polyglot.ast.Field) || (expr instanceof polyglot.ast.ArrayAccess)) { //if ((expr instanceof * polyglot.ast.Field) && (needsPrivateAccessor((polyglot.ast.Field)expr) || * needsProtectedAccessor((polyglot.ast.Field)expr))){ if (base().needsAccessor(expr)){ handlePrivateFieldSet(expr, * local); } else { soot.Value actualUnaryExpr = createLHS(expr); soot.jimple.AssignStmt s = * soot.jimple.Jimple.v().newAssignStmt(actualUnaryExpr, local); body.getUnits().add(s); * * Util.addLnPosTags(s, expr.position()); Util.addLnPosTags(s.getLeftOpBox(), expr.position()); } } * * return retLocal; * * } else if (op == polyglot.ast.Unary.PRE_INC) { * * soot.Value sootExpr = base().createExpr(expr); * * soot.jimple.AddExpr addExpr = soot.jimple.Jimple.v().newAddExpr(sootExpr, getConstant(sootExpr.getType(), 1)); * Util.addLnPosTags(addExpr.getOp1Box(), expr.position()); * * soot.Local local = generateLocal(expr.type()); * * soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(local, addExpr); * * body.getUnits().add(stmt); Util.addLnPosTags(stmt, expr.position()); * * if ((expr instanceof polyglot.ast.Field) || (expr instanceof polyglot.ast.ArrayAccess) || (expr instanceof * polyglot.ast.Local)) { //if ((expr instanceof polyglot.ast.Field) && (needsPrivateAccessor((polyglot.ast.Field)expr) * || needsProtectedAccessor((polyglot.ast.Field)expr))){ if (base().needsAccessor(expr)){ handlePrivateFieldSet(expr, * local); } else { soot.Value actualUnaryExpr = createLHS(expr); * body.getUnits().add(soot.jimple.Jimple.v().newAssignStmt( actualUnaryExpr, local)); } } * * return local; * * } else if (op == polyglot.ast.Unary.PRE_DEC) { * * soot.Value sootExpr = base().createExpr(expr); * * soot.jimple.SubExpr subExpr = soot.jimple.Jimple.v().newSubExpr(sootExpr, getConstant(sootExpr.getType(), 1)); * Util.addLnPosTags(subExpr.getOp1Box(), expr.position()); * * soot.Local local = generateLocal(expr.type()); * * soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(local, subExpr); * * body.getUnits().add(stmt); Util.addLnPosTags(stmt, expr.position()); * * if ((expr instanceof polyglot.ast.Field) || (expr instanceof polyglot.ast.ArrayAccess) || (expr instanceof * polyglot.ast.Local)) { * * //if ((expr instanceof polyglot.ast.Field) && (needsPrivateAccessor((polyglot.ast.Field)expr) || * needsProtectedAccessor((polyglot.ast.Field)expr))){ if (base().needsAccessor(expr)){ handlePrivateFieldSet(expr, * local); } else { soot.Value actualUnaryExpr = createLHS(expr); * body.getUnits().add(soot.jimple.Jimple.v().newAssignStmt( actualUnaryExpr, local)); } } * * return local; * * } */ else if (op == polyglot.ast.Unary.BIT_NOT) { soot.jimple.IntConstant int1 = soot.jimple.IntConstant.v(-1); soot.Local retLocal = generateLocal(expr.type()); soot.Value sootExpr = base().createAggressiveExpr(expr, false, false); soot.jimple.XorExpr xor = soot.jimple.Jimple.v().newXorExpr(sootExpr, base().getConstant(sootExpr.getType(), -1)); Util.addLnPosTags(xor.getOp1Box(), expr.position()); soot.jimple.Stmt assign1 = soot.jimple.Jimple.v().newAssignStmt(retLocal, xor); body.getUnits().add(assign1); Util.addLnPosTags(assign1, unary.position()); return retLocal; } else if (op == polyglot.ast.Unary.NEG) { soot.Value sootExpr; if (expr instanceof polyglot.ast.IntLit) { long longVal = ((polyglot.ast.IntLit) expr).value(); if (((polyglot.ast.IntLit) expr).kind() == polyglot.ast.IntLit.LONG) { sootExpr = soot.jimple.LongConstant.v(-longVal); } else { sootExpr = soot.jimple.IntConstant.v(-(int) longVal); } } else if (expr instanceof polyglot.ast.FloatLit) { double doubleVal = ((polyglot.ast.FloatLit) expr).value(); if (((polyglot.ast.FloatLit) expr).kind() == polyglot.ast.FloatLit.DOUBLE) { sootExpr = soot.jimple.DoubleConstant.v(-doubleVal); } else { sootExpr = soot.jimple.FloatConstant.v(-(float) doubleVal); } } else { soot.Value local = base().createAggressiveExpr(expr, false, false); soot.jimple.NegExpr negExpr = soot.jimple.Jimple.v().newNegExpr(local); sootExpr = negExpr; Util.addLnPosTags(negExpr.getOpBox(), expr.position()); } soot.Local retLocal = generateLocal(expr.type()); soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(retLocal, sootExpr); body.getUnits().add(assign); Util.addLnPosTags(assign, expr.position()); return retLocal; } else if (op == polyglot.ast.Unary.POS) { soot.Local retLocal = generateLocal(expr.type()); soot.Value sootExpr = base().createAggressiveExpr(expr, false, false); soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(retLocal, sootExpr); body.getUnits().add(assign); Util.addLnPosTags(assign, expr.position()); return retLocal; } else if (op == polyglot.ast.Unary.NOT) { // pop any trueNoop and falseNoop - if its in an if and in a unary // then it needs old style generation boolean repush = false; soot.jimple.Stmt tNoop = null; soot.jimple.Stmt fNoop = null; if (!trueNoop.empty() && !falseNoop.empty()) { tNoop = trueNoop.pop(); fNoop = falseNoop.pop(); repush = true; } soot.Value local = base().createAggressiveExpr(expr, false, false); // repush right away to optimize ! for ifs if (repush) { trueNoop.push(tNoop); falseNoop.push(fNoop); } if (local instanceof soot.jimple.ConditionExpr) { local = handleCondBinExpr((soot.jimple.ConditionExpr) local); } soot.jimple.NeExpr neExpr = soot.jimple.Jimple.v().newNeExpr(local, base().getConstant(local.getType(), 0)); soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.IfStmt ifStmt; if (!falseNoop.empty()) { ifStmt = soot.jimple.Jimple.v().newIfStmt(neExpr, falseNoop.peek()); } else { ifStmt = soot.jimple.Jimple.v().newIfStmt(neExpr, noop1); } body.getUnits().add(ifStmt); Util.addLnPosTags(ifStmt, expr.position()); Util.addLnPosTags(ifStmt.getConditionBox(), expr.position()); if (!falseNoop.empty()) { return soot.jimple.IntConstant.v(1); } soot.Local retLocal = lg.generateLocal(local.getType()); soot.jimple.Stmt assign1 = soot.jimple.Jimple.v().newAssignStmt(retLocal, base().getConstant(retLocal.getType(), 1)); body.getUnits().add(assign1); Util.addLnPosTags(assign1, expr.position()); soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt goto1 = soot.jimple.Jimple.v().newGotoStmt(noop2); body.getUnits().add(goto1); body.getUnits().add(noop1); soot.jimple.Stmt assign2 = soot.jimple.Jimple.v().newAssignStmt(retLocal, base().getConstant(retLocal.getType(), 0)); body.getUnits().add(assign2); Util.addLnPosTags(assign2, expr.position()); body.getUnits().add(noop2); return retLocal; } else { throw new RuntimeException("Unhandled Unary Expr"); } } /** * Returns a needed constant given a type and val */ @Override protected soot.jimple.Constant getConstant(soot.Type type, int val) { if (type instanceof soot.DoubleType) { return soot.jimple.DoubleConstant.v(val); } else if (type instanceof soot.FloatType) { return soot.jimple.FloatConstant.v(val); } else if (type instanceof soot.LongType) { return soot.jimple.LongConstant.v(val); } else { return soot.jimple.IntConstant.v(val); } } /** * Cast Expression Creation */ private soot.Value getCastLocal(polyglot.ast.Cast castExpr) { // if its already the right type if (castExpr.expr().type().equals(castExpr.type()) || (castExpr.type().isClass() && Util.getSootType(castExpr.type()).toString().equals("java.lang.Object"))) { return base().createAggressiveExpr(castExpr.expr(), false, false); } soot.Value val; val = base().createAggressiveExpr(castExpr.expr(), false, false); soot.Type type = Util.getSootType(castExpr.type()); soot.jimple.CastExpr cast = soot.jimple.Jimple.v().newCastExpr(val, type); Util.addLnPosTags(cast.getOpBox(), castExpr.expr().position()); soot.Local retLocal = lg.generateLocal(cast.getCastType()); soot.jimple.Stmt castAssign = soot.jimple.Jimple.v().newAssignStmt(retLocal, cast); body.getUnits().add(castAssign); Util.addLnPosTags(castAssign, castExpr.position()); return retLocal; } /** * Procedure Call Helper Methods Returns list of params */ private ArrayList getSootParams(polyglot.ast.ProcedureCall call) { ArrayList sootParams = new ArrayList(); Iterator it = call.arguments().iterator(); while (it.hasNext()) { polyglot.ast.Expr next = (polyglot.ast.Expr) it.next(); soot.Value nextExpr = base().createAggressiveExpr(next, false, false); if (nextExpr instanceof soot.jimple.ConditionExpr) { nextExpr = handleCondBinExpr((soot.jimple.ConditionExpr) nextExpr); } sootParams.add(nextExpr); } return sootParams; } /** * Returns list of param types */ private ArrayList getSootParamsTypes(polyglot.ast.ProcedureCall call) { ArrayList sootParamsTypes = new ArrayList(); Iterator it = call.procedureInstance().formalTypes().iterator(); while (it.hasNext()) { Object next = it.next(); sootParamsTypes.add(Util.getSootType((polyglot.types.Type) next)); } return sootParamsTypes; } /** * Gets the Soot Method form the given Soot Class */ private soot.SootMethodRef getMethodFromClass(soot.SootClass sootClass, String name, ArrayList paramTypes, soot.Type returnType, boolean isStatic) { soot.SootMethodRef ref = soot.Scene.v().makeMethodRef(sootClass, name, paramTypes, returnType, isStatic); return ref; } /** * Adds extra params */ private void handleFinalLocalParams(ArrayList sootParams, ArrayList sootParamTypes, polyglot.types.ClassType keyType) { HashMap<IdentityKey, AnonLocalClassInfo> finalLocalInfo = soot.javaToJimple.InitialResolver.v().finalLocalInfo(); if (finalLocalInfo != null) { if (finalLocalInfo.containsKey(new polyglot.util.IdentityKey(keyType))) { AnonLocalClassInfo alci = finalLocalInfo.get(new polyglot.util.IdentityKey(keyType)); ArrayList<IdentityKey> finalLocals = alci.finalLocalsUsed(); if (finalLocals != null) { Iterator<IdentityKey> it = finalLocals.iterator(); while (it.hasNext()) { Object next = it.next(); polyglot.types.LocalInstance li = (polyglot.types.LocalInstance) ((polyglot.util.IdentityKey) next).object(); sootParamTypes.add(Util.getSootType(li.type())); sootParams.add(getLocal(li)); } } } } } @Override protected soot.Local getThis(soot.Type sootType) { return Util.getThis(sootType, body, getThisMap, lg); } protected boolean needsOuterClassRef(polyglot.types.ClassType typeToInvoke) { // anon and local AnonLocalClassInfo info = InitialResolver.v().finalLocalInfo().get(new polyglot.util.IdentityKey(typeToInvoke)); if (InitialResolver.v().isAnonInCCall(typeToInvoke)) { return false; } if ((info != null) && (!info.inStaticMethod())) { return true; } // other nested else if (typeToInvoke.isNested() && !typeToInvoke.flags().isStatic() && !typeToInvoke.isAnonymous() && !typeToInvoke.isLocal()) { return true; } return false; } /** * adds outer class params */ private void handleOuterClassParams(ArrayList sootParams, soot.Value qVal, ArrayList sootParamsTypes, polyglot.types.ClassType typeToInvoke) { ArrayList needsRef = soot.javaToJimple.InitialResolver.v().getHasOuterRefInInit(); boolean addRef = needsOuterClassRef(typeToInvoke);// (needsRef != null) // && // (needsRef.contains(Util.getSootType(typeToInvoke))); if (addRef) { // if adding an outer type ref always add exact type soot.SootClass outerClass = ((soot.RefType) Util.getSootType(typeToInvoke.outer())).getSootClass(); sootParamsTypes.add(outerClass.getType()); } if (addRef && !typeToInvoke.isAnonymous() && (qVal != null)) { // for nested and local if qualifier use that for param sootParams.add(qVal); } else if (addRef && !typeToInvoke.isAnonymous()) { soot.SootClass outerClass = ((soot.RefType) Util.getSootType(typeToInvoke.outer())).getSootClass(); sootParams.add(getThis(outerClass.getType())); } else if (addRef && typeToInvoke.isAnonymous()) { soot.SootClass outerClass = ((soot.RefType) Util.getSootType(typeToInvoke.outer())).getSootClass(); sootParams.add(getThis(outerClass.getType())); } // handle anon qualifiers if (typeToInvoke.isAnonymous() && (qVal != null)) { sootParamsTypes.add(qVal.getType()); sootParams.add(qVal); } } /** * Constructor Call Creation */ private void createConstructorCall(polyglot.ast.ConstructorCall cCall) { ArrayList sootParams = new ArrayList(); ArrayList sootParamsTypes = new ArrayList(); polyglot.types.ConstructorInstance cInst = cCall.constructorInstance(); String containerName = null; if (cInst.container() instanceof polyglot.types.ClassType) { containerName = ((polyglot.types.ClassType) cInst.container()).fullName(); } soot.SootClass classToInvoke; if (cCall.kind() == polyglot.ast.ConstructorCall.SUPER) { classToInvoke = ((soot.RefType) Util.getSootType(cInst.container())).getSootClass(); } else if (cCall.kind() == polyglot.ast.ConstructorCall.THIS) { classToInvoke = body.getMethod().getDeclaringClass(); } else { throw new RuntimeException("Unknown kind of Constructor Call"); } soot.Local base = specialThisLocal; polyglot.types.ClassType objType = (polyglot.types.ClassType) cInst.container(); soot.Local qVal = null; if (cCall.qualifier() != null) { // && (!(cCall.qualifier() instanceof // polyglot.ast.Special && // ((polyglot.ast.Special)cCall.qualifier()).kind() // == polyglot.ast.Special.THIS)) ){ qVal = (soot.Local) base().createAggressiveExpr(cCall.qualifier(), false, false); } handleOuterClassParams(sootParams, qVal, sootParamsTypes, objType); sootParams.addAll(getSootParams(cCall)); sootParamsTypes.addAll(getSootParamsTypes(cCall)); handleFinalLocalParams(sootParams, sootParamsTypes, (polyglot.types.ClassType) cCall.constructorInstance().container()); soot.SootMethodRef methodToInvoke = getMethodFromClass(classToInvoke, "<init>", sootParamsTypes, soot.VoidType.v(), false); soot.jimple.SpecialInvokeExpr specialInvokeExpr = soot.jimple.Jimple.v().newSpecialInvokeExpr(base, methodToInvoke, sootParams); soot.jimple.Stmt invokeStmt = soot.jimple.Jimple.v().newInvokeStmt(specialInvokeExpr); body.getUnits().add(invokeStmt); Util.addLnPosTags(invokeStmt, cCall.position()); // this is clearly broken if an outer class this ref was added as first // param int numParams = 0; Iterator invokeParamsIt = cCall.arguments().iterator(); while (invokeParamsIt.hasNext()) { Util.addLnPosTags(specialInvokeExpr.getArgBox(numParams), ((polyglot.ast.Expr) invokeParamsIt.next()).position()); numParams++; } // if method is <init> handle field inits if (body.getMethod().getName().equals("<init>") && (cCall.kind() == polyglot.ast.ConstructorCall.SUPER)) { handleOuterClassThisInit(body.getMethod()); handleFinalLocalInits(); handleFieldInits(body.getMethod()); handleInitializerBlocks(body.getMethod()); } } private void handleFinalLocalInits() { ArrayList<SootField> finalsList = ((PolyglotMethodSource) body.getMethod().getSource()).getFinalsList(); if (finalsList == null) { return; } int paramCount = paramRefCount - finalsList.size(); Iterator<SootField> it = finalsList.iterator(); while (it.hasNext()) { soot.SootField sf = it.next(); soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newInstanceFieldRef(specialThisLocal, sf.makeRef()); soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(fieldRef, body.getParameterLocal(paramCount)); body.getUnits().add(stmt); paramCount++; } } /** * Local Class Decl - Local Inner Class */ private void createLocalClassDecl(polyglot.ast.LocalClassDecl cDecl) { BiMap lcMap = InitialResolver.v().getLocalClassMap(); String name = Util.getSootType(cDecl.decl().type()).toString(); if (!InitialResolver.v().hasClassInnerTag(body.getMethod().getDeclaringClass(), name)) { Util.addInnerClassTag(body.getMethod().getDeclaringClass(), name, null, cDecl.decl().name(), Util.getModifier(cDecl.decl().flags())); } } /** * New Expression Creation */ private soot.Local getNewLocal(polyglot.ast.New newExpr) { // handle parameters/args ArrayList sootParams = new ArrayList(); ArrayList sootParamsTypes = new ArrayList(); polyglot.types.ClassType objType = (polyglot.types.ClassType) newExpr.objectType().type(); if (newExpr.anonType() != null) { objType = newExpr.anonType(); // add inner class tags for any anon classes created String name = Util.getSootType(objType).toString(); polyglot.types.ClassType outerType = objType.outer(); if (!InitialResolver.v().hasClassInnerTag(body.getMethod().getDeclaringClass(), name)) { Util.addInnerClassTag(body.getMethod().getDeclaringClass(), name, null, null, outerType.flags().isInterface() ? soot.Modifier.PUBLIC | soot.Modifier.STATIC : Util.getModifier(objType.flags())); } } else { // not an anon class but actually invoking a new something if (!objType.isTopLevel()) { String name = Util.getSootType(objType).toString(); polyglot.types.ClassType outerType = objType.outer(); if (!InitialResolver.v().hasClassInnerTag(body.getMethod().getDeclaringClass(), name)) { Util.addInnerClassTag(body.getMethod().getDeclaringClass(), name, Util.getSootType(outerType).toString(), objType.name(), outerType.flags().isInterface() ? soot.Modifier.PUBLIC | soot.Modifier.STATIC : Util.getModifier(objType.flags())); } } } soot.RefType sootType = (soot.RefType) Util.getSootType(objType); soot.Local retLocal = lg.generateLocal(sootType); soot.jimple.NewExpr sootNew = soot.jimple.Jimple.v().newNewExpr(sootType); soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, sootNew); body.getUnits().add(stmt); Util.addLnPosTags(stmt, newExpr.position()); Util.addLnPosTags(stmt.getRightOpBox(), newExpr.position()); soot.SootClass classToInvoke = sootType.getSootClass(); // if no qualifier --> X to invoke is static soot.Value qVal = null; // System.out.println("new qualifier: "+newExpr.qualifier()); // if (newExpr.qualifier() != null) { if (newExpr.qualifier() != null) { // && (!(newExpr.qualifier() // instanceof polyglot.ast.Special // && // ((polyglot.ast.Special)newExpr.qualifier()).kind() // == polyglot.ast.Special.THIS)) ){ qVal = base().createAggressiveExpr(newExpr.qualifier(), false, false); } handleOuterClassParams(sootParams, qVal, sootParamsTypes, objType); boolean repush = false; soot.jimple.Stmt tNoop = null; soot.jimple.Stmt fNoop = null; if (!trueNoop.empty() && !falseNoop.empty()) { tNoop = trueNoop.pop(); fNoop = falseNoop.pop(); repush = true; } sootParams.addAll(getSootParams(newExpr)); if (repush) { trueNoop.push(tNoop); falseNoop.push(fNoop); } sootParamsTypes.addAll(getSootParamsTypes(newExpr)); handleFinalLocalParams(sootParams, sootParamsTypes, objType); soot.SootMethodRef methodToInvoke = getMethodFromClass(classToInvoke, "<init>", sootParamsTypes, soot.VoidType.v(), false); soot.jimple.SpecialInvokeExpr specialInvokeExpr = soot.jimple.Jimple.v().newSpecialInvokeExpr(retLocal, methodToInvoke, sootParams); soot.jimple.Stmt invokeStmt = soot.jimple.Jimple.v().newInvokeStmt(specialInvokeExpr); body.getUnits().add(invokeStmt); Util.addLnPosTags(invokeStmt, newExpr.position()); int numParams = 0; Iterator invokeParamsIt = newExpr.arguments().iterator(); while (invokeParamsIt.hasNext()) { Util.addLnPosTags(specialInvokeExpr.getArgBox(numParams), ((polyglot.ast.Expr) invokeParamsIt.next()).position()); numParams++; } return retLocal; } @Override protected soot.SootMethodRef getSootMethodRef(polyglot.ast.Call call) { soot.Type sootRecType; soot.SootClass receiverTypeClass; if (Util.getSootType(call.methodInstance().container()).equals(soot.RefType.v("java.lang.Object"))) { sootRecType = soot.RefType.v("java.lang.Object"); receiverTypeClass = soot.Scene.v().getSootClass("java.lang.Object"); } else { if (call.target().type() == null) { sootRecType = Util.getSootType(call.methodInstance().container()); } else { sootRecType = Util.getSootType(call.target().type()); } if (sootRecType instanceof soot.RefType) { receiverTypeClass = ((soot.RefType) sootRecType).getSootClass(); } else if (sootRecType instanceof soot.ArrayType) { receiverTypeClass = soot.Scene.v().getSootClass("java.lang.Object"); } else { throw new RuntimeException("call target problem: " + call); } } polyglot.types.MethodInstance methodInstance = call.methodInstance(); soot.Type sootRetType = Util.getSootType(methodInstance.returnType()); ArrayList sootParamsTypes = getSootParamsTypes(call); soot.SootMethodRef callMethod = soot.Scene.v().makeMethodRef(receiverTypeClass, methodInstance.name(), sootParamsTypes, sootRetType, methodInstance.flags().isStatic()); return callMethod; } /** * Call Expression Creation */ private soot.Local getCallLocal(polyglot.ast.Call call) { // handle name String name = call.name(); // handle receiver/target polyglot.ast.Receiver receiver = call.target(); // System.out.println("call: "+call+" receiver: "+receiver); soot.Local baseLocal; if ((receiver instanceof polyglot.ast.Special) && (((polyglot.ast.Special) receiver).kind() == polyglot.ast.Special.SUPER) && (((polyglot.ast.Special) receiver).qualifier() != null)) { baseLocal = getSpecialSuperQualifierLocal(call); return baseLocal; } baseLocal = (soot.Local) base().getBaseLocal(receiver); // System.out.println("base local: "+baseLocal); boolean repush = false; soot.jimple.Stmt tNoop = null; soot.jimple.Stmt fNoop = null; if (!trueNoop.empty() && !falseNoop.empty()) { tNoop = trueNoop.pop(); fNoop = falseNoop.pop(); repush = true; } ArrayList sootParams = getSootParams(call); if (repush) { trueNoop.push(tNoop); falseNoop.push(fNoop); } soot.SootMethodRef callMethod = base().getSootMethodRef(call); soot.Type sootRecType; soot.SootClass receiverTypeClass; if (Util.getSootType(call.methodInstance().container()).equals(soot.RefType.v("java.lang.Object"))) { sootRecType = soot.RefType.v("java.lang.Object"); receiverTypeClass = soot.Scene.v().getSootClass("java.lang.Object"); } else { if (call.target().type() == null) { sootRecType = Util.getSootType(call.methodInstance().container()); } else { sootRecType = Util.getSootType(call.target().type()); } if (sootRecType instanceof soot.RefType) { receiverTypeClass = ((soot.RefType) sootRecType).getSootClass(); } else if (sootRecType instanceof soot.ArrayType) { receiverTypeClass = soot.Scene.v().getSootClass("java.lang.Object"); } else { throw new RuntimeException("call target problem: " + call); } } polyglot.types.MethodInstance methodInstance = call.methodInstance(); /* * soot.Type sootRetType = Util.getSootType(methodInstance.returnType()); ArrayList sootParamsTypes = * getSootParamsTypes(call); ArrayList sootParams = getSootParams(call); * * soot.SootMethodRef callMethod = soot.Scene.v().makeMethodRef(receiverTypeClass, methodInstance.name(), * sootParamsTypes, sootRetType, methodInstance.flags().isStatic()); */ boolean isPrivateAccess = false; // if (call.methodInstance().flags().isPrivate() && // !Util.getSootType(call.methodInstance().container()).equals(body.getMethod().getDeclaringClass().getType())){ if (needsAccessor(call)) { soot.SootClass containingClass = ((soot.RefType) Util.getSootType(call.methodInstance().container())).getSootClass(); soot.SootClass classToAddMethTo = containingClass; if (call.methodInstance().flags().isProtected()) { if (InitialResolver.v().hierarchy() == null) { InitialResolver.v().hierarchy(new soot.FastHierarchy()); } soot.SootClass addToClass; if (body.getMethod().getDeclaringClass().hasOuterClass()) { addToClass = body.getMethod().getDeclaringClass().getOuterClass(); while (!InitialResolver.v().hierarchy().canStoreType(containingClass.getType(), addToClass.getType())) { if (addToClass.hasOuterClass()) { addToClass = addToClass.getOuterClass(); } else { break; } } } else { addToClass = containingClass; } classToAddMethTo = addToClass; } callMethod = addGetMethodAccessMeth(classToAddMethTo, call).makeRef(); if (!call.methodInstance().flags().isStatic()) { if (call.target() instanceof polyglot.ast.Expr) { sootParams.add(0, baseLocal); } else if (body.getMethod().getDeclaringClass().declaresFieldByName("this$0")) { sootParams.add(0, getThis(Util.getSootType(call.methodInstance().container())));// baseLocal); } else { sootParams.add(0, baseLocal); } } isPrivateAccess = true; } soot.jimple.InvokeExpr invokeExpr; if (isPrivateAccess) { // for accessing private methods in outer class -> always static invokeExpr = soot.jimple.Jimple.v().newStaticInvokeExpr(callMethod, sootParams); } else if (soot.Modifier.isInterface(receiverTypeClass.getModifiers()) && methodInstance.flags().isAbstract()) { // if reciever class is interface and method is abstract -> // interface invokeExpr = soot.jimple.Jimple.v().newInterfaceInvokeExpr(baseLocal, callMethod, sootParams); } else if (methodInstance.flags().isStatic()) { // if flag isStatic -> static invoke invokeExpr = soot.jimple.Jimple.v().newStaticInvokeExpr(callMethod, sootParams); } else if (methodInstance.flags().isPrivate()) { // if flag isPrivate -> special invoke invokeExpr = soot.jimple.Jimple.v().newSpecialInvokeExpr(baseLocal, callMethod, sootParams); } else if ((receiver instanceof polyglot.ast.Special) && (((polyglot.ast.Special) receiver).kind() == polyglot.ast.Special.SUPER)) { // receiver is special super -> special invokeExpr = soot.jimple.Jimple.v().newSpecialInvokeExpr(baseLocal, callMethod, sootParams); } else { // else virtual invoke invokeExpr = soot.jimple.Jimple.v().newVirtualInvokeExpr(baseLocal, callMethod, sootParams); } int numParams = 0; Iterator callParamsIt = call.arguments().iterator(); while (callParamsIt.hasNext()) { Util.addLnPosTags(invokeExpr.getArgBox(numParams), ((polyglot.ast.Expr) callParamsIt.next()).position()); numParams++; } if (invokeExpr instanceof soot.jimple.InstanceInvokeExpr) { Util.addLnPosTags(((soot.jimple.InstanceInvokeExpr) invokeExpr).getBaseBox(), call.target().position()); } // create an assign stmt so invoke can be used somewhere else if (invokeExpr.getMethodRef().returnType().equals(soot.VoidType.v())) { soot.jimple.Stmt invoke = soot.jimple.Jimple.v().newInvokeStmt(invokeExpr); body.getUnits().add(invoke); Util.addLnPosTags(invoke, call.position()); return null; } else { soot.Local retLocal = lg.generateLocal(invokeExpr.getMethodRef().returnType()); soot.jimple.Stmt assignStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, invokeExpr); // add assign stmt to body body.getUnits().add(assignStmt); Util.addLnPosTags(assignStmt, call.position()); return retLocal; } } @Override protected soot.Value getBaseLocal(polyglot.ast.Receiver receiver) { if (receiver instanceof polyglot.ast.TypeNode) { return generateLocal(((polyglot.ast.TypeNode) receiver).type()); } else { soot.Value val = base().createAggressiveExpr((polyglot.ast.Expr) receiver, false, false); if (val instanceof soot.jimple.Constant) { soot.Local retLocal = lg.generateLocal(val.getType()); soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, val); body.getUnits().add(stmt); return retLocal; } return val; } } /** * NewArray Expression Creation */ private soot.Local getNewArrayLocal(polyglot.ast.NewArray newArrExpr) { soot.Type sootType = Util.getSootType(newArrExpr.type()); // System.out.println("creating new array of type: "+sootType); soot.jimple.Expr expr; if (newArrExpr.numDims() == 1) { soot.Value dimLocal; if (newArrExpr.additionalDims() == 1) { dimLocal = soot.jimple.IntConstant.v(1); } else { dimLocal = base().createAggressiveExpr((polyglot.ast.Expr) newArrExpr.dims().get(0), false, false); } // System.out.println("creating new array: // "+((soot.ArrayType)sootType).getElementType()); soot.jimple.NewArrayExpr newArrayExpr = soot.jimple.Jimple.v().newNewArrayExpr(((soot.ArrayType) sootType).getElementType(), dimLocal); expr = newArrayExpr; if (newArrExpr.additionalDims() != 1) { Util.addLnPosTags(newArrayExpr.getSizeBox(), ((polyglot.ast.Expr) newArrExpr.dims().get(0)).position()); } } else { ArrayList valuesList = new ArrayList(); Iterator it = newArrExpr.dims().iterator(); while (it.hasNext()) { valuesList.add(base().createAggressiveExpr((polyglot.ast.Expr) it.next(), false, false)); } if (newArrExpr.additionalDims() != 0) { valuesList.add(soot.jimple.IntConstant.v(newArrExpr.additionalDims())); } soot.jimple.NewMultiArrayExpr newMultiArrayExpr = soot.jimple.Jimple.v().newNewMultiArrayExpr((soot.ArrayType) sootType, valuesList); expr = newMultiArrayExpr; Iterator sizeBoxIt = newArrExpr.dims().iterator(); int counter = 0; while (sizeBoxIt.hasNext()) { Util.addLnPosTags(newMultiArrayExpr.getSizeBox(counter), ((polyglot.ast.Expr) sizeBoxIt.next()).position()); counter++; } } soot.Local retLocal = lg.generateLocal(sootType); soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, expr); body.getUnits().add(stmt); Util.addLnPosTags(stmt, newArrExpr.position()); Util.addLnPosTags(stmt.getRightOpBox(), newArrExpr.position()); // handle array init if one exists if (newArrExpr.init() != null) { soot.Value initVal = getArrayInitLocal(newArrExpr.init(), newArrExpr.type()); soot.jimple.AssignStmt initStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, initVal); body.getUnits().add(initStmt); } return retLocal; } /** * create ArrayInit given init and the array local */ private soot.Local getArrayInitLocal(polyglot.ast.ArrayInit arrInit, polyglot.types.Type lhsType) { // System.out.println("lhs type: "+lhsType); soot.Local local = generateLocal(lhsType); // System.out.println("creating new array: // "+((soot.ArrayType)local.getType()).getElementType()); soot.jimple.NewArrayExpr arrExpr = soot.jimple.Jimple.v().newNewArrayExpr( ((soot.ArrayType) local.getType()).getElementType(), soot.jimple.IntConstant.v(arrInit.elements().size())); soot.jimple.Stmt assign = soot.jimple.Jimple.v().newAssignStmt(local, arrExpr); body.getUnits().add(assign); Util.addLnPosTags(assign, arrInit.position()); Iterator it = arrInit.elements().iterator(); int index = 0; while (it.hasNext()) { polyglot.ast.Expr elemExpr = (polyglot.ast.Expr) it.next(); soot.Value elem; if (elemExpr instanceof polyglot.ast.ArrayInit) { if (((polyglot.ast.ArrayInit) elemExpr).type() instanceof polyglot.types.NullType) { if (lhsType instanceof polyglot.types.ArrayType) { // System.out.println("coming from 1 in get // arrayinitlocal"+((polyglot.types.ArrayType)lhsType).base()); elem = getArrayInitLocal((polyglot.ast.ArrayInit) elemExpr, ((polyglot.types.ArrayType) lhsType).base()); } else { // System.out.println("coming from 2 in get // arrayinitlocal"+((polyglot.types.ArrayType)lhsType).base()); elem = getArrayInitLocal((polyglot.ast.ArrayInit) elemExpr, lhsType); } } else { // System.out.println("coming from 3 in get // arrayinitlocal"+((polyglot.types.ArrayType)lhsType).base()); // elem = // getArrayInitLocal((polyglot.ast.ArrayInit)elemExpr, // ((polyglot.ast.ArrayInit)elemExpr).type()); elem = getArrayInitLocal((polyglot.ast.ArrayInit) elemExpr, ((polyglot.types.ArrayType) lhsType).base()); } } else { elem = base().createAggressiveExpr(elemExpr, false, false); } soot.jimple.ArrayRef arrRef = soot.jimple.Jimple.v().newArrayRef(local, soot.jimple.IntConstant.v(index)); soot.jimple.AssignStmt elemAssign = soot.jimple.Jimple.v().newAssignStmt(arrRef, elem); body.getUnits().add(elemAssign); Util.addLnPosTags(elemAssign, elemExpr.position()); Util.addLnPosTags(elemAssign.getRightOpBox(), elemExpr.position()); index++; } return local; } /** * create LHS expressions */ @Override protected soot.Value createLHS(polyglot.ast.Expr expr) { if (expr instanceof polyglot.ast.Local) { return getLocal((polyglot.ast.Local) expr); } else if (expr instanceof polyglot.ast.ArrayAccess) { return getArrayRefLocalLeft((polyglot.ast.ArrayAccess) expr); } else if (expr instanceof polyglot.ast.Field) { return getFieldLocalLeft((polyglot.ast.Field) expr); } else { throw new RuntimeException("Unhandled LHS"); } } /** * Array Ref Expression Creation - LHS */ private soot.Value getArrayRefLocalLeft(polyglot.ast.ArrayAccess arrayRefExpr) { polyglot.ast.Expr array = arrayRefExpr.array(); polyglot.ast.Expr access = arrayRefExpr.index(); soot.Local arrLocal = (soot.Local) base().createAggressiveExpr(array, false, false); soot.Value arrAccess = base().createAggressiveExpr(access, false, false); soot.Local retLocal = generateLocal(arrayRefExpr.type()); soot.jimple.ArrayRef ref = soot.jimple.Jimple.v().newArrayRef(arrLocal, arrAccess); Util.addLnPosTags(ref.getBaseBox(), arrayRefExpr.array().position()); Util.addLnPosTags(ref.getIndexBox(), arrayRefExpr.index().position()); return ref; } /** * Array Ref Expression Creation */ private soot.Value getArrayRefLocal(polyglot.ast.ArrayAccess arrayRefExpr) { polyglot.ast.Expr array = arrayRefExpr.array(); polyglot.ast.Expr access = arrayRefExpr.index(); soot.Local arrLocal = (soot.Local) base().createAggressiveExpr(array, false, false); soot.Value arrAccess = base().createAggressiveExpr(access, false, false); soot.Local retLocal = generateLocal(arrayRefExpr.type()); soot.jimple.ArrayRef ref = soot.jimple.Jimple.v().newArrayRef(arrLocal, arrAccess); Util.addLnPosTags(ref.getBaseBox(), arrayRefExpr.array().position()); Util.addLnPosTags(ref.getIndexBox(), arrayRefExpr.index().position()); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, ref); body.getUnits().add(stmt); Util.addLnPosTags(stmt, arrayRefExpr.position()); return retLocal; } private soot.Local getSpecialSuperQualifierLocal(polyglot.ast.Expr expr) { soot.SootClass classToInvoke; ArrayList methodParams = new ArrayList(); if (expr instanceof polyglot.ast.Call) { polyglot.ast.Special target = (polyglot.ast.Special) ((polyglot.ast.Call) expr).target(); classToInvoke = ((soot.RefType) Util.getSootType(target.qualifier().type())).getSootClass(); methodParams = getSootParams((polyglot.ast.Call) expr); } else if (expr instanceof polyglot.ast.Field) { polyglot.ast.Special target = (polyglot.ast.Special) ((polyglot.ast.Field) expr).target(); classToInvoke = ((soot.RefType) Util.getSootType(target.qualifier().type())).getSootClass(); } else { throw new RuntimeException("Trying to create special super qualifier for: " + expr + " which is not a field or call"); } // make an access method soot.SootMethod methToInvoke = makeSuperAccessMethod(classToInvoke, expr); // invoke it soot.Local classToInvokeLocal = Util.getThis(classToInvoke.getType(), body, getThisMap, lg); methodParams.add(0, classToInvokeLocal); soot.jimple.InvokeExpr invokeExpr = soot.jimple.Jimple.v().newStaticInvokeExpr(methToInvoke.makeRef(), methodParams); // return the local of return type if not void if (!methToInvoke.getReturnType().equals(soot.VoidType.v())) { soot.Local retLocal = lg.generateLocal(methToInvoke.getReturnType()); soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, invokeExpr); body.getUnits().add(stmt); return retLocal; } else { body.getUnits().add(soot.jimple.Jimple.v().newInvokeStmt(invokeExpr)); return null; } } /** * Special Expression Creation */ private soot.Local getSpecialLocal(polyglot.ast.Special specialExpr) { // System.out.println(specialExpr); if (specialExpr.kind() == polyglot.ast.Special.SUPER) { if (specialExpr.qualifier() == null) { return specialThisLocal; } else { // this isn't enough // need to getThis for the type which may be several levels up // add access$N method to class of the type which returns // field or method wanted // invoke it // and it needs to be called specially when getting fields // or calls because need to know field or method to access // as it access' a field or meth in the super class of the // outer class refered to by the qualifier return getThis(Util.getSootType(specialExpr.qualifier().type())); } } else if (specialExpr.kind() == polyglot.ast.Special.THIS) { // System.out.println("this is special this: "+specialExpr); if (specialExpr.qualifier() == null) { return specialThisLocal; } else { return getThis(Util.getSootType(specialExpr.qualifier().type())); } } else { throw new RuntimeException("Unknown Special"); } } private soot.SootMethod makeSuperAccessMethod(soot.SootClass classToInvoke, Object memberToAccess) { String name = "access$" + soot.javaToJimple.InitialResolver.v().getNextPrivateAccessCounter() + "00"; ArrayList paramTypes = new ArrayList(); paramTypes.add(classToInvoke.getType()); soot.SootMethod meth; soot.MethodSource src; if (memberToAccess instanceof polyglot.ast.Field) { polyglot.ast.Field fieldToAccess = (polyglot.ast.Field) memberToAccess; meth = Scene.v().makeSootMethod(name, paramTypes, Util.getSootType(fieldToAccess.type()), soot.Modifier.STATIC); PrivateFieldAccMethodSource fSrc = new PrivateFieldAccMethodSource(Util.getSootType(fieldToAccess.type()), fieldToAccess.name(), fieldToAccess.flags().isStatic(), ((soot.RefType) Util.getSootType(fieldToAccess.target().type())).getSootClass()); src = fSrc; } else if (memberToAccess instanceof polyglot.ast.Call) { polyglot.ast.Call methToAccess = (polyglot.ast.Call) memberToAccess; paramTypes.addAll(getSootParamsTypes(methToAccess)); meth = Scene.v().makeSootMethod(name, paramTypes, Util.getSootType(methToAccess.methodInstance().returnType()), soot.Modifier.STATIC); PrivateMethodAccMethodSource mSrc = new PrivateMethodAccMethodSource(methToAccess.methodInstance()); src = mSrc; } else { throw new RuntimeException("trying to access unhandled member type: " + memberToAccess); } classToInvoke.addMethod(meth); meth.setActiveBody(src.getBody(meth, null)); meth.addTag(new soot.tagkit.SyntheticTag()); return meth; } /** * InstanceOf Expression Creation */ private soot.Local getInstanceOfLocal(polyglot.ast.Instanceof instExpr) { soot.Type sootType = Util.getSootType(instExpr.compareType().type()); soot.Value local = base().createAggressiveExpr(instExpr.expr(), false, false); soot.jimple.InstanceOfExpr instOfExpr = soot.jimple.Jimple.v().newInstanceOfExpr(local, sootType); soot.Local lhs = lg.generateLocal(soot.BooleanType.v()); soot.jimple.AssignStmt instAssign = soot.jimple.Jimple.v().newAssignStmt(lhs, instOfExpr); body.getUnits().add(instAssign); Util.addLnPosTags(instAssign, instExpr.position()); Util.addLnPosTags(instAssign.getRightOpBox(), instExpr.position()); Util.addLnPosTags(instOfExpr.getOpBox(), instExpr.expr().position()); return lhs; } /** * Condition Expression Creation - can maybe merge with If */ private soot.Local getConditionalLocal(polyglot.ast.Conditional condExpr) { // handle cond soot.jimple.Stmt noop1 = soot.jimple.Jimple.v().newNopStmt(); polyglot.ast.Expr condition = condExpr.cond(); createBranchingExpr(condition, noop1, false); soot.Local retLocal = generateLocal(condExpr.type()); // handle consequence polyglot.ast.Expr consequence = condExpr.consequent(); soot.Value conseqVal = base().createAggressiveExpr(consequence, false, false); if (conseqVal instanceof soot.jimple.ConditionExpr) { conseqVal = handleCondBinExpr((soot.jimple.ConditionExpr) conseqVal); } soot.jimple.AssignStmt conseqAssignStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, conseqVal); body.getUnits().add(conseqAssignStmt); Util.addLnPosTags(conseqAssignStmt, condExpr.position()); Util.addLnPosTags(conseqAssignStmt.getRightOpBox(), consequence.position()); soot.jimple.Stmt noop2 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.Stmt goto1 = soot.jimple.Jimple.v().newGotoStmt(noop2); body.getUnits().add(goto1); // handle alternative body.getUnits().add(noop1); polyglot.ast.Expr alternative = condExpr.alternative(); if (alternative != null) { soot.Value altVal = base().createAggressiveExpr(alternative, false, false); if (altVal instanceof soot.jimple.ConditionExpr) { altVal = handleCondBinExpr((soot.jimple.ConditionExpr) altVal); } soot.jimple.AssignStmt altAssignStmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, altVal); body.getUnits().add(altAssignStmt); Util.addLnPosTags(altAssignStmt, condExpr.position()); Util.addLnPosTags(altAssignStmt, alternative.position()); Util.addLnPosTags(altAssignStmt.getRightOpBox(), alternative.position()); } body.getUnits().add(noop2); return retLocal; } /** * Utility methods */ /* * private boolean isLitOrLocal(polyglot.ast.Expr exp) { if (exp instanceof polyglot.ast.Lit) return true; if (exp * instanceof polyglot.ast.Local) return true; else return false; } */ /** * Extra Local Variables Generation */ @Override protected soot.Local generateLocal(polyglot.types.Type polyglotType) { soot.Type type = Util.getSootType(polyglotType); return lg.generateLocal(type); } @Override protected soot.Local generateLocal(soot.Type sootType) { return lg.generateLocal(sootType); } }
192,707
38.873371
125
java
soot
soot-master/src/main/java/soot/javaToJimple/JimpleBodyBuilderFactory.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class JimpleBodyBuilderFactory extends AbstractJBBFactory { protected AbstractJimpleBodyBuilder createJimpleBodyBuilder() { return new JimpleBodyBuilder(); } }
1,005
30.4375
71
java
soot
soot-master/src/main/java/soot/javaToJimple/LocalClassDeclFinder.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class LocalClassDeclFinder extends polyglot.visit.NodeVisitor { private polyglot.types.ClassType typeToFind; private polyglot.ast.LocalClassDecl declFound; public void typeToFind(polyglot.types.ClassType type) { typeToFind = type; } public polyglot.ast.LocalClassDecl declFound() { return declFound; } public LocalClassDeclFinder() { declFound = null; } public polyglot.visit.NodeVisitor enter(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.LocalClassDecl) { if (((polyglot.ast.LocalClassDecl) n).decl().type().equals(typeToFind)) { declFound = (polyglot.ast.LocalClassDecl) n; } } return enter(n); } }
1,540
28.634615
90
java
soot
soot-master/src/main/java/soot/javaToJimple/LocalUsesChecker.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import polyglot.ast.Node; import polyglot.util.IdentityKey; public class LocalUsesChecker extends polyglot.visit.NodeVisitor { private final ArrayList<IdentityKey> locals; private final ArrayList<IdentityKey> localDecls; private final ArrayList<Node> news; public ArrayList<IdentityKey> getLocals() { return locals; } public ArrayList<Node> getNews() { return news; } public ArrayList<IdentityKey> getLocalDecls() { return localDecls; } public LocalUsesChecker() { locals = new ArrayList<IdentityKey>(); localDecls = new ArrayList<IdentityKey>(); news = new ArrayList<Node>(); } public polyglot.ast.Node leave(polyglot.ast.Node old, polyglot.ast.Node n, polyglot.visit.NodeVisitor visitor) { if (n instanceof polyglot.ast.Local) { if (!(locals.contains(new polyglot.util.IdentityKey(((polyglot.ast.Local) n).localInstance())))) { if (!((polyglot.ast.Local) n).isConstant()) { locals.add(new polyglot.util.IdentityKey(((polyglot.ast.Local) n).localInstance())); } } } if (n instanceof polyglot.ast.LocalDecl) { localDecls.add(new polyglot.util.IdentityKey(((polyglot.ast.LocalDecl) n).localInstance())); } if (n instanceof polyglot.ast.Formal) { localDecls.add(new polyglot.util.IdentityKey(((polyglot.ast.Formal) n).localInstance())); } if (n instanceof polyglot.ast.New) { news.add(n); } return n; } }
2,313
28.666667
114
java
soot
soot-master/src/main/java/soot/javaToJimple/MethodFinalsChecker.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import polyglot.ast.Node; import polyglot.util.IdentityKey; public class MethodFinalsChecker extends polyglot.visit.NodeVisitor { private final ArrayList<IdentityKey> inners; private final ArrayList<IdentityKey> finalLocals; private final HashMap<IdentityKey, ArrayList<IdentityKey>> typeToLocalsUsed; private final ArrayList<Node> ccallList; public HashMap<IdentityKey, ArrayList<IdentityKey>> typeToLocalsUsed() { return typeToLocalsUsed; } public ArrayList<IdentityKey> finalLocals() { return finalLocals; } public ArrayList<IdentityKey> inners() { return inners; } public ArrayList<Node> ccallList() { return ccallList; } public MethodFinalsChecker() { finalLocals = new ArrayList<IdentityKey>(); inners = new ArrayList<IdentityKey>(); ccallList = new ArrayList<Node>(); typeToLocalsUsed = new HashMap<IdentityKey, ArrayList<IdentityKey>>(); } public polyglot.ast.Node override(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.LocalClassDecl) { inners.add(new polyglot.util.IdentityKey(((polyglot.ast.LocalClassDecl) n).decl().type())); polyglot.ast.ClassBody localClassBody = ((polyglot.ast.LocalClassDecl) n).decl().body(); LocalUsesChecker luc = new LocalUsesChecker(); localClassBody.visit(luc); typeToLocalsUsed.put(new polyglot.util.IdentityKey(((polyglot.ast.LocalClassDecl) n).decl().type()), luc.getLocals()); return n; } else if (n instanceof polyglot.ast.New) { if (((polyglot.ast.New) n).anonType() != null) { inners.add(new polyglot.util.IdentityKey(((polyglot.ast.New) n).anonType())); polyglot.ast.ClassBody anonClassBody = ((polyglot.ast.New) n).body(); LocalUsesChecker luc = new LocalUsesChecker(); anonClassBody.visit(luc); typeToLocalsUsed.put(new polyglot.util.IdentityKey(((polyglot.ast.New) n).anonType()), luc.getLocals()); return n; } } return null; } public polyglot.visit.NodeVisitor enter(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.LocalDecl) { polyglot.ast.LocalDecl ld = (polyglot.ast.LocalDecl) n; if (ld.flags().isFinal()) { if (!finalLocals.contains(new polyglot.util.IdentityKey(ld.localInstance()))) { finalLocals.add(new polyglot.util.IdentityKey(ld.localInstance())); } } } if (n instanceof polyglot.ast.Formal) { polyglot.ast.Formal ld = (polyglot.ast.Formal) n; if (ld.flags().isFinal()) { if (!finalLocals.contains(new polyglot.util.IdentityKey(ld.localInstance()))) { finalLocals.add(new polyglot.util.IdentityKey(ld.localInstance())); } } } if (n instanceof polyglot.ast.ConstructorCall) { ccallList.add(n); } return enter(n); } }
3,739
33.953271
124
java
soot
soot-master/src/main/java/soot/javaToJimple/NestedClassListBuilder.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import polyglot.ast.Node; public class NestedClassListBuilder extends polyglot.visit.NodeVisitor { private final ArrayList<Node> classDeclsList; private final ArrayList<Node> anonClassBodyList; private final ArrayList<Node> nestedUsedList; public ArrayList<Node> getClassDeclsList() { return classDeclsList; } public ArrayList<Node> getAnonClassBodyList() { return anonClassBodyList; } public ArrayList<Node> getNestedUsedList() { return nestedUsedList; } public NestedClassListBuilder() { classDeclsList = new ArrayList<Node>(); anonClassBodyList = new ArrayList<Node>(); nestedUsedList = new ArrayList<Node>(); } public polyglot.visit.NodeVisitor enter(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.New) { if ((((polyglot.ast.New) n).anonType() != null) && (((polyglot.ast.New) n).body() != null)) { anonClassBodyList.add(n); } else if (((polyglot.types.ClassType) ((polyglot.ast.New) n).objectType().type()).isNested()) { nestedUsedList.add(n); } } if (n instanceof polyglot.ast.ClassDecl) { if (((polyglot.types.ClassType) ((polyglot.ast.ClassDecl) n).type()).isNested()) { classDeclsList.add(n); } } return enter(n); } }
2,150
28.875
102
java
soot
soot-master/src/main/java/soot/javaToJimple/PolyglotMethodSource.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import polyglot.ast.Block; import polyglot.ast.FieldDecl; import soot.MethodSource; import soot.PackManager; import soot.Scene; import soot.SootClass; import soot.SootField; public class PolyglotMethodSource implements MethodSource { private polyglot.ast.Block block; private List formals; private ArrayList<FieldDecl> fieldInits; private ArrayList<FieldDecl> staticFieldInits; private ArrayList<Block> initializerBlocks; private ArrayList<Block> staticInitializerBlocks; private soot.Local outerClassThisInit; private boolean hasAssert = false; private ArrayList<SootField> finalsList; private HashMap newToOuterMap; private AbstractJimpleBodyBuilder ajbb; public PolyglotMethodSource() { this.block = null; this.formals = null; } public PolyglotMethodSource(polyglot.ast.Block block, List formals) { this.block = block; this.formals = formals; } public soot.Body getBody(soot.SootMethod sm, String phaseName) { // JimpleBodyBuilder jbb = new JimpleBodyBuilder(); soot.jimple.JimpleBody jb = ajbb.createJimpleBody(block, formals, sm); PackManager.v().getPack("jj").apply(jb); return jb; } public void setJBB(AbstractJimpleBodyBuilder ajbb) { this.ajbb = ajbb; } public void setFieldInits(ArrayList<FieldDecl> fieldInits) { this.fieldInits = fieldInits; } public void setStaticFieldInits(ArrayList<FieldDecl> staticFieldInits) { this.staticFieldInits = staticFieldInits; } public ArrayList<FieldDecl> getFieldInits() { return fieldInits; } public ArrayList<FieldDecl> getStaticFieldInits() { return staticFieldInits; } public void setStaticInitializerBlocks(ArrayList<Block> staticInits) { staticInitializerBlocks = staticInits; } public void setInitializerBlocks(ArrayList<Block> inits) { initializerBlocks = inits; } public ArrayList<Block> getStaticInitializerBlocks() { return staticInitializerBlocks; } public ArrayList<Block> getInitializerBlocks() { return initializerBlocks; } public void setOuterClassThisInit(soot.Local l) { outerClassThisInit = l; } public soot.Local getOuterClassThisInit() { return outerClassThisInit; } public boolean hasAssert() { return hasAssert; } public void hasAssert(boolean val) { hasAssert = val; } public void addAssertInits(soot.Body body) { // if class is inner get desired assertion status from outer most class soot.SootClass assertStatusClass = body.getMethod().getDeclaringClass(); HashMap<SootClass, InnerClassInfo> innerMap = soot.javaToJimple.InitialResolver.v().getInnerClassInfoMap(); while ((innerMap != null) && (innerMap.containsKey(assertStatusClass))) { assertStatusClass = innerMap.get(assertStatusClass).getOuterClass(); } String paramName = assertStatusClass.getName(); String fieldName = "class$" + assertStatusClass.getName().replaceAll(".", "$"); if (assertStatusClass.isInterface()) { assertStatusClass = InitialResolver.v().specialAnonMap().get(assertStatusClass); } // field ref soot.SootFieldRef field = soot.Scene.v().makeFieldRef(assertStatusClass, fieldName, soot.RefType.v("java.lang.Class"), true); soot.Local fieldLocal = soot.jimple.Jimple.v().newLocal("$r0", soot.RefType.v("java.lang.Class")); body.getLocals().add(fieldLocal); soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(field); soot.jimple.AssignStmt fieldAssignStmt = soot.jimple.Jimple.v().newAssignStmt(fieldLocal, fieldRef); body.getUnits().add(fieldAssignStmt); // if field not null soot.jimple.ConditionExpr cond = soot.jimple.Jimple.v().newNeExpr(fieldLocal, soot.jimple.NullConstant.v()); soot.jimple.NopStmt nop1 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(cond, nop1); body.getUnits().add(ifStmt); // if alternative soot.Local invokeLocal = soot.jimple.Jimple.v().newLocal("$r1", soot.RefType.v("java.lang.Class")); body.getLocals().add(invokeLocal); ArrayList paramTypes = new ArrayList(); paramTypes.add(soot.RefType.v("java.lang.String")); soot.SootMethodRef methodToInvoke = soot.Scene.v().makeMethodRef(assertStatusClass, "class$", paramTypes, soot.RefType.v("java.lang.Class"), true); ArrayList params = new ArrayList(); params.add(soot.jimple.StringConstant.v(paramName)); soot.jimple.StaticInvokeExpr invoke = soot.jimple.Jimple.v().newStaticInvokeExpr(methodToInvoke, params); soot.jimple.AssignStmt invokeAssign = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, invoke); body.getUnits().add(invokeAssign); // field ref assign soot.jimple.AssignStmt fieldRefAssign = soot.jimple.Jimple.v().newAssignStmt(fieldRef, invokeLocal); body.getUnits().add(fieldRefAssign); soot.jimple.NopStmt nop2 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.GotoStmt goto1 = soot.jimple.Jimple.v().newGotoStmt(nop2); body.getUnits().add(goto1); // add nop1 - and if consequence body.getUnits().add(nop1); soot.jimple.AssignStmt fieldRefAssign2 = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, fieldRef); body.getUnits().add(fieldRefAssign2); body.getUnits().add(nop2); // boolean tests soot.Local boolLocal1 = soot.jimple.Jimple.v().newLocal("$z0", soot.BooleanType.v()); body.getLocals().add(boolLocal1); soot.Local boolLocal2 = soot.jimple.Jimple.v().newLocal("$z1", soot.BooleanType.v()); body.getLocals().add(boolLocal2); // virtual invoke soot.SootMethodRef vMethodToInvoke = Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.Class"), "desiredAssertionStatus", new ArrayList(), soot.BooleanType.v(), false); soot.jimple.VirtualInvokeExpr vInvoke = soot.jimple.Jimple.v().newVirtualInvokeExpr(invokeLocal, vMethodToInvoke, new ArrayList()); soot.jimple.AssignStmt testAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal1, vInvoke); body.getUnits().add(testAssign); // if soot.jimple.ConditionExpr cond2 = soot.jimple.Jimple.v().newNeExpr(boolLocal1, soot.jimple.IntConstant.v(0)); soot.jimple.NopStmt nop3 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.IfStmt ifStmt2 = soot.jimple.Jimple.v().newIfStmt(cond2, nop3); body.getUnits().add(ifStmt2); // alternative soot.jimple.AssignStmt altAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal2, soot.jimple.IntConstant.v(1)); body.getUnits().add(altAssign); soot.jimple.NopStmt nop4 = soot.jimple.Jimple.v().newNopStmt(); soot.jimple.GotoStmt goto2 = soot.jimple.Jimple.v().newGotoStmt(nop4); body.getUnits().add(goto2); body.getUnits().add(nop3); soot.jimple.AssignStmt conAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal2, soot.jimple.IntConstant.v(0)); body.getUnits().add(conAssign); body.getUnits().add(nop4); // field assign soot.SootFieldRef fieldD = Scene.v().makeFieldRef(body.getMethod().getDeclaringClass(), "$assertionsDisabled", soot.BooleanType.v(), true); soot.jimple.FieldRef fieldRefD = soot.jimple.Jimple.v().newStaticFieldRef(fieldD); soot.jimple.AssignStmt fAssign = soot.jimple.Jimple.v().newAssignStmt(fieldRefD, boolLocal2); body.getUnits().add(fAssign); } public void setFinalsList(ArrayList<SootField> list) { finalsList = list; } public ArrayList<SootField> getFinalsList() { return finalsList; } public void setNewToOuterMap(HashMap map) { newToOuterMap = map; } public HashMap getNewToOuterMap() { return newToOuterMap; } }
8,580
31.381132
122
java
soot
soot-master/src/main/java/soot/javaToJimple/PrivateAccessChecker.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import polyglot.types.MemberInstance; public class PrivateAccessChecker extends polyglot.visit.NodeVisitor { private final ArrayList<MemberInstance> list; public ArrayList<MemberInstance> getList() { return list; } public PrivateAccessChecker() { list = new ArrayList<MemberInstance>(); } public polyglot.ast.Node leave(polyglot.ast.Node old, polyglot.ast.Node n, polyglot.visit.NodeVisitor visitor) { if (n instanceof polyglot.ast.Field) { polyglot.types.FieldInstance fi = ((polyglot.ast.Field) n).fieldInstance(); if (fi.flags().isPrivate()) { list.add(fi); } } if (n instanceof polyglot.ast.Call) { polyglot.types.MethodInstance mi = ((polyglot.ast.Call) n).methodInstance(); if (mi.flags().isPrivate()) { list.add(mi); } } return n; } }
1,703
26.483871
114
java
soot
soot-master/src/main/java/soot/javaToJimple/PrivateAccessUses.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import polyglot.util.IdentityKey; public class PrivateAccessUses extends polyglot.visit.NodeVisitor { private final ArrayList<IdentityKey> list; private ArrayList avail; public ArrayList<IdentityKey> getList() { return list; } public void avail(ArrayList list) { avail = list; } public PrivateAccessUses() { list = new ArrayList<IdentityKey>(); } public polyglot.ast.Node leave(polyglot.ast.Node old, polyglot.ast.Node n, polyglot.visit.NodeVisitor visitor) { if (n instanceof polyglot.ast.Field) { polyglot.types.FieldInstance fi = ((polyglot.ast.Field) n).fieldInstance(); if (avail.contains(new polyglot.util.IdentityKey(fi))) { list.add(new polyglot.util.IdentityKey(fi)); } } if (n instanceof polyglot.ast.Call) { polyglot.types.ProcedureInstance pi = ((polyglot.ast.Call) n).methodInstance(); if (avail.contains(new polyglot.util.IdentityKey(pi))) { list.add(new polyglot.util.IdentityKey(pi)); } } if (n instanceof polyglot.ast.New) { polyglot.types.ProcedureInstance pi = ((polyglot.ast.New) n).constructorInstance(); if (avail.contains(new polyglot.util.IdentityKey(pi))) { list.add(new polyglot.util.IdentityKey(pi)); } } if (n instanceof polyglot.ast.ConstructorCall) { polyglot.types.ProcedureInstance pi = ((polyglot.ast.ConstructorCall) n).constructorInstance(); if (avail.contains(new polyglot.util.IdentityKey(pi))) { list.add(new polyglot.util.IdentityKey(pi)); } } return n; } }
2,441
28.421687
114
java
soot
soot-master/src/main/java/soot/javaToJimple/PrivateFieldAccMethodSource.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import soot.LocalGenerator; import soot.Scene; public class PrivateFieldAccMethodSource implements soot.MethodSource { private final soot.Type fieldType; private final String fieldName; private final boolean isStatic; private final soot.SootClass classToInvoke; public PrivateFieldAccMethodSource(soot.Type fieldType, String fieldName, boolean isStatic, soot.SootClass classToInvoke) { this.fieldType = fieldType; this.fieldName = fieldName; this.isStatic = isStatic; this.classToInvoke = classToInvoke; } public soot.Body getBody(soot.SootMethod sootMethod, String phaseName) { soot.Body body = soot.jimple.Jimple.v().newBody(sootMethod); LocalGenerator lg = Scene.v().createLocalGenerator(body); soot.Local fieldBase = null; // create parameters Iterator paramIt = sootMethod.getParameterTypes().iterator(); while (paramIt.hasNext()) { soot.Type sootType = (soot.Type) paramIt.next(); soot.Local paramLocal = lg.generateLocal(sootType); soot.jimple.ParameterRef paramRef = soot.jimple.Jimple.v().newParameterRef(sootType, 0); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(paramLocal, paramRef); body.getUnits().add(stmt); fieldBase = paramLocal; } // create field type local soot.Local fieldLocal = lg.generateLocal(fieldType); // assign local to fieldRef soot.SootFieldRef field = soot.Scene.v().makeFieldRef(classToInvoke, fieldName, fieldType, isStatic); soot.jimple.FieldRef fieldRef = null; if (isStatic) { fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(field); } else { fieldRef = soot.jimple.Jimple.v().newInstanceFieldRef(fieldBase, field); } soot.jimple.AssignStmt assign = soot.jimple.Jimple.v().newAssignStmt(fieldLocal, fieldRef); body.getUnits().add(assign); // return local soot.jimple.Stmt retStmt = soot.jimple.Jimple.v().newReturnStmt(fieldLocal); body.getUnits().add(retStmt); return body; } }
2,868
33.154762
125
java
soot
soot-master/src/main/java/soot/javaToJimple/PrivateFieldSetMethodSource.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import soot.LocalGenerator; import soot.Scene; public class PrivateFieldSetMethodSource implements soot.MethodSource { private final soot.Type fieldType; private final String fieldName; private final boolean isStatic; public PrivateFieldSetMethodSource(soot.Type fieldType, String fieldName, boolean isStatic) { this.fieldType = fieldType; this.fieldName = fieldName; this.isStatic = isStatic; } public soot.Body getBody(soot.SootMethod sootMethod, String phaseName) { soot.Body body = soot.jimple.Jimple.v().newBody(sootMethod); LocalGenerator lg = Scene.v().createLocalGenerator(body); soot.Local fieldBase = null; soot.Local assignLocal = null; // create parameters int paramCounter = 0; Iterator paramIt = sootMethod.getParameterTypes().iterator(); while (paramIt.hasNext()) { soot.Type sootType = (soot.Type) paramIt.next(); soot.Local paramLocal = lg.generateLocal(sootType); soot.jimple.ParameterRef paramRef = soot.jimple.Jimple.v().newParameterRef(sootType, paramCounter); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(paramLocal, paramRef); body.getUnits().add(stmt); if (paramCounter == 0) { fieldBase = paramLocal; } assignLocal = paramLocal; paramCounter++; } // create field type local // soot.Local fieldLocal = lg.generateLocal(fieldType); // assign local to fieldRef soot.SootFieldRef field = soot.Scene.v().makeFieldRef(sootMethod.getDeclaringClass(), fieldName, fieldType, isStatic); soot.jimple.FieldRef fieldRef = null; if (isStatic) { fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(field); } else { fieldRef = soot.jimple.Jimple.v().newInstanceFieldRef(fieldBase, field); } soot.jimple.AssignStmt assign = soot.jimple.Jimple.v().newAssignStmt(fieldRef, assignLocal); body.getUnits().add(assign); // return local soot.jimple.Stmt retStmt = soot.jimple.Jimple.v().newReturnStmt(assignLocal); body.getUnits().add(retStmt); return body; } }
2,942
32.067416
122
java
soot
soot-master/src/main/java/soot/javaToJimple/PrivateInstancesAvailable.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import polyglot.util.IdentityKey; public class PrivateInstancesAvailable extends polyglot.visit.NodeVisitor { private final ArrayList<IdentityKey> list; public ArrayList<IdentityKey> getList() { return list; } public PrivateInstancesAvailable() { list = new ArrayList<IdentityKey>(); } public polyglot.ast.Node leave(polyglot.ast.Node old, polyglot.ast.Node n, polyglot.visit.NodeVisitor visitor) { if (n instanceof polyglot.ast.FieldDecl) { polyglot.types.FieldInstance fi = ((polyglot.ast.FieldDecl) n).fieldInstance(); if (fi.flags().isPrivate()) { list.add(new polyglot.util.IdentityKey(fi)); } } if (n instanceof polyglot.ast.ProcedureDecl) { polyglot.types.ProcedureInstance pi = ((polyglot.ast.ProcedureDecl) n).procedureInstance(); if (pi.flags().isPrivate()) { list.add(new polyglot.util.IdentityKey(pi)); } } return n; } }
1,794
27.951613
114
java
soot
soot-master/src/main/java/soot/javaToJimple/PrivateMethodAccMethodSource.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Iterator; import soot.LocalGenerator; import soot.Scene; public class PrivateMethodAccMethodSource implements soot.MethodSource { public PrivateMethodAccMethodSource(polyglot.types.MethodInstance methInst) { this.methodInst = methInst; } private polyglot.types.MethodInstance methodInst; public void setMethodInst(polyglot.types.MethodInstance mi) { methodInst = mi; } private boolean isCallParamType(soot.Type sootType) { Iterator it = methodInst.formalTypes().iterator(); while (it.hasNext()) { soot.Type compareType = Util.getSootType((polyglot.types.Type) it.next()); if (compareType.equals(sootType)) { return true; } } return false; } public soot.Body getBody(soot.SootMethod sootMethod, String phaseName) { soot.Body body = soot.jimple.Jimple.v().newBody(sootMethod); LocalGenerator lg = Scene.v().createLocalGenerator(body); soot.Local base = null; ArrayList methParams = new ArrayList(); ArrayList methParamsTypes = new ArrayList(); // create parameters Iterator paramIt = sootMethod.getParameterTypes().iterator(); int paramCounter = 0; while (paramIt.hasNext()) { soot.Type sootType = (soot.Type) paramIt.next(); soot.Local paramLocal = lg.generateLocal(sootType); // body.getLocals().add(paramLocal); soot.jimple.ParameterRef paramRef = soot.jimple.Jimple.v().newParameterRef(sootType, paramCounter); soot.jimple.Stmt stmt = soot.jimple.Jimple.v().newIdentityStmt(paramLocal, paramRef); body.getUnits().add(stmt); if (!isCallParamType(sootType)) { base = paramLocal; } else { methParams.add(paramLocal); methParamsTypes.add(paramLocal.getType()); } paramCounter++; } // create return type local soot.Type type = Util.getSootType(methodInst.returnType()); soot.Local returnLocal = null; if (!(type instanceof soot.VoidType)) { returnLocal = lg.generateLocal(type); // body.getLocals().add(returnLocal); } // assign local to meth soot.SootMethodRef meth = soot.Scene.v().makeMethodRef(((soot.RefType) Util.getSootType(methodInst.container())).getSootClass(), methodInst.name(), methParamsTypes, Util.getSootType(methodInst.returnType()), methodInst.flags().isStatic()); soot.jimple.InvokeExpr invoke = null; if (methodInst.flags().isStatic()) { invoke = soot.jimple.Jimple.v().newStaticInvokeExpr(meth, methParams); } else { invoke = soot.jimple.Jimple.v().newSpecialInvokeExpr(base, meth, methParams); } soot.jimple.Stmt stmt = null; if (!(type instanceof soot.VoidType)) { stmt = soot.jimple.Jimple.v().newAssignStmt(returnLocal, invoke); } else { stmt = soot.jimple.Jimple.v().newInvokeStmt(invoke); } body.getUnits().add(stmt); // return local soot.jimple.Stmt retStmt = null; if (!(type instanceof soot.VoidType)) { retStmt = soot.jimple.Jimple.v().newReturnStmt(returnLocal); } else { retStmt = soot.jimple.Jimple.v().newReturnVoidStmt(); } body.getUnits().add(retStmt); return body; } }
4,047
31.645161
122
java
soot
soot-master/src/main/java/soot/javaToJimple/ReturnStmtChecker.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class ReturnStmtChecker extends polyglot.visit.NodeVisitor { private boolean hasReturn; public boolean hasRet() { return hasReturn; } public ReturnStmtChecker() { hasReturn = false; } public polyglot.ast.Node leave(polyglot.ast.Node old, polyglot.ast.Node n, polyglot.visit.NodeVisitor visitor) { if (n instanceof polyglot.ast.Return) { hasReturn = true; } return n; } }
1,251
26.822222
114
java
soot
soot-master/src/main/java/soot/javaToJimple/SaveASTVisitor.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashMap; import polyglot.frontend.Job; import polyglot.frontend.Source; public class SaveASTVisitor extends polyglot.frontend.AbstractPass { private polyglot.frontend.Job job; private polyglot.frontend.ExtensionInfo extInfo; public SaveASTVisitor(polyglot.frontend.Pass.ID id, polyglot.frontend.Job job, polyglot.frontend.ExtensionInfo extInfo) { super(id); this.job = job; this.extInfo = extInfo; } public boolean run() { if (extInfo instanceof soot.javaToJimple.jj.ExtensionInfo) { soot.javaToJimple.jj.ExtensionInfo jjInfo = (soot.javaToJimple.jj.ExtensionInfo) extInfo; if (jjInfo.sourceJobMap() == null) { jjInfo.sourceJobMap(new HashMap<Source, Job>()); } jjInfo.sourceJobMap().put(job.source(), job); return true; } return false; } }
1,665
30.433962
123
java
soot
soot-master/src/main/java/soot/javaToJimple/StrictFPPropagator.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class StrictFPPropagator extends polyglot.visit.NodeVisitor { boolean strict = false; public StrictFPPropagator(boolean val) { strict = val; } public polyglot.visit.NodeVisitor enter(polyglot.ast.Node parent, polyglot.ast.Node n) { if (n instanceof polyglot.ast.ClassDecl) { if (((polyglot.ast.ClassDecl) n).flags().isStrictFP()) { return new StrictFPPropagator(true); } } if (n instanceof polyglot.ast.LocalClassDecl) { if (((polyglot.ast.LocalClassDecl) n).decl().flags().isStrictFP()) { return new StrictFPPropagator(true); } } if (n instanceof polyglot.ast.MethodDecl) { if (((polyglot.ast.MethodDecl) n).flags().isStrictFP()) { return new StrictFPPropagator(true); } } if (n instanceof polyglot.ast.ConstructorDecl) { if (((polyglot.ast.ConstructorDecl) n).flags().isStrictFP()) { return new StrictFPPropagator(true); } } return this; } public polyglot.ast.Node leave(polyglot.ast.Node old, polyglot.ast.Node n, polyglot.visit.NodeVisitor nodeVisitor) { if (n instanceof polyglot.ast.MethodDecl) { polyglot.ast.MethodDecl decl = (polyglot.ast.MethodDecl) n; if (strict && !decl.flags().isAbstract() && !decl.flags().isStrictFP()) { // System.out.println("changing method decl "+decl); decl = decl.flags(decl.flags().StrictFP()); // System.out.println("changed decl: "+decl); return decl; } } if (n instanceof polyglot.ast.ConstructorDecl) { polyglot.ast.ConstructorDecl decl = (polyglot.ast.ConstructorDecl) n; if (strict && !decl.flags().isAbstract() && !decl.flags().isStrictFP()) { return decl.flags(decl.flags().StrictFP()); } } if (n instanceof polyglot.ast.LocalClassDecl) { polyglot.ast.LocalClassDecl decl = (polyglot.ast.LocalClassDecl) n; if (decl.decl().flags().isStrictFP()) { return decl.decl().flags(decl.decl().flags().clearStrictFP()); } } if (n instanceof polyglot.ast.ClassDecl) { polyglot.ast.ClassDecl decl = (polyglot.ast.ClassDecl) n; if (decl.flags().isStrictFP()) { return decl.flags(decl.flags().clearStrictFP()); } } return n; } }
3,101
33.466667
118
java
soot
soot-master/src/main/java/soot/javaToJimple/TypeListBuilder.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashSet; import polyglot.types.Type; public class TypeListBuilder extends polyglot.visit.NodeVisitor { private final HashSet<Type> list; public HashSet<Type> getList() { return list; } public TypeListBuilder() { list = new HashSet<Type>(); } public polyglot.ast.Node leave(polyglot.ast.Node old, polyglot.ast.Node n, polyglot.visit.NodeVisitor visitor) { if (n instanceof polyglot.ast.Typed) { polyglot.ast.Typed typedNode = (polyglot.ast.Typed) n; if (typedNode.type() instanceof polyglot.types.ClassType) { list.add(typedNode.type()); } else { } } if (n instanceof polyglot.ast.ClassDecl) { polyglot.ast.ClassDecl cd = (polyglot.ast.ClassDecl) n; list.add(cd.type()); } return n; } }
1,625
27.034483
114
java
soot
soot-master/src/main/java/soot/javaToJimple/Util.java
package soot.javaToJimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import soot.LocalGenerator; import soot.Scene; import soot.tagkit.EnclosingTag; import soot.tagkit.QualifyingTag; public class Util { public static void addInnerClassTag(soot.SootClass sc, String innerName, String outerName, String simpleName, int access) { // maybe need file sep here - may break windows innerName = innerName.replaceAll(".", "/"); if (outerName != null) { outerName = outerName.replaceAll(".", "/"); } sc.addTag(new soot.tagkit.InnerClassTag(innerName, outerName, simpleName, access)); } public static String getParamNameForClassLit(polyglot.types.Type type) { String name = ""; if (type.isArray()) { int dims = ((polyglot.types.ArrayType) type).dims(); polyglot.types.Type arrType = ((polyglot.types.ArrayType) type).base(); while (arrType instanceof polyglot.types.ArrayType) { arrType = ((polyglot.types.ArrayType) arrType).base(); } String fieldName = ""; if (arrType.isBoolean()) { fieldName = "Z"; } else if (arrType.isByte()) { fieldName = "B"; } else if (arrType.isChar()) { fieldName = "C"; } else if (arrType.isDouble()) { fieldName = "D"; } else if (arrType.isFloat()) { fieldName = "F"; } else if (arrType.isInt()) { fieldName = "I"; } else if (arrType.isLong()) { fieldName = "J"; } else if (arrType.isShort()) { fieldName = "S"; } else { String typeSt = getSootType(arrType).toString(); fieldName = "L" + typeSt; } for (int i = 0; i < dims; i++) { name += "["; } name += fieldName; if (!arrType.isPrimitive()) { name += ";"; } } else { name = getSootType(type).toString(); } return name; } public static String getFieldNameForClassLit(polyglot.types.Type type) { String fieldName = ""; if (type.isArray()) { int dims = ((polyglot.types.ArrayType) type).dims(); polyglot.types.Type arrType = ((polyglot.types.ArrayType) type).base(); while (arrType instanceof polyglot.types.ArrayType) { arrType = ((polyglot.types.ArrayType) arrType).base(); } fieldName = "array$"; for (int i = 0; i < (dims - 1); i++) { fieldName += "$"; } if (arrType.isBoolean()) { fieldName += "Z"; } else if (arrType.isByte()) { fieldName += "B"; } else if (arrType.isChar()) { fieldName += "C"; } else if (arrType.isDouble()) { fieldName += "D"; } else if (arrType.isFloat()) { fieldName += "F"; } else if (arrType.isInt()) { fieldName += "I"; } else if (arrType.isLong()) { fieldName += "J"; } else if (arrType.isShort()) { fieldName += "S"; } else { String typeSt = getSootType(arrType).toString(); typeSt = typeSt.replaceAll(".", "$"); fieldName = fieldName + "L" + typeSt; } } else { fieldName = "class$"; String typeSt = getSootType(type).toString(); typeSt = typeSt.replaceAll(".", "$"); fieldName = fieldName + typeSt; } return fieldName; } public static String getSourceFileOfClass(soot.SootClass sootClass) { String name = sootClass.getName(); int index = name.indexOf("$"); // inner classes are found in the very outer class if (index != -1) { name = name.substring(0, index); } return name; } public static void addLnPosTags(soot.tagkit.Host host, polyglot.util.Position pos) { if (pos != null) { if (soot.options.Options.v().keep_line_number()) { if (pos.file() != null) { host.addTag( new soot.tagkit.SourceLnNamePosTag(pos.file(), pos.line(), pos.endLine(), pos.column(), pos.endColumn())); } else { host.addTag(new soot.tagkit.SourceLnPosTag(pos.line(), pos.endLine(), pos.column(), pos.endColumn())); } } } } public static void addLnPosTags(soot.tagkit.Host host, int sline, int eline, int spos, int epos) { if (soot.options.Options.v().keep_line_number()) { host.addTag(new soot.tagkit.SourceLnPosTag(sline, eline, spos, epos)); } } /** * Position Tag Adder */ public static void addPosTag(soot.tagkit.Host host, polyglot.util.Position pos) { if (pos != null) { addPosTag(host, pos.column(), pos.endColumn()); } } public static void addMethodPosTag(soot.tagkit.Host meth, int start, int end) { meth.addTag(new soot.tagkit.SourcePositionTag(start, end)); } /** * Position Tag Adder */ public static void addPosTag(soot.tagkit.Host host, int sc, int ec) { host.addTag(new soot.tagkit.SourcePositionTag(sc, ec)); } public static void addMethodLineTag(soot.tagkit.Host host, int sline, int eline) { if (soot.options.Options.v().keep_line_number()) { host.addTag(new soot.tagkit.SourceLineNumberTag(sline, eline)); } } /** * Line Tag Adder */ public static void addLineTag(soot.tagkit.Host host, polyglot.ast.Node node) { if (soot.options.Options.v().keep_line_number()) { if (node.position() != null) { host.addTag(new soot.tagkit.SourceLineNumberTag(node.position().line(), node.position().line())); } } } /** * Line Tag Adder */ public static void addLineTag(soot.tagkit.Host host, int sLine, int eLine) { host.addTag(new soot.tagkit.SourceLineNumberTag(sLine, eLine)); } public static soot.Local getThis(soot.Type sootType, soot.Body body, HashMap getThisMap, LocalGenerator lg) { if (InitialResolver.v().hierarchy() == null) { InitialResolver.v().hierarchy(new soot.FastHierarchy()); } soot.FastHierarchy fh = InitialResolver.v().hierarchy(); // System.out.println("getting this for type: "+sootType); // if this for type already created return it from map // if (getThisMap.containsKey(sootType)){ // return (soot.Local)getThisMap.get(sootType); // } soot.Local specialThisLocal = body.getThisLocal(); // if need this just return it if (specialThisLocal.getType().equals(sootType)) { getThisMap.put(sootType, specialThisLocal); return specialThisLocal; } // check to see if this method has a local of the correct type (it will // if its an initializer - then ust use it) // here we need an exact type I think if (bodyHasLocal(body, sootType)) { soot.Local l = getLocalOfType(body, sootType); getThisMap.put(sootType, l); return l; } // otherwise get this$0 for one level up soot.SootClass classToInvoke = ((soot.RefType) specialThisLocal.getType()).getSootClass(); soot.SootField outerThisField = classToInvoke.getFieldByName("this$0"); soot.Local t1 = lg.generateLocal(outerThisField.getType()); soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newInstanceFieldRef(specialThisLocal, outerThisField.makeRef()); soot.jimple.AssignStmt fieldAssignStmt = soot.jimple.Jimple.v().newAssignStmt(t1, fieldRef); body.getUnits().add(fieldAssignStmt); if (fh.canStoreType(t1.getType(), sootType)) { getThisMap.put(sootType, t1); return t1; } // check to see if this method has a local of the correct type (it will // if its an initializer - then ust use it) // here we need an exact type I think /* * if (bodyHasLocal(body, sootType)){ soot.Local l = getLocalOfType(body, sootType); getThisMap.put(sootType, l); return * l; } */ // otherwise make a new access method soot.Local t2 = t1; return getThisGivenOuter(sootType, getThisMap, body, lg, t2); } private static soot.Local getLocalOfType(soot.Body body, soot.Type type) { soot.FastHierarchy fh = InitialResolver.v().hierarchy(); Iterator stmtsIt = body.getUnits().iterator(); soot.Local correctLocal = null; while (stmtsIt.hasNext()) { soot.jimple.Stmt s = (soot.jimple.Stmt) stmtsIt.next(); if (s instanceof soot.jimple.IdentityStmt && (s.hasTag(EnclosingTag.NAME) || s.hasTag(QualifyingTag.NAME))) { Iterator it = s.getDefBoxes().iterator(); while (it.hasNext()) { soot.ValueBox vb = (soot.ValueBox) it.next(); if ((vb.getValue() instanceof soot.Local) && (fh.canStoreType(type, vb.getValue().getType()))) { // (vb.getValue().getType().equals(type))){ correctLocal = (soot.Local) vb.getValue(); } } } } return correctLocal; } private static boolean bodyHasLocal(soot.Body body, soot.Type type) { soot.FastHierarchy fh = InitialResolver.v().hierarchy(); Iterator stmtsIt = body.getUnits().iterator(); while (stmtsIt.hasNext()) { soot.jimple.Stmt s = (soot.jimple.Stmt) stmtsIt.next(); if (s instanceof soot.jimple.IdentityStmt && (s.hasTag(EnclosingTag.NAME) || s.hasTag(QualifyingTag.NAME))) { Iterator it = s.getDefBoxes().iterator(); while (it.hasNext()) { soot.ValueBox vb = (soot.ValueBox) it.next(); if ((vb.getValue() instanceof soot.Local) && (fh.canStoreType(type, vb.getValue().getType()))) { // (vb.getValue().getType().equals(type))){ return true; } } } } return false; /* * soot.FastHierarchy fh = InitialResolver.v().hierarchy(); Iterator it = body.getDefBoxes().iterator(); while * (it.hasNext()){ soot.ValueBox vb = (soot.ValueBox)it.next(); if ((vb.getValue() instanceof soot.Local) && * (fh.canStoreType(type, vb.getValue().getType()))){//(vb.getValue().getType().equals(type))){ return true; } } return * false; */ } public static soot.Local getThisGivenOuter(soot.Type sootType, HashMap getThisMap, soot.Body body, LocalGenerator lg, soot.Local t2) { if (InitialResolver.v().hierarchy() == null) { InitialResolver.v().hierarchy(new soot.FastHierarchy()); } soot.FastHierarchy fh = InitialResolver.v().hierarchy(); while (!fh.canStoreType(t2.getType(), sootType)) { soot.SootClass classToInvoke = ((soot.RefType) t2.getType()).getSootClass(); // make an access method and add it to that class for accessing // its private this$0 field soot.SootMethod methToInvoke = makeOuterThisAccessMethod(classToInvoke); // generate a local that corresponds to the invoke of that meth soot.Local t3 = lg.generateLocal(methToInvoke.getReturnType()); ArrayList methParams = new ArrayList(); methParams.add(t2); soot.Local res = getPrivateAccessFieldInvoke(methToInvoke.makeRef(), methParams, body, lg); soot.jimple.AssignStmt assign = soot.jimple.Jimple.v().newAssignStmt(t3, res); body.getUnits().add(assign); t2 = t3; } getThisMap.put(sootType, t2); return t2; } private static soot.SootMethod makeOuterThisAccessMethod(soot.SootClass classToInvoke) { String name = "access$" + soot.javaToJimple.InitialResolver.v().getNextPrivateAccessCounter() + "00"; ArrayList paramTypes = new ArrayList(); paramTypes.add(classToInvoke.getType()); soot.SootMethod meth = Scene.v().makeSootMethod(name, paramTypes, classToInvoke.getFieldByName("this$0").getType(), soot.Modifier.STATIC); classToInvoke.addMethod(meth); PrivateFieldAccMethodSource src = new PrivateFieldAccMethodSource(classToInvoke.getFieldByName("this$0").getType(), "this$0", classToInvoke.getFieldByName("this$0").isStatic(), classToInvoke); meth.setActiveBody(src.getBody(meth, null)); meth.addTag(new soot.tagkit.SyntheticTag()); return meth; } public static soot.Local getPrivateAccessFieldInvoke(soot.SootMethodRef toInvoke, ArrayList params, soot.Body body, LocalGenerator lg) { soot.jimple.InvokeExpr invoke = soot.jimple.Jimple.v().newStaticInvokeExpr(toInvoke, params); soot.Local retLocal = lg.generateLocal(toInvoke.returnType()); soot.jimple.AssignStmt stmt = soot.jimple.Jimple.v().newAssignStmt(retLocal, invoke); body.getUnits().add(stmt); return retLocal; } public static boolean isSubType(polyglot.types.ClassType type, polyglot.types.ClassType superType) { if (type.equals(superType)) { return true; } if (type.superType() == null) { return false; } return isSubType((polyglot.types.ClassType) type.superType(), superType); } /** * Type handling */ public static soot.Type getSootType(polyglot.types.Type type) { if (type == null) { throw new RuntimeException("Trying to get soot type for null polyglot type"); } soot.Type sootType = null; if (type.isInt()) { sootType = soot.IntType.v(); } else if (type.isArray()) { polyglot.types.Type polyglotBase = ((polyglot.types.ArrayType) type).base(); while (polyglotBase instanceof polyglot.types.ArrayType) { polyglotBase = ((polyglot.types.ArrayType) polyglotBase).base(); } soot.Type baseType = getSootType(polyglotBase); int dims = ((polyglot.types.ArrayType) type).dims(); // do something here if baseType is still an array sootType = soot.ArrayType.v(baseType, dims); } else if (type.isBoolean()) { sootType = soot.BooleanType.v(); } else if (type.isByte()) { sootType = soot.ByteType.v(); } else if (type.isChar()) { sootType = soot.CharType.v(); } else if (type.isDouble()) { sootType = soot.DoubleType.v(); } else if (type.isFloat()) { sootType = soot.FloatType.v(); } else if (type.isLong()) { sootType = soot.LongType.v(); } else if (type.isShort()) { sootType = soot.ShortType.v(); } else if (type.isNull()) { sootType = soot.NullType.v(); } else if (type.isVoid()) { sootType = soot.VoidType.v(); } else if (type.isClass()) { polyglot.types.ClassType classType = (polyglot.types.ClassType) type; String className; if (classType.isNested()) { if (classType.isAnonymous() && (soot.javaToJimple.InitialResolver.v().getAnonTypeMap() != null) && soot.javaToJimple.InitialResolver.v().getAnonTypeMap() .containsKey(new polyglot.util.IdentityKey(classType))) { className = soot.javaToJimple.InitialResolver.v().getAnonTypeMap().get(new polyglot.util.IdentityKey(classType)); } else if (classType.isLocal() && (soot.javaToJimple.InitialResolver.v().getLocalTypeMap() != null) && soot.javaToJimple.InitialResolver.v().getLocalTypeMap() .containsKey(new polyglot.util.IdentityKey(classType))) { className = soot.javaToJimple.InitialResolver.v().getLocalTypeMap().get(new polyglot.util.IdentityKey(classType)); } else { String pkgName = ""; if (classType.package_() != null) { pkgName = classType.package_().fullName(); } className = classType.name(); if (classType.outer().isAnonymous() || classType.outer().isLocal()) { className = getSootType(classType.outer()).toString() + "$" + className; } else { while (classType.outer() != null) { className = classType.outer().name() + "$" + className; classType = classType.outer(); } if (!pkgName.equals("")) { className = pkgName + "." + className; } } } } else { className = classType.fullName(); } sootType = soot.RefType.v(className); } else { throw new RuntimeException("Unknown Type"); } return sootType; } /** * Modifier Creation */ public static int getModifier(polyglot.types.Flags flags) { int modifier = 0; if (flags.isPublic()) { modifier = modifier | soot.Modifier.PUBLIC; } if (flags.isPrivate()) { modifier = modifier | soot.Modifier.PRIVATE; } if (flags.isProtected()) { modifier = modifier | soot.Modifier.PROTECTED; } if (flags.isFinal()) { modifier = modifier | soot.Modifier.FINAL; } if (flags.isStatic()) { modifier = modifier | soot.Modifier.STATIC; } if (flags.isNative()) { modifier = modifier | soot.Modifier.NATIVE; } if (flags.isAbstract()) { modifier = modifier | soot.Modifier.ABSTRACT; } if (flags.isVolatile()) { modifier = modifier | soot.Modifier.VOLATILE; } if (flags.isTransient()) { modifier = modifier | soot.Modifier.TRANSIENT; } if (flags.isSynchronized()) { modifier = modifier | soot.Modifier.SYNCHRONIZED; } if (flags.isInterface()) { modifier = modifier | soot.Modifier.INTERFACE; } if (flags.isStrictFP()) { modifier = modifier | soot.Modifier.STRICTFP; } return modifier; } }
17,777
33.520388
125
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ExtensionInfo.java
package soot.javaToJimple.jj; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.util.HashMap; import java.util.List; import polyglot.ast.NodeFactory; import polyglot.frontend.Job; import polyglot.frontend.Source; import polyglot.main.Options; import polyglot.types.TypeSystem; import soot.javaToJimple.jj.ast.JjNodeFactory_c; import soot.javaToJimple.jj.types.JjTypeSystem_c; /** * Extension information for jj extension. */ public class ExtensionInfo extends polyglot.ext.jl.ExtensionInfo { static { // force Topics to load new Topics(); } public String defaultFileExtension() { return "jj"; } public String compilerName() { return "jjc"; } /* * public Parser parser(Reader reader, FileSource source, ErrorQueue eq) { Lexer lexer = new Lexer_c(reader, source.name(), * eq); Grm grm = new Grm(lexer, ts, nf, eq); return new CupParser(grm, source, eq); } */ protected NodeFactory createNodeFactory() { return new JjNodeFactory_c(); } protected TypeSystem createTypeSystem() { return new JjTypeSystem_c(); } public List passes(Job job) { List passes = super.passes(job); // TODO: add passes as needed by your compiler return passes; } private HashMap<Source, Job> sourceJobMap; public HashMap<Source, Job> sourceJobMap() { return sourceJobMap; } public void sourceJobMap(HashMap<Source, Job> map) { sourceJobMap = map; } /** * Appends the soot classpath to the default system classpath. */ protected Options createOptions() { return new Options(this) { /** * Appends the soot classpath to the default system classpath. */ public String constructFullClasspath() { String cp = super.constructFullClasspath(); cp += File.pathSeparator + soot.options.Options.v().soot_classpath(); return cp; } }; } }
2,661
25.098039
125
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/Topics.java
package soot.javaToJimple.jj; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.main.Report; /** * Extension information for jj extension. */ public class Topics { public static final String jj = "jj"; static { Report.topics.add(jj); } }
1,019
26.567568
71
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/Version.java
package soot.javaToJimple.jj; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Version information for jj extension */ public class Version extends polyglot.main.Version { public String name() { return "jj"; } // TODO: define a version number, the default (below) is 0.1.0 public int major() { return 0; } public int minor() { return 1; } public int patch_level() { return 0; } }
1,177
24.608696
71
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjAccessField_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import polyglot.ast.Call; import polyglot.ast.Expr; import polyglot.ast.Field; import polyglot.ast.Node; import polyglot.ast.Term; import polyglot.ext.jl.ast.Expr_c; import polyglot.util.Position; import polyglot.visit.CFGBuilder; import polyglot.visit.NodeVisitor; public class JjAccessField_c extends Expr_c implements Expr { private Call getMeth; private Call setMeth; private Field field; public JjAccessField_c(Position pos, Call getMeth, Call setMeth, Field field) { super(pos); this.getMeth = getMeth; this.setMeth = setMeth; this.field = field; } public Call getMeth() { return getMeth; } public Call setMeth() { return setMeth; } public Field field() { return field; } public String toString() { return field + " " + getMeth + " " + setMeth; } public List acceptCFG(CFGBuilder v, List succs) { return succs; } public Term entry() { return field.entry(); } public Node visitChildren(NodeVisitor v) { visitChild(field, v); visitChild(getMeth, v); visitChild(setMeth, v); return this; } }
1,958
23.185185
81
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjArrayAccessAssign_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.ArrayAccess; import polyglot.ast.Expr; import polyglot.ext.jl.ast.ArrayAccessAssign_c; import polyglot.types.Type; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjArrayAccessAssign_c extends ArrayAccessAssign_c { public JjArrayAccessAssign_c(Position pos, ArrayAccess left, Operator op, Expr right) { super(pos, left, op, right); } public Type childExpectedType(Expr child, AscriptionVisitor av) { if (op == SHL_ASSIGN || op == SHR_ASSIGN || op == USHR_ASSIGN) { return child.type(); } if (child == right) { return left.type(); } return child.type(); } }
1,499
28.411765
89
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjArrayInit_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.List; import polyglot.ast.Expr; import polyglot.ext.jl.ast.ArrayInit_c; import polyglot.types.Type; import polyglot.util.InternalCompilerError; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjArrayInit_c extends ArrayInit_c { public JjArrayInit_c(Position pos, List elements) { super(pos, elements); } public Type childExpectedType(Expr child, AscriptionVisitor av) { if (elements.isEmpty()) { return child.type(); } Type t = av.toType(); // System.out.println("t type: "+t); if (t == null) { // System.out.println("t is null"); return child.type(); } if (!t.isArray()) { throw new InternalCompilerError("Type of array initializer must be " + "an array.", position()); } t = t.toArray().base(); for (Iterator i = elements.iterator(); i.hasNext();) { Expr e = (Expr) i.next(); if (e == child) { return t; } } return child.type(); } }
1,871
25.742857
102
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjBinary_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.Binary; import polyglot.ast.Expr; import polyglot.ext.jl.ast.Binary_c; import polyglot.types.Type; import polyglot.types.TypeSystem; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjBinary_c extends Binary_c { public JjBinary_c(Position pos, Expr left, Binary.Operator op, Expr right) { super(pos, left, op, right); } public Type childExpectedType(Expr child, AscriptionVisitor av) { Expr other; // System.out.println("child: "+child+" op: "+op); if (child == left) { other = right; } else if (child == right) { other = left; } else { return child.type(); } TypeSystem ts = av.typeSystem(); if (op == EQ || op == NE) { // Coercion to compatible types. if (other.type().isReference() || other.type().isNull()) { return ts.Object(); } if (other.type().isBoolean()) { return ts.Boolean(); } if (other.type().isNumeric()) { if (other.type().isDouble() || child.type().isDouble()) { return ts.Double(); } else if (other.type().isFloat() || child.type().isFloat()) { return ts.Float(); } else if (other.type().isLong() || child.type().isLong()) { return ts.Long(); } else { return ts.Int(); } } } if (op == ADD && ts.equals(type, ts.String())) { // Implicit coercion to String. return ts.String(); } if (op == GT || op == LT || op == GE || op == LE) { if (other.type().isBoolean()) { return ts.Boolean(); } if (other.type().isNumeric()) { if (other.type().isDouble() || child.type().isDouble()) { return ts.Double(); } else if (other.type().isFloat() || child.type().isFloat()) { return ts.Float(); } else if (other.type().isLong() || child.type().isLong()) { return ts.Long(); } else { return ts.Int(); } } } if (op == COND_OR || op == COND_AND) { return ts.Boolean(); } if (op == BIT_AND || op == BIT_OR || op == BIT_XOR) { if (other.type().isBoolean()) { return ts.Boolean(); } if (other.type().isNumeric()) { if (other.type().isLong() || child.type().isLong()) { return ts.Long(); } else { return ts.Int(); } } } if (op == ADD || op == SUB || op == MUL || op == DIV || op == MOD) { // System.out.println("other: "+other+" type: "+other.type()); // System.out.println("child: "+child+" child: "+child.type()); if (other.type().isNumeric()) { if (other.type().isDouble() || child.type().isDouble()) { return ts.Double(); } else if (other.type().isFloat() || child.type().isFloat()) { return ts.Float(); } else if (other.type().isLong() || child.type().isLong()) { return ts.Long(); } else { return ts.Int(); } } } if (op == SHL || op == SHR || op == USHR) { if (child == right || !child.type().isLong()) { return ts.Int(); } else { return child.type(); } } return child.type(); } /* * public Node foldConstants(ConstantFolder cf) { if (left instanceof Binary || left instanceof Field){ left = * left.del.foldConstants(cf); } if (right instanceof Binary || right instanceof Field){ right = * right.del.foldConstants(cf); } if (left instanceof StringLit && right instanceof StringLit) { String l = ((StringLit) * left).value(); String r = ((StringLit) right).value(); if (op == ADD) return nf.StringLit(position(), l + r); } else if * (left instanceof } */ }
4,584
29.164474
124
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjCast_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.Expr; import polyglot.ast.TypeNode; import polyglot.ext.jl.ast.Cast_c; import polyglot.types.Type; import polyglot.types.TypeSystem; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjCast_c extends Cast_c { public JjCast_c(Position pos, TypeNode castType, Expr expr) { super(pos, castType, expr); } public Type childExpectedType(Expr child, AscriptionVisitor av) { TypeSystem ts = av.typeSystem(); if (child == expr) { if (castType.type().isReference()) { return ts.Object(); } else if (castType.type().isNumeric()) { return castType.type(); // return ts.Double(); } else if (castType.type().isBoolean()) { return ts.Boolean(); } } return child.type(); } }
1,639
27.77193
71
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjComma_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import polyglot.ast.Expr; import polyglot.ast.Term; import polyglot.ext.jl.ast.Expr_c; import polyglot.util.Position; import polyglot.visit.CFGBuilder; public class JjComma_c extends Expr_c implements Expr { private Expr first; private Expr second; public JjComma_c(Position pos, Expr first, Expr second) { super(pos); this.first = first; this.second = second; } public Expr first() { return first; } public Expr second() { return second; } public List acceptCFG(CFGBuilder v, List succs) { return succs; } public Term entry() { return first.entry(); } }
1,473
23.566667
71
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjFieldAssign_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.Expr; import polyglot.ast.Field; import polyglot.ext.jl.ast.FieldAssign_c; import polyglot.types.Type; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjFieldAssign_c extends FieldAssign_c { public JjFieldAssign_c(Position pos, Field left, Operator op, Expr right) { super(pos, left, op, right); } public Type childExpectedType(Expr child, AscriptionVisitor av) { if (op == SHL_ASSIGN || op == SHR_ASSIGN || op == USHR_ASSIGN) { return child.type(); } if (child == right) { return left.type(); } return child.type(); } }
1,463
27.705882
77
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjFieldDecl_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.Expr; import polyglot.ast.TypeNode; import polyglot.ext.jl.ast.FieldDecl_c; import polyglot.types.Flags; import polyglot.types.Type; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjFieldDecl_c extends FieldDecl_c { public JjFieldDecl_c(Position pos, Flags flags, TypeNode type, String name, Expr init) { super(pos, flags, type, name, init); } public Type childExpectedType(Expr child, AscriptionVisitor av) { return type().type(); } }
1,348
30.372093
90
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjLocalAssign_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.Expr; import polyglot.ast.Local; import polyglot.ext.jl.ast.LocalAssign_c; import polyglot.types.Type; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjLocalAssign_c extends LocalAssign_c { public JjLocalAssign_c(Position pos, Local left, Operator op, Expr right) { super(pos, left, op, right); } public Type childExpectedType(Expr child, AscriptionVisitor av) { if (op == SHL_ASSIGN || op == SHR_ASSIGN || op == USHR_ASSIGN) { // System.out.println("local assign: child type: "+child.type()+" child: "+child); return child.type(); } if (child == right) { return left.type(); } return child.type(); } }
1,552
28.865385
88
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjLocalDecl_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.Expr; import polyglot.ast.TypeNode; import polyglot.ext.jl.ast.LocalDecl_c; import polyglot.types.Flags; import polyglot.types.Type; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjLocalDecl_c extends LocalDecl_c { public JjLocalDecl_c(Position pos, Flags flags, TypeNode type, String name, Expr init) { super(pos, flags, type, name, init); } public Type childExpectedType(Expr child, AscriptionVisitor av) { return type().type(); } }
1,349
29.681818
90
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjNodeFactory.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.Expr; import polyglot.ast.NodeFactory; import polyglot.util.Position; /** * NodeFactory for jj extension. */ public interface JjNodeFactory extends NodeFactory { // TODO: Declare any factory methods for new AST nodes. public JjComma_c JjComma(Position pos, Expr first, Expr second); }
1,147
30.888889
71
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjNodeFactory_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import polyglot.ast.ArrayAccess; import polyglot.ast.ArrayAccessAssign; import polyglot.ast.ArrayInit; import polyglot.ast.Assign; import polyglot.ast.Binary; import polyglot.ast.Call; import polyglot.ast.Cast; import polyglot.ast.Expr; import polyglot.ast.Field; import polyglot.ast.FieldAssign; import polyglot.ast.FieldDecl; import polyglot.ast.Local; import polyglot.ast.LocalAssign; import polyglot.ast.LocalDecl; import polyglot.ast.NewArray; import polyglot.ast.Return; import polyglot.ast.TypeNode; import polyglot.ast.Unary; import polyglot.ext.jl.ast.NodeFactory_c; import polyglot.types.Flags; import polyglot.util.Position; /** * NodeFactory for jj extension. */ public class JjNodeFactory_c extends NodeFactory_c implements JjNodeFactory { // TODO: Implement factory methods for new AST nodes. // TODO: Override factory methods for overriden AST nodes. // TODO: Override factory methods for AST nodes with new extension nodes. public JjComma_c JjComma(Position pos, Expr first, Expr second) { JjComma_c n = new JjComma_c(pos, first, second); return n; } public JjAccessField_c JjAccessField(Position pos, Call getMeth, Call setMeth, Field field) { JjAccessField_c n = new JjAccessField_c(pos, getMeth, setMeth, field); return n; } public Unary Unary(Position pos, Unary.Operator op, Expr expr) { Unary n = new JjUnary_c(pos, op, expr); n = (Unary) n.ext(extFactory().extUnary()); n = (Unary) n.del(delFactory().delUnary()); return n; } public Binary Binary(Position pos, Expr left, Binary.Operator op, Expr right) { Binary n = new JjBinary_c(pos, left, op, right); n = (Binary) n.ext(extFactory().extBinary()); n = (Binary) n.del(delFactory().delBinary()); return n; } public Assign Assign(Position pos, Expr left, Assign.Operator op, Expr right) { if (left instanceof Local) { return LocalAssign(pos, (Local) left, op, right); } else if (left instanceof Field) { return FieldAssign(pos, (Field) left, op, right); } else if (left instanceof ArrayAccess) { return ArrayAccessAssign(pos, (ArrayAccess) left, op, right); } return AmbAssign(pos, left, op, right); } public LocalAssign LocalAssign(Position pos, Local left, Assign.Operator op, Expr right) { LocalAssign n = new JjLocalAssign_c(pos, left, op, right); n = (LocalAssign) n.ext(extFactory().extLocalAssign()); n = (LocalAssign) n.del(delFactory().delLocalAssign()); return n; } public LocalDecl LocalDecl(Position pos, Flags flags, TypeNode type, String name, Expr init) { LocalDecl n = new JjLocalDecl_c(pos, flags, type, name, init); n = (LocalDecl) n.ext(extFactory().extLocalDecl()); n = (LocalDecl) n.del(delFactory().delLocalDecl()); return n; } public FieldAssign FieldAssign(Position pos, Field left, Assign.Operator op, Expr right) { FieldAssign n = new JjFieldAssign_c(pos, left, op, right); n = (FieldAssign) n.ext(extFactory().extFieldAssign()); n = (FieldAssign) n.del(delFactory().delFieldAssign()); return n; } public FieldDecl FieldDecl(Position pos, Flags flags, TypeNode type, String name, Expr init) { FieldDecl n = new JjFieldDecl_c(pos, flags, type, name, init); n = (FieldDecl) n.ext(extFactory().extFieldDecl()); n = (FieldDecl) n.del(delFactory().delFieldDecl()); return n; } public ArrayAccessAssign ArrayAccessAssign(Position pos, ArrayAccess left, Assign.Operator op, Expr right) { ArrayAccessAssign n = new JjArrayAccessAssign_c(pos, left, op, right); n = (ArrayAccessAssign) n.ext(extFactory().extArrayAccessAssign()); n = (ArrayAccessAssign) n.del(delFactory().delArrayAccessAssign()); return n; } public Cast Cast(Position pos, TypeNode type, Expr expr) { Cast n = new JjCast_c(pos, type, expr); n = (Cast) n.ext(extFactory().extCast()); n = (Cast) n.del(delFactory().delCast()); return n; } public NewArray NewArray(Position pos, TypeNode base, List dims, int addDims, ArrayInit init) { // System.out.println("new array pos: "+pos); return super.NewArray(pos, base, dims, addDims, init); } public ArrayInit ArrayInit(Position pos, List elements) { ArrayInit n = new JjArrayInit_c(pos, elements); n = (ArrayInit) n.ext(extFactory().extArrayInit()); n = (ArrayInit) n.del(delFactory().delArrayInit()); return n; } public Return Return(Position pos, Expr expr) { Return n = new JjReturn_c(pos, expr); n = (Return) n.ext(extFactory().extReturn()); n = (Return) n.del(delFactory().delReturn()); return n; } }
5,468
34.512987
110
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjReturn_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.Expr; import polyglot.ext.jl.ast.Return_c; import polyglot.types.CodeInstance; import polyglot.types.Context; import polyglot.types.MethodInstance; import polyglot.types.Type; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjReturn_c extends Return_c { public JjReturn_c(Position pos, Expr expr) { super(pos, expr); } public Type childExpectedType(Expr child, AscriptionVisitor av) { if (child == expr) { Context c = av.context(); CodeInstance ci = c.currentCode(); if (ci instanceof MethodInstance) { MethodInstance mi = (MethodInstance) ci; return mi.returnType(); } } return child.type(); } }
1,559
27.363636
71
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/ast/JjUnary_c.java
package soot.javaToJimple.jj.ast; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ast.Expr; import polyglot.ast.Unary; import polyglot.ext.jl.ast.Unary_c; import polyglot.types.Type; import polyglot.types.TypeSystem; import polyglot.util.Position; import polyglot.visit.AscriptionVisitor; public class JjUnary_c extends Unary_c { public JjUnary_c(Position pos, Unary.Operator op, Expr expr) { super(pos, op, expr); } public Type childExpectedType(Expr child, AscriptionVisitor av) { TypeSystem ts = av.typeSystem(); if (child == expr) { if (op == POST_INC || op == POST_DEC || op == PRE_INC || op == PRE_DEC) { // if (child.type().isByte() || child.type().isShort()){// || child.type().isChar()) { // return ts.Int(); // } return child.type(); } else if (op == NEG || op == POS) { // if (child.type().isByte() || child.type().isShort() || child.type().isChar()) { // return ts.Int(); // } return child.type(); } else if (op == BIT_NOT) { // if (child.type().isByte() || child.type().isShort() || child.type().isChar()) { // return ts.Int(); // } return child.type(); } else if (op == NOT) { return ts.Boolean(); } } return child.type(); } }
2,078
30.029851
94
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/types/JjTypeSystem.java
package soot.javaToJimple.jj.types; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.types.TypeSystem; public interface JjTypeSystem extends TypeSystem { // TODO: declare any new methods needed }
967
31.266667
71
java
soot
soot-master/src/main/java/soot/javaToJimple/jj/types/JjTypeSystem_c.java
package soot.javaToJimple.jj.types; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import polyglot.ext.jl.types.TypeSystem_c; public class JjTypeSystem_c extends TypeSystem_c implements JjTypeSystem { // TODO: implement new methods in JjTypeSystem. // TODO: override methods as needed from TypeSystem_c. }
1,065
33.387097
74
java
soot
soot-master/src/main/java/soot/javaToJimple/toolkits/CondTransformer.java
package soot.javaToJimple.toolkits; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.Singletons; import soot.jimple.AssignStmt; import soot.jimple.BinopExpr; import soot.jimple.EqExpr; import soot.jimple.GotoStmt; import soot.jimple.IfStmt; import soot.jimple.IntConstant; import soot.jimple.Jimple; import soot.jimple.Stmt; public class CondTransformer extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(CondTransformer.class); public CondTransformer(Singletons.Global g) { } public static CondTransformer v() { return G.v().soot_javaToJimple_toolkits_CondTransformer(); } private static final int SEQ_LENGTH = 6; private Stmt[] stmtSeq = new Stmt[SEQ_LENGTH]; private boolean sameGoto = true; protected void internalTransform(Body b, String phaseName, Map options) { // logger.debug("running cond and/or transformer"); boolean change = true; /* * the idea is to look for groups of statements of the form if cond goto L0 if cond goto L0 z0 = 1 goto L1 L0: z0 = 0 L1: * if z0 == 0 goto L2 conseq L2: altern * * and transform to if cond goto L0 if cond goto L0 conseq L0: altern * */ while (change) { Iterator it = b.getUnits().iterator(); int pos = 0; while (it.hasNext()) { change = false; Stmt s = (Stmt) it.next(); if (testStmtSeq(s, pos)) { pos++; } if (pos == 6) { // found seq now transform then continue // logger.debug("found sequence will transform"); change = true; break; } } if (change) { transformBody(b, (Stmt) it.next()); pos = 0; stmtSeq = new Stmt[SEQ_LENGTH]; } } } private void transformBody(Body b, Stmt next) { // change target of stmts 0 and 1 to target of stmt 5 // remove stmts 2, 3, 4, 5 Stmt newTarget = null; Stmt oldTarget = null; if (sameGoto) { newTarget = ((IfStmt) stmtSeq[5]).getTarget(); } else { newTarget = next; oldTarget = ((IfStmt) stmtSeq[5]).getTarget(); } ((IfStmt) stmtSeq[0]).setTarget(newTarget); ((IfStmt) stmtSeq[1]).setTarget(newTarget); for (int i = 2; i <= 5; i++) { b.getUnits().remove(stmtSeq[i]); } if (!sameGoto) { b.getUnits().insertAfter(Jimple.v().newGotoStmt(oldTarget), stmtSeq[1]); } } private boolean testStmtSeq(Stmt s, int pos) { switch (pos) { case 0: { if (s instanceof IfStmt) { stmtSeq[pos] = s; return true; } break; } case 1: { if (s instanceof IfStmt) { if (sameTarget(stmtSeq[pos - 1], s)) { stmtSeq[pos] = s; return true; } } break; } case 2: { if (s instanceof AssignStmt) { stmtSeq[pos] = s; if ((((AssignStmt) s).getRightOp() instanceof IntConstant) && (((IntConstant) ((AssignStmt) s).getRightOp())).value == 0) { sameGoto = false; } return true; } break; } case 3: { if (s instanceof GotoStmt) { stmtSeq[pos] = s; return true; } break; } case 4: { if (s instanceof AssignStmt) { if (isTarget(((IfStmt) stmtSeq[0]).getTarget(), s) && sameLocal(stmtSeq[2], s)) { stmtSeq[pos] = s; return true; } } break; } case 5: { if (s instanceof IfStmt) { if (isTarget((Stmt) ((GotoStmt) stmtSeq[3]).getTarget(), s) && sameCondLocal(stmtSeq[4], s) && (((IfStmt) s).getCondition() instanceof EqExpr)) { stmtSeq[pos] = s; return true; } else if (isTarget((Stmt) ((GotoStmt) stmtSeq[3]).getTarget(), s) && sameCondLocal(stmtSeq[4], s)) { stmtSeq[pos] = s; sameGoto = false; return true; } } break; } default: { break; } } return false; } private boolean sameTarget(Stmt s1, Stmt s2) { IfStmt is1 = (IfStmt) s1; IfStmt is2 = (IfStmt) s2; if (is1.getTarget().equals(is2.getTarget())) { return true; } return false; } private boolean isTarget(Stmt s1, Stmt s) { if (s1.equals(s)) { return true; } return false; } private boolean sameLocal(Stmt s1, Stmt s2) { AssignStmt as1 = (AssignStmt) s1; AssignStmt as2 = (AssignStmt) s2; if (as1.getLeftOp().equals(as2.getLeftOp())) { return true; } return false; } private boolean sameCondLocal(Stmt s1, Stmt s2) { AssignStmt as1 = (AssignStmt) s1; IfStmt is2 = (IfStmt) s2; if (is2.getCondition() instanceof BinopExpr) { BinopExpr bs2 = (BinopExpr) is2.getCondition(); if (as1.getLeftOp().equals(bs2.getOp1())) { return true; } } return false; } }
5,931
25.963636
125
java
soot
soot-master/src/main/java/soot/jbco/IJbcoTransform.java
package soot.jbco; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.PrintStream; import soot.G; /** * @author Michael Batchelder * <p> * Created on 19-Jun-2006 */ public interface IJbcoTransform { @Deprecated PrintStream out = soot.G.v().out; /** * @deprecated Use soot.jbco.IJbcoTransform#isVerbose() instead */ @Deprecated boolean output = G.v().soot_options_Options().verbose() || soot.jbco.Main.jbcoVerbose; @Deprecated boolean debug = soot.jbco.Main.jbcoDebug; /** * Gets the code name of {@link IJbcoTransform jbco transformer} implementation. * * @return the code name of {@link IJbcoTransform jbco transformer} */ String getName(); /** * Gets array of {@link IJbcoTransform jbco transformer} code names on which current transformer depends on. * * @return array of code names */ String[] getDependencies(); /** * Prints summary of the produced changes. */ void outputSummary(); /** * Checks if {@link IJbcoTransform jbco transformer} can log extra information. * * @return {@code true} when {@link IJbcoTransform jbco transformer} can log extra information; {@code false} otherwise */ default boolean isVerbose() { return G.v().soot_options_Options().verbose() || soot.jbco.Main.jbcoVerbose; } /** * Checks if {@link IJbcoTransform jbco transformer} can log debug information. * * @return {@code true} when {@link IJbcoTransform jbco transformer} can log debug information; {@code false} otherwise */ default boolean isDebugEnabled() { return soot.jbco.Main.jbcoDebug; } }
2,392
26.825581
121
java
soot
soot-master/src/main/java/soot/jbco/LineNumberGenerator.java
package soot.jbco; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.PackManager; import soot.Transform; import soot.Unit; import soot.tagkit.LineNumberTag; public class LineNumberGenerator { BafLineNumberer bln = new BafLineNumberer(); public static void main(String[] argv) { // if you do not want soot to output new class files, run with comman line option "-f n" // if you want the source code line numbers for jimple statements, use this: PackManager.v().getPack("jtp").add(new Transform("jtp.lnprinter", new LineNumberGenerator().bln)); // if you want the source code line numbers for baf instructions, use this: PackManager.v().getPack("bb").add(new Transform("bb.lnprinter", new LineNumberGenerator().bln)); soot.Main.main(argv); } protected static class BafLineNumberer extends BodyTransformer { @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { System.out.println("Printing Line Numbers for: " + b.getMethod().getSignature()); for (Unit u : b.getUnits()) { // for each jimple statement or baf instruction LineNumberTag tag = (LineNumberTag) u.getTag(LineNumberTag.NAME); if (tag != null) { // see if a LineNumberTag exists (it will if you use -keep-line-number) System.out.println(u + " has Line Number: " + tag.getLineNumber()); // print out the unit and line number } else { System.out.println(u + " has no Line Number"); } } System.out.println("\n"); } } }
2,399
34.820896
115
java
soot
soot-master/src/main/java/soot/jbco/Main.java
package soot.jbco; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Local; import soot.Pack; import soot.PackManager; import soot.SootClass; import soot.SootMethod; import soot.Transform; import soot.Transformer; import soot.jbco.bafTransformations.AddJSRs; import soot.jbco.bafTransformations.BAFCounter; import soot.jbco.bafTransformations.BAFPrintout; import soot.jbco.bafTransformations.BafLineNumberer; import soot.jbco.bafTransformations.ConstructorConfuser; import soot.jbco.bafTransformations.FindDuplicateSequences; import soot.jbco.bafTransformations.FixUndefinedLocals; import soot.jbco.bafTransformations.IfNullToTryCatch; import soot.jbco.bafTransformations.IndirectIfJumpsToCaughtGotos; import soot.jbco.bafTransformations.Jimple2BafLocalBuilder; import soot.jbco.bafTransformations.LocalsToBitField; import soot.jbco.bafTransformations.MoveLoadsAboveIfs; import soot.jbco.bafTransformations.RemoveRedundantPushStores; import soot.jbco.bafTransformations.TryCatchCombiner; import soot.jbco.bafTransformations.UpdateConstantsToFields; import soot.jbco.bafTransformations.WrapSwitchesInTrys; import soot.jbco.jimpleTransformations.AddSwitches; import soot.jbco.jimpleTransformations.ArithmeticTransformer; import soot.jbco.jimpleTransformations.BuildIntermediateAppClasses; import soot.jbco.jimpleTransformations.ClassRenamer; import soot.jbco.jimpleTransformations.CollectConstants; import soot.jbco.jimpleTransformations.CollectJimpleLocals; import soot.jbco.jimpleTransformations.FieldRenamer; import soot.jbco.jimpleTransformations.GotoInstrumenter; import soot.jbco.jimpleTransformations.LibraryMethodWrappersBuilder; import soot.jbco.jimpleTransformations.MethodRenamer; /** * @author Michael Batchelder * * Created on 24-Jan-2006 */ public class Main { private static final Logger logger = LoggerFactory.getLogger(Main.class); public static boolean jbcoDebug = false; public static boolean jbcoSummary = true; public static boolean jbcoVerbose = false; public static boolean metrics = false; public static Map<String, Integer> transformsToWeights = new ConcurrentHashMap<>(); public static Map<String, Map<Object, Integer>> transformsToMethodsToWeights = new ConcurrentHashMap<>(); public static Map method2Locals2REALTypes = new ConcurrentHashMap(); public static Map<SootMethod, Map<Local, Local>> methods2Baf2JLocals = new ConcurrentHashMap<>(); public static Map<SootMethod, List<Local>> methods2JLocals = new ConcurrentHashMap<>(); public static List<SootClass> IntermediateAppClasses = new CopyOnWriteArrayList<>(); static List<Transformer> jbcotransforms = new CopyOnWriteArrayList<>(); static String[][] optionStrings = new String[][] { { "Rename Classes", "Rename Methods", "Rename Fields", "Build API Buffer Methods", "Build Library Buffer Classes", "Goto Instruction Augmentation", "Add Dead Switche Statements", "Convert Arith. Expr. To Bitshifting Ops", "Convert Branches to JSR Instructions", "Disobey Constructor Conventions", "Reuse Duplicate Sequences", "Replace If(Non)Nulls with Try-Catch", "Indirect If Instructions", "Pack Locals into Bitfields", "Reorder Loads Above Ifs", "Combine Try and Catch Blocks", "Embed Constants in Fields", "Partially Trap Switches" }, { "wjtp.jbco_cr", "wjtp.jbco_mr", "wjtp.jbco_fr", "wjtp.jbco_blbc", "wjtp.jbco_bapibm", "jtp.jbco_gia", "jtp.jbco_adss", "jtp.jbco_cae2bo", "bb.jbco_cb2ji", "bb.jbco_dcc", "bb.jbco_rds", "bb.jbco_riitcb", "bb.jbco_iii", "bb.jbco_plvb", "bb.jbco_rlaii", "bb.jbco_ctbcb", "bb.jbco_ecvf", "bb.jbco_ptss" } }; public static void main(String[] argv) { int rcount = 0; Vector<String> transformsToAdd = new Vector<String>(); boolean remove[] = new boolean[argv.length]; for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.equals("-jbco:help")) { System.out.println("The Java Bytecode Obfuscator (JBCO)\n\nGeneral Options:"); System.out.println("\t-jbco:help - print this help message."); System.out.println("\t-jbco:verbose - print extra information during obfuscation."); System.out.println("\t-jbco:silent - turn off all output, including summary information."); System.out.println("\t-jbco:metrics - calculate total vertices and edges;\n" + "\t calculate avg. and highest graph degrees."); System.out.println("\t-jbco:debug - turn on extra debugging like\n" + "\t stack height and type verifier.\n\nTransformations ( -t:[W:]<name>[:pattern] )\n" + "\tW - specify obfuscation weight (0-9)\n" + "\t<name> - name of obfuscation (from list below)\n" + "\tpattern - limit to method names matched by pattern\n" + "\t prepend * to pattern if a regex\n"); for (int j = 0; j < optionStrings[0].length; j++) { String line = "\t" + optionStrings[1][j]; int size = 20 - line.length(); while (size-- > 0) { line += " "; } line += "- " + optionStrings[0][j]; System.out.println(line); } System.exit(0); } else if (arg.equals("-jbco:metrics")) { metrics = true; remove[i] = true; rcount++; } // temp dumby arg to printout name of benchmark for output files else if (arg.startsWith("-jbco:name:")) { remove[i] = true; rcount++; } // dumby dumby dumby else if (arg.startsWith("-t:")) { arg = arg.substring(3); int tweight = 9; char cweight = arg.charAt(0); if (cweight >= '0' && cweight <= '9') { try { tweight = Integer.parseInt(arg.substring(0, 1)); } catch (NumberFormatException nfe) { logger.debug("Improperly formated transformation weight: " + argv[i]); System.exit(1); } arg = arg.substring(arg.indexOf(':') + 1); } transformsToAdd.add(arg); transformsToWeights.put(arg, new Integer(tweight)); if (arg.equals("wjtp.jbco_fr")) { FieldRenamer.v().setRenameFields(true); } remove[i] = true; rcount++; } else if (arg.equals("-jbco:verbose")) { jbcoVerbose = true; remove[i] = true; rcount++; } else if (arg.equals("-jbco:silent")) { jbcoSummary = false; jbcoVerbose = false; remove[i] = true; rcount++; } else if (arg.equals("-jbco:debug")) { jbcoDebug = true; remove[i] = true; rcount++; } else if (arg.startsWith("-i") && arg.length() > 4 && arg.charAt(3) == ':' && arg.charAt(2) == 't') { Object o = null; arg = arg.substring(4); int tweight = 9; char cweight = arg.charAt(0); if (cweight >= '0' && cweight <= '9') { try { tweight = Integer.parseInt(arg.substring(0, 1)); } catch (NumberFormatException nfe) { logger.debug("Improperly formatted transformation weight: " + argv[i]); System.exit(1); } if (arg.indexOf(':') < 0) { logger.debug("Illegally Formatted Option: " + argv[i]); System.exit(1); } arg = arg.substring(arg.indexOf(':') + 1); } int index = arg.indexOf(':'); if (index < 0) { logger.debug("Illegally Formatted Option: " + argv[i]); System.exit(1); } String trans = arg.substring(0, index); arg = arg.substring(index + 1, arg.length()); if (arg.startsWith("*")) { arg = arg.substring(1); try { o = java.util.regex.Pattern.compile(arg); } catch (java.util.regex.PatternSyntaxException pse) { logger.debug("Illegal Regular Expression Pattern: " + arg); System.exit(1); } } else { o = arg; } transformsToAdd.add(trans); Map<Object, Integer> htmp = transformsToMethodsToWeights.get(trans); if (htmp == null) { htmp = new HashMap<Object, Integer>(); transformsToMethodsToWeights.put(trans, htmp); } htmp.put(o, new Integer(tweight)); remove[i] = true; rcount++; } else { remove[i] = false; } } if (rcount > 0) { int index = 0; String tmp[] = (String[]) argv.clone(); argv = new String[argv.length - rcount]; for (int i = 0; i < tmp.length; i++) { if (!remove[i]) { argv[index++] = tmp[i]; } } } transformsToAdd.remove("wjtp.jbco_cc"); transformsToAdd.remove("jtp.jbco_jl"); transformsToAdd.remove("bb.jbco_j2bl"); transformsToAdd.remove("bb.jbco_ful"); if (!metrics) { if (transformsToAdd.size() == 0) { logger.debug("No Jbco tasks to complete. Shutting Down..."); System.exit(0); } Pack wjtp = PackManager.v().getPack("wjtp"); Pack jtp = PackManager.v().getPack("jtp"); Pack bb = PackManager.v().getPack("bb"); if (transformsToAdd.contains("jtp.jbco_adss")) { wjtp.add(new Transform("wjtp.jbco_fr", newTransform((Transformer) getTransform("wjtp.jbco_fr")))); if (transformsToAdd.remove("wjtp.jbco_fr")) { FieldRenamer.v().setRenameFields(true); } } if (transformsToAdd.contains("bb.jbco_ecvf")) { wjtp.add(new Transform("wjtp.jbco_cc", newTransform((Transformer) getTransform("wjtp.jbco_cc")))); } String jl = null; for (int i = 0; i < transformsToAdd.size(); i++) { if (transformsToAdd.get(i).startsWith("bb")) { jl = "jtp.jbco_jl"; jtp.add(new Transform(jl, newTransform((Transformer) getTransform(jl)))); bb.insertBefore(new Transform("bb.jbco_j2bl", newTransform((Transformer) getTransform("bb.jbco_j2bl"))), "bb.lso"); bb.insertBefore(new Transform("bb.jbco_ful", newTransform((Transformer) getTransform("bb.jbco_ful"))), "bb.lso"); bb.add(new Transform("bb.jbco_rrps", newTransform((Transformer) getTransform("bb.jbco_rrps")))); break; } } for (int i = 0; i < transformsToAdd.size(); i++) { String tname = transformsToAdd.get(i); IJbcoTransform t = getTransform(tname); Pack p = tname.startsWith("wjtp") ? wjtp : tname.startsWith("jtp") ? jtp : bb; String insertBefore = p == jtp ? jl : p == bb ? "bb.jbco_ful" : null; if (insertBefore != null) { p.insertBefore(new Transform(tname, newTransform((Transformer) t)), insertBefore); } else { p.add(new Transform(tname, newTransform((Transformer) t))); } } for (Iterator<Transform> phases = wjtp.iterator(); phases.hasNext();) { if (((Transform) phases.next()).getPhaseName().indexOf("jbco") > 0) { argv = checkWhole(argv, true); break; } } if (jbcoSummary) { for (int i = 0; i < 3; i++) { Iterator<Transform> phases = i == 0 ? wjtp.iterator() : i == 1 ? jtp.iterator() : bb.iterator(); logger.debug(i == 0 ? "Whole Program Jimple Transformations:" : i == 1 ? "Jimple Method Body Transformations:" : "Baf Method Body Transformations:"); while (phases.hasNext()) { Transform o = (Transform) phases.next(); Transformer t = o.getTransformer(); if (t instanceof IJbcoTransform) { logger.debug("\t" + ((IJbcoTransform) t).getName() + " JBCO"); } else { logger.debug("\t" + o.getPhaseName() + " default"); } } } } bb.add(new Transform("bb.jbco_bln", new BafLineNumberer())); bb.add(new Transform("bb.jbco_lta", soot.tagkit.LineNumberTagAggregator.v())); } else { argv = checkWhole(argv, false); } soot.Main.main(argv); if (jbcoSummary) { logger.debug("\n***** JBCO SUMMARY *****\n"); Iterator<Transformer> tit = jbcotransforms.iterator(); while (tit.hasNext()) { Object o = tit.next(); if (o instanceof IJbcoTransform) { ((IJbcoTransform) o).outputSummary(); } } logger.debug("\n***** END SUMMARY *****\n"); } } private static String[] checkWhole(String argv[], boolean add) { for (int i = 0; i < argv.length; i++) { if (argv[i].equals("-w")) { if (add) { return argv; } else { String tmp[] = new String[argv.length - 1]; if (i == 0) { System.arraycopy(argv, 1, tmp, 0, tmp.length); } else { System.arraycopy(argv, 0, tmp, 0, i); if (i < (argv.length - 1)) { System.arraycopy(argv, i + 1, tmp, i, tmp.length - i); } } return tmp; } } } if (add) { String tmp[] = new String[argv.length + 1]; tmp[0] = "-w"; System.arraycopy(argv, 0, tmp, 1, argv.length); return tmp; } return argv; } private static Transformer newTransform(Transformer t) { jbcotransforms.add(t); return t; } private static IJbcoTransform getTransform(String name) { if (name.startsWith("bb.jbco_rrps")) { return new RemoveRedundantPushStores(); } if (name.startsWith("bb.printout")) { return new BAFPrintout(name, true); } if (name.equals("bb.jbco_j2bl")) { return new Jimple2BafLocalBuilder(); } if (name.equals("jtp.jbco_gia")) { return new GotoInstrumenter(); } if (name.equals("jtp.jbco_cae2bo")) { return new ArithmeticTransformer(); } if (name.equals("wjtp.jbco_cc")) { return new CollectConstants(); } if (name.equals("bb.jbco_ecvf")) { return new UpdateConstantsToFields(); } if (name.equals("bb.jbco_rds")) { return new FindDuplicateSequences(); } if (name.equals("bb.jbco_plvb")) { return new LocalsToBitField(); } if (name.equals("bb.jbco_rlaii")) { return new MoveLoadsAboveIfs(); } if (name.equals("bb.jbco_ptss")) { return new WrapSwitchesInTrys(); } if (name.equals("bb.jbco_iii")) { return new IndirectIfJumpsToCaughtGotos(); } if (name.equals("bb.jbco_ctbcb")) { return new TryCatchCombiner(); } if (name.equals("bb.jbco_cb2ji")) { return new AddJSRs(); } if (name.equals("bb.jbco_riitcb")) { return new IfNullToTryCatch(); } if (name.equals("wjtp.jbco_blbc")) { return new LibraryMethodWrappersBuilder(); } if (name.equals("wjtp.jbco_bapibm")) { return new BuildIntermediateAppClasses(); } if (name.equals("wjtp.jbco_cr")) { return ClassRenamer.v(); } if (name.equals("bb.jbco_ful")) { return new FixUndefinedLocals(); } if (name.equals("wjtp.jbco_fr")) { return FieldRenamer.v(); } if (name.equals("wjtp.jbco_mr")) { return MethodRenamer.v(); } if (name.equals("jtp.jbco_adss")) { return new AddSwitches(); } if (name.equals("jtp.jbco_jl")) { return new CollectJimpleLocals(); } if (name.equals("bb.jbco_dcc")) { return new ConstructorConfuser(); } if (name.equals("bb.jbco_counter")) { return new BAFCounter(); } return null; } private static int getWeight(String phasename) { int weight = 9; Integer intg = transformsToWeights.get(phasename); if (intg != null) { weight = intg.intValue(); } return weight; } public static int getWeight(String phasename, String method) { Map<Object, Integer> htmp = transformsToMethodsToWeights.get(phasename); int result = 10; if (htmp != null) { Iterator<Object> keys = htmp.keySet().iterator(); while (keys.hasNext()) { Integer intg = null; Object o = keys.next(); if (o instanceof java.util.regex.Pattern) { if (((java.util.regex.Pattern) o).matcher(method).matches()) { intg = (Integer) htmp.get(o); } else { intg = 0; } } else if (o instanceof String && method.equals(o)) { intg = (Integer) htmp.get(o); } if (intg != null && intg.intValue() < result) { result = intg.intValue(); } } } if (result > 9 || result < 0) { result = getWeight(phasename); } if (jbcoVerbose) { logger.debug("[" + phasename + "] Processing " + method + " with weight: " + result); } return result; } } /* * //bb.insertBefore(new Transform("bb.printout2", newTransform(new BAFPrintout(true))),"bb.lp"); * * for (int i = 0; i < transformsToAdd.size(); i++) { String t = (String)transformsToAdd.get(i); * * if (t.equals("bb.jbco_j2bl")) bb.insertBefore(new Transform("bb.jbco_j2bl", newTransform(new * Jimple2BafLocalBuilder())),"bb.lp"); else { * * } } //bb.insertBefore(new Transform("bb.jbco_j2bl", newTransform(new Jimple2BafLocalBuilder())),"bb.lp"); // requires * CollecJimpleLocals in jtp pack to run * * //jtp.add(new Transform("jtp.jbco_gia", newTransform(new GotoInstrumenter()))); // seems like this might cause issues - * too obvious? not worth it? * * { // works fine - no problems whatsoever //jtp.add(new Transform("jtp.jbco_cae2bo", newTransform(new * ArithmeticTransformer()))); } * * // these two must come together - THESE ARE _not_ CAUSING PROBLEMS IN TRIPHASE?!?!?! { //wjtp.add(new * Transform("wjtp.jbco_cc", newTransform(new CollectConstants()))); //bb.add(new Transform("bb.jbco_ecvf", newTransform(new * UpdateConstantsToFields()))); } * * // these two must come together { // works fine //bb.insertBefore(new Transform("bb.jbco_rds", newTransform(new * FindDuplicateSequences())),"bb.lp"); * * // THIS HAS BEEN TESTED AND RESULTS REPORTED // this SLOWS performance - not worth it //bb.insertBefore(new * Transform("bb.jbco_plvb", newTransform(new LocalsToBitField())),"bb.lp"); } * * // works fine - having problems with this in TRIPHASE?? bb.insertBefore(new Transform("bb.jbco_rlaii", newTransform(new * MoveLoadsAboveIfs())),"bb.lp"); * * // works fine //bb.insertBefore(new Transform("bb.jbco_ptss", newTransform(new WrapSwitchesInTrys())),"bb.lp"); * * // works fine //bb.insertBefore(new Transform("bb.jbco_iii", newTransform(new IndirectIfJumpsToCaughtGotos())),"bb.lp"); * * // should be LAST CALLED in bb // works fine //bb.insertBefore(new Transform("bb.jbco_ctbcb", newTransform(new * TryCatchCombiner())),"bb.lp"); * * // works fine //bb.insertBefore(new Transform("bb.jbco_cb2ji", newTransform(new AddJSRs())),"bb.lp"); * * //bb.insertBefore(new Transform("bb.jbco_riitcb", newTransform(new IfNullToTryCatch())),"bb.lp"); /////bb.add(new * Transform("bb.jbco_v2s", newTransform(new Virtual2Special()))); // working on it //wjtp.add(new * Transform("wjtp.jbco_c2lco", newTransform(new _ConvertToLeastCommonObject()))); * * // works fine //wjtp.add(new Transform("wjtp.jbco_blbc", newTransform(new LibraryMethodWrappersBuilder()))); * //wjtp.add(new Transform("wjtp.jbco_TEST", new jimpleTester())); * * // works fine //wjtp.add(new Transform("wjtp.jbco_bapibm", newTransform(new BuildIntermediateAppClasses()))); * * // works fine //wjtp.add(new Transform("wjtp.jbco_cr", newTransform(new ClassRenamer()))); * * * //bb.insertBefore(new Transform("bb.jbco_ful", newTransform(new FixUndefinedLocals())),"bb.lp"); * * * // works fine wjtp.add(new Transform("wjtp.jbco_fr", newTransform(new FieldRenamer()))); * * FieldRenamer.rename_fields = true; * * // works fine wjtp.add(new Transform("wjtp.jbco_mr", newTransform(new MethodRenamer()))); * * // jtp.add(new Transform("jtp.jbco_v2s", newTransform(new Virtual2SpecialConverter()))); * * * * bb.insertBefore(new Transform("bb.printout1", newTransform(new BAFPrintout(true))),"bb.lp"); // always call BEFORE * localpacker, else you're in trouble * * jtp.add(new Transform("jtp.jbco_adss", newTransform(new AddSwitches()))); * * //bb.insertBefore(new Transform("bb.printout1", new BAFPrintout(true)),"bb.lp"); * * //bb.add(new Transform("bb.printout", new BAFPrintout(true))); * * //jtp.add(new Transform("jtp.jbco_jl", newTransform(new CollectJimpleLocals()))); // helper transform for B2J Local */
21,580
36.33737
125
java
soot
soot-master/src/main/java/soot/jbco/package-info.java
@Deprecated package soot.jbco; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */
849
33
71
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/AddJSRs.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.PatchingChain; import soot.RefType; import soot.Trap; import soot.Unit; import soot.baf.Baf; import soot.baf.GotoInst; import soot.baf.JSRInst; import soot.baf.LookupSwitchInst; import soot.baf.PopInst; import soot.baf.TableSwitchInst; import soot.baf.TargetArgInst; import soot.jbco.IJbcoTransform; import soot.jbco.util.BodyBuilder; import soot.jbco.util.Rand; /** * @author Michael Batchelder * * Created on 22-Mar-2006 * * This transformer transforms gotos/ifs into JSRS, but not all of them. */ public class AddJSRs extends BodyTransformer implements IJbcoTransform { private static final Logger logger = LoggerFactory.getLogger(AddJSRs.class); int jsrcount = 0; public static String dependancies[] = new String[] { "jtp.jbco_jl", "bb.jbco_cb2ji", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_cb2ji"; public String getName() { return name; } public void outputSummary() { logger.info("{} If/Gotos replaced with JSRs.", jsrcount); } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { int weight = soot.jbco.Main.getWeight(phaseName, b.getMethod().getSignature()); if (weight == 0) { return; } // TODO: introduce switch statement to all pops which never happens? // TODO: introduce if-jsr opaque jumps that never happen? boolean fallsthrough = false; HashMap<Trap, Unit> trapsToHandler = new HashMap<Trap, Unit>(); for (Trap t : b.getTraps()) { trapsToHandler.put(t, t.getHandlerUnit()); } List<Unit> targets = new ArrayList<Unit>(); List<Unit> seenUts = new ArrayList<Unit>(); HashMap<Unit, List<Unit>> switches = new HashMap<Unit, List<Unit>>(); HashMap<Unit, Unit> switchDefs = new HashMap<Unit, Unit>(); HashMap<TargetArgInst, Unit> ignoreJumps = new HashMap<TargetArgInst, Unit>(); PatchingChain<Unit> u = b.getUnits(); Iterator<Unit> it = u.snapshotIterator(); while (it.hasNext()) { Unit unit = it.next(); if (unit instanceof TargetArgInst) { TargetArgInst ti = (TargetArgInst) unit; Unit tu = ti.getTarget(); // test if we've already seen the target - if so, it might be a loop so // let's not slow things down if (Rand.getInt(10) > weight) { ignoreJumps.put(ti, tu); } else if (!targets.contains(tu)) { targets.add(tu); } } if (unit instanceof TableSwitchInst) { TableSwitchInst ts = (TableSwitchInst) unit; switches.put(unit, new ArrayList<Unit>(ts.getTargets())); switchDefs.put(unit, ts.getDefaultTarget()); } else if (unit instanceof LookupSwitchInst) { LookupSwitchInst ls = (LookupSwitchInst) unit; switches.put(unit, new ArrayList<Unit>(ls.getTargets())); switchDefs.put(unit, ls.getDefaultTarget()); } seenUts.add(unit); } it = u.snapshotIterator(); ArrayList<Unit> processedLabels = new ArrayList<Unit>(); HashMap<Unit, JSRInst> builtJsrs = new HashMap<Unit, JSRInst>(); HashMap<Unit, Unit> popsBuilt = new HashMap<Unit, Unit>(); Unit prev = null; while (it.hasNext()) { Unit unit = (Unit) it.next(); // check if prev unit falls through to this unit (non-jump). If so, and // it's ALSO a target // we need to make a jsr from previous unit to this one, to deal with pop. // ignore GOTOs as they will, themselves, become a jsr. if (targets.contains(unit)) { if (fallsthrough) { JSRInst ji = Baf.v().newJSRInst(unit); builtJsrs.put(unit, ji); u.insertAfter(ji, prev); jsrcount++; } PopInst pop = Baf.v().newPopInst(RefType.v()); u.insertBefore(pop, unit); processedLabels.add(unit); popsBuilt.put(pop, unit); } fallsthrough = unit.fallsThrough(); prev = unit; } it = u.snapshotIterator(); while (it.hasNext()) { Unit unit = (Unit) it.next(); if (builtJsrs.containsValue(unit)) { continue; } if (unit instanceof TargetArgInst && !ignoreJumps.containsKey(unit)) { TargetArgInst ti = (TargetArgInst) unit; Unit tu = ti.getTarget(); // if we haven't dealt with a target yet, add the pop inst if (!popsBuilt.containsKey(tu)) { throw new RuntimeException( "It appears a target was found that was not updated with a POP.\n\"This makes no sense,\" " + "said the bug as it flew through the code."); } JSRInst ji = builtJsrs.get(popsBuilt.get(tu)); if (BodyBuilder.isBafIf(unit)) { if (Rand.getInt(10) > weight) { ti.setTarget(popsBuilt.get(tu)); } else if (ji != null) { ti.setTarget(ji); } else { ji = Baf.v().newJSRInst(tu); u.insertAfter(ji, u.getPredOf(tu)); ti.setTarget(ji); builtJsrs.put(popsBuilt.get(tu), ji); jsrcount++; } } else if (unit instanceof GotoInst) { if (ji != null) { if (Rand.getInt(10) < weight) { ((GotoInst) unit).setTarget(ji); } else { ((GotoInst) unit).setTarget(popsBuilt.get(tu)); } } else { ((GotoInst) unit).setTarget(popsBuilt.get(tu)); } } } } for (Trap t : trapsToHandler.keySet()) { t.setHandlerUnit(trapsToHandler.get(t)); } for (TargetArgInst ti : ignoreJumps.keySet()) { if (popsBuilt.containsKey(ti.getTarget())) { ti.setTarget(popsBuilt.get(ti.getTarget())); } } targets.clear(); it = u.snapshotIterator(); while (it.hasNext()) { Unit unit = (Unit) it.next(); if (!(unit instanceof TargetArgInst)) { continue; } Unit targ = ((TargetArgInst) unit).getTarget(); if (!targets.contains(targ)) { targets.add(targ); } } it = popsBuilt.keySet().iterator(); while (it.hasNext()) { Unit pop = (Unit) it.next(); if (!targets.contains(pop)) { u.remove(pop); } } it = switches.keySet().iterator(); while (it.hasNext()) { Unit sw = (Unit) it.next(); List<Unit> targs = switches.get(sw); for (int i = 0; i < targs.size(); i++) { if (Rand.getInt(10) > weight) { continue; } Unit unit = targs.get(i); Unit ji = builtJsrs.get(unit); if (ji != null) { targs.set(i, ji); } } Unit def = switchDefs.get(sw); if (Rand.getInt(10) < weight && builtJsrs.get(def) != null) { def = builtJsrs.get(def); } if (sw instanceof TableSwitchInst) { ((TableSwitchInst) sw).setTargets(targs); ((TableSwitchInst) sw).setDefaultTarget(def); } else if (sw instanceof LookupSwitchInst) { ((LookupSwitchInst) sw).setTargets(targs); ((LookupSwitchInst) sw).setDefaultTarget(def); } } if (debug) { StackTypeHeightCalculator.calculateStackHeights(b); } } }
8,314
29.796296
112
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/BAFCounter.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.Unit; import soot.baf.GotoInst; import soot.baf.JSRInst; import soot.baf.TargetArgInst; import soot.jbco.IJbcoTransform; public class BAFCounter extends BodyTransformer implements IJbcoTransform { static int count = 0; public static String dependancies[] = new String[] { "bb.jbco_counter" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_counter"; public String getName() { return name; } public void outputSummary() { out.println("Count: " + count); } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { for (Unit u : b.getUnits()) { if (u instanceof TargetArgInst && !(u instanceof GotoInst) && !(u instanceof JSRInst)) { count++; } } } }
1,727
26.870968
94
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/BAFPrintout.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Map; import java.util.Stack; import soot.Body; import soot.BodyTransformer; import soot.Local; import soot.Type; import soot.Unit; import soot.jbco.IJbcoTransform; /** * @author Michael Batchelder * * Created on 15-Jun-2006 */ public class BAFPrintout extends BodyTransformer implements IJbcoTransform { public static String name = "bb.printout"; public void outputSummary() { } public String[] getDependencies() { return new String[0]; } public String getName() { return name; } static boolean stack = false; public BAFPrintout() { } public BAFPrintout(String newname, boolean print_stack) { name = newname; stack = print_stack; } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { // if (b.getMethod().getSignature().indexOf("run")<0) return; System.out.println("\n" + b.getMethod().getSignature()); if (stack) { Map<Unit, Stack<Type>> stacks = null; Map<Local, Local> b2j = soot.jbco.Main.methods2Baf2JLocals.get(b.getMethod()); try { if (b2j == null) { stacks = StackTypeHeightCalculator.calculateStackHeights(b); } else { stacks = StackTypeHeightCalculator.calculateStackHeights(b, b2j); } StackTypeHeightCalculator.printStack(b.getUnits(), stacks, true); } catch (Exception exc) { System.out.println("\n**************Exception calculating height " + exc + ", printing plain bytecode now\n\n"); soot.jbco.util.Debugger.printUnits(b, " FINAL"); } } else { soot.jbco.util.Debugger.printUnits(b, " FINAL"); } System.out.println(); } }
2,539
26.912088
120
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/BafLineNumberer.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.List; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.PatchingChain; import soot.Unit; import soot.baf.IdentityInst; import soot.baf.Inst; import soot.jbco.IJbcoTransform; import soot.tagkit.LineNumberTag; import soot.tagkit.Tag; public class BafLineNumberer extends BodyTransformer implements IJbcoTransform { public static String name = "bb.jbco_bln"; public void outputSummary() { } public String[] getDependencies() { return new String[] { name }; } public String getName() { return name; } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { int idx = 0; PatchingChain<Unit> units = b.getUnits(); Iterator<Unit> it = units.iterator(); while (it.hasNext()) { Inst i = (Inst) it.next(); List<Tag> tags = i.getTags(); for (int k = 0; k < tags.size(); k++) { Tag t = (Tag) tags.get(k); if (t instanceof LineNumberTag) { tags.remove(k); break; } } if (i instanceof IdentityInst) { continue; } i.addTag(new LineNumberTag(idx++)); } } }
2,042
26.608108
91
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/ConstructorConfuser.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.Local; import soot.PatchingChain; import soot.RefType; import soot.SootClass; import soot.SootMethodRef; import soot.Type; import soot.Unit; import soot.baf.Baf; import soot.baf.LoadInst; import soot.baf.SpecialInvokeInst; import soot.jbco.IJbcoTransform; import soot.jbco.util.BodyBuilder; import soot.jbco.util.Rand; import soot.jbco.util.ThrowSet; import soot.jimple.NullConstant; public class ConstructorConfuser extends BodyTransformer implements IJbcoTransform { static int count = 0; static int instances[] = new int[4]; public static String dependancies[] = new String[] { "bb.jbco_dcc", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_dcc"; public String getName() { return name; } public void outputSummary() { out.println("Constructor methods have been jumbled: " + count); } @SuppressWarnings("fallthrough") protected void internalTransform(Body b, String phaseName, Map<String, String> options) { if (!b.getMethod().getSubSignature().equals("void <init>()")) { return; } int weight = soot.jbco.Main.getWeight(phaseName, b.getMethod().getSignature()); if (weight == 0) { return; } SootClass origClass = b.getMethod().getDeclaringClass(); SootClass c = origClass; if (c.hasSuperclass()) { c = c.getSuperclass(); } else { c = null; } PatchingChain<Unit> units = b.getUnits(); Iterator<Unit> it = units.snapshotIterator(); Unit prev = null; SpecialInvokeInst sii = null; while (it.hasNext()) { Unit u = (Unit) it.next(); if (u instanceof SpecialInvokeInst) { sii = (SpecialInvokeInst) u; SootMethodRef smr = sii.getMethodRef(); if (c == null || !smr.declaringClass().getName().equals(c.getName()) || !smr.name().equals("<init>")) { sii = null; } else { break; } } prev = u; } if (sii == null) { return; } int lowi = -1, lowest = 99999999, rand = Rand.getInt(4); for (int i = 0; i < instances.length; i++) { if (lowest > instances[i]) { lowest = instances[i]; lowi = i; } } if (instances[rand] > instances[lowi]) { rand = lowi; } boolean done = false; switch (rand) { case 0: if (prev != null && prev instanceof LoadInst && sii.getMethodRef().parameterTypes().size() == 0 && !BodyBuilder.isExceptionCaughtAt(units, sii, b.getTraps().iterator())) { Local bl = ((LoadInst) prev).getLocal(); Map<Local, Local> locals = soot.jbco.Main.methods2Baf2JLocals.get(b.getMethod()); if (locals != null && locals.containsKey(bl)) { Type t = ((Local) locals.get(bl)).getType(); if (t instanceof RefType && ((RefType) t).getSootClass().getName().equals(origClass.getName())) { units.insertBefore(Baf.v().newDup1Inst(RefType.v()), sii); Unit ifinst = Baf.v().newIfNullInst(sii); units.insertBeforeNoRedirect(ifinst, sii); units.insertAfter(Baf.v().newThrowInst(), ifinst); units.insertAfter(Baf.v().newPushInst(NullConstant.v()), ifinst); Unit pop = Baf.v().newPopInst(RefType.v()); units.add(pop); units.add((Unit) prev.clone()); b.getTraps().add(Baf.v().newTrap(ThrowSet.getRandomThrowable(), ifinst, sii, pop)); if (Rand.getInt() % 2 == 0) { pop = (Unit) pop.clone(); units.insertBefore(pop, sii); units.insertBefore(Baf.v().newGotoInst(sii), pop); units.add(Baf.v().newJSRInst(pop)); } else { units.add(Baf.v().newGotoInst(sii)); } done = true; break; } } } case 1: if (!BodyBuilder.isExceptionCaughtAt(units, sii, b.getTraps().iterator())) { Unit handler = Baf.v().newThrowInst(); units.add(handler); b.getTraps().add(Baf.v().newTrap(ThrowSet.getRandomThrowable(), sii, (Unit) units.getSuccOf(sii), handler)); done = true; break; } case 2: if (sii.getMethodRef().parameterTypes().size() == 0 && !BodyBuilder.isExceptionCaughtAt(units, sii, b.getTraps().iterator())) { while (c != null) { if (c.getName().equals("java.lang.Throwable")) { Unit throwThis = Baf.v().newThrowInst(); units.insertBefore(throwThis, sii); b.getTraps().add(Baf.v().newTrap(origClass, throwThis, sii, sii)); done = true; break; } if (c.hasSuperclass()) { c = c.getSuperclass(); } else { c = null; } } } if (done) { break; } case 3: Unit pop = Baf.v().newPopInst(RefType.v()); units.insertBefore(pop, sii); units.insertBeforeNoRedirect(Baf.v().newJSRInst(pop), pop); done = true; break; } if (done) { instances[rand]++; count++; } if (debug) { StackTypeHeightCalculator.calculateStackHeights(b); } } }
6,285
30.273632
118
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/Counter.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Map; import soot.Body; import soot.BodyTransformer; public class Counter extends BodyTransformer { protected void internalTransform(Body b, String phaseName, Map<String, String> options) { // TODO Auto-generated method stub } }
1,104
28.078947
91
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/FindDuplicateSequences.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import soot.Body; import soot.BodyTransformer; import soot.DoubleType; import soot.FloatType; import soot.IntType; import soot.Local; import soot.LongType; import soot.PatchingChain; import soot.PrimType; import soot.RefType; import soot.Trap; import soot.Type; import soot.Unit; import soot.UnitBox; import soot.baf.Baf; import soot.baf.DupInst; import soot.baf.FieldArgInst; import soot.baf.IdentityInst; import soot.baf.IncInst; import soot.baf.InstanceCastInst; import soot.baf.InstanceOfInst; import soot.baf.LoadInst; import soot.baf.MethodArgInst; import soot.baf.NewArrayInst; import soot.baf.NewInst; import soot.baf.NewMultiArrayInst; import soot.baf.NoArgInst; import soot.baf.OpTypeArgInst; import soot.baf.PopInst; import soot.baf.PrimitiveCastInst; import soot.baf.PushInst; import soot.baf.ReturnInst; import soot.baf.SpecialInvokeInst; import soot.baf.StoreInst; import soot.baf.SwapInst; import soot.baf.TargetArgInst; import soot.jbco.IJbcoTransform; import soot.jimple.Constant; import soot.jimple.DoubleConstant; import soot.jimple.FloatConstant; import soot.jimple.IntConstant; import soot.jimple.Jimple; import soot.jimple.LongConstant; import soot.jimple.NullConstant; import soot.jimple.StringConstant; import soot.toolkits.graph.BriefUnitGraph; import soot.util.Chain; /** * @author Michael Batchelder * * Created on 12-May-2006 */ public class FindDuplicateSequences extends BodyTransformer implements IJbcoTransform { int totalcounts[] = new int[512]; public static String dependancies[] = new String[] { "bb.jbco_j2bl", "bb.jbco_rds", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_rds"; public String getName() { return name; } public void outputSummary() { out.println("Duplicate Sequences:"); for (int count = totalcounts.length - 1; count >= 0; count--) { if (totalcounts[count] > 0) { out.println("\t" + count + " total: " + totalcounts[count]); } } } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { int weight = soot.jbco.Main.getWeight(phaseName, b.getMethod().getSignature()); if (weight == 0) { return; } if (output) { out.println("Checking " + b.getMethod().getName() + " for duplicate sequences.."); } List<Unit> illegalUnits = new ArrayList<Unit>(); List<Unit> seenUnits = new ArrayList<Unit>(); List<Unit> workList = new ArrayList<Unit>(); PatchingChain<Unit> units = b.getUnits(); BriefUnitGraph bug = new BriefUnitGraph(b); workList.addAll(bug.getHeads()); while (workList.size() > 0) { Unit u = workList.remove(0); if (seenUnits.contains(u)) { continue; } if (u instanceof NewInst) { RefType t = ((NewInst) u).getBaseType(); List<Unit> tmpWorkList = new ArrayList<Unit>(); tmpWorkList.add(u); while (tmpWorkList.size() > 0) { Unit v = tmpWorkList.remove(0); // horrible approximatin about which init call belongs to which new if (v instanceof SpecialInvokeInst) { SpecialInvokeInst si = (SpecialInvokeInst) v; if (si.getMethodRef().getSignature().indexOf("void <init>") < 0 || si.getMethodRef().declaringClass() != t.getSootClass()) { tmpWorkList.addAll(bug.getSuccsOf(v)); } } else { tmpWorkList.addAll(bug.getSuccsOf(v)); } illegalUnits.add(v); } } seenUnits.add(u); workList.addAll(bug.getSuccsOf(u)); } seenUnits = null; int controlLocalIndex = 0; int longestSeq = (units.size() / 2) - 1; if (longestSeq > 20) { longestSeq = 20; } Local controlLocal = null; Collection<Local> bLocals = b.getLocals(); int counts[] = new int[longestSeq + 1]; // ArrayList protectedUnits = new ArrayList(); Map<Local, Local> bafToJLocals = soot.jbco.Main.methods2Baf2JLocals.get(b.getMethod()); boolean changed = true; Map<Unit, Stack<Type>> stackHeightsBefore = null; for (int count = longestSeq; count > 2; count--) { Unit uArry[] = units.toArray(new Unit[units.size()]); if (uArry.length <= 0) { return; } // int count = uArry.length > 100 ? 4 : uArry.length > 50 ? 3 : 2; List<List<Unit>> candidates = new ArrayList<List<Unit>>(); List<Unit> unitIDs = new ArrayList<Unit>(); if (changed) { stackHeightsBefore = StackTypeHeightCalculator.calculateStackHeights(b, bafToJLocals); bug = StackTypeHeightCalculator.bug; changed = false; } LOOP: for (int i = 0; i < uArry.length; i++) { unitIDs.add(uArry[i]); if (i + count > uArry.length) { continue; } List<Unit> seq = new ArrayList<Unit>(); for (int j = 0; j < count; j++) { Unit u = uArry[i + j]; if (u instanceof IdentityInst || u instanceof ReturnInst || illegalUnits.contains(u)) { break; } // don't allow units within the sequence that have more than one // predecessor that is not _within_ the sequence if (j > 0) { List<Unit> preds = bug.getPredsOf(u); if (preds.size() > 0) { int found = 0; Iterator<Unit> pit = preds.iterator(); while (pit.hasNext()) { Unit p = pit.next(); for (int jj = 0; jj < count; jj++) { if (p == uArry[i + jj]) { found++; break; } } } if (found < preds.size()) { continue LOOP; } } } seq.add(u); } if (seq.size() == count) { if (seq.get(seq.size() - 1).fallsThrough()) { candidates.add(seq); } } } Map<List<Unit>, List<List<Unit>>> selected = new HashMap<List<Unit>, List<List<Unit>>>(); for (int i = 0; i < candidates.size(); i++) { List<Unit> seq = candidates.get(i); List<List<Unit>> matches = new ArrayList<List<Unit>>(); for (int j = 0; j < (uArry.length - count); j++) { if (overlap(uArry, seq, j, count)) { continue; } boolean found = false; for (int k = 0; k < count; k++) { Unit u = seq.get(k); found = false; Unit v = uArry[j + k]; if (!equalUnits(u, v, b) || illegalUnits.contains(v)) { break; } if (k > 0) { List<Unit> preds = bug.getPredsOf(v); if (preds.size() > 0) { int fcount = 0; Iterator<Unit> pit = preds.iterator(); while (pit.hasNext()) { Unit p = pit.next(); for (int jj = 0; jj < count; jj++) { if (p == uArry[j + jj]) { fcount++; break; } } } if (fcount < preds.size()) { break; } } } // No need to calc AFTER stack, since they are equal units if (!stackHeightsBefore.get(u).equals(stackHeightsBefore.get(v))) { break; } found = true; } if (found) { List<Unit> foundSeq = new ArrayList<Unit>(); for (int m = 0; m < count; m++) { foundSeq.add(uArry[j + m]); } matches.add(foundSeq); } } if (matches.size() > 0) { boolean done = false; for (int x = 0; x < seq.size(); x++) { if (!unitIDs.contains(seq.get(x))) { done = true; } else { unitIDs.remove(seq.get(x)); } } if (!done) { matches = cullOverlaps(b, unitIDs, matches); if (matches.size() > 0) { selected.put(seq, matches); } } } } if (selected.size() <= 0) { continue; } Iterator<List<Unit>> keys = selected.keySet().iterator(); while (keys.hasNext()) { List<Unit> key = keys.next(); List<List<Unit>> avalues = selected.get(key); if (avalues.size() < 1 || soot.jbco.util.Rand.getInt(10) <= weight) { continue; } changed = true; controlLocal = Baf.v().newLocal("controlLocalfordups" + controlLocalIndex, IntType.v()); bLocals.add(controlLocal); bafToJLocals.put(controlLocal, Jimple.v().newLocal("controlLocalfordups" + controlLocalIndex++, IntType.v())); counts[key.size()] += avalues.size(); List<Unit> jumps = new ArrayList<Unit>(); Unit first = key.get(0); // protectedUnits.addAll(key); Unit store = Baf.v().newStoreInst(IntType.v(), controlLocal); // protectedUnits.add(store); units.insertBefore(store, first); Unit pushUnit = Baf.v().newPushInst(IntConstant.v(0)); // protectedUnits.add(pushUnit); units.insertBefore(pushUnit, store); int index = 1; Iterator<List<Unit>> values = avalues.iterator(); while (values.hasNext()) { List<Unit> next = values.next(); Unit jump = units.getSuccOf(next.get(next.size() - 1)); // protectedUnits.add(jump); Unit firstt = next.get(0); Unit storet = (Unit) store.clone(); // protectedUnits.add(storet); units.insertBefore(storet, firstt); pushUnit = Baf.v().newPushInst(IntConstant.v(index++)); // protectedUnits.add(pushUnit); units.insertBefore(pushUnit, storet); Unit goUnit = Baf.v().newGotoInst(first); // protectedUnits.add(goUnit); units.insertAfter(goUnit, storet); jumps.add(jump); } Unit insertAfter = key.get(key.size() - 1); // protectedUnits.add(insertAfter); Unit swUnit = Baf.v().newTableSwitchInst(units.getSuccOf(insertAfter), 1, jumps.size(), jumps); // protectedUnits.add(swUnit); units.insertAfter(swUnit, insertAfter); Unit loadUnit = Baf.v().newLoadInst(IntType.v(), controlLocal); // protectedUnits.add(loadUnit); units.insertAfter(loadUnit, insertAfter); values = avalues.iterator(); while (values.hasNext()) { List<Unit> next = values.next(); units.removeAll(next); // protectedUnits.removeAll(next); } } } // end of for loop for duplicate seq of various length boolean dupsExist = false; if (output) { System.out.println("Duplicate Sequences for " + b.getMethod().getName()); } for (int count = longestSeq; count >= 0; count--) { if (counts[count] > 0) { if (output) { out.println(count + " total: " + counts[count]); } dupsExist = true; totalcounts[count] += counts[count]; } } if (!dupsExist) { if (output) { out.println("\tnone"); } } else if (debug) { StackTypeHeightCalculator.calculateStackHeights(b); } } private boolean equalUnits(Object o1, Object o2, Body b) { if (o1.getClass() != o2.getClass()) { return false; } // this is actually handled by the predecessor checks // if units are targets of different jumps then not equal // if (!((Unit)o1).getBoxesPointingToThis().equals( // ((Unit)o2).getBoxesPointingToThis())) // return false; List<Trap> l1 = getTrapsForUnit(o1, b); List<Trap> l2 = getTrapsForUnit(o2, b); if (l1.size() != l2.size()) { return false; } else { for (int i = 0; i < l1.size(); i++) { if (l1.get(i) != l2.get(i)) { return false; } } } if (o1 instanceof NoArgInst) { return true; } /* * if (o1 instanceof IncInst) { IncInst ii = (IncInst)o1; if (ii.getLocal() != ((IncInst)o2).getLocal() || * ii.getConstant() != ((IncInst)o2).getConstant()) return false; return true; } */ if (o1 instanceof TargetArgInst) { // return false; // Maybe shouldn't allow duplicate target units? if (o1 instanceof OpTypeArgInst) { return ((TargetArgInst) o1).getTarget() == ((TargetArgInst) o2).getTarget() && ((OpTypeArgInst) o1).getOpType() == ((OpTypeArgInst) o2).getOpType(); } else { return ((TargetArgInst) o1).getTarget() == ((TargetArgInst) o2).getTarget(); } } if (o1 instanceof OpTypeArgInst) { return ((OpTypeArgInst) o1).getOpType() == ((OpTypeArgInst) o2).getOpType(); } if (o1 instanceof MethodArgInst) { return ((MethodArgInst) o1).getMethod() == ((MethodArgInst) o2).getMethod(); } if (o1 instanceof FieldArgInst) { return ((FieldArgInst) o1).getField() == ((FieldArgInst) o2).getField(); } if (o1 instanceof PrimitiveCastInst) { return ((PrimitiveCastInst) o1).getFromType() == ((PrimitiveCastInst) o2).getFromType() && ((PrimitiveCastInst) o1).getToType() == ((PrimitiveCastInst) o2).getToType(); } if (o1 instanceof DupInst) { return compareDups(o1, o2); } if (o1 instanceof LoadInst) { return ((LoadInst) o1).getLocal() == ((LoadInst) o2).getLocal(); } if (o1 instanceof StoreInst) { return ((StoreInst) o1).getLocal() == ((StoreInst) o2).getLocal(); } if (o1 instanceof PushInst) { return equalConstants(((PushInst) o1).getConstant(), ((PushInst) o2).getConstant()); } if (o1 instanceof IncInst) { if (equalConstants(((IncInst) o1).getConstant(), ((IncInst) o2).getConstant())) { return (((IncInst) o1).getLocal() == ((IncInst) o2).getLocal()); } } if (o1 instanceof InstanceCastInst) { return equalTypes(((InstanceCastInst) o1).getCastType(), ((InstanceCastInst) o2).getCastType()); } if (o1 instanceof InstanceOfInst) { return equalTypes(((InstanceOfInst) o1).getCheckType(), ((InstanceOfInst) o2).getCheckType()); } if (o1 instanceof NewArrayInst) { return equalTypes(((NewArrayInst) o1).getBaseType(), ((NewArrayInst) o2).getBaseType()); } if (o1 instanceof NewInst) { return equalTypes(((NewInst) o1).getBaseType(), ((NewInst) o2).getBaseType()); } if (o1 instanceof NewMultiArrayInst) { return equalTypes(((NewMultiArrayInst) o1).getBaseType(), ((NewMultiArrayInst) o2).getBaseType()) && ((NewMultiArrayInst) o1).getDimensionCount() == ((NewMultiArrayInst) o2).getDimensionCount(); } if (o1 instanceof PopInst) { return ((PopInst) o1).getWordCount() == ((PopInst) o2).getWordCount(); } if (o1 instanceof SwapInst) { return ((SwapInst) o1).getFromType() == ((SwapInst) o2).getFromType() && ((SwapInst) o1).getToType() == ((SwapInst) o2).getToType(); } return false; } private List<Trap> getTrapsForUnit(Object o, Body b) { ArrayList<Trap> list = new ArrayList<Trap>(); Chain<Trap> traps = b.getTraps(); if (traps.size() != 0) { PatchingChain<Unit> units = b.getUnits(); Iterator<Trap> it = traps.iterator(); while (it.hasNext()) { Trap t = it.next(); Iterator<Unit> tit = units.iterator(t.getBeginUnit(), t.getEndUnit()); while (tit.hasNext()) { if (tit.next() == o) { list.add(t); break; } } } } return list; } private boolean overlap(Object units[], List<?> list, int idx, int count) { if (idx < 0 || list == null || list.size() == 0) { return false; } Object first = list.get(0); Object last = list.get(list.size() - 1); for (int i = idx; i < idx + count; i++) { if (i < units.length && (first == units[i] || last == units[i])) { return true; } } return false; } private boolean equalConstants(Constant c1, Constant c2) { Type t = c1.getType(); if (t != c2.getType()) { return false; } if (t instanceof IntType) { return ((IntConstant) c1).value == ((IntConstant) c2).value; } if (t instanceof FloatType) { return ((FloatConstant) c1).value == ((FloatConstant) c2).value; } if (t instanceof LongType) { return ((LongConstant) c1).value == ((LongConstant) c2).value; } if (t instanceof DoubleType) { return ((DoubleConstant) c1).value == ((DoubleConstant) c2).value; } if (c1 instanceof StringConstant && c2 instanceof StringConstant) { return ((StringConstant) c1).value == ((StringConstant) c2).value; } return c1 instanceof NullConstant && c2 instanceof NullConstant; } private boolean compareDups(Object o1, Object o2) { DupInst d1 = (DupInst) o1; DupInst d2 = (DupInst) o2; List<Type> l1 = d1.getOpTypes(); List<Type> l2 = d2.getOpTypes(); for (int k = 0; k < 2; k++) { if (k == 1) { l1 = d1.getUnderTypes(); l2 = d2.getUnderTypes(); } if (l1.size() != l2.size()) { return false; } for (int i = 0; i < l1.size(); i++) { if (l1.get(i) != l2.get(i)) { return false; } } } return true; } private boolean equalTypes(Type t1, Type t2) { if (t1 instanceof RefType) { if (t2 instanceof RefType) { // TODO: more discerning comparison here? RefType rt1 = (RefType) t1; RefType rt2 = (RefType) t2; return rt1.compareTo(rt2) == 0; } return false; } if (t1 instanceof PrimType && t2 instanceof PrimType) { return t1.getClass() == t2.getClass(); } return false; } private static List<List<Unit>> cullOverlaps(Body b, List<Unit> ids, List<List<Unit>> matches) { List<List<Unit>> newMatches = new ArrayList<List<Unit>>(); for (int i = 0; i < matches.size(); i++) { List<Unit> match = matches.get(i); Iterator<Unit> it = match.iterator(); boolean clean = true; while (it.hasNext()) { if (!ids.contains(it.next())) { clean = false; break; } } if (clean) { List<UnitBox> targs = b.getUnitBoxes(true); for (int j = 0; j < targs.size() && clean; j++) { Unit u = targs.get(j).getUnit(); it = match.iterator(); while (it.hasNext()) { if (u == it.next()) { clean = false; break; } } } } if (clean) { it = match.iterator(); while (it.hasNext()) { ids.remove(it.next()); } newMatches.add(match); } } return newMatches; } }
20,073
28.564065
118
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/FixUndefinedLocals.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.ArrayType; import soot.Body; import soot.BodyTransformer; import soot.DoubleType; import soot.FloatType; import soot.IntType; import soot.IntegerType; import soot.Local; import soot.LongType; import soot.PatchingChain; import soot.RefLikeType; import soot.StmtAddressType; import soot.Type; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.baf.Baf; import soot.baf.DoubleWordType; import soot.baf.IdentityInst; import soot.baf.IncInst; import soot.baf.NopInst; import soot.baf.OpTypeArgInst; import soot.baf.PushInst; import soot.baf.WordType; import soot.baf.internal.AbstractOpTypeInst; import soot.jbco.IJbcoTransform; import soot.jimple.DoubleConstant; import soot.jimple.FloatConstant; import soot.jimple.IntConstant; import soot.jimple.LongConstant; import soot.jimple.NullConstant; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.scalar.GuaranteedDefs; /** * @author Michael Batchelder * * Created on 16-Jun-2006 */ public class FixUndefinedLocals extends BodyTransformer implements IJbcoTransform { private int undefined = 0; public static String dependancies[] = new String[] { "bb.jbco_j2bl", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_ful"; public String getName() { return name; } public void outputSummary() { out.println("Undefined Locals fixed with pre-initializers: " + undefined); } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { // deal with locals not defined at all used points int icount = 0; boolean passedIDs = false; Map<Local, Local> bafToJLocals = soot.jbco.Main.methods2Baf2JLocals.get(b.getMethod()); ArrayList<Value> initialized = new ArrayList<Value>(); PatchingChain<Unit> units = b.getUnits(); GuaranteedDefs gd = new GuaranteedDefs(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b)); Iterator<Unit> unitIt = units.snapshotIterator(); Unit after = null; while (unitIt.hasNext()) { Unit u = unitIt.next(); if (!passedIDs && u instanceof IdentityInst) { Value v = ((IdentityInst) u).getLeftOp(); if (v instanceof Local) { initialized.add(v); icount++; } after = u; continue; } passedIDs = true; if (after == null) { after = Baf.v().newNopInst(); units.addFirst(after); } List<?> defs = gd.getGuaranteedDefs(u); Iterator<ValueBox> useIt = u.getUseBoxes().iterator(); while (useIt.hasNext()) { Value v = ((ValueBox) useIt.next()).getValue(); if (!(v instanceof Local) || defs.contains(v) || initialized.contains(v)) { continue; } Type t = null; Local l = (Local) v; Local jl = (Local) bafToJLocals.get(l); if (jl != null) { t = jl.getType(); } else { // We should hopefully never get here. There should be a jimple // local unless it's one of our ControlDups t = l.getType(); if (u instanceof OpTypeArgInst) { OpTypeArgInst ota = (OpTypeArgInst) u; t = ota.getOpType(); } else if (u instanceof AbstractOpTypeInst) { AbstractOpTypeInst ota = (AbstractOpTypeInst) u; t = ota.getOpType(); } else if (u instanceof IncInst) { t = IntType.v(); } if (t instanceof DoubleWordType || t instanceof WordType) { throw new RuntimeException("Shouldn't get here (t is a double or word type: in FixUndefinedLocals)"); } } Unit store = Baf.v().newStoreInst(t, l); units.insertAfter(store, after); // TODO: is this necessary if I fix the other casting issues? if (t instanceof ArrayType) { Unit tmp = Baf.v().newInstanceCastInst(t); units.insertBefore(tmp, store); store = tmp; } ///// Unit pinit = getPushInitializer(l, t); units.insertBefore(pinit, store); /* * if (t instanceof RefType) { SootClass sc = ((RefType)t).getSootClass(); if (sc != null) * units.insertAfter(Baf.v().newInstanceCastInst(t), pinit); } */ initialized.add(l); } } if (after instanceof NopInst) { units.remove(after); } undefined += initialized.size() - icount; } public static PushInst getPushInitializer(Local l, Type t) { if (t instanceof IntegerType) { return Baf.v().newPushInst(IntConstant.v(soot.jbco.util.Rand.getInt())); } else if (t instanceof RefLikeType || t instanceof StmtAddressType) { return Baf.v().newPushInst(NullConstant.v()); } else if (t instanceof LongType) { return Baf.v().newPushInst(LongConstant.v(soot.jbco.util.Rand.getLong())); } else if (t instanceof FloatType) { return Baf.v().newPushInst(FloatConstant.v(soot.jbco.util.Rand.getFloat())); } else if (t instanceof DoubleType) { return Baf.v().newPushInst(DoubleConstant.v(soot.jbco.util.Rand.getDouble())); } return null; } /* * * private Unit findInitializerSpotFor(Value v, Unit u, UnitGraph ug, GuaranteedDefs gd) { List preds = ug.getPredsOf(u); * while (preds.size() == 1) { Unit p = (Unit) preds.get(0); //if (p instanceof IdentityInst) // break; * * u = p; preds = ug.getPredsOf(u); } * * if (preds.size() <= 1) return u; * * ArrayList nodef = new ArrayList(); Iterator pIt = preds.iterator(); while (pIt.hasNext()) { Unit u1 = (Unit) pIt.next(); * if (!gd.getGuaranteedDefs(u1).contains(v)) { nodef.add(u1); } } * * if (nodef.size() == preds.size()) return u; * * if (nodef.size() == 1) return findInitializerSpotFor(v, (Unit) nodef.get(0), ug, gd); * * throw new RuntimeException("Shouldn't Ever Get Here!"); } */ }
6,904
31.41784
125
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/IfNullToTryCatch.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.BooleanType; import soot.G; import soot.PatchingChain; import soot.RefType; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.baf.Baf; import soot.baf.IfNonNullInst; import soot.baf.IfNullInst; import soot.jbco.IJbcoTransform; import soot.jbco.util.BodyBuilder; import soot.jbco.util.Rand; import soot.jimple.NullConstant; /** * @author Michael Batchelder * * Created on 20-Jun-2006 */ public class IfNullToTryCatch extends BodyTransformer implements IJbcoTransform { int count = 0; int totalifs = 0; public static String dependancies[] = new String[] { "bb.jbco_riitcb", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_riitcb"; public String getName() { return name; } public void outputSummary() { out.println("If(Non)Nulls changed to traps: " + count); out.println("Total ifs found: " + totalifs); } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { int weight = soot.jbco.Main.getWeight(phaseName, b.getMethod().getSignature()); if (weight == 0) { return; } SootClass exc = G.v().soot_Scene().getSootClass("java.lang.NullPointerException"); SootClass obj = G.v().soot_Scene().getSootClass("java.lang.Object"); SootMethod toStrg = obj.getMethodByName("toString"); SootMethod eq = obj.getMethodByName("equals"); boolean change = false; PatchingChain<Unit> units = b.getUnits(); Iterator<Unit> uit = units.snapshotIterator(); while (uit.hasNext()) { Unit u = uit.next(); if (BodyBuilder.isBafIf(u)) { totalifs++; } if (u instanceof IfNullInst && Rand.getInt(10) <= weight) { Unit targ = ((IfNullInst) u).getTarget(); Unit succ = units.getSuccOf(u); Unit pop = Baf.v().newPopInst(RefType.v()); Unit popClone = (Unit) pop.clone(); units.insertBefore(pop, targ); Unit gotoTarg = Baf.v().newGotoInst(targ); units.insertBefore(gotoTarg, pop); if (Rand.getInt(2) == 0) { Unit methCall = Baf.v().newVirtualInvokeInst(toStrg.makeRef()); units.insertBefore(methCall, u); if (Rand.getInt(2) == 0) { units.remove(u); units.insertAfter(popClone, methCall); } b.getTraps().add(Baf.v().newTrap(exc, methCall, succ, pop)); } else { Unit throwu = Baf.v().newThrowInst(); units.insertBefore(throwu, u); units.remove(u); units.insertBefore(Baf.v().newPushInst(NullConstant.v()), throwu); Unit ifunit = Baf.v().newIfCmpNeInst(RefType.v(), succ); units.insertBefore(ifunit, throwu); units.insertBefore(Baf.v().newPushInst(NullConstant.v()), throwu); b.getTraps().add(Baf.v().newTrap(exc, throwu, succ, pop)); } count++; change = true; } else if (u instanceof IfNonNullInst && Rand.getInt(10) <= weight) { Unit targ = ((IfNonNullInst) u).getTarget(); Unit methCall = Baf.v().newVirtualInvokeInst(eq.makeRef()); units.insertBefore(methCall, u); units.insertBefore(Baf.v().newPushInst(NullConstant.v()), methCall); if (Rand.getInt(2) == 0) { Unit pop = Baf.v().newPopInst(BooleanType.v()); units.insertBefore(pop, u); Unit gotoTarg = Baf.v().newGotoInst(targ); units.insertBefore(gotoTarg, u); pop = Baf.v().newPopInst(RefType.v()); units.insertAfter(pop, u); units.remove(u); // add first, so it is always checked first in the exception table b.getTraps().addFirst(Baf.v().newTrap(exc, methCall, gotoTarg, pop)); } else { Unit iffalse = Baf.v().newIfEqInst(targ); units.insertBefore(iffalse, u); units.insertBefore(Baf.v().newPushInst(NullConstant.v()), u); Unit pop = Baf.v().newPopInst(RefType.v()); units.insertAfter(pop, u); units.remove(u); // add first, so it is always checked first in the exception table b.getTraps().addFirst(Baf.v().newTrap(exc, methCall, iffalse, pop)); } count++; change = true; } } if (change && debug) { StackTypeHeightCalculator.calculateStackHeights(b); // StackTypeHeightCalculator.printStack(units, StackTypeHeightCalculator.calculateStackHeights(b), true) } } }
5,457
32.078788
110
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/IndirectIfJumpsToCaughtGotos.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Stack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.ByteType; import soot.IntType; import soot.IntegerType; import soot.Local; import soot.PatchingChain; import soot.RefType; import soot.SootField; import soot.SootMethod; import soot.Trap; import soot.Type; import soot.Unit; import soot.baf.Baf; import soot.baf.GotoInst; import soot.baf.IdentityInst; import soot.baf.JSRInst; import soot.baf.TargetArgInst; import soot.baf.ThrowInst; import soot.jbco.IJbcoTransform; import soot.jbco.util.BodyBuilder; import soot.jbco.util.Rand; import soot.jbco.util.ThrowSet; import soot.util.Chain; /** * @author Michael Batchelder * * Created on 2-May-2006 * * This transformer takes a portion of gotos/ifs and moves them into a TRY/CATCH block */ public class IndirectIfJumpsToCaughtGotos extends BodyTransformer implements IJbcoTransform { private static final Logger logger = LoggerFactory.getLogger(IndirectIfJumpsToCaughtGotos.class); int count = 0; public static String dependancies[] = new String[] { "bb.jbco_iii", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_iii"; public String getName() { return name; } public void outputSummary() { out.println("Indirected Ifs through Traps: " + count); } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { int weight = soot.jbco.Main.getWeight(phaseName, b.getMethod().getSignature()); if (weight == 0) { return; } PatchingChain<Unit> units = b.getUnits(); Unit nonTrap = findNonTrappedUnit(units, b.getTraps()); if (nonTrap == null) { Unit last = null; nonTrap = Baf.v().newNopInst(); for (Iterator<Unit> it = units.iterator(); it.hasNext();) { Unit u = (Unit) it.next(); if (u instanceof IdentityInst && ((IdentityInst) u).getLeftOp() instanceof Local) { last = u; continue; } else { if (last != null) { units.insertAfter(nonTrap, last); } else { units.addFirst(nonTrap); } break; } } } Stack<Type> stack = StackTypeHeightCalculator.getAfterStack(b, nonTrap); ArrayList<Unit> addedUnits = new ArrayList<Unit>(); Iterator<Unit> it = units.snapshotIterator(); while (it.hasNext()) { Unit u = (Unit) it.next(); if (isIf(u) && Rand.getInt(10) <= weight) { TargetArgInst ifu = (TargetArgInst) u; Unit newTarg = Baf.v().newGotoInst(ifu.getTarget()); units.add(newTarg); ifu.setTarget(newTarg); addedUnits.add(newTarg); } } if (addedUnits.size() <= 0) { return; } Unit nop = Baf.v().newNopInst(); units.add(nop); ArrayList<Unit> toinsert = new ArrayList<Unit>(); SootField field = null; try { field = soot.jbco.jimpleTransformations.FieldRenamer.v().getRandomOpaques()[Rand.getInt(2)]; } catch (NullPointerException npe) { logger.debug(npe.getMessage(), npe); } if (field != null && Rand.getInt(3) > 0) { toinsert.add(Baf.v().newStaticGetInst(field.makeRef())); if (field.getType() instanceof IntegerType) { toinsert.add(Baf.v().newIfGeInst((Unit) units.getSuccOf(nonTrap))); } else { SootMethod boolInit = ((RefType) field.getType()).getSootClass().getMethod("boolean booleanValue()"); toinsert.add(Baf.v().newVirtualInvokeInst(boolInit.makeRef())); toinsert.add(Baf.v().newIfGeInst((Unit) units.getSuccOf(nonTrap))); } } else { toinsert.add(Baf.v().newPushInst(soot.jimple.IntConstant.v(BodyBuilder.getIntegerNine()))); toinsert.add(Baf.v().newPrimitiveCastInst(IntType.v(), ByteType.v())); toinsert.add(Baf.v().newPushInst(soot.jimple.IntConstant.v(Rand.getInt() % 2 == 0 ? 9 : 3))); toinsert.add(Baf.v().newRemInst(ByteType.v())); /* * toinsert.add(Baf.v().newDup1Inst(ByteType.v())); * toinsert.add(Baf.v().newPrimitiveCastInst(ByteType.v(),IntType.v())); * toinsert.add(Baf.v().newStaticGetInst(sys.getFieldByName("out").makeRef())); * toinsert.add(Baf.v().newSwapInst(IntType.v(),RefType.v())); ArrayList parms = new ArrayList(); * parms.add(IntType.v()); toinsert.add(Baf.v().newVirtualInvokeInst(out.getMethod("println",parms).makeRef())); */ toinsert.add(Baf.v().newIfEqInst((Unit) units.getSuccOf(nonTrap))); } ArrayList<Unit> toinserttry = new ArrayList<Unit>(); while (stack.size() > 0) { toinserttry.add(Baf.v().newPopInst(stack.pop())); } toinserttry.add(Baf.v().newPushInst(soot.jimple.NullConstant.v())); Unit handler = Baf.v().newThrowInst(); int rand = Rand.getInt(toinserttry.size()); while (rand++ < toinserttry.size()) { toinsert.add(toinserttry.get(0)); toinserttry.remove(0); } if (toinserttry.size() > 0) { toinserttry.add(Baf.v().newGotoInst(handler)); toinsert.add(Baf.v().newGotoInst(toinserttry.get(0))); units.insertBefore(toinserttry, nop); } toinsert.add(handler); units.insertAfter(toinsert, nonTrap); b.getTraps().add(Baf.v().newTrap(ThrowSet.getRandomThrowable(), addedUnits.get(0), nop, handler)); count += addedUnits.size(); if (addedUnits.size() > 0 && debug) { StackTypeHeightCalculator.calculateStackHeights(b); // StackTypeHeightCalculator.printStack(units, StackTypeHeightCalculator.calculateStackHeights(b), false); } } private Unit findNonTrappedUnit(PatchingChain<Unit> units, Chain<Trap> traps) { int intrap = 0; ArrayList<Unit> untrapped = new ArrayList<Unit>(); Iterator<Unit> it = units.snapshotIterator(); while (it.hasNext()) { Unit u = it.next(); Iterator<Trap> tit = traps.iterator(); while (tit.hasNext()) { Trap t = tit.next(); if (u == t.getBeginUnit()) { intrap++; } if (u == t.getEndUnit()) { intrap--; } } if (intrap == 0) { untrapped.add(u); } } Unit result = null; if (untrapped.size() > 0) { int count = 0; while (result == null && count < 10) { count++; result = untrapped.get(Rand.getInt(999999) % untrapped.size()); if (!result.fallsThrough() || units.getSuccOf(result) == null || units.getSuccOf(result) instanceof ThrowInst) { result = null; } } } return result; } private boolean isIf(Unit u) { // TODO: will a RET statement be a TargetArgInst? return (u instanceof TargetArgInst) && !(u instanceof GotoInst) && !(u instanceof JSRInst); } }
7,735
31.099585
120
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/Jimple2BafLocalBuilder.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.Local; import soot.jbco.IJbcoTransform; /** * @author Michael Batchelder * * Created on 16-Jun-2006 */ public class Jimple2BafLocalBuilder extends BodyTransformer implements IJbcoTransform { public static String dependancies[] = new String[] { "jtp.jbco_jl", "bb.jbco_j2bl", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_j2bl"; public String getName() { return name; } public void outputSummary() { } private static boolean runOnce = false; protected void internalTransform(Body b, String phaseName, Map<String, String> options) { if (soot.jbco.Main.methods2JLocals.size() == 0) { if (!runOnce) { runOnce = true; out.println("[Jimple2BafLocalBuilder]:: Jimple Local Lists have not been built"); out.println(" Skipping Jimple To Baf Builder\n"); } return; } Collection<Local> bLocals = b.getLocals(); HashMap<Local, Local> bafToJLocals = new HashMap<Local, Local>(); Iterator<Local> jlocIt = soot.jbco.Main.methods2JLocals.get(b.getMethod()).iterator(); while (jlocIt.hasNext()) { Local jl = jlocIt.next(); Iterator<Local> blocIt = bLocals.iterator(); while (blocIt.hasNext()) { Local bl = (Local) blocIt.next(); if (bl.getName().equals(jl.getName())) { bafToJLocals.put(bl, jl); break; } } } soot.jbco.Main.methods2Baf2JLocals.put(b.getMethod(), bafToJLocals); } }
2,556
28.732558
96
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/LocalsToBitField.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.BooleanType; import soot.ByteType; import soot.CharType; import soot.DoubleType; import soot.IntType; import soot.Local; import soot.LongType; import soot.PatchingChain; import soot.PrimType; import soot.ShortType; import soot.Type; import soot.Unit; import soot.Value; import soot.baf.Baf; import soot.baf.IdentityInst; import soot.baf.IncInst; import soot.baf.LoadInst; import soot.baf.StoreInst; import soot.jbco.IJbcoTransform; import soot.jbco.util.Rand; import soot.jimple.IntConstant; import soot.jimple.LongConstant; import soot.jimple.ParameterRef; import soot.util.Chain; public class LocalsToBitField extends BodyTransformer implements IJbcoTransform { int replaced = 0; int locals = 0; public static String dependancies[] = new String[] { "jtp.jbco_jl", "bb.jbco_plvb", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_plvb"; public String getName() { return name; } public void outputSummary() { out.println("Local fields inserted into bitfield: " + replaced); out.println("Original number of locals: " + locals); } @SuppressWarnings("fallthrough") protected void internalTransform(Body b, String phaseName, Map<String, String> options) { int weight = soot.jbco.Main.getWeight(phaseName, b.getMethod().getSignature()); if (weight == 0) { return; } // build mapping of baf locals to jimple locals Chain<Local> bLocals = b.getLocals(); PatchingChain<Unit> u = b.getUnits(); Unit first = null; List<Value> params = new ArrayList<Value>(); Iterator<Unit> uit = u.iterator(); while (uit.hasNext()) { Unit unit = uit.next(); if (unit instanceof IdentityInst) { IdentityInst ii = (IdentityInst) unit; if (ii.getRightOpBox().getValue() instanceof ParameterRef) { Value v = ii.getLeftOp(); if (v instanceof Local) { params.add(v); first = unit; } } } } // build mapping of baf locals to jimple locals Map<Local, Local> bafToJLocals = new HashMap<Local, Local>(); Iterator<Local> jlocIt = soot.jbco.Main.methods2JLocals.get(b.getMethod()).iterator(); while (jlocIt.hasNext()) { Local jl = jlocIt.next(); Iterator<Local> blocIt = bLocals.iterator(); while (blocIt.hasNext()) { Local bl = blocIt.next(); if (bl.getName().equals(jl.getName())) { bafToJLocals.put(bl, jl); break; } } } List<Local> booleans = new ArrayList<Local>(); List<Local> bytes = new ArrayList<Local>(); List<Local> chars = new ArrayList<Local>(); List<Local> ints = new ArrayList<Local>(); Map<Local, Integer> sizes = new HashMap<Local, Integer>(); Iterator<Local> blocs = bLocals.iterator(); while (blocs.hasNext()) { Local bl = blocs.next(); if (params.contains(bl)) { continue; } locals++; Local jlocal = bafToJLocals.get(bl); if (jlocal != null) { Type t = jlocal.getType(); if (t instanceof PrimType && !(t instanceof DoubleType || t instanceof LongType) && Rand.getInt(10) <= weight) { if (t instanceof BooleanType) { booleans.add(bl); sizes.put(bl, 1); } else if (t instanceof ByteType) { bytes.add(bl); sizes.put(bl, 8); } else if (t instanceof CharType) { // || t instanceof ShortType) { chars.add(bl); sizes.put(bl, 16); } else if (t instanceof IntType) { ints.add(bl); sizes.put(bl, 32); } } } } int count = 0; Map<Local, Local> bafToNewLocs = new HashMap<Local, Local>(); int total = booleans.size() + bytes.size() * 8 + chars.size() * 16 + ints.size() * 32; Map<Local, Map<Local, Integer>> newLocs = new HashMap<Local, Map<Local, Integer>>(); while (total >= 32 && booleans.size() + bytes.size() + chars.size() + ints.size() > 2) { Local nloc = Baf.v().newLocal("newDumby" + count++, LongType.v()); // soot.jbco.util.Rand.getInt(2) > 0 ? // DoubleType.v() : LongType.v()); Map<Local, Integer> nlocMap = new HashMap<Local, Integer>(); boolean done = false; int index = 0; while (index < 64 && !done) { int max = 64 - index; max = max > 31 ? 4 : max > 15 ? 3 : max > 7 ? 2 : 1; int rand = Rand.getInt(max); max = index; switch (rand) { case 3: if (ints.size() > 0) { Local l = ints.remove(Rand.getInt(ints.size())); nlocMap.put(l, index); index = index + 32; bafToNewLocs.put(l, nloc); index = getNewIndex(index, ints, chars, bytes, booleans); break; } case 2: if (chars.size() > 0) { Local l = chars.remove(Rand.getInt(chars.size())); nlocMap.put(l, index); index = index + 16; bafToNewLocs.put(l, nloc); index = getNewIndex(index, ints, chars, bytes, booleans); break; } case 1: if (bytes.size() > 0) { Local l = bytes.remove(Rand.getInt(bytes.size())); nlocMap.put(l, index); index = index + 8; bafToNewLocs.put(l, nloc); index = getNewIndex(index, ints, chars, bytes, booleans); break; } case 0: if (booleans.size() > 0) { Local l = booleans.remove(Rand.getInt(booleans.size())); nlocMap.put(l, index++); bafToNewLocs.put(l, nloc); index = getNewIndex(index, ints, chars, bytes, booleans); break; } } // end switch if (max == index) { done = true; } } newLocs.put(nloc, nlocMap); bLocals.add(nloc); if (first != null) { u.insertAfter(Baf.v().newStoreInst(LongType.v(), nloc), first); u.insertAfter(Baf.v().newPushInst(LongConstant.v(0)), first); } else { u.addFirst(Baf.v().newStoreInst(LongType.v(), nloc)); u.addFirst(Baf.v().newPushInst(LongConstant.v(0))); } total = booleans.size() + bytes.size() * 8 + chars.size() * 16 + ints.size() * 32; } if (bafToNewLocs.size() == 0) { return; } Iterator<Unit> it = u.snapshotIterator(); while (it.hasNext()) { Unit unit = it.next(); if (unit instanceof StoreInst) { StoreInst si = (StoreInst) unit; Local bafLoc = si.getLocal(); Local nloc = bafToNewLocs.get(bafLoc); if (nloc != null) { Local jloc = bafToJLocals.get(bafLoc); int index = newLocs.get(nloc).get(bafLoc); int size = sizes.get(bafLoc); long longmask = ~((size == 1 ? 0x1L : size == 8 ? 0xFFL : size == 16 ? 0xFFFFL : 0xFFFFFFFFL) << index); u.insertBefore(Baf.v().newPrimitiveCastInst(jloc.getType(), LongType.v()), unit); if (index > 0) { u.insertBefore(Baf.v().newPushInst(IntConstant.v(index)), unit); u.insertBefore(Baf.v().newShlInst(LongType.v()), unit); } u.insertBefore(Baf.v().newPushInst(LongConstant.v(~longmask)), unit); u.insertBefore(Baf.v().newAndInst(LongType.v()), unit); u.insertBefore(Baf.v().newLoadInst(LongType.v(), nloc), unit); u.insertBefore(Baf.v().newPushInst(LongConstant.v(longmask)), unit); u.insertBefore(Baf.v().newAndInst(LongType.v()), unit); u.insertBefore(Baf.v().newXorInst(LongType.v()), unit); u.insertBefore(Baf.v().newStoreInst(LongType.v(), nloc), unit); u.remove(unit); } } else if (unit instanceof LoadInst) { LoadInst li = (LoadInst) unit; Local bafLoc = li.getLocal(); Local nloc = bafToNewLocs.get(bafLoc); if (nloc != null) { int index = newLocs.get(nloc).get(bafLoc); int size = sizes.get(bafLoc); long longmask = (size == 1 ? 0x1L : size == 8 ? 0xFFL : size == 16 ? 0xFFFFL : 0xFFFFFFFFL) << index; u.insertBefore(Baf.v().newLoadInst(LongType.v(), nloc), unit); u.insertBefore(Baf.v().newPushInst(LongConstant.v(longmask)), unit); u.insertBefore(Baf.v().newAndInst(LongType.v()), unit); if (index > 0) { u.insertBefore(Baf.v().newPushInst(IntConstant.v(index)), unit); u.insertBefore(Baf.v().newShrInst(LongType.v()), unit); } Type origType = bafToJLocals.get(bafLoc).getType(); Type t = getType(origType); u.insertBefore(Baf.v().newPrimitiveCastInst(LongType.v(), t), unit); if (!(origType instanceof IntType) && !(origType instanceof BooleanType)) { u.insertBefore(Baf.v().newPrimitiveCastInst(t, origType), unit); } u.remove(unit); } } else if (unit instanceof IncInst) { IncInst ii = (IncInst) unit; Local bafLoc = ii.getLocal(); Local nloc = bafToNewLocs.get(bafLoc); if (nloc != null) { Type jlocType = getType(bafToJLocals.get(bafLoc).getType()); int index = newLocs.get(nloc).get(bafLoc); int size = sizes.get(bafLoc); long longmask = (size == 1 ? 0x1L : size == 8 ? 0xFFL : size == 16 ? 0xFFFFL : 0xFFFFFFFFL) << index; u.insertBefore(Baf.v().newPushInst(ii.getConstant()), unit); u.insertBefore(Baf.v().newLoadInst(LongType.v(), nloc), unit); u.insertBefore(Baf.v().newPushInst(LongConstant.v(longmask)), unit); u.insertBefore(Baf.v().newAndInst(LongType.v()), unit); if (index > 0) { u.insertBefore(Baf.v().newPushInst(IntConstant.v(index)), unit); u.insertBefore(Baf.v().newShrInst(LongType.v()), unit); } u.insertBefore(Baf.v().newPrimitiveCastInst(LongType.v(), ii.getConstant().getType()), unit); u.insertBefore(Baf.v().newAddInst(ii.getConstant().getType()), unit); u.insertBefore(Baf.v().newPrimitiveCastInst(jlocType, LongType.v()), unit); if (index > 0) { u.insertBefore(Baf.v().newPushInst(IntConstant.v(index)), unit); u.insertBefore(Baf.v().newShlInst(LongType.v()), unit); } longmask = ~longmask; u.insertBefore(Baf.v().newLoadInst(LongType.v(), nloc), unit); u.insertBefore(Baf.v().newPushInst(LongConstant.v(longmask)), unit); u.insertBefore(Baf.v().newAndInst(LongType.v()), unit); u.insertBefore(Baf.v().newXorInst(LongType.v()), unit); u.insertBefore(Baf.v().newStoreInst(LongType.v(), nloc), unit); u.remove(unit); } } } Iterator<Local> localIterator = bLocals.snapshotIterator(); while (localIterator.hasNext()) { Local l = localIterator.next(); if (bafToNewLocs.containsKey(l)) { bLocals.remove(l); replaced++; } } } private Type getType(Type t) { if (t instanceof BooleanType || t instanceof CharType || t instanceof ShortType || t instanceof ByteType) { return IntType.v(); } else { return t; } } private int getNewIndex(int index, List<Local> ints, List<Local> chars, List<Local> bytes, List<Local> booleans) { int max = 0; if (booleans.size() > 0 && index < 63) { max = 64; } else if (bytes.size() > 0 && index < 56) { max = 57; } else if (chars.size() > 0 && index < 48) { max = 49; } else if (ints.size() > 0 && index < 32) { max = 33; } if (max != 0) { int rand = Rand.getInt(4); max = max - index; if (max > rand) { max = rand; } else if (max != 1) { max = Rand.getInt(max); } index += max; } return index; } }
13,076
34.827397
120
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/MoveLoadsAboveIfs.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.DoubleType; import soot.IntType; import soot.Local; import soot.LongType; import soot.PatchingChain; import soot.RefType; import soot.Type; import soot.Unit; import soot.baf.Baf; import soot.baf.IfNonNullInst; import soot.baf.IfNullInst; import soot.baf.OpTypeArgInst; import soot.baf.TargetArgInst; import soot.baf.internal.BLoadInst; import soot.jbco.IJbcoTransform; import soot.jbco.util.Rand; import soot.toolkits.graph.BriefUnitGraph; /** * @author Michael Batchelder * * Created on 31-Mar-2006 */ public class MoveLoadsAboveIfs extends BodyTransformer implements IJbcoTransform { int movedloads = 0; public static String dependancies[] = new String[] { "bb.jbco_rlaii", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_rlaii"; public String getName() { return name; } public void outputSummary() { out.println("Moved Loads Above Ifs: " + movedloads); } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { int weight = soot.jbco.Main.getWeight(phaseName, b.getMethod().getSignature()); if (weight == 0) { return; } BriefUnitGraph bug = new BriefUnitGraph(b); List<Unit> candidates = new ArrayList<Unit>(); List<Unit> visited = new ArrayList<Unit>(); List<Unit> worklist = new ArrayList<Unit>(); worklist.addAll(bug.getHeads()); while (worklist.size() > 0) { Unit u = (Unit) worklist.remove(0); if (visited.contains(u)) { continue; } visited.add(u); List<Unit> succs = bug.getSuccsOf(u); if (u instanceof TargetArgInst) { if (checkCandidate(succs, bug)) { candidates.add(u); } } for (int i = 0; i < succs.size(); i++) { Unit o = succs.get(i); if (!visited.contains(o)) { worklist.add(o); } } } int orig = movedloads; boolean changed = false; PatchingChain<Unit> units = b.getUnits(); for (int i = 0; i < candidates.size(); i++) { Unit u = candidates.get(i); List<Unit> succs = bug.getSuccsOf(u); BLoadInst clone = (BLoadInst) ((BLoadInst) succs.get(0)).clone(); if (u instanceof IfNonNullInst || u instanceof IfNullInst) { if (category(clone.getOpType()) == 2 || Rand.getInt(10) > weight) { continue; } units.insertBefore(clone, u); units.insertBefore(Baf.v().newSwapInst(RefType.v(), clone.getOpType()), u); // units.insertAfter(clone,p); // units.insertAfter(Baf.v().newSwapInst(RefType.v(),clone.getOpType()),clone); } else if (u instanceof OpTypeArgInst) { Type t = ((OpTypeArgInst) u).getOpType(); if (category(t) == 2 || Rand.getInt(10) > weight) { continue; } units.insertBefore(clone, u); Type t2 = clone.getOpType(); Unit dup; if (category(t2) == 2) { dup = Baf.v().newDup2_x2Inst(t2, null, t, t); } else { dup = Baf.v().newDup1_x2Inst(t2, t, t); } units.insertBefore(dup, u); units.insertBefore(Baf.v().newPopInst(t2), u); /* * units.insertAfter(clone,p); Type t2 = clone.getOpType(); Unit dup; if (category(t2)==2) { dup = * Baf.v().newDup2_x2Inst(t2,null,t,t); } else { dup = Baf.v().newDup1_x2Inst(t2,t,t); } * units.insertAfter(dup,clone); units.insertAfter(Baf.v().newPopInst(t2),dup); */ } else { if (category(clone.getOpType()) == 2 || Rand.getInt(10) > weight) { continue; } units.insertBefore(clone, u); units.insertBefore(Baf.v().newSwapInst(IntType.v(), clone.getOpType()), u); // units.insertAfter(clone,p); // units.insertAfter(Baf.v().newSwapInst(IntType.v(),clone.getOpType()),clone); } movedloads++; // remove old loads after the jump for (int j = 0; j < succs.size(); j++) { Unit suc = (Unit) succs.get(j); List<Unit> sucPreds = bug.getPredsOf(suc); if (sucPreds.size() > 1) { if (suc == ((TargetArgInst) u).getTarget()) { ((TargetArgInst) u).setTarget((Unit) bug.getSuccsOf(suc).get(0)); } else { units.insertAfter(Baf.v().newGotoInst((Unit) bug.getSuccsOf(suc).get(0)), u); } } else { units.remove(suc); } } if (i < candidates.size() - 1) { bug = new BriefUnitGraph(b); } changed = true; } if (changed) { if (output) { out.println((movedloads - orig) + " loads moved above ifs in " + b.getMethod().getSignature()); } if (debug) { StackTypeHeightCalculator.calculateStackHeights(b); } } } private boolean checkCandidate(List<Unit> succs, BriefUnitGraph bug) { if (succs.size() < 2) { return false; } Object o = succs.get(0); for (int i = 1; i < succs.size(); i++) { if (succs.get(i).getClass() != o.getClass()) { return false; } } if (o instanceof BLoadInst) { BLoadInst bl = (BLoadInst) o; Local l = bl.getLocal(); for (int i = 1; i < succs.size(); i++) { BLoadInst bld = (BLoadInst) succs.get(i); if (bld.getLocal() != l || bug.getPredsOf(bld).size() > 1) { return false; } } return true; } return false; } private int category(Type t) { return ((t instanceof LongType || t instanceof DoubleType) ? 2 : 1); } }
6,558
27.767544
106
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/RemoveRedundantPushStores.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.Local; import soot.PatchingChain; import soot.Trap; import soot.Unit; import soot.baf.PushInst; import soot.baf.StoreInst; import soot.jbco.IJbcoTransform; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.util.Chain; /** * @author Michael Batchelder * * Created on 16-Jun-2006 */ public class RemoveRedundantPushStores extends BodyTransformer implements IJbcoTransform { public static String dependancies[] = new String[] { "bb.jbco_rrps" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_rrps"; public String getName() { return name; } public void outputSummary() { } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { // removes all redundant load-stores boolean changed = true; PatchingChain<Unit> units = b.getUnits(); while (changed) { changed = false; Unit prevprevprev = null, prevprev = null, prev = null; ExceptionalUnitGraph eug = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b); Iterator<Unit> it = units.snapshotIterator(); while (it.hasNext()) { Unit u = it.next(); if (prev != null && prev instanceof PushInst && u instanceof StoreInst) { if (prevprev != null && prevprev instanceof StoreInst && prevprevprev != null && prevprevprev instanceof PushInst) { Local lprev = ((StoreInst) prevprev).getLocal(); Local l = ((StoreInst) u).getLocal(); if (l == lprev && eug.getSuccsOf(prevprevprev).size() == 1 && eug.getSuccsOf(prevprev).size() == 1) { fixJumps(prevprevprev, prev, b.getTraps()); fixJumps(prevprev, u, b.getTraps()); units.remove(prevprevprev); units.remove(prevprev); changed = true; break; } } } prevprevprev = prevprev; prevprev = prev; prev = u; } } // end while changes have been made } private void fixJumps(Unit from, Unit to, Chain<Trap> t) { from.redirectJumpsToThisTo(to); for (Trap trap : t) { if (trap.getBeginUnit() == from) { trap.setBeginUnit(to); } if (trap.getEndUnit() == from) { trap.setEndUnit(to); } if (trap.getHandlerUnit() == from) { trap.setHandlerUnit(to); } } } }
3,440
30
113
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/StackTypeHeightCalculator.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.DoubleType; import soot.FloatType; import soot.IntType; import soot.IntegerType; import soot.Local; import soot.LongType; import soot.PatchingChain; import soot.RefLikeType; import soot.RefType; import soot.SootMethod; import soot.StmtAddressType; import soot.Trap; import soot.Type; import soot.Unit; import soot.VoidType; import soot.baf.AddInst; import soot.baf.AndInst; import soot.baf.ArrayLengthInst; import soot.baf.ArrayReadInst; import soot.baf.ArrayWriteInst; import soot.baf.BafBody; import soot.baf.CmpInst; import soot.baf.CmpgInst; import soot.baf.CmplInst; import soot.baf.DivInst; import soot.baf.Dup1Inst; import soot.baf.Dup1_x1Inst; import soot.baf.Dup1_x2Inst; import soot.baf.Dup2Inst; import soot.baf.Dup2_x1Inst; import soot.baf.Dup2_x2Inst; import soot.baf.DynamicInvokeInst; import soot.baf.EnterMonitorInst; import soot.baf.ExitMonitorInst; import soot.baf.FieldGetInst; import soot.baf.FieldPutInst; import soot.baf.GotoInst; import soot.baf.IdentityInst; import soot.baf.IfCmpEqInst; import soot.baf.IfCmpGeInst; import soot.baf.IfCmpGtInst; import soot.baf.IfCmpLeInst; import soot.baf.IfCmpLtInst; import soot.baf.IfCmpNeInst; import soot.baf.IfEqInst; import soot.baf.IfGeInst; import soot.baf.IfGtInst; import soot.baf.IfLeInst; import soot.baf.IfLtInst; import soot.baf.IfNeInst; import soot.baf.IfNonNullInst; import soot.baf.IfNullInst; import soot.baf.IncInst; import soot.baf.Inst; import soot.baf.InstSwitch; import soot.baf.InstanceCastInst; import soot.baf.InstanceOfInst; import soot.baf.InterfaceInvokeInst; import soot.baf.JSRInst; import soot.baf.LoadInst; import soot.baf.LookupSwitchInst; import soot.baf.MethodArgInst; import soot.baf.MulInst; import soot.baf.NegInst; import soot.baf.NewArrayInst; import soot.baf.NewInst; import soot.baf.NewMultiArrayInst; import soot.baf.NopInst; import soot.baf.OpTypeArgInst; import soot.baf.OrInst; import soot.baf.PopInst; import soot.baf.PrimitiveCastInst; import soot.baf.PushInst; import soot.baf.RemInst; import soot.baf.ReturnInst; import soot.baf.ReturnVoidInst; import soot.baf.ShlInst; import soot.baf.ShrInst; import soot.baf.SpecialInvokeInst; import soot.baf.StaticGetInst; import soot.baf.StaticInvokeInst; import soot.baf.StaticPutInst; import soot.baf.StoreInst; import soot.baf.SubInst; import soot.baf.SwapInst; import soot.baf.TableSwitchInst; import soot.baf.TargetArgInst; import soot.baf.ThrowInst; import soot.baf.UshrInst; import soot.baf.VirtualInvokeInst; import soot.baf.XorInst; import soot.baf.internal.AbstractOpTypeInst; import soot.toolkits.graph.BriefUnitGraph; import soot.util.Chain; /** * @author Michael Batchelder * * Created on 3-May-2006 */ public class StackTypeHeightCalculator { private static final Logger logger = LoggerFactory.getLogger(StackTypeHeightCalculator.class); protected class StackEffectSwitch implements InstSwitch { public boolean shouldThrow = true; public Map<Local, Local> bafToJLocals = null; public Type remove_types[] = null; public Type add_types[] = null; public void caseReturnInst(ReturnInst i) { remove_types = new Type[] { i.getOpType() }; add_types = null; } public void caseReturnVoidInst(ReturnVoidInst i) { remove_types = null; add_types = null; } public void caseNopInst(NopInst i) { remove_types = null; add_types = null; } public void caseGotoInst(GotoInst i) { remove_types = null; add_types = null; } public void caseJSRInst(JSRInst i) { remove_types = null; // add_types=new Type[]{RefType.v()}; add_types = new Type[] { StmtAddressType.v() }; } public void casePushInst(PushInst i) { remove_types = null; add_types = new Type[] { i.getConstant().getType() }; } public void casePopInst(PopInst i) { remove_types = new Type[] { ((soot.baf.internal.BPopInst) i).getType() }; add_types = null; } public void caseIdentityInst(IdentityInst i) { remove_types = null; add_types = null; } public void caseStoreInst(StoreInst i) { remove_types = new Type[] { ((AbstractOpTypeInst) i).getOpType() }; add_types = null; } public void caseLoadInst(LoadInst i) { remove_types = null; add_types = null; if (bafToJLocals != null) { Local jl = (Local) bafToJLocals.get(i.getLocal()); if (jl != null) { add_types = new Type[] { jl.getType() }; } } if (add_types == null) { add_types = new Type[] { i.getOpType() }; } } public void caseArrayWriteInst(ArrayWriteInst i) { // RefType replaces the arraytype remove_types = new Type[] { RefType.v(), IntType.v(), i.getOpType() }; add_types = null; } public void caseArrayReadInst(ArrayReadInst i) { remove_types = new Type[] { RefType.v(), IntType.v() }; add_types = new Type[] { i.getOpType() }; } public void caseIfNullInst(IfNullInst i) { remove_types = new Type[] { RefType.v("java.lang.Object") }; add_types = null; } public void caseIfNonNullInst(IfNonNullInst i) { remove_types = new Type[] { RefType.v("java.lang.Object") }; add_types = null; } public void caseIfEqInst(IfEqInst i) { remove_types = new Type[] { IntType.v() }; add_types = null; } public void caseIfNeInst(IfNeInst i) { remove_types = new Type[] { IntType.v() }; add_types = null; } public void caseIfGtInst(IfGtInst i) { remove_types = new Type[] { IntType.v() }; add_types = null; } public void caseIfGeInst(IfGeInst i) { remove_types = new Type[] { IntType.v() }; add_types = null; } public void caseIfLtInst(IfLtInst i) { remove_types = new Type[] { IntType.v() }; add_types = null; } public void caseIfLeInst(IfLeInst i) { remove_types = new Type[] { IntType.v() }; add_types = null; } public void caseIfCmpEqInst(IfCmpEqInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = null; } public void caseIfCmpNeInst(IfCmpNeInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = null; } public void caseIfCmpGtInst(IfCmpGtInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = null; } public void caseIfCmpGeInst(IfCmpGeInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = null; } public void caseIfCmpLtInst(IfCmpLtInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = null; } public void caseIfCmpLeInst(IfCmpLeInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = null; } public void caseStaticGetInst(StaticGetInst i) { remove_types = null; add_types = new Type[] { i.getField().getType() }; } public void caseStaticPutInst(StaticPutInst i) { remove_types = new Type[] { i.getField().getType() }; add_types = null; } public void caseFieldGetInst(FieldGetInst i) { remove_types = new Type[] { i.getField().getDeclaringClass().getType() }; add_types = new Type[] { i.getField().getType() }; } public void caseFieldPutInst(FieldPutInst i) { remove_types = new Type[] { i.getField().getDeclaringClass().getType(), i.getField().getType() }; add_types = null; } public void caseInstanceCastInst(InstanceCastInst i) { remove_types = new Type[] { RefType.v("java.lang.Object") }; add_types = new Type[] { i.getCastType() }; } public void caseInstanceOfInst(InstanceOfInst i) { remove_types = new Type[] { RefType.v("java.lang.Object") }; add_types = new Type[] { IntType.v() }; } public void casePrimitiveCastInst(PrimitiveCastInst i) { remove_types = new Type[] { i.getFromType() }; add_types = new Type[] { i.getToType() }; } public void caseDynamicInvokeInst(DynamicInvokeInst i) { SootMethod m = i.getMethod(); Object args[] = m.getParameterTypes().toArray(); remove_types = new Type[args.length]; for (int ii = 0; ii < args.length; ii++) { remove_types[ii] = (Type) args[ii]; } if (m.getReturnType() instanceof VoidType) { add_types = null; } else { add_types = new Type[] { m.getReturnType() }; } } public void caseStaticInvokeInst(StaticInvokeInst i) { SootMethod m = i.getMethod(); Object args[] = m.getParameterTypes().toArray(); remove_types = new Type[args.length]; for (int ii = 0; ii < args.length; ii++) { remove_types[ii] = (Type) args[ii]; } if (m.getReturnType() instanceof VoidType) { add_types = null; } else { add_types = new Type[] { m.getReturnType() }; } } private void instanceinvoke(MethodArgInst i) { SootMethod m = i.getMethod(); int length = m.getParameterCount(); remove_types = new Type[length + 1]; remove_types[0] = RefType.v(); System.arraycopy(m.getParameterTypes().toArray(), 0, remove_types, 1, length); if (m.getReturnType() instanceof VoidType) { add_types = null; } else { add_types = new Type[] { m.getReturnType() }; } } public void caseVirtualInvokeInst(VirtualInvokeInst i) { instanceinvoke(i); } public void caseInterfaceInvokeInst(InterfaceInvokeInst i) { instanceinvoke(i); } public void caseSpecialInvokeInst(SpecialInvokeInst i) { instanceinvoke(i); } public void caseThrowInst(ThrowInst i) { remove_types = new Type[] { RefType.v("java.lang.Throwable") }; add_types = null; } public void caseAddInst(AddInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { i.getOpType() }; } private void bitOps(OpTypeArgInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { i.getOpType() }; } public void caseAndInst(AndInst i) { bitOps(i); } public void caseOrInst(OrInst i) { bitOps(i); } public void caseXorInst(XorInst i) { bitOps(i); } public void caseArrayLengthInst(ArrayLengthInst i) { remove_types = new Type[] { RefType.v() }; add_types = new Type[] { IntType.v() }; } public void caseCmpInst(CmpInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { IntType.v() }; } public void caseCmpgInst(CmpgInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { IntType.v() }; } public void caseCmplInst(CmplInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { IntType.v() }; } public void caseDivInst(DivInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { i.getOpType() }; } public void caseIncInst(IncInst i) { remove_types = null; add_types = null; } public void caseMulInst(MulInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { i.getOpType() }; } public void caseRemInst(RemInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { i.getOpType() }; } public void caseSubInst(SubInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { i.getOpType() }; } public void caseShlInst(ShlInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { i.getOpType() }; } public void caseShrInst(ShrInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { i.getOpType() }; } public void caseUshrInst(UshrInst i) { remove_types = new Type[] { i.getOpType(), i.getOpType() }; add_types = new Type[] { i.getOpType() }; } public void caseNewInst(NewInst i) { remove_types = null; add_types = new Type[] { i.getBaseType() }; } public void caseNegInst(NegInst i) { remove_types = null; add_types = null; } public void caseSwapInst(SwapInst i) { remove_types = new Type[] { i.getFromType(), i.getToType() }; add_types = new Type[] { i.getToType(), i.getFromType() }; } public void caseDup1Inst(Dup1Inst i) { remove_types = new Type[] { i.getOp1Type() }; add_types = new Type[] { i.getOp1Type(), i.getOp1Type() }; } public void caseDup2Inst(Dup2Inst i) { if (!(i.getOp1Type() instanceof DoubleType || i.getOp1Type() instanceof LongType)) { add_types = new Type[] { i.getOp2Type(), i.getOp1Type() }; remove_types = null; } else { add_types = new Type[] { i.getOp1Type() }; remove_types = null; } } public void caseDup1_x1Inst(Dup1_x1Inst i) { remove_types = new Type[] { i.getUnder1Type(), i.getOp1Type() }; add_types = new Type[] { i.getOp1Type(), i.getUnder1Type(), i.getOp1Type() }; } public void caseDup1_x2Inst(Dup1_x2Inst i) { Type u1 = i.getUnder1Type(); if (u1 instanceof DoubleType || u1 instanceof LongType) { remove_types = new Type[] { u1, i.getOp1Type() }; add_types = new Type[] { i.getOp1Type(), u1, i.getOp1Type() }; } else { remove_types = new Type[] { i.getUnder2Type(), u1, i.getOp1Type() }; add_types = new Type[] { i.getOp1Type(), i.getUnder2Type(), u1, i.getOp1Type() }; } } public void caseDup2_x1Inst(Dup2_x1Inst i) { Type ot = i.getOp1Type(); if (ot instanceof DoubleType || ot instanceof LongType) { remove_types = new Type[] { i.getUnder1Type(), ot }; add_types = new Type[] { ot, i.getUnder1Type(), ot }; } else { remove_types = new Type[] { i.getUnder1Type(), i.getOp2Type(), ot }; add_types = new Type[] { i.getOp2Type(), ot, i.getUnder1Type(), i.getOp2Type(), ot }; } } public void caseDup2_x2Inst(Dup2_x2Inst i) { Type u1 = i.getUnder1Type(); Type o1 = i.getOp1Type(); if (u1 instanceof DoubleType || u1 instanceof LongType) { if (o1 instanceof DoubleType || o1 instanceof LongType) { remove_types = new Type[] { u1, o1 }; add_types = new Type[] { o1, u1, o1 }; } else { remove_types = new Type[] { u1, i.getOp2Type(), o1 }; add_types = new Type[] { i.getOp2Type(), o1, u1, i.getOp2Type(), o1 }; } } else if (o1 instanceof DoubleType || o1 instanceof LongType) { remove_types = new Type[] { i.getUnder2Type(), u1, o1 }; add_types = new Type[] { o1, i.getUnder2Type(), u1, o1 }; } else { remove_types = new Type[] { i.getUnder2Type(), u1, i.getOp2Type(), o1 }; add_types = new Type[] { i.getOp2Type(), o1, i.getUnder2Type(), u1, i.getOp2Type(), o1 }; } } public void caseNewArrayInst(NewArrayInst i) { remove_types = new Type[] { IntType.v() }; add_types = new Type[] { RefType.v() }; } public void caseNewMultiArrayInst(NewMultiArrayInst i) { remove_types = new Type[i.getDimensionCount()]; for (int ii = 0; ii < remove_types.length; ii++) { remove_types[ii] = IntType.v(); } add_types = new Type[] { RefType.v() }; } public void caseLookupSwitchInst(LookupSwitchInst i) { remove_types = new Type[] { IntType.v() }; add_types = null; } public void caseTableSwitchInst(TableSwitchInst i) { remove_types = new Type[] { IntType.v() }; add_types = null; } public void caseEnterMonitorInst(EnterMonitorInst i) { remove_types = new Type[] { RefType.v("java.lang.Object") }; add_types = null; } public void caseExitMonitorInst(ExitMonitorInst i) { remove_types = new Type[] { RefType.v("java.lang.Object") }; add_types = null; } } public static StackEffectSwitch sw = new StackTypeHeightCalculator().new StackEffectSwitch(); public static BriefUnitGraph bug = null; public static Map<Unit, Stack<Type>> calculateStackHeights(Body b, Map<Local, Local> b2JLocs) { sw.bafToJLocals = b2JLocs; return calculateStackHeights(b, true); } public static Map<Unit, Stack<Type>> calculateStackHeights(Body b) { sw.bafToJLocals = null; return calculateStackHeights(b, false); } public static Map<Unit, Stack<Type>> calculateStackHeights(Body b, boolean jimpleLocals) { if (!(b instanceof BafBody)) { throw new java.lang.RuntimeException("Expecting Baf Body"); // System.out.println("\n"+b.getMethod().getName()); } Map<Unit, Stack<Type>> results = new HashMap<Unit, Stack<Type>>(); bug = new BriefUnitGraph(b); List<Unit> heads = bug.getHeads(); for (int i = 0; i < heads.size(); i++) { Unit h = heads.get(i); RefType handlerExc = isHandlerUnit(b.getTraps(), h); Stack<Type> stack = (Stack<Type>) results.get(h); if (stack != null) { if (stack.size() != (handlerExc != null ? 1 : 0)) { throw new java.lang.RuntimeException("Problem with stack height - head expects ZERO or one if handler"); } continue; } List<Unit> worklist = new ArrayList<Unit>(); stack = new Stack<Type>(); if (handlerExc != null) { stack.push(handlerExc); } results.put(h, stack); worklist.add(h); while (!worklist.isEmpty()) { Inst inst = (Inst) worklist.remove(0); inst.apply(sw); stack = updateStack(sw, (Stack<Type>) results.get(inst)); Iterator<Unit> lit = bug.getSuccsOf(inst).iterator(); while (lit.hasNext()) { Unit next = lit.next(); Stack<Type> nxtStck = results.get(next); if (nxtStck != null) { if (nxtStck.size() != stack.size()) { printStack(b.getUnits(), results, false); throw new java.lang.RuntimeException( "Problem with stack height at: " + next + "\n\rHas Stack " + nxtStck + " but is expecting " + stack); } continue; } results.put(next, stack); worklist.add(next); } } } return results; } public static Stack<Type> updateStack(Unit u, Stack<Type> st) { u.apply(sw); return updateStack(sw, st); } public static Stack<Type> updateStack(StackEffectSwitch sw, Stack<Type> st) { @SuppressWarnings("unchecked") Stack<Type> clone = (Stack<Type>) st.clone(); if (sw.remove_types != null) { if (sw.remove_types.length > clone.size()) { String exc = "Expecting values on stack: "; for (Type element : sw.remove_types) { String type = element.toString(); if (type.trim().length() == 0) { type = element instanceof RefLikeType ? "L" : "U"; } exc += type + " "; } exc += "\n\tbut only found: "; for (int i = 0; i < clone.size(); i++) { String type = clone.get(i).toString(); if (type.trim().length() == 0) { type = clone.get(i) instanceof RefLikeType ? "L" : "U"; } exc += type + " "; } if (sw.shouldThrow) { throw new RuntimeException(exc); } else { logger.debug("" + exc); } } for (int i = sw.remove_types.length - 1; i >= 0; i--) { try { Type t = clone.pop(); if (!checkTypes(t, sw.remove_types[i])) { // System.out.println("Incompatible types: " + t + " : "+sw.remove_types[i]); } } catch (Exception exc) { return null; } } } if (sw.add_types != null) { for (Type element : sw.add_types) { clone.push(element); } } return clone; } private static boolean checkTypes(Type t1, Type t2) { if (t1 == t2) { return true; } if (t1 instanceof RefLikeType && t2 instanceof RefLikeType) { return true; } if (t1 instanceof IntegerType && t2 instanceof IntegerType) { return true; } if (t1 instanceof LongType && t2 instanceof LongType) { return true; } if (t1 instanceof DoubleType && t2 instanceof DoubleType) { return true; } if (t1 instanceof FloatType && t2 instanceof FloatType) { return true; } return false; } public static void printStack(PatchingChain<Unit> units, Map<Unit, Stack<Type>> stacks, boolean before) { int count = 0; sw.shouldThrow = false; Map<Unit, Integer> indexes = new HashMap<Unit, Integer>(); Iterator<Unit> it = units.snapshotIterator(); while (it.hasNext()) { indexes.put(it.next(), new Integer(count++)); } it = units.snapshotIterator(); while (it.hasNext()) { String s = ""; Unit unit = it.next(); if (unit instanceof TargetArgInst) { Object t = ((TargetArgInst) unit).getTarget(); s = indexes.get(t).toString(); } else if (unit instanceof TableSwitchInst) { TableSwitchInst tswi = (TableSwitchInst) unit; s += "\r\tdefault: " + tswi.getDefaultTarget() + " " + indexes.get(tswi.getDefaultTarget()); int index = 0; for (int x = tswi.getLowIndex(); x <= tswi.getHighIndex(); x++) { s += "\r\t " + x + ": " + tswi.getTarget(index) + " " + indexes.get(tswi.getTarget(index++)); } } try { s = indexes.get(unit) + " " + unit + " " + s + " ["; } catch (Exception e) { logger.debug("Error in StackTypeHeightCalculator trying to find index of unit"); } Stack<Type> stack = stacks.get(unit); if (stack != null) { if (!before) { ((Unit) unit).apply(sw); stack = updateStack(sw, stack); if (stack == null) { soot.jbco.util.Debugger.printUnits(units, " StackTypeHeightCalc failed"); sw.shouldThrow = true; return; } } for (int i = 0; i < stack.size(); i++) { s += printType(stack.get(i)); } } else { s += "***missing***"; } System.out.println(s + "]"); } sw.shouldThrow = true; } private static String printType(Type t) { if (t instanceof IntegerType) { return "I"; } else if (t instanceof FloatType) { return "F"; } else if (t instanceof DoubleType) { return "D"; } else if (t instanceof LongType) { return "J"; } else if (t instanceof RefLikeType) { // if (t instanceof RefType && ((RefType)t).getSootClass() != null) // return "L(" + ((RefType)t).getSootClass().getName()+")"; // else return "L" + t.toString(); } else { return "U(" + t.getClass().toString() + ")"; } } private static RefType isHandlerUnit(Chain<Trap> traps, Unit h) { Iterator<Trap> it = traps.iterator(); while (it.hasNext()) { Trap t = (Trap) it.next(); if (t.getHandlerUnit() == h) { return t.getException().getType(); } } return null; } public static Stack<Type> getAfterStack(Body b, Unit u) { Stack<Type> stack = calculateStackHeights(b).get(u); u.apply(sw); return updateStack(sw, stack); } public static Stack<Type> getAfterStack(Stack<Type> beforeStack, Unit u) { u.apply(sw); return updateStack(sw, beforeStack); } }
24,881
29.16
119
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/TryCatchCombiner.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.BooleanType; import soot.IntType; import soot.Local; import soot.PatchingChain; import soot.RefType; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.StmtAddressType; import soot.Trap; import soot.Type; import soot.Unit; import soot.baf.Baf; import soot.baf.GotoInst; import soot.baf.IdentityInst; import soot.baf.JSRInst; import soot.baf.TargetArgInst; import soot.jbco.IJbcoTransform; import soot.jbco.jimpleTransformations.FieldRenamer; import soot.jbco.util.Rand; import soot.jimple.IntConstant; import soot.jimple.NullConstant; import soot.toolkits.graph.BriefUnitGraph; public class TryCatchCombiner extends BodyTransformer implements IJbcoTransform { private static final Logger logger = LoggerFactory.getLogger(TryCatchCombiner.class); int totalcount = 0; int changedcount = 0; public static String dependancies[] = new String[] { "bb.jbco_j2bl", "bb.jbco_ctbcb", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_ctbcb"; public String getName() { return name; } public void outputSummary() { out.println("Total try blocks found: " + totalcount); out.println("Combined TryCatches: " + changedcount); } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { int weight = soot.jbco.Main.getWeight(phaseName, b.getMethod().getSignature()); if (weight == 0) { return; } int trapCount = 0; PatchingChain<Unit> units = b.getUnits(); ArrayList<Unit> headList = new ArrayList<Unit>(); ArrayList<Trap> trapList = new ArrayList<Trap>(); Iterator<Trap> traps = b.getTraps().iterator(); // build list of heads and corresponding traps while (traps.hasNext()) { Trap t = traps.next(); totalcount++; // skip runtime exceptions if (!isRewritable(t)) { continue; } headList.add(t.getBeginUnit()); trapList.add(t); trapCount++; } if (trapCount == 0) { return; } // check if any traps have same head, if so insert dumby NOP to disambiguate for (int i = 0; i < headList.size(); i++) { for (int j = 0; j < headList.size(); j++) { if (i == j) { continue; } if (headList.get(i) == headList.get(j)) { Trap t = trapList.get(i); Unit nop = Baf.v().newNopInst(); units.insertBeforeNoRedirect(nop, headList.get(i)); headList.set(i, nop); t.setBeginUnit(nop); } } } Unit first = null; Iterator<Unit> uit = units.iterator(); while (uit.hasNext()) { Unit unit = (Unit) uit.next(); if (!(unit instanceof IdentityInst)) { break; } first = unit; } if (first == null) { first = Baf.v().newNopInst(); units.insertBefore(first, units.getFirst()); } else { first = (Unit) units.getSuccOf(first); } Collection<Local> locs = b.getLocals(); Map<Unit, Stack<Type>> stackHeightsBefore = null; Map<Local, Local> bafToJLocals = soot.jbco.Main.methods2Baf2JLocals.get(b.getMethod()); int varCount = trapCount + 1; traps = b.getTraps().snapshotIterator(); while (traps.hasNext()) { Trap t = traps.next(); Unit begUnit = t.getBeginUnit(); if (!isRewritable(t) || Rand.getInt(10) > weight) { continue; } stackHeightsBefore = StackTypeHeightCalculator.calculateStackHeights(b, bafToJLocals); boolean badType = false; @SuppressWarnings("unchecked") Stack<Type> s = (Stack<Type>) stackHeightsBefore.get(begUnit).clone(); if (s.size() > 0) { for (int i = 0; i < s.size(); i++) { if (s.pop() instanceof StmtAddressType) { badType = true; break; } } } if (badType) { continue; } // local to hold control flow flag (0=try, 1=catch) Local controlLocal = Baf.v().newLocal("controlLocal_tccomb" + trapCount, IntType.v()); locs.add(controlLocal); // initialize local to 0=try Unit pushZero = Baf.v().newPushInst(IntConstant.v(0)); Unit storZero = Baf.v().newStoreInst(IntType.v(), controlLocal); // this is necessary even though it seems like it shouldn't be units.insertBeforeNoRedirect((Unit) pushZero.clone(), first); units.insertBeforeNoRedirect((Unit) storZero.clone(), first); BriefUnitGraph graph = new BriefUnitGraph(b); List<Unit> l = graph.getPredsOf(begUnit); // add initializer seq for try - sets local to zero and loads null exc units.add(pushZero); units.add(storZero); Stack<Local> varsToLoad = new Stack<Local>(); s = stackHeightsBefore.get(begUnit); if (s.size() > 0) { for (int i = 0; i < s.size(); i++) { Type type = s.pop(); Local varLocal = Baf.v().newLocal("varLocal_tccomb" + varCount++, type); locs.add(varLocal); varsToLoad.push(varLocal); units.add(Baf.v().newStoreInst(type, varLocal)); units.insertBeforeNoRedirect(FixUndefinedLocals.getPushInitializer(varLocal, type), first); units.insertBeforeNoRedirect(Baf.v().newStoreInst(type, varLocal), first); } } units.add(Baf.v().newPushInst(NullConstant.v())); units.add(Baf.v().newGotoInst(begUnit)); // for each pred of the beginUnit of the try, we must insert goto initializer for (int i = 0; i < l.size(); i++) { Unit pred = l.get(i); if (isIf(pred)) { TargetArgInst ifPred = ((TargetArgInst) pred); if (ifPred.getTarget() == begUnit) { ifPred.setTarget(pushZero); } Unit succ = units.getSuccOf(ifPred); if (succ == begUnit) { units.insertAfter(Baf.v().newGotoInst(pushZero), ifPred); } } else if (pred instanceof GotoInst && ((GotoInst) pred).getTarget() == begUnit) { ((GotoInst) pred).setTarget(pushZero); } else { units.insertAfter(Baf.v().newGotoInst(pushZero), pred); } } Unit handlerUnit = t.getHandlerUnit(); Unit newBeginUnit = Baf.v().newLoadInst(IntType.v(), controlLocal); units.insertBefore(newBeginUnit, begUnit); units.insertBefore(Baf.v().newIfNeInst(handlerUnit), begUnit); units.insertBefore(Baf.v().newPopInst(RefType.v()), begUnit); while (varsToLoad.size() > 0) { Local varLocal = (Local) varsToLoad.pop(); units.insertBefore(Baf.v().newLoadInst(varLocal.getType(), varLocal), begUnit); } try { SootField f[] = FieldRenamer.v().getRandomOpaques(); if (f[0] != null && f[1] != null) { loadBooleanValue(units, f[0], begUnit); loadBooleanValue(units, f[1], begUnit); units.insertBeforeNoRedirect(Baf.v().newIfCmpEqInst(BooleanType.v(), begUnit), begUnit); } } catch (NullPointerException npe) { logger.debug(npe.getMessage(), npe); } // randomize the increment - sometimes store one, sometimes just set to 1 if (Rand.getInt() % 2 == 0) { units.insertBeforeNoRedirect(Baf.v().newPushInst(IntConstant.v(Rand.getInt(3) + 1)), begUnit); units.insertBeforeNoRedirect(Baf.v().newStoreInst(IntType.v(), controlLocal), begUnit); } else { units.insertBeforeNoRedirect(Baf.v().newIncInst(controlLocal, IntConstant.v(Rand.getInt(3) + 1)), begUnit); } trapCount--; t.setBeginUnit(newBeginUnit); t.setHandlerUnit(newBeginUnit); changedcount++; if (debug) { StackTypeHeightCalculator.printStack(units, StackTypeHeightCalculator.calculateStackHeights(b), false); } } } private void loadBooleanValue(PatchingChain<Unit> units, SootField f, Unit insert) { units.insertBefore(Baf.v().newStaticGetInst(f.makeRef()), insert); if (f.getType() instanceof RefType) { SootMethod boolInit = ((RefType) f.getType()).getSootClass().getMethod("boolean booleanValue()"); units.insertBefore(Baf.v().newVirtualInvokeInst(boolInit.makeRef()), insert); } } private boolean isIf(Unit u) { // TODO: will a RET statement be a TargetArgInst? return (u instanceof TargetArgInst) && !(u instanceof GotoInst) && !(u instanceof JSRInst); } private boolean isRewritable(Trap t) { // ignore traps that already catch their own begin unit if (t.getBeginUnit() == t.getHandlerUnit()) { return false; } // ignore runtime try blocks - these may have weird side-effects do to asynchronous exceptions SootClass exc = t.getException(); if (exc.getName().equals("java.lang.Throwable")) { return false; } do { if (exc.getName().equals("java.lang.RuntimeException")) { return false; } } while (exc.hasSuperclass() && (exc = exc.getSuperclass()) != null); return true; } }
10,108
31.504823
115
java
soot
soot-master/src/main/java/soot/jbco/bafTransformations/UpdateConstantsToFields.java
package soot.jbco.bafTransformations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.PatchingChain; import soot.SootField; import soot.Unit; import soot.baf.Baf; import soot.baf.PushInst; import soot.jbco.IJbcoTransform; import soot.jbco.jimpleTransformations.CollectConstants; import soot.jbco.util.BodyBuilder; import soot.jbco.util.Rand; /** * @author Michael Batchelder * * Created on 31-May-2006 */ public class UpdateConstantsToFields extends BodyTransformer implements IJbcoTransform { public static String dependancies[] = new String[] { "wjtp.jbco_cc", "bb.jbco_ecvf", "bb.jbco_ful", "bb.lp" }; public String[] getDependencies() { return dependancies; } public static String name = "bb.jbco_ecvf"; public String getName() { return name; } static int updated = 0; public void outputSummary() { out.println("Updated constant references: " + updated); } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { if (b.getMethod().getName().indexOf("<clinit>") >= 0) { return; } int weight = soot.jbco.Main.getWeight(phaseName, b.getMethod().getSignature()); if (weight == 0) { return; } PatchingChain<Unit> units = b.getUnits(); Iterator<Unit> iter = units.snapshotIterator(); while (iter.hasNext()) { Unit u = (Unit) iter.next(); if (u instanceof PushInst) { SootField f = CollectConstants.constantsToFields.get(((PushInst) u).getConstant()); if (f != null && Rand.getInt(10) <= weight) { Unit get = Baf.v().newStaticGetInst(f.makeRef()); units.insertBefore(get, u); BodyBuilder.updateTraps(get, u, b.getTraps()); units.remove(u); updated++; } } } } }
2,657
28.208791
112
java