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/dava/internal/AST/ASTAndCondition.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.dava.DavaUnitPrinter;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public class ASTAndCondition extends ASTAggregatedCondition {
public ASTAndCondition(ASTCondition left, ASTCondition right) {
super(left, right);
}
public void apply(Analysis a) {
a.caseASTAndCondition(this);
}
public String toString() {
if (left instanceof ASTUnaryBinaryCondition) {
if (right instanceof ASTUnaryBinaryCondition) {
if (not) {
return "!(" + left.toString() + " && " + right.toString() + ")";
} else {
return left.toString() + " && " + right.toString();
}
} else { // right is ASTAggregatedCondition
if (not) {
return "!(" + left.toString() + " && (" + right.toString() + " ))";
} else {
return left.toString() + " && (" + right.toString() + " )";
}
}
} else { // left is ASTAggregatedCondition
if (right instanceof ASTUnaryBinaryCondition) {
if (not) {
return "!(( " + left.toString() + ") && " + right.toString() + ")";
} else {
return "( " + left.toString() + ") && " + right.toString();
}
} else { // right is ASTAggregatedCondition also
if (not) {
return "!(( " + left.toString() + ") && (" + right.toString() + " ))";
} else {
return "( " + left.toString() + ") && (" + right.toString() + " )";
}
}
}
}
public void toString(UnitPrinter up) {
if (up instanceof DavaUnitPrinter) {
if (not) {
// print !
((DavaUnitPrinter) up).addNot();
// print left paren
((DavaUnitPrinter) up).addLeftParen();
}
if (left instanceof ASTUnaryBinaryCondition) {
if (right instanceof ASTUnaryBinaryCondition) {
left.toString(up);
((DavaUnitPrinter) up).addAggregatedAnd();
right.toString(up);
} else { // right is ASTAggregatedCondition
left.toString(up);
((DavaUnitPrinter) up).addAggregatedAnd();
((DavaUnitPrinter) up).addLeftParen();
right.toString(up);
((DavaUnitPrinter) up).addRightParen();
}
} else { // left is ASTAggregatedCondition
if (right instanceof ASTUnaryBinaryCondition) {
((DavaUnitPrinter) up).addLeftParen();
left.toString(up);
((DavaUnitPrinter) up).addRightParen();
((DavaUnitPrinter) up).addAggregatedAnd();
right.toString(up);
} else { // right is ASTAggregatedCondition also
((DavaUnitPrinter) up).addLeftParen();
left.toString(up);
((DavaUnitPrinter) up).addRightParen();
((DavaUnitPrinter) up).addAggregatedAnd();
((DavaUnitPrinter) up).addLeftParen();
right.toString(up);
((DavaUnitPrinter) up).addRightParen();
}
}
if (not) {
// print right paren
((DavaUnitPrinter) up).addRightParen();
}
} else {
throw new RuntimeException();
}
}
}
| 3,936
| 28.601504
| 80
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTBinaryCondition.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.dava.toolkits.base.AST.analysis.Analysis;
import soot.dava.toolkits.base.misc.ConditionFlipper;
import soot.jimple.ConditionExpr;
import soot.jimple.Jimple;
public class ASTBinaryCondition extends ASTUnaryBinaryCondition {
ConditionExpr condition;
public ASTBinaryCondition(ConditionExpr condition) {
this.condition = condition;
}
public ConditionExpr getConditionExpr() {
return condition;
}
public void apply(Analysis a) {
a.caseASTBinaryCondition(this);
}
public String toString() {
return condition.toString();
}
public void toString(UnitPrinter up) {
(Jimple.v().newConditionExprBox(condition)).toString(up);
}
public void flip() {
this.condition = ConditionFlipper.flip(condition);
}
/*
* Since a conditionExpr can always be flipped we always return true
*
*/
public boolean isNotted() {
return true;
}
}
| 1,759
| 25.666667
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTCondition.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public abstract class ASTCondition {
public abstract void apply(Analysis a);
public abstract void toString(UnitPrinter up);
public abstract void flip();
/*
* should return true if there is a not symbol infront of it for ASTBinaryCondition it should always return true since u
* can always flip it
*/
public abstract boolean isNotted();
}
| 1,273
| 30.073171
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTControlFlowNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 2005 Nomair A. Naeem
* %%
* 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.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.ASTAnalysis;
import soot.dava.toolkits.base.AST.ASTWalker;
import soot.dava.toolkits.base.AST.TryContentsFinder;
import soot.jimple.ConditionExpr;
public abstract class ASTControlFlowNode extends ASTLabeledNode {
// protected ValueBox conditionBox;
ASTCondition condition;
public ASTControlFlowNode(SETNodeLabel label, ConditionExpr condition) {
super(label);
// this.conditionBox = Jimple.v().newConditionExprBox(condition);
this.condition = new ASTBinaryCondition(condition);
}
/*
* Nomair A. Naeem 17-FEB-05 Needed because of change of grammar of condition being stored as a ASTCondition rather than
* the ConditionExpr which was the case before
*/
public ASTControlFlowNode(SETNodeLabel label, ASTCondition condition) {
super(label);
this.condition = condition;
}
public ASTCondition get_Condition() {
return condition;
}
public void set_Condition(ASTCondition condition) {
this.condition = condition;
}
public void perform_Analysis(ASTAnalysis a) {
/*
* Nomair A Naeem 17-FEB-05 Changed because the ASTControlFlowNode does not have a ConditionBox anymore
*
* The if check is not an ideal way of implementation What should be done is to do a DepthFirst of the Complete Condition
* hierarcy and walk all values that are found
*
* Notice this condition will always return true UNLESS transformations aggregating the control flow have been performed.
*
* This method is deprecated do not use it. Use the DepthFirstAdapter class in dava.toolkits.base.AST.analysis.
*/
if (condition instanceof ASTBinaryCondition) {
ConditionExpr condExpr = ((ASTBinaryCondition) condition).getConditionExpr();
ASTWalker.v().walk_value(a, condExpr);
}
if (a instanceof TryContentsFinder) {
TryContentsFinder.v().add_ExceptionSet(this, TryContentsFinder.v().remove_CurExceptionSet());
}
perform_AnalysisOnSubBodies(a);
}
}
| 2,924
| 34.670732
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTDoWhileNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 2005 Nomair A. Naeem
* %%
* 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 soot.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.analysis.Analysis;
import soot.jimple.ConditionExpr;
public class ASTDoWhileNode extends ASTControlFlowNode {
private List<Object> body;
public ASTDoWhileNode(SETNodeLabel label, ConditionExpr ce, List<Object> body) {
super(label, ce);
this.body = body;
subBodies.add(body);
}
/*
* Nomair A. Naeem 17-FEB-05 Needed because of change of grammar of condition being stored as a ASTCondition rather than
* the ConditionExpr which was the case before
*/
public ASTDoWhileNode(SETNodeLabel label, ASTCondition ce, List<Object> body) {
super(label, ce);
this.body = body;
subBodies.add(body);
}
/*
* Nomair A Naeem 20-FEB-2005 Added for UselessLabeledBlockRemover
*/
public void replaceBody(List<Object> body) {
this.body = body;
subBodies = new ArrayList<Object>();
subBodies.add(body);
}
public Object clone() {
return new ASTDoWhileNode(get_Label(), get_Condition(), body);
}
public void toString(UnitPrinter up) {
label_toString(up);
up.literal("do");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, body);
up.decIndent();
up.literal("}");
up.newline();
up.literal("while");
up.literal(" ");
up.literal("(");
condition.toString(up);
up.literal(")");
up.literal(";");
up.newline();
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("do");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString(body));
b.append("}");
b.append(NEWLINE);
b.append("while (");
b.append(get_Condition().toString());
b.append(");");
b.append(NEWLINE);
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTDoWhileNode(this);
}
}
| 3,043
| 23.352
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTForLoopNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 soot.Unit;
import soot.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.toolkits.base.AST.analysis.Analysis;
/*
Will contain the For loop Construct
________ _______ _______
for ( |___A____| ;|___B___| ;|___C___| )
* A has to be the following (look at the java grammar specs)
--> local variable declarations (int a=0,b=3,c=10)
OR
--> assignment expressions
--> increment/decrement expressions both pre and post e.g. ++bla,--bla,bla++,bla--
--> all sorts of method invocations
--> new class instance declaration (dont know exactly what these include)
* B can be any ASTCondition
* C can be
--> assignment expressions
--> increment/decrement expressions both pre and post e.g. ++bla,--bla,bla++,bla--
--> all sorts of method invocations
--> new class instance declaration (dont know exactly what these include)
Extend the ASTControlFlowNode since there is a B (ASTCondition involved)
and also since that extends ASTlabeledNoce and a for loop can have an associated label
*/
public class ASTForLoopNode extends ASTControlFlowNode {
private List<AugmentedStmt> init; // list of values
// notice B is an ASTCondition and is stored in the parent
private List<AugmentedStmt> update; // list of values
private List<Object> body;
public ASTForLoopNode(SETNodeLabel label, List<AugmentedStmt> init, ASTCondition condition, List<AugmentedStmt> update,
List<Object> body) {
super(label, condition);
this.body = body;
this.init = init;
this.update = update;
subBodies.add(body);
}
public List<AugmentedStmt> getInit() {
return init;
}
public List<AugmentedStmt> getUpdate() {
return update;
}
public void replaceBody(List<Object> body) {
this.body = body;
subBodies = new ArrayList<Object>();
subBodies.add(body);
}
public Object clone() {
return new ASTForLoopNode(get_Label(), init, get_Condition(), update, body);
}
public void toString(UnitPrinter up) {
label_toString(up);
up.literal("for");
up.literal(" ");
up.literal("(");
Iterator<AugmentedStmt> it = init.iterator();
while (it.hasNext()) {
AugmentedStmt as = it.next();
Unit u = as.get_Stmt();
u.toString(up);
if (it.hasNext()) {
up.literal(" , ");
}
}
up.literal("; ");
condition.toString(up);
up.literal("; ");
it = update.iterator();
while (it.hasNext()) {
AugmentedStmt as = it.next();
Unit u = as.get_Stmt();
u.toString(up);
if (it.hasNext()) {
up.literal(" , ");
}
}
up.literal(")");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, body);
up.decIndent();
up.literal("}");
up.newline();
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("for (");
Iterator<AugmentedStmt> it = init.iterator();
while (it.hasNext()) {
b.append(it.next().get_Stmt().toString());
if (it.hasNext()) {
b.append(" , ");
}
}
b.append("; ");
b.append(get_Condition().toString());
b.append("; ");
it = update.iterator();
while (it.hasNext()) {
b.append(it.next().get_Stmt().toString());
if (it.hasNext()) {
b.append(" , ");
}
}
b.append(")");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString(body));
b.append("}");
b.append(NEWLINE);
return b.toString();
}
public void apply(Analysis a) {
a.caseASTForLoopNode(this);
}
}
| 4,597
| 23.457447
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTIfElseNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 2005 Nomair A. Naeem
* %%
* 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 soot.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.analysis.Analysis;
import soot.jimple.ConditionExpr;
public class ASTIfElseNode extends ASTControlFlowNode {
private List<Object> ifBody, elseBody;
public ASTIfElseNode(SETNodeLabel label, ConditionExpr condition, List<Object> ifBody, List<Object> elseBody) {
super(label, condition);
this.ifBody = ifBody;
this.elseBody = elseBody;
subBodies.add(ifBody);
subBodies.add(elseBody);
}
/*
* Nomair A. Naeem 17-FEB-05 Needed because of change of grammar of condition being stored as a ASTCondition rather than
* the ConditionExpr which was the case before
*/
public ASTIfElseNode(SETNodeLabel label, ASTCondition condition, List<Object> ifBody, List<Object> elseBody) {
super(label, condition);
this.ifBody = ifBody;
this.elseBody = elseBody;
subBodies.add(ifBody);
subBodies.add(elseBody);
}
/*
* Nomair A. Naeem 19-FEB-2005 Added to support aggregation of conditions
*/
public void replace(SETNodeLabel newLabel, ASTCondition newCond, List<Object> newBody, List<Object> bodyTwo) {
this.ifBody = newBody;
this.elseBody = bodyTwo;
subBodies = new ArrayList<Object>();
subBodies.add(newBody);
subBodies.add(bodyTwo);
set_Condition(newCond);
set_Label(newLabel);
}
/*
* Nomair A. Naeem 21-FEB-2005 Added to support UselessLabelBlockRemover
*/
public void replaceBody(List<Object> ifBody, List<Object> elseBody) {
this.ifBody = ifBody;
this.elseBody = elseBody;
subBodies = new ArrayList<Object>();
subBodies.add(ifBody);
subBodies.add(elseBody);
}
/*
* Nomair A. Naeem 21-FEB-2005 Added to support OrAggregatorTwo
*/
public void replaceElseBody(List<Object> elseBody) {
this.elseBody = elseBody;
subBodies = new ArrayList<Object>();
subBodies.add(ifBody);
subBodies.add(elseBody);
}
/*
* Nomair A. Naeem 21-FEB-05 Used by OrAggregatorTwo
*/
public List<Object> getIfBody() {
return ifBody;
}
public List<Object> getElseBody() {
return elseBody;
}
public Object clone() {
return new ASTIfElseNode(get_Label(), get_Condition(), ifBody, elseBody);
}
public void toString(UnitPrinter up) {
label_toString(up);
up.literal("if");
up.literal(" ");
up.literal("(");
condition.toString(up);
up.literal(")");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, ifBody);
up.decIndent();
up.literal("}");
up.newline();
up.literal("else");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, elseBody);
up.decIndent();
up.literal("}");
up.newline();
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("if (");
b.append(get_Condition().toString());
b.append(")");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString(ifBody));
b.append("}");
b.append(NEWLINE);
b.append("else");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString(elseBody));
b.append("}");
b.append(NEWLINE);
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTIfElseNode(this);
}
}
| 4,495
| 23.172043
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTIfNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 2005 Nomair A. Naeem
* %%
* 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 soot.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.analysis.Analysis;
import soot.jimple.ConditionExpr;
public class ASTIfNode extends ASTControlFlowNode {
private List<Object> body;
public ASTIfNode(SETNodeLabel label, ConditionExpr condition, List<Object> body) {
super(label, condition);
this.body = body;
subBodies.add(body);
}
/*
* Nomair A. Naeem 17-FEB-05 Needed because of change of grammar of condition being stored as a ASTCondition rather than
* the ConditionExpr which was the case before
*/
public ASTIfNode(SETNodeLabel label, ASTCondition condition, List<Object> body) {
super(label, condition);
this.body = body;
subBodies.add(body);
}
/*
* Nomair A. Naeem 21-FEB-05 Used by OrAggregatorTwo
*/
public List<Object> getIfBody() {
return body;
}
public Object clone() {
return new ASTIfNode(get_Label(), get_Condition(), body);
}
/*
* Nomair A. Naeem 19-FEB-2005 Added to support aggregation of conditions
*/
public void replace(SETNodeLabel label, ASTCondition condition, List<Object> body) {
this.body = body;
subBodies = new ArrayList<Object>();
subBodies.add(body);
set_Condition(condition);
set_Label(label);
}
/*
* Nomair A Naeem 20-FEB-2005 Added for UselessLabeledBlockRemover
*/
public void replaceBody(List<Object> body) {
this.body = body;
subBodies = new ArrayList<Object>();
subBodies.add(body);
}
public void toString(UnitPrinter up) {
label_toString(up);
up.literal("if");
up.literal(" ");
up.literal("(");
condition.toString(up);
up.literal(")");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, body);
up.decIndent();
up.literal("}");
up.newline();
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("if (");
b.append(get_Condition().toString());
b.append(")");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString(body));
b.append("}");
b.append(NEWLINE);
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTIfNode(this);
}
}
| 3,376
| 23.830882
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTLabeledBlockNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 2005 Nomair A. Naeem
* %%
* 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 soot.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public class ASTLabeledBlockNode extends ASTLabeledNode {
private List<Object> body;
public ASTLabeledBlockNode(SETNodeLabel label, List<Object> body) {
super(label);
this.body = body;
subBodies.add(body);
}
/*
* Nomair A Naeem 20-FEB-2005 Added for OrAggregatorOne/UselessLabeledBlockRemover
*/
public void replaceBody(List<Object> body) {
this.body = body;
subBodies = new ArrayList<Object>();
subBodies.add(body);
}
public int size() {
return body.size();
}
public Object clone() {
return new ASTLabeledBlockNode(get_Label(), body);
}
public void toString(UnitPrinter up) {
label_toString(up);
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, body);
up.decIndent();
up.literal("} //end ");
label_toString(up);
up.newline();
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("{");
b.append(NEWLINE);
b.append(body_toString(body));
b.append("} //");
b.append(label_toString());
b.append(NEWLINE);
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTLabeledBlockNode(this);
}
}
| 2,429
| 22.823529
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTLabeledNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 2006 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.ASTAnalysis;
public abstract class ASTLabeledNode extends ASTNode {
private SETNodeLabel label;
public ASTLabeledNode(SETNodeLabel label) {
super();
set_Label(label);
}
public SETNodeLabel get_Label() {
return label;
}
public void set_Label(SETNodeLabel label) {
this.label = label;
}
public void perform_Analysis(ASTAnalysis a) {
perform_AnalysisOnSubBodies(a);
}
public void label_toString(UnitPrinter up) {
if (label.toString() != null) {
up.literal(label.toString());
up.literal(":");
up.newline();
}
}
public String label_toString() {
if (label.toString() == null) {
return new String();
} else {
StringBuffer b = new StringBuffer();
b.append(label.toString());
b.append(":");
b.append(ASTNode.NEWLINE);
return b.toString();
}
}
}
| 1,853
| 24.39726
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTMethodNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 2005 Nomair A. Naeem
* %%
* 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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.Body;
import soot.Local;
import soot.Type;
import soot.Unit;
import soot.UnitPrinter;
import soot.Value;
import soot.dava.DavaBody;
import soot.dava.DavaUnitPrinter;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DVariableDeclarationStmt;
import soot.dava.toolkits.base.AST.ASTAnalysis;
import soot.dava.toolkits.base.AST.analysis.Analysis;
import soot.dava.toolkits.base.renamer.RemoveFullyQualifiedName;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.Stmt;
import soot.util.DeterministicHashMap;
import soot.util.IterableSet;
/*
* ALWAYS REMEMBER THAT THE FIRST NODE IN THE BODY OF A METHODNODE HAS TO BE A STATEMENT
* SEQUENCE NODE WITH DECLARATIONS!!!!
*/
public class ASTMethodNode extends ASTNode {
private List<Object> body;
private DavaBody davaBody;
private ASTStatementSequenceNode declarations;
/*
* Variables that are used in shortcu statements are kept in the declarations since other analyses need quick access to all
* the declared locals in the method
*
* Any local in the dontPrintLocals list is not printed in the top declarations
*/
private List<Local> dontPrintLocals = new ArrayList<Local>();
public ASTStatementSequenceNode getDeclarations() {
return declarations;
}
public void setDeclarations(ASTStatementSequenceNode decl) {
declarations = decl;
}
public void setDavaBody(DavaBody bod) {
this.davaBody = bod;
}
public DavaBody getDavaBody() {
return davaBody;
}
public void storeLocals(Body OrigBody) {
if ((OrigBody instanceof DavaBody) == false) {
throw new RuntimeException("Only DavaBodies should invoke this method");
}
davaBody = (DavaBody) OrigBody;
Map<Type, List<Local>> typeToLocals = new DeterministicHashMap(OrigBody.getLocalCount() * 2 + 1, 0.7f);
HashSet params = new HashSet();
params.addAll(davaBody.get_ParamMap().values());
params.addAll(davaBody.get_CaughtRefs());
HashSet<Object> thisLocals = davaBody.get_ThisLocals();
// populating the typeToLocals Map
Iterator localIt = OrigBody.getLocals().iterator();
while (localIt.hasNext()) {
Local local = (Local) localIt.next();
if (params.contains(local) || thisLocals.contains(local)) {
continue;
}
List<Local> localList;
String typeName;
Type t = local.getType();
typeName = t.toString();
if (typeToLocals.containsKey(t)) {
localList = typeToLocals.get(t);
} else {
localList = new ArrayList<Local>();
typeToLocals.put(t, localList);
}
localList.add(local);
}
// create a StatementSequenceNode with all the declarations
List<AugmentedStmt> statementSequence = new ArrayList<AugmentedStmt>();
Iterator<Type> typeIt = typeToLocals.keySet().iterator();
while (typeIt.hasNext()) {
Type typeObject = typeIt.next();
String type = typeObject.toString();
DVariableDeclarationStmt varStmt = null;
varStmt = new DVariableDeclarationStmt(typeObject, davaBody);
List<Local> localList = typeToLocals.get(typeObject);
for (Local element : localList) {
varStmt.addLocal(element);
}
AugmentedStmt as = new AugmentedStmt(varStmt);
statementSequence.add(as);
}
declarations = new ASTStatementSequenceNode(statementSequence);
body.add(0, declarations);
subBodies = new ArrayList<Object>();
subBodies.add(body);
}
public ASTMethodNode(List<Object> body) {
super();
this.body = body;
subBodies.add(body);
}
/*
* Nomair A. Naeem 23rd November 2005 Need to efficiently get all locals being declared in the declarations node Dont
* really care what type they are.. Interesting thing is that they are all different names :)
*/
public List getDeclaredLocals() {
List toReturn = new ArrayList();
for (AugmentedStmt as : declarations.getStatements()) {
// going through each stmt
Stmt s = as.get_Stmt();
if (!(s instanceof DVariableDeclarationStmt)) {
continue;// shouldnt happen since this node only contains declarations
}
DVariableDeclarationStmt varStmt = (DVariableDeclarationStmt) s;
// get the locals of this particular type
List declarations = varStmt.getDeclarations();
Iterator decIt = declarations.iterator();
while (decIt.hasNext()) {
// going through each local declared
toReturn.add(decIt.next());
} // going through all locals of this type
} // going through all stmts
return toReturn;
}
/*
* Given a local first searches the declarations for the local Once it is found the local is removed from its declaring
* stmt If the declaring stmt does not declare any more locals the stmt itself is removed IT WOULD BE NICE TO ALSO CHECK IF
* THIS WAS THE LAST STMT IN THE NODE IN WHICH CASE THE NODE SHOULD BE REMOVED just afraid of its after effects on other
* analyses!!!!
*/
public void removeDeclaredLocal(Local local) {
Stmt s = null;
for (AugmentedStmt as : declarations.getStatements()) {
// going through each stmt
s = as.get_Stmt();
if (!(s instanceof DVariableDeclarationStmt)) {
continue;// shouldnt happen since this node only contains declarations
}
DVariableDeclarationStmt varStmt = (DVariableDeclarationStmt) s;
// get the locals declared in this stmt
List declarations = varStmt.getDeclarations();
Iterator decIt = declarations.iterator();
boolean foundIt = false;// becomes true if the local was found in this stmt
while (decIt.hasNext()) {
// going through each local declared
Local temp = (Local) decIt.next();
if (temp.getName().compareTo(local.getName()) == 0) {
// found it
foundIt = true;
break;
}
}
if (foundIt) {
varStmt.removeLocal(local);
break; // breaks going through other stmts as we already did what we needed to do
}
}
// the removal of a local might have made some declaration empty
// remove such a declaraion
List<AugmentedStmt> newSequence = new ArrayList<AugmentedStmt>();
for (AugmentedStmt as : declarations.getStatements()) {
s = as.get_Stmt();
if (!(s instanceof DVariableDeclarationStmt)) {
continue;
}
DVariableDeclarationStmt varStmt = (DVariableDeclarationStmt) s;
if (varStmt.getDeclarations().size() != 0) {
newSequence.add(as);
}
}
declarations.setStatements(newSequence);
}
/*
* Nomair A Naeem 21-FEB-2005 Used by UselessLabeledBlockRemove to update a body
*/
public void replaceBody(List<Object> body) {
this.body = body;
subBodies = new ArrayList<Object>();
subBodies.add(body);
}
public Object clone() {
ASTMethodNode toReturn = new ASTMethodNode(body);
toReturn.setDeclarations((ASTStatementSequenceNode) declarations.clone());
toReturn.setDontPrintLocals(dontPrintLocals);
return toReturn;
}
public void setDontPrintLocals(List<Local> list) {
dontPrintLocals = list;
}
public void addToDontPrintLocalsList(Local toAdd) {
dontPrintLocals.add(toAdd);
}
public void perform_Analysis(ASTAnalysis a) {
perform_AnalysisOnSubBodies(a);
}
public void toString(UnitPrinter up) {
if (!(up instanceof DavaUnitPrinter)) {
throw new RuntimeException("Only DavaUnitPrinter should be used to print DavaBody");
}
DavaUnitPrinter dup = (DavaUnitPrinter) up;
/*
* Print out constructor first
*/
if (davaBody != null) {
InstanceInvokeExpr constructorExpr = davaBody.get_ConstructorExpr();
if (constructorExpr != null) {
boolean printCloseBrace = true;
if (davaBody.getMethod().getDeclaringClass().getName()
.equals(constructorExpr.getMethodRef().declaringClass().toString())) {
dup.printString(" this(");
} else {
// only invoke super if its not the default call since the default is
// called automatically
if (constructorExpr.getArgCount() > 0) {
dup.printString(" super(");
} else {
printCloseBrace = false;
}
}
Iterator ait = constructorExpr.getArgs().iterator();
while (ait.hasNext()) {
/*
* January 12th, 2006 found a problem here. If a super has a method call as one of the args then the toString
* prints the jimple representation and does not convert it into java syntax
*/
Object arg = ait.next();
if (arg instanceof Value) {
// dup.printString(((Value)arg).toString());
// already in super no indentation required
dup.noIndent();
((Value) arg).toString(dup);
} else {
/**
* Staying with the old style
*/
dup.printString(arg.toString());
}
if (ait.hasNext()) {
dup.printString(", ");
}
}
if (printCloseBrace) {
dup.printString(");\n");
}
}
// print out the remaining body
up.newline();
} // if //davaBody != null
// notice that for an ASTMethod Node the first element of the body list is the
// declared variables print it here so that we can control what gets printed
printDeclarationsFollowedByBody(up, body);
}
/*
* This method has been written to bring into the printing of the method body the printing of the declared locals
*
* This is required because the dontPrintLocals list contains a list of locals which are declared from within the body and
* hence we dont want to print them here at the top of the method. However at the same time we dont want to remove the
* local entry in the declarations node since this is used by analyses throughout as a quick and easy way to find out which
* locals are used by this method...... bad code design but hey what can i say :(
*/
public void printDeclarationsFollowedByBody(UnitPrinter up, List<Object> body) {
// System.out.println("printing body from within MEthodNode\n\n"+body.toString());
for (AugmentedStmt as : declarations.getStatements()) {
// System.out.println("Stmt is:"+as.get_Stmt());
Unit u = as.get_Stmt();
// stupid sanity check cos i am paranoid
if (u instanceof DVariableDeclarationStmt) {
DVariableDeclarationStmt declStmt = (DVariableDeclarationStmt) u;
List localDeclarations = declStmt.getDeclarations();
/*
* Check that of the localDeclarations List atleast one is not present in the dontPrintLocals list
*/
boolean shouldContinue = false;
Iterator declsIt = localDeclarations.iterator();
while (declsIt.hasNext()) {
if (!dontPrintLocals.contains(declsIt.next())) {
shouldContinue = true;
break;
}
}
if (!shouldContinue) {
// shouldnt print this declaration stmt
continue;
}
if (localDeclarations.size() == 0) {
continue;
}
if (!(up instanceof DavaUnitPrinter)) {
throw new RuntimeException("DavaBody should always be printed using the DavaUnitPrinter");
}
DavaUnitPrinter dup = (DavaUnitPrinter) up;
dup.startUnit(u);
String type = declStmt.getType().toString();
if (type.equals("null_type")) {
dup.printString("Object");
} else {
IterableSet importSet = davaBody.getImportList();
if (!importSet.contains(type)) {
davaBody.addToImportList(type);
}
type = RemoveFullyQualifiedName.getReducedName(davaBody.getImportList(), type, declStmt.getType());
dup.printString(type);
}
dup.printString(" ");
int number = 0;
Iterator decIt = localDeclarations.iterator();
while (decIt.hasNext()) {
Local tempDec = (Local) decIt.next();
if (dontPrintLocals.contains(tempDec)) {
continue;
}
if (number != 0) {
dup.printString(", ");
}
number++;
dup.printString(tempDec.getName());
}
up.literal(";");
up.endUnit(u);
up.newline();
} // if DVariableDeclarationStmt
else {
up.startUnit(u);
u.toString(up);
up.literal(";");
up.endUnit(u);
up.newline();
}
}
boolean printed = false;
if (body.size() > 0) {
ASTNode firstNode = (ASTNode) body.get(0);
if (firstNode instanceof ASTStatementSequenceNode) {
List<AugmentedStmt> tempstmts = ((ASTStatementSequenceNode) firstNode).getStatements();
if (tempstmts.size() != 0) {
AugmentedStmt tempas = tempstmts.get(0);
Stmt temps = tempas.get_Stmt();
if (temps instanceof DVariableDeclarationStmt) {
printed = true;
body_toString(up, body.subList(1, body.size()));
}
}
}
}
if (!printed) {
// System.out.println("Here for method"+this.getDavaBody().getMethod().toString());
body_toString(up, body);
}
}
public String toString() {
StringBuffer b = new StringBuffer();
/*
* Print out constructor first
*/
if (davaBody != null) {
InstanceInvokeExpr constructorExpr = davaBody.get_ConstructorExpr();
if (constructorExpr != null) {
if (davaBody.getMethod().getDeclaringClass().getName()
.equals(constructorExpr.getMethodRef().declaringClass().toString())) {
b.append(" this(");
} else {
b.append(" super(");
}
boolean isFirst = true;
for (Value val : constructorExpr.getArgs()) {
if (!isFirst) {
b.append(", ");
}
b.append(val.toString());
isFirst = false;
}
b.append(");\n\n");
}
}
// print out the remaining body
b.append(body_toString(body));
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTMethodNode(this);
}
}
| 15,467
| 30.567347
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 soot.AbstractUnit;
import soot.UnitPrinter;
import soot.dava.toolkits.base.AST.ASTAnalysis;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public abstract class ASTNode extends AbstractUnit {
public static final String TAB = " ", NEWLINE = "\n";
protected List<Object> subBodies;
public ASTNode() {
subBodies = new ArrayList<Object>();
}
public abstract void toString(UnitPrinter up);
protected void body_toString(UnitPrinter up, List<Object> body) {
Iterator<Object> it = body.iterator();
while (it.hasNext()) {
((ASTNode) it.next()).toString(up);
if (it.hasNext()) {
up.newline();
}
}
}
protected String body_toString(List<Object> body) {
StringBuffer b = new StringBuffer();
Iterator<Object> it = body.iterator();
while (it.hasNext()) {
b.append(((ASTNode) it.next()).toString());
if (it.hasNext()) {
b.append(NEWLINE);
}
}
return b.toString();
}
public List<Object> get_SubBodies() {
return subBodies;
}
public abstract void perform_Analysis(ASTAnalysis a);
protected void perform_AnalysisOnSubBodies(ASTAnalysis a) {
Iterator<Object> sbit = subBodies.iterator();
while (sbit.hasNext()) {
Object subBody = sbit.next();
Iterator it = null;
if (this instanceof ASTTryNode) {
it = ((List) ((ASTTryNode.container) subBody).o).iterator();
} else {
it = ((List) subBody).iterator();
}
while (it.hasNext()) {
((ASTNode) it.next()).perform_Analysis(a);
}
}
a.analyseASTNode(this);
}
public boolean fallsThrough() {
return false;
}
public boolean branches() {
return false;
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
throw new RuntimeException("Analysis invoked apply method on ASTNode");
}
}
| 2,944
| 24.608696
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTOrCondition.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.dava.DavaUnitPrinter;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public class ASTOrCondition extends ASTAggregatedCondition {
public ASTOrCondition(ASTCondition left, ASTCondition right) {
super(left, right);
}
public void apply(Analysis a) {
a.caseASTOrCondition(this);
}
public String toString() {
if (left instanceof ASTUnaryBinaryCondition) {
if (right instanceof ASTUnaryBinaryCondition) {
if (not) {
return "!(" + left.toString() + " || " + right.toString() + ")";
} else {
return left.toString() + " || " + right.toString();
}
} else { // right is ASTAggregatedCondition
if (not) {
return "!(" + left.toString() + " || (" + right.toString() + " ))";
} else {
return left.toString() + " || (" + right.toString() + " )";
}
}
} else { // left is ASTAggregatedCondition
if (right instanceof ASTUnaryBinaryCondition) {
if (not) {
return "!(( " + left.toString() + ") || " + right.toString() + ")";
} else {
return "( " + left.toString() + ") || " + right.toString();
}
} else { // right is ASTAggregatedCondition also
if (not) {
return "!(( " + left.toString() + ") || (" + right.toString() + " ))";
} else {
return "( " + left.toString() + ") || (" + right.toString() + " )";
}
}
}
}
public void toString(UnitPrinter up) {
if (up instanceof DavaUnitPrinter) {
if (not) {
// print !
((DavaUnitPrinter) up).addNot();
// print LeftParen
((DavaUnitPrinter) up).addLeftParen();
}
if (left instanceof ASTUnaryBinaryCondition) {
if (right instanceof ASTUnaryBinaryCondition) {
left.toString(up);
((DavaUnitPrinter) up).addAggregatedOr();
right.toString(up);
} else { // right is ASTAggregatedCondition
left.toString(up);
((DavaUnitPrinter) up).addAggregatedOr();
((DavaUnitPrinter) up).addLeftParen();
right.toString(up);
((DavaUnitPrinter) up).addRightParen();
}
} else { // left is ASTAggregatedCondition
if (right instanceof ASTUnaryBinaryCondition) {
((DavaUnitPrinter) up).addLeftParen();
left.toString(up);
((DavaUnitPrinter) up).addRightParen();
((DavaUnitPrinter) up).addAggregatedOr();
right.toString(up);
} else { // right is ASTAggregatedCondition also
((DavaUnitPrinter) up).addLeftParen();
left.toString(up);
((DavaUnitPrinter) up).addRightParen();
((DavaUnitPrinter) up).addAggregatedOr();
((DavaUnitPrinter) up).addLeftParen();
right.toString(up);
((DavaUnitPrinter) up).addRightParen();
}
}
if (not) {
((DavaUnitPrinter) up).addRightParen();
}
} else {
throw new RuntimeException();
}
}
}
| 3,896
| 29.209302
| 80
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTStatementSequenceNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.toolkits.base.AST.ASTAnalysis;
import soot.dava.toolkits.base.AST.ASTWalker;
import soot.dava.toolkits.base.AST.TryContentsFinder;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public class ASTStatementSequenceNode extends ASTNode {
private List<AugmentedStmt> statementSequence;
public ASTStatementSequenceNode(List<AugmentedStmt> statementSequence) {
super();
this.statementSequence = statementSequence;
}
public Object clone() {
return new ASTStatementSequenceNode(statementSequence);
}
public void perform_Analysis(ASTAnalysis a) {
if (a.getAnalysisDepth() > ASTAnalysis.ANALYSE_AST) {
for (AugmentedStmt as : statementSequence) {
ASTWalker.v().walk_stmt(a, as.get_Stmt());
}
}
if (a instanceof TryContentsFinder) {
TryContentsFinder.v().add_ExceptionSet(this, TryContentsFinder.v().remove_CurExceptionSet());
}
}
public void toString(UnitPrinter up) {
for (AugmentedStmt as : statementSequence) {
// System.out.println("Stmt is:"+as.get_Stmt());
Unit u = as.get_Stmt();
up.startUnit(u);
u.toString(up);
up.literal(";");
up.endUnit(u);
up.newline();
}
}
public String toString() {
StringBuffer b = new StringBuffer();
for (AugmentedStmt as : statementSequence) {
b.append(as.get_Stmt().toString());
b.append(";");
b.append(NEWLINE);
}
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public List<AugmentedStmt> getStatements() {
return statementSequence;
}
public void apply(Analysis a) {
a.caseASTStatementSequenceNode(this);
}
/*
* Nomair A. Naeem added 3-MAY-05
*/
public void setStatements(List<AugmentedStmt> statementSequence) {
this.statementSequence = statementSequence;
}
}
| 2,927
| 26.885714
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTSwitchNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.Value;
import soot.ValueBox;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.ASTAnalysis;
import soot.dava.toolkits.base.AST.ASTWalker;
import soot.dava.toolkits.base.AST.TryContentsFinder;
import soot.dava.toolkits.base.AST.analysis.Analysis;
import soot.jimple.Jimple;
public class ASTSwitchNode extends ASTLabeledNode {
private ValueBox keyBox;
private List<Object> indexList;
private Map<Object, List<Object>> index2BodyList;
public ASTSwitchNode(SETNodeLabel label, Value key, List<Object> indexList, Map<Object, List<Object>> index2BodyList) {
super(label);
this.keyBox = Jimple.v().newRValueBox(key);
this.indexList = indexList;
this.index2BodyList = index2BodyList;
Iterator<Object> it = indexList.iterator();
while (it.hasNext()) {
List body = index2BodyList.get(it.next());
if (body != null) {
subBodies.add(body);
}
}
}
/*
* Nomair A. Naeem 22-FEB-2005 Added for ASTCleaner
*/
public List<Object> getIndexList() {
return indexList;
}
public Map<Object, List<Object>> getIndex2BodyList() {
return index2BodyList;
}
public void replaceIndex2BodyList(Map<Object, List<Object>> index2BodyList) {
this.index2BodyList = index2BodyList;
subBodies = new ArrayList<Object>();
Iterator<Object> it = indexList.iterator();
while (it.hasNext()) {
List body = index2BodyList.get(it.next());
if (body != null) {
subBodies.add(body);
}
}
}
public ValueBox getKeyBox() {
return keyBox;
}
public Value get_Key() {
return keyBox.getValue();
}
public void set_Key(Value key) {
this.keyBox = Jimple.v().newRValueBox(key);
}
public Object clone() {
return new ASTSwitchNode(get_Label(), get_Key(), indexList, index2BodyList);
}
public void perform_Analysis(ASTAnalysis a) {
ASTWalker.v().walk_value(a, get_Key());
if (a instanceof TryContentsFinder) {
TryContentsFinder.v().add_ExceptionSet(this, TryContentsFinder.v().remove_CurExceptionSet());
}
perform_AnalysisOnSubBodies(a);
}
public void toString(UnitPrinter up) {
label_toString(up);
up.literal("switch");
up.literal(" ");
up.literal("(");
keyBox.toString(up);
up.literal(")");
up.newline();
up.literal("{");
up.newline();
Iterator<Object> it = indexList.iterator();
while (it.hasNext()) {
Object index = it.next();
up.incIndent();
if (index instanceof String) {
up.literal("default");
} else {
up.literal("case");
up.literal(" ");
up.literal(index.toString());
}
up.literal(":");
up.newline();
List<Object> subBody = index2BodyList.get(index);
if (subBody != null) {
up.incIndent();
body_toString(up, subBody);
if (it.hasNext()) {
up.newline();
}
up.decIndent();
}
up.decIndent();
}
up.literal("}");
up.newline();
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("switch (");
b.append(get_Key());
b.append(")");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
Iterator<Object> it = indexList.iterator();
while (it.hasNext()) {
Object index = it.next();
b.append(TAB);
if (index instanceof String) {
b.append("default");
} else {
b.append("case ");
b.append(((Integer) index).toString());
}
b.append(":");
b.append(NEWLINE);
List<Object> subBody = index2BodyList.get(index);
if (subBody != null) {
b.append(body_toString(subBody));
if (it.hasNext()) {
b.append(NEWLINE);
}
}
}
b.append("}");
b.append(NEWLINE);
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTSwitchNode(this);
}
}
| 5,128
| 22.527523
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTSynchronizedBlockNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 soot.Local;
import soot.UnitPrinter;
import soot.Value;
import soot.ValueBox;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.analysis.Analysis;
import soot.jimple.Jimple;
public class ASTSynchronizedBlockNode extends ASTLabeledNode {
private List<Object> body;
private ValueBox localBox;
public ASTSynchronizedBlockNode(SETNodeLabel label, List<Object> body, Value local) {
super(label);
this.body = body;
this.localBox = Jimple.v().newLocalBox(local);
subBodies.add(body);
}
/*
* Nomair A Naeem 21-FEB-2005 Used by UselessLabeledBlockRemove to update a body
*/
public void replaceBody(List<Object> body) {
this.body = body;
subBodies = new ArrayList<Object>();
subBodies.add(body);
}
public int size() {
return body.size();
}
public Local getLocal() {
return (Local) localBox.getValue();
}
public void setLocal(Local local) {
this.localBox = Jimple.v().newLocalBox(local);
}
public Object clone() {
return new ASTSynchronizedBlockNode(get_Label(), body, getLocal());
}
public void toString(UnitPrinter up) {
label_toString(up);
/*
* up.literal( "synchronized" ); up.literal( " " ); up.literal( "(" );
*/
up.literal("synchronized (");
localBox.toString(up);
up.literal(")");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, body);
up.decIndent();
up.literal("}");
up.newline();
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("synchronized (");
b.append(getLocal());
b.append(")");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString(body));
b.append("}");
b.append(NEWLINE);
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTSynchronizedBlockNode(this);
}
}
| 3,023
| 23.192
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTTryNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Local;
import soot.SootClass;
import soot.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.ASTAnalysis;
import soot.dava.toolkits.base.AST.TryContentsFinder;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public class ASTTryNode extends ASTLabeledNode {
private List<Object> tryBody, catchList;
private Map<Object, Object> exceptionMap, paramMap;
private container tryBodyContainer;
public class container {
public Object o;
public container(Object o) {
this.o = o;
}
public void replaceBody(Object newBody) {
this.o = newBody;
}
}
public ASTTryNode(SETNodeLabel label, List<Object> tryBody, List<Object> catchList, Map<Object, Object> exceptionMap,
Map<Object, Object> paramMap) {
super(label);
this.tryBody = tryBody;
tryBodyContainer = new container(tryBody);
this.catchList = new ArrayList<Object>();
Iterator<Object> cit = catchList.iterator();
while (cit.hasNext()) {
this.catchList.add(new container(cit.next()));
}
this.exceptionMap = new HashMap<Object, Object>();
cit = this.catchList.iterator();
while (cit.hasNext()) {
container c = (container) cit.next();
this.exceptionMap.put(c, exceptionMap.get(c.o));
}
this.paramMap = new HashMap<Object, Object>();
cit = this.catchList.iterator();
while (cit.hasNext()) {
container c = (container) cit.next();
this.paramMap.put(c, paramMap.get(c.o));
}
subBodies.add(tryBodyContainer);
cit = this.catchList.iterator();
while (cit.hasNext()) {
subBodies.add(cit.next());
}
}
/*
* Nomair A Naeem 21-FEB-2005 used to support UselessLabeledBlockRemover
*/
public void replaceTryBody(List<Object> tryBody) {
this.tryBody = tryBody;
tryBodyContainer = new container(tryBody);
List<Object> oldSubBodies = subBodies;
subBodies = new ArrayList<Object>();
subBodies.add(tryBodyContainer);
Iterator<Object> oldIt = oldSubBodies.iterator();
// discard the first since that was the old tryBodyContainer
oldIt.next();
while (oldIt.hasNext()) {
subBodies.add(oldIt.next());
}
}
protected void perform_AnalysisOnSubBodies(ASTAnalysis a) {
if (a instanceof TryContentsFinder) {
Iterator<Object> sbit = subBodies.iterator();
while (sbit.hasNext()) {
container subBody = (container) sbit.next();
Iterator it = ((List) subBody.o).iterator();
while (it.hasNext()) {
ASTNode n = (ASTNode) it.next();
n.perform_Analysis(a);
TryContentsFinder.v().add_ExceptionSet(subBody, TryContentsFinder.v().get_ExceptionSet(n));
}
}
a.analyseASTNode(this);
} else {
super.perform_AnalysisOnSubBodies(a);
}
}
public boolean isEmpty() {
return tryBody.isEmpty();
}
public List<Object> get_TryBody() {
return tryBody;
}
public container get_TryBodyContainer() {
return tryBodyContainer;
}
public List<Object> get_CatchList() {
return catchList;
}
public Map<Object, Object> get_ExceptionMap() {
return exceptionMap;
}
/*
* Nomair A. Naeem 08-FEB-2005 Needed for call from DepthFirstAdapter
*/
public Map<Object, Object> get_ParamMap() {
return paramMap;
}
public Set<Object> get_ExceptionSet() {
HashSet<Object> s = new HashSet<Object>();
Iterator<Object> it = catchList.iterator();
while (it.hasNext()) {
s.add(exceptionMap.get(it.next()));
}
return s;
}
public Object clone() {
ArrayList<Object> newCatchList = new ArrayList<Object>();
Iterator<Object> it = catchList.iterator();
while (it.hasNext()) {
newCatchList.add(((container) it.next()).o);
}
return new ASTTryNode(get_Label(), tryBody, newCatchList, exceptionMap, paramMap);
}
public void toString(UnitPrinter up) {
label_toString(up);
up.literal("try");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, tryBody);
up.decIndent();
up.literal("}");
up.newline();
Iterator<Object> cit = catchList.iterator();
while (cit.hasNext()) {
container catchBody = (container) cit.next();
up.literal("catch");
up.literal(" ");
up.literal("(");
up.type(((SootClass) exceptionMap.get(catchBody)).getType());
up.literal(" ");
up.local((Local) paramMap.get(catchBody));
up.literal(")");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, (List<Object>) catchBody.o);
up.decIndent();
up.literal("}");
up.newline();
}
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("try");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString(tryBody));
b.append("}");
b.append(NEWLINE);
Iterator<Object> cit = catchList.iterator();
while (cit.hasNext()) {
container catchBody = (container) cit.next();
b.append("catch (");
b.append(((SootClass) exceptionMap.get(catchBody)).getName());
b.append(" ");
b.append(((Local) paramMap.get(catchBody)).getName());
b.append(")");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString((List<Object>) catchBody.o));
b.append("}");
b.append(NEWLINE);
}
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTTryNode(this);
}
}
| 6,819
| 24.073529
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTUnaryBinaryCondition.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 ASTUnaryBinaryCondition extends ASTCondition {
}
| 905
| 31.357143
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTUnaryCondition.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.Value;
import soot.dava.internal.javaRep.DNotExpr;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public class ASTUnaryCondition extends ASTUnaryBinaryCondition {
Value value;
public ASTUnaryCondition(Value value) {
this.value = value;
}
public void apply(Analysis a) {
a.caseASTUnaryCondition(this);
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
public String toString() {
return value.toString();
}
public void toString(UnitPrinter up) {
value.toString(up);
}
public void flip() {
/*
* Since its a unarycondition we know this is a flag See if its a DNotExpr if yes set this.value to the op inside
* DNotExpr If it is NOT a DNotExpr make one
*/
if (value instanceof DNotExpr) {
this.value = ((DNotExpr) value).getOp();
} else {
this.value = new DNotExpr(value);
}
}
public boolean isNotted() {
return (value instanceof DNotExpr);
}
}
| 1,882
| 24.794521
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTUnconditionalLoopNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 soot.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public class ASTUnconditionalLoopNode extends ASTLabeledNode {
private List<Object> body;
public ASTUnconditionalLoopNode(SETNodeLabel label, List<Object> body) {
super(label);
this.body = body;
subBodies.add(body);
}
/*
* Nomair A Naeem 20-FEB-2005 Added for UselessLabeledBlockRemover
*/
public void replaceBody(List<Object> body) {
this.body = body;
subBodies = new ArrayList<Object>();
subBodies.add(body);
}
public Object clone() {
return new ASTUnconditionalLoopNode(get_Label(), body);
}
public void toString(UnitPrinter up) {
label_toString(up);
up.literal("while");
up.literal(" ");
up.literal("(");
up.literal("true");
up.literal(")");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, body);
up.decIndent();
up.literal("}");
up.newline();
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("while (true)");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString(body));
b.append("}");
b.append(NEWLINE);
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTUnconditionalLoopNode(this);
}
}
| 2,491
| 23.194175
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/AST/ASTWhileNode.java
|
package soot.dava.internal.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 2005 Nomair A. Naeem
* %%
* 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 soot.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.analysis.Analysis;
import soot.jimple.ConditionExpr;
public class ASTWhileNode extends ASTControlFlowNode {
private List<Object> body;
public ASTWhileNode(SETNodeLabel label, ConditionExpr ce, List<Object> body) {
super(label, ce);
this.body = body;
subBodies.add(body);
}
/*
* Nomair A. Naeem 17-FEB-05 Needed because of change of grammar of condition being stored as a ASTCondition rather than
* the ConditionExpr which was the case before
*/
public ASTWhileNode(SETNodeLabel label, ASTCondition ce, List<Object> body) {
super(label, ce);
this.body = body;
subBodies.add(body);
}
/*
* Nomair A Naeem 20-FEB-2005 Added for UselessLabeledBlockRemover
*/
public void replaceBody(List<Object> body) {
this.body = body;
subBodies = new ArrayList<Object>();
subBodies.add(body);
}
public Object clone() {
return new ASTWhileNode(get_Label(), get_Condition(), body);
}
public void toString(UnitPrinter up) {
label_toString(up);
up.literal("while");
up.literal(" ");
up.literal("(");
condition.toString(up);
up.literal(")");
up.newline();
up.literal("{");
up.newline();
up.incIndent();
body_toString(up, body);
up.decIndent();
up.literal("}");
up.newline();
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(label_toString());
b.append("while (");
b.append(get_Condition().toString());
b.append(")");
b.append(NEWLINE);
b.append("{");
b.append(NEWLINE);
b.append(body_toString(body));
b.append("}");
b.append(NEWLINE);
return b.toString();
}
/*
* Nomair A. Naeem, 7-FEB-05 Part of Visitor Design Implementation for AST See: soot.dava.toolkits.base.AST.analysis For
* details
*/
public void apply(Analysis a) {
a.caseASTWhileNode(this);
}
}
| 2,926
| 23.805085
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETBasicBlock.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.G;
import soot.util.IterableSet;
public class SETBasicBlock implements Comparable {
private static final Logger logger = LoggerFactory.getLogger(SETBasicBlock.class);
private SETNode entryNode, exitNode;
private final IterableSet predecessors, successors, body;
private int priority;
public SETBasicBlock() {
predecessors = new IterableSet();
successors = new IterableSet();
body = new IterableSet();
entryNode = exitNode = null;
priority = -1;
}
public int compareTo(Object o) {
if (o == this) {
return 0;
}
SETBasicBlock other = (SETBasicBlock) o;
int difference = other.get_Priority() - get_Priority(); // major sorting order ... _descending_
if (difference == 0) {
difference = 1; // but it doesn't matter.
}
return difference;
}
private int get_Priority() {
if (priority == -1) {
priority = 0;
if (predecessors.size() == 1) {
Iterator sit = successors.iterator();
while (sit.hasNext()) {
int sucScore = ((SETBasicBlock) sit.next()).get_Priority();
if (sucScore > priority) {
priority = sucScore;
}
}
priority++;
}
}
return priority;
}
/*
* adds must be done in order such that the entry node is done first and the exit is done last.
*/
public void add(SETNode sn) {
if (body.isEmpty()) {
entryNode = sn;
}
body.add(sn);
G.v().SETBasicBlock_binding.put(sn, this);
exitNode = sn;
}
public SETNode get_EntryNode() {
return entryNode;
}
public SETNode get_ExitNode() {
return exitNode;
}
public IterableSet get_Predecessors() {
return predecessors;
}
public IterableSet get_Successors() {
return successors;
}
public IterableSet get_Body() {
return body;
}
public static SETBasicBlock get_SETBasicBlock(SETNode o) {
return G.v().SETBasicBlock_binding.get(o);
}
public void printSig() {
Iterator it = body.iterator();
while (it.hasNext()) {
((SETNode) it.next()).dump();
}
}
public void dump() {
printSig();
logger.debug("" + "=== preds ===");
Iterator it = predecessors.iterator();
while (it.hasNext()) {
((SETBasicBlock) it.next()).printSig();
}
logger.debug("" + "=== succs ===");
it = successors.iterator();
while (it.hasNext()) {
((SETBasicBlock) it.next()).printSig();
}
}
}
| 3,390
| 21.758389
| 99
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETControlFlowNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.Iterator;
import soot.dava.internal.asg.AugmentedStmt;
import soot.jimple.GotoStmt;
import soot.util.IterableSet;
public abstract class SETControlFlowNode extends SETNode {
private AugmentedStmt characterizingStmt;
public SETControlFlowNode(AugmentedStmt characterizingStmt, IterableSet<AugmentedStmt> body) {
super(body);
this.characterizingStmt = characterizingStmt;
}
public AugmentedStmt get_CharacterizingStmt() {
return characterizingStmt;
}
protected boolean resolve(SETNode parent) {
for (IterableSet subBody : parent.get_SubBodies()) {
if (subBody.contains(get_EntryStmt()) == false) {
continue;
}
IterableSet<SETNode> childChain = parent.get_Body2ChildChain().get(subBody);
HashSet childUnion = new HashSet();
for (SETNode child : childChain) {
IterableSet childBody = child.get_Body();
childUnion.addAll(childBody);
if (childBody.contains(characterizingStmt)) {
for (Iterator<AugmentedStmt> asIt = get_Body().snapshotIterator(); asIt.hasNext();) {
AugmentedStmt as = asIt.next();
if (childBody.contains(as) == false) {
remove_AugmentedStmt(as);
} else if ((child instanceof SETControlFlowNode) && ((child instanceof SETUnconditionalWhileNode) == false)) {
SETControlFlowNode scfn = (SETControlFlowNode) child;
if ((scfn.get_CharacterizingStmt() == as) || ((as.cpreds.size() == 1) && (as.get_Stmt() instanceof GotoStmt)
&& (scfn.get_CharacterizingStmt() == as.cpreds.get(0)))) {
remove_AugmentedStmt(as);
}
}
}
return true;
}
}
}
return true;
}
}
| 2,632
| 31.506173
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETCycleNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.dava.internal.asg.AugmentedStmt;
import soot.util.IterableSet;
public abstract class SETCycleNode extends SETControlFlowNode {
public SETCycleNode(AugmentedStmt characterizingStmt, IterableSet body) {
super(characterizingStmt, body);
}
}
| 1,097
| 32.272727
| 75
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETDagNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.dava.internal.asg.AugmentedStmt;
import soot.util.IterableSet;
public abstract class SETDagNode extends SETControlFlowNode {
public SETDagNode(AugmentedStmt characterizingStmt, IterableSet body) {
super(characterizingStmt, body);
}
public AugmentedStmt get_EntryStmt() {
return get_CharacterizingStmt();
}
}
| 1,176
| 30.810811
| 73
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETDoWhileNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.jimple.ConditionExpr;
import soot.jimple.IfStmt;
import soot.util.IterableSet;
public class SETDoWhileNode extends SETCycleNode {
private AugmentedStmt entryPoint;
public SETDoWhileNode(AugmentedStmt characterizingStmt, AugmentedStmt entryPoint, IterableSet body) {
super(characterizingStmt, body);
this.entryPoint = entryPoint;
IterableSet subBody = (IterableSet) body.clone();
subBody.remove(characterizingStmt);
add_SubBody(subBody);
}
public IterableSet get_NaturalExits() {
IterableSet c = new IterableSet();
c.add(get_CharacterizingStmt());
return c;
}
public ASTNode emit_AST() {
return new ASTDoWhileNode(get_Label(), (ConditionExpr) ((IfStmt) get_CharacterizingStmt().get_Stmt()).getCondition(),
emit_ASTBody(body2childChain.get(subBodies.get(0))));
}
public AugmentedStmt get_EntryStmt() {
return entryPoint;
}
}
| 1,878
| 29.306452
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETIfElseNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.toolkits.base.misc.ConditionFlipper;
import soot.jimple.ConditionExpr;
import soot.jimple.IfStmt;
import soot.util.IterableSet;
public class SETIfElseNode extends SETDagNode {
private IterableSet ifBody, elseBody;
public SETIfElseNode(AugmentedStmt characterizingStmt, IterableSet body, IterableSet ifBody, IterableSet elseBody) {
super(characterizingStmt, body);
this.ifBody = ifBody;
this.elseBody = elseBody;
add_SubBody(ifBody);
add_SubBody(elseBody);
}
public IterableSet get_NaturalExits() {
IterableSet c = new IterableSet();
IterableSet ifChain = body2childChain.get(ifBody);
if (ifChain.isEmpty() == false) {
c.addAll(((SETNode) ifChain.getLast()).get_NaturalExits());
}
IterableSet elseChain = body2childChain.get(elseBody);
if (elseChain.isEmpty() == false) {
c.addAll(((SETNode) elseChain.getLast()).get_NaturalExits());
}
return c;
}
public ASTNode emit_AST() {
List<Object> astBody0 = emit_ASTBody(body2childChain.get(ifBody)),
astBody1 = emit_ASTBody(body2childChain.get(elseBody));
ConditionExpr ce = (ConditionExpr) ((IfStmt) get_CharacterizingStmt().get_Stmt()).getCondition();
if (astBody0.isEmpty()) {
List<Object> tbody = astBody0;
astBody0 = astBody1;
astBody1 = tbody;
ce = ConditionFlipper.flip(ce);
}
if (astBody1.isEmpty()) {
return new ASTIfNode(get_Label(), ce, astBody0);
} else {
return new ASTIfElseNode(get_Label(), ce, astBody0, astBody1);
}
}
}
| 2,591
| 29.139535
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETLabeledBlockNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.util.IterableSet;
public class SETLabeledBlockNode extends SETNode {
public SETLabeledBlockNode(IterableSet body) {
super(body);
add_SubBody(body);
}
public IterableSet get_NaturalExits() {
return ((SETNode) body2childChain.get(subBodies.get(0)).getLast()).get_NaturalExits();
}
public ASTNode emit_AST() {
return new ASTLabeledBlockNode(get_Label(), emit_ASTBody(body2childChain.get(subBodies.get(0))));
}
public AugmentedStmt get_EntryStmt() {
return ((SETNode) body2childChain.get(subBodies.get(0)).getFirst()).get_EntryStmt();
}
protected boolean resolve(SETNode parent) {
throw new RuntimeException("Attempting auto-nest a SETLabeledBlockNode.");
}
}
| 1,690
| 31.519231
| 101
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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 java.util.HashMap;
import java.util.HashSet;
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.G;
import soot.dava.DavaBody;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.toolkits.base.finders.AbruptEdgeFinder;
import soot.dava.toolkits.base.finders.LabeledBlockFinder;
import soot.dava.toolkits.base.finders.SequenceFinder;
import soot.util.IterableSet;
import soot.util.UnmodifiableIterableSet;
public abstract class SETNode {
private static final Logger logger = LoggerFactory.getLogger(SETNode.class);
private IterableSet<AugmentedStmt> body;
private final SETNodeLabel label;
protected SETNode parent;
protected AugmentedStmt entryStmt;
protected IterableSet predecessors, successors;
protected LinkedList<IterableSet> subBodies;
protected Map<IterableSet, IterableSet> body2childChain;
public abstract IterableSet get_NaturalExits();
public abstract ASTNode emit_AST();
public abstract AugmentedStmt get_EntryStmt();
protected abstract boolean resolve(SETNode parent);
public SETNode(IterableSet<AugmentedStmt> body) {
this.body = body;
parent = null;
label = new SETNodeLabel();
subBodies = new LinkedList<IterableSet>();
body2childChain = new HashMap<IterableSet, IterableSet>();
predecessors = new IterableSet();
successors = new IterableSet();
}
public void add_SubBody(IterableSet body) {
subBodies.add(body);
body2childChain.put(body, new IterableSet());
}
public Map<IterableSet, IterableSet> get_Body2ChildChain() {
return body2childChain;
}
public List<IterableSet> get_SubBodies() {
return subBodies;
}
public IterableSet<AugmentedStmt> get_Body() {
return body;
}
public SETNodeLabel get_Label() {
return label;
}
public SETNode get_Parent() {
return parent;
}
public boolean contains(Object o) {
return body.contains(o);
}
public IterableSet get_Successors() {
return successors;
}
public IterableSet get_Predecessors() {
return predecessors;
}
public boolean add_Child(SETNode child, IterableSet children) {
if ((this == child) || (children.contains(child))) {
return false;
}
children.add(child);
child.parent = this;
return true;
}
public boolean remove_Child(SETNode child, IterableSet children) {
if ((this == child) || (children.contains(child) == false)) {
return false;
}
children.remove(child);
child.parent = null;
return true;
}
public boolean insert_ChildBefore(SETNode child, SETNode point, IterableSet children) {
if ((this == child) || (this == point) || (children.contains(point) == false)) {
return false;
}
children.insertBefore(child, point);
child.parent = this;
return true;
}
public List<Object> emit_ASTBody(IterableSet children) {
LinkedList<Object> l = new LinkedList<Object>();
Iterator cit = children.iterator();
while (cit.hasNext()) {
ASTNode astNode = ((SETNode) cit.next()).emit_AST();
if (astNode != null) {
l.addLast(astNode);
}
}
return l;
}
/*
* Basic inter-SETNode utilities.
*/
public IterableSet<AugmentedStmt> get_IntersectionWith(SETNode other) {
return body.intersection(other.get_Body());
}
public boolean has_IntersectionWith(SETNode other) {
for (AugmentedStmt as : other.get_Body()) {
if (body.contains(as)) {
return true;
}
}
return false;
}
public boolean is_SupersetOf(SETNode other) {
return body.isSupersetOf(other.get_Body());
}
public boolean is_StrictSupersetOf(SETNode other) {
return body.isStrictSubsetOf(other.get_Body());
}
/*
* Tree traversing utilities.
*/
public void find_SmallestSETNode(AugmentedStmt as) {
Iterator<IterableSet> sbit = subBodies.iterator();
while (sbit.hasNext()) {
Iterator it = body2childChain.get(sbit.next()).iterator();
while (it.hasNext()) {
SETNode child = (SETNode) it.next();
if (child.contains(as)) {
child.find_SmallestSETNode(as);
return;
}
}
}
as.myNode = this;
}
public void find_LabeledBlocks(LabeledBlockFinder lbf) {
Iterator<IterableSet> sbit = subBodies.iterator();
while (sbit.hasNext()) {
Iterator cit = body2childChain.get(sbit.next()).iterator();
while (cit.hasNext()) {
((SETNode) cit.next()).find_LabeledBlocks(lbf);
}
}
lbf.perform_ChildOrder(this);
lbf.find_LabeledBlocks(this);
}
public void find_StatementSequences(SequenceFinder sf, DavaBody davaBody) {
Iterator<IterableSet> sbit = subBodies.iterator();
while (sbit.hasNext()) {
IterableSet body = sbit.next();
IterableSet children = body2childChain.get(body);
HashSet<AugmentedStmt> childUnion = new HashSet<AugmentedStmt>();
Iterator cit = children.iterator();
while (cit.hasNext()) {
SETNode child = (SETNode) cit.next();
child.find_StatementSequences(sf, davaBody);
childUnion.addAll(child.get_Body());
}
sf.find_StatementSequences(this, body, childUnion, davaBody);
}
}
public void find_AbruptEdges(AbruptEdgeFinder aef) {
Iterator<IterableSet> sbit = subBodies.iterator();
while (sbit.hasNext()) {
IterableSet body = sbit.next();
IterableSet children = body2childChain.get(body);
Iterator cit = children.iterator();
while (cit.hasNext()) {
((SETNode) cit.next()).find_AbruptEdges(aef);
}
aef.find_Continues(this, body, children);
}
sbit = subBodies.iterator();
while (sbit.hasNext()) {
IterableSet children = body2childChain.get(sbit.next());
Iterator cit = children.iterator();
if (cit.hasNext()) {
SETNode cur = (SETNode) cit.next(), prev = null;
while (cit.hasNext()) {
prev = cur;
cur = (SETNode) cit.next();
aef.find_Breaks(prev, cur);
}
}
}
}
protected void remove_AugmentedStmt(AugmentedStmt as) {
IterableSet childChain = body2childChain.remove(body);
if (body instanceof UnmodifiableIterableSet) {
((UnmodifiableIterableSet<AugmentedStmt>) body).forceRemove(as);
} else {
body.remove(as);
}
if (childChain != null) {
body2childChain.put(body, childChain);
}
for (IterableSet subBody : subBodies) {
if (subBody.contains(as)) {
childChain = body2childChain.remove(subBody);
if (subBody instanceof UnmodifiableIterableSet) {
((UnmodifiableIterableSet<AugmentedStmt>) subBody).forceRemove(as);
} else {
subBody.remove(as);
}
if (childChain != null) {
body2childChain.put(subBody, childChain);
}
return;
}
}
}
public boolean nest(SETNode other) {
if (other.resolve(this) == false) {
return false;
}
IterableSet otherBody = other.get_Body();
Iterator<IterableSet> sbit = subBodies.iterator();
while (sbit.hasNext()) {
IterableSet subBody = sbit.next();
if (subBody.intersects(otherBody)) {
IterableSet childChain = body2childChain.get(subBody);
Iterator ccit = childChain.snapshotIterator();
while (ccit.hasNext()) {
SETNode curChild = (SETNode) ccit.next();
IterableSet childBody = curChild.get_Body();
if (childBody.intersects(otherBody)) {
if (childBody.isSupersetOf(otherBody)) {
return curChild.nest(other);
} else {
remove_Child(curChild, childChain);
Iterator<IterableSet> osbit = other.subBodies.iterator();
while (osbit.hasNext()) {
IterableSet otherSubBody = osbit.next();
if (otherSubBody.isSupersetOf(childBody)) {
other.add_Child(curChild, other.get_Body2ChildChain().get(otherSubBody));
break;
}
}
}
}
}
add_Child(other, childChain);
}
}
return true;
}
/*
* Debugging stuff.
*/
public void dump() {
dump(G.v().out);
}
public void dump(PrintStream out) {
dump(out, "");
}
private void dump(PrintStream out, String indentation) {
String TOP = ".---", TAB = "| ", MID = "+---", BOT = "`---";
out.println(indentation);
out.println(indentation + TOP);
out.println(indentation + TAB + getClass());
out.println(indentation + TAB);
Iterator it = body.iterator();
while (it.hasNext()) {
out.println(indentation + TAB + ((AugmentedStmt) it.next()).toString());
}
Iterator<IterableSet> sbit = subBodies.iterator();
while (sbit.hasNext()) {
IterableSet subBody = sbit.next();
out.println(indentation + MID);
Iterator bit = subBody.iterator();
while (bit.hasNext()) {
out.println(indentation + TAB + ((AugmentedStmt) bit.next()).toString());
}
out.println(indentation + TAB);
Iterator cit = body2childChain.get(subBody).iterator();
while (cit.hasNext()) {
((SETNode) cit.next()).dump(out, TAB + indentation);
}
}
out.println(indentation + BOT);
}
public void verify() {
Iterator<IterableSet> sbit = subBodies.iterator();
while (sbit.hasNext()) {
IterableSet body = sbit.next();
Iterator bit = body.iterator();
while (bit.hasNext()) {
if ((bit.next() instanceof AugmentedStmt) == false) {
logger.debug("Error in body: " + getClass());
}
}
Iterator cit = body2childChain.get(body).iterator();
while (cit.hasNext()) {
((SETNode) cit.next()).verify();
}
}
}
@Override
public boolean equals(Object other) {
if (other instanceof SETNode == false) {
return false;
}
SETNode typed_other = (SETNode) other;
if (body.equals(typed_other.body) == false) {
return false;
}
if (subBodies.equals(typed_other.subBodies) == false) {
return false;
}
if (body2childChain.equals(typed_other.body2childChain) == false) {
return false;
}
return true;
}
@Override
public int hashCode() {
return 1;
}
}
| 11,315
| 25.133949
| 91
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETNodeLabel.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.G;
public class SETNodeLabel {
private String name;
public SETNodeLabel() {
name = null;
}
public void set_Name() {
if (name == null) {
name = "label_" + Integer.toString(G.v().SETNodeLabel_uniqueId++);
}
}
public void set_Name(String name) {
this.name = name;
}
public String toString() {
return name;
}
public void clear_Name() {
name = null;
}
}
| 1,257
| 23.192308
| 72
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETStatementSequenceNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.LinkedList;
import java.util.List;
import soot.SootMethod;
import soot.Value;
import soot.dava.DavaBody;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DAbruptStmt;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.GotoStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.MonitorStmt;
import soot.jimple.ParameterRef;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
import soot.util.IterableSet;
public class SETStatementSequenceNode extends SETNode {
private DavaBody davaBody;
private boolean hasContinue;
public SETStatementSequenceNode(IterableSet body, DavaBody davaBody) {
super(body);
add_SubBody(body);
this.davaBody = davaBody;
hasContinue = false;
}
public SETStatementSequenceNode(IterableSet body) {
this(body, null);
}
public boolean has_Continue() {
return hasContinue;
}
public IterableSet get_NaturalExits() {
IterableSet c = new IterableSet();
AugmentedStmt last = (AugmentedStmt) get_Body().getLast();
if ((last.csuccs != null) && (last.csuccs.isEmpty() == false)) {
c.add(last);
}
return c;
}
public ASTNode emit_AST() {
List<AugmentedStmt> l = new LinkedList<AugmentedStmt>();
boolean isStaticInitializer = davaBody.getMethod().getName().equals(SootMethod.staticInitializerName);
Iterator it = get_Body().iterator();
while (it.hasNext()) {
AugmentedStmt as = (AugmentedStmt) it.next();
Stmt s = as.get_Stmt();
if (davaBody != null) {
if ((s instanceof ReturnVoidStmt) && (isStaticInitializer)) {
continue;
}
if (s instanceof GotoStmt) {
continue;
}
if (s instanceof MonitorStmt) {
continue;
}
/*
* January 12th 2006 Trying to fix the super problem we need to not ignore constructor unit i.e. this or super
*/
if (s == davaBody.get_ConstructorUnit()) {
// System.out.println("ALLOWING this.init STMT TO GET ADDED..............SETStatementSequenceNode");
// continue;
}
if (s instanceof IdentityStmt) {
IdentityStmt ids = (IdentityStmt) s;
Value rightOp = ids.getRightOp(), leftOp = ids.getLeftOp();
if (davaBody.get_ThisLocals().contains(leftOp)) {
continue;
}
if (rightOp instanceof ParameterRef) {
continue;
}
if (rightOp instanceof CaughtExceptionRef) {
continue;
}
}
}
l.add(as);
}
if (l.isEmpty()) {
return null;
} else {
return new ASTStatementSequenceNode(l);
}
}
public AugmentedStmt get_EntryStmt() {
return (AugmentedStmt) get_Body().getFirst();
}
public void insert_AbruptStmt(DAbruptStmt stmt) {
if (hasContinue) {
return;
}
get_Body().addLast(new AugmentedStmt(stmt));
hasContinue = stmt.is_Continue();
}
protected boolean resolve(SETNode parent) {
throw new RuntimeException("Attempting auto-nest a SETStatementSequenceNode.");
}
}
| 4,090
| 25.393548
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETSwitchNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.LinkedList;
import java.util.List;
import java.util.Map;
import soot.Value;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.toolkits.base.finders.SwitchNode;
import soot.util.IterableSet;
public class SETSwitchNode extends SETDagNode {
private List<SwitchNode> switchNodeList;
private Value key;
public SETSwitchNode(AugmentedStmt characterizingStmt, Value key, IterableSet body, List<SwitchNode> switchNodeList,
IterableSet junkBody) {
super(characterizingStmt, body);
this.key = key;
this.switchNodeList = switchNodeList;
Iterator<SwitchNode> it = switchNodeList.iterator();
while (it.hasNext()) {
add_SubBody(it.next().get_Body());
}
add_SubBody(junkBody);
}
public IterableSet get_NaturalExits() {
return new IterableSet();
}
public ASTNode emit_AST() {
LinkedList<Object> indexList = new LinkedList<Object>();
Map<Object, List<Object>> index2ASTBody = new HashMap<Object, List<Object>>();
Iterator<SwitchNode> it = switchNodeList.iterator();
while (it.hasNext()) {
SwitchNode sn = it.next();
Object lastIndex = sn.get_IndexSet().last();
Iterator iit = sn.get_IndexSet().iterator();
while (iit.hasNext()) {
Object index = iit.next();
indexList.addLast(index);
if (index != lastIndex) {
index2ASTBody.put(index, null);
} else {
index2ASTBody.put(index, emit_ASTBody(get_Body2ChildChain().get(sn.get_Body())));
}
}
}
return new ASTSwitchNode(get_Label(), key, indexList, index2ASTBody);
}
public AugmentedStmt get_EntryStmt() {
return get_CharacterizingStmt();
}
}
| 2,668
| 28.655556
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETSynchronizedBlockNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.Value;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.toolkits.base.finders.ExceptionNode;
import soot.util.IterableSet;
public class SETSynchronizedBlockNode extends SETNode {
private Value local;
public SETSynchronizedBlockNode(ExceptionNode en, Value local) {
super(en.get_Body());
add_SubBody(en.get_TryBody());
add_SubBody(en.get_CatchBody());
this.local = local;
}
public IterableSet get_NaturalExits() {
return ((SETNode) body2childChain.get(subBodies.get(0)).getLast()).get_NaturalExits();
}
public ASTNode emit_AST() {
return new ASTSynchronizedBlockNode(get_Label(), emit_ASTBody(body2childChain.get(subBodies.get(0))), local);
}
public AugmentedStmt get_EntryStmt() {
return ((SETNode) body2childChain.get(subBodies.get(0)).getFirst()).get_EntryStmt();
}
protected boolean resolve(SETNode parent) {
Iterator<IterableSet> sbit = parent.get_SubBodies().iterator();
while (sbit.hasNext()) {
IterableSet subBody = sbit.next();
if (subBody.intersects(get_Body())) {
return subBody.isSupersetOf(get_Body());
}
}
return true;
}
}
| 2,125
| 28.527778
| 113
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETTopNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.util.IterableSet;
public class SETTopNode extends SETNode {
public SETTopNode(IterableSet body) {
super(body);
add_SubBody(body);
}
public IterableSet get_NaturalExits() {
return new IterableSet();
}
public ASTNode emit_AST() {
return new ASTMethodNode(emit_ASTBody(body2childChain.get(subBodies.get(0))));
}
public AugmentedStmt get_EntryStmt() {
throw new RuntimeException("Not implemented.");
// FIXME the following turned out to be ill-typed after applying type
// inference for generics
// body2childChain maps to IterableSet !
// return (AugmentedStmt) ((SETNode) body2childChain.get(
// subBodies.get(0))).get_EntryStmt();
}
protected boolean resolve(SETNode parent) {
throw new RuntimeException("Attempting auto-nest a SETTopNode.");
}
}
| 1,794
| 30.491228
| 82
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETTryNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.LinkedList;
import java.util.List;
import soot.Value;
import soot.dava.DavaBody;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.dava.toolkits.base.finders.ExceptionFinder;
import soot.dava.toolkits.base.finders.ExceptionNode;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.GotoStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.Stmt;
import soot.util.IterableSet;
public class SETTryNode extends SETNode {
private ExceptionNode en;
private DavaBody davaBody;
private AugmentedStmtGraph asg;
private final HashMap<IterableSet, IterableSet> cb2clone;
public SETTryNode(IterableSet body, ExceptionNode en, AugmentedStmtGraph asg, DavaBody davaBody) {
super(body);
this.en = en;
this.asg = asg;
this.davaBody = davaBody;
add_SubBody(en.get_TryBody());
cb2clone = new HashMap<IterableSet, IterableSet>();
Iterator it = en.get_CatchList().iterator();
while (it.hasNext()) {
IterableSet catchBody = (IterableSet) it.next();
IterableSet clone = (IterableSet) catchBody.clone();
cb2clone.put(catchBody, clone);
add_SubBody(clone);
}
getEntryStmt: {
entryStmt = null;
it = body.iterator();
while (it.hasNext()) {
AugmentedStmt as = (AugmentedStmt) it.next();
Iterator pit = as.cpreds.iterator();
while (pit.hasNext()) {
if (body.contains(pit.next()) == false) {
entryStmt = as;
break getEntryStmt;
}
}
}
}
}
public AugmentedStmt get_EntryStmt() {
if (entryStmt != null) {
return entryStmt;
} else {
return (AugmentedStmt) (en.get_TryBody()).getFirst();
}
// return ((SETNode) ((IterableSet) body2childChain.get(
// en.get_TryBody())).getFirst()).get_EntryStmt();
}
public IterableSet get_NaturalExits() {
IterableSet c = new IterableSet();
Iterator<IterableSet> it = subBodies.iterator();
while (it.hasNext()) {
Iterator eit = ((SETNode) body2childChain.get(it.next()).getLast()).get_NaturalExits().iterator();
while (eit.hasNext()) {
Object o = eit.next();
if (c.contains(o) == false) {
c.add(o);
}
}
}
return c;
}
public ASTNode emit_AST() {
LinkedList<Object> catchList = new LinkedList<Object>();
HashMap<Object, Object> exceptionMap = new HashMap<Object, Object>(), paramMap = new HashMap<Object, Object>();
Iterator it = en.get_CatchList().iterator();
while (it.hasNext()) {
IterableSet originalCatchBody = (IterableSet) it.next();
IterableSet catchBody = cb2clone.get(originalCatchBody);
List<Object> astBody = emit_ASTBody(body2childChain.get(catchBody));
exceptionMap.put(astBody, en.get_Exception(originalCatchBody));
catchList.addLast(astBody);
Iterator bit = catchBody.iterator();
while (bit.hasNext()) {
Stmt s = ((AugmentedStmt) bit.next()).get_Stmt();
/*
* 04.04.2006 mbatch if an implicit try due to a finally block, make sure to get the exception identifier from the
* goto target (it's a different block)
*/
// TODO: HOW the heck do you handle finallys with NO finally?
// Semantics are
// technically incorrect here
if (s instanceof GotoStmt) {
s = (Stmt) ((GotoStmt) s).getTarget();
/* 04.04.2006 mbatch end */
}
if (s instanceof IdentityStmt) {
IdentityStmt ids = (IdentityStmt) s;
Value rightOp = ids.getRightOp(), leftOp = ids.getLeftOp();
if (rightOp instanceof CaughtExceptionRef) {
paramMap.put(astBody, leftOp);
break;
}
}
}
}
return new ASTTryNode(get_Label(), emit_ASTBody(body2childChain.get(en.get_TryBody())), catchList, exceptionMap,
paramMap);
}
protected boolean resolve(SETNode parent) {
Iterator<IterableSet> sbit = parent.get_SubBodies().iterator();
while (sbit.hasNext()) {
IterableSet subBody = sbit.next();
if (subBody.intersects(en.get_TryBody())) {
IterableSet childChain = parent.get_Body2ChildChain().get(subBody);
Iterator ccit = childChain.iterator();
while (ccit.hasNext()) {
SETNode child = (SETNode) ccit.next();
IterableSet childBody = child.get_Body();
if ((childBody.intersects(en.get_TryBody()) == false) || (childBody.isSubsetOf(en.get_TryBody()))) {
continue;
}
if (childBody.isSupersetOf(get_Body())) {
return true;
}
IterableSet newTryBody = childBody.intersection(en.get_TryBody());
if (newTryBody.isStrictSubsetOf(en.get_TryBody())) {
en.splitOff_ExceptionNode(newTryBody, asg, davaBody.get_ExceptionFacts());
Iterator enlit = davaBody.get_ExceptionFacts().iterator();
while (enlit.hasNext()) {
((ExceptionNode) enlit.next()).refresh_CatchBody(ExceptionFinder.v());
}
return false;
}
Iterator cit = en.get_CatchList().iterator();
while (cit.hasNext()) {
Iterator bit = cb2clone.get(cit.next()).snapshotIterator();
while (bit.hasNext()) {
AugmentedStmt as = (AugmentedStmt) bit.next();
if (childBody.contains(as) == false) {
remove_AugmentedStmt(as);
} else if ((child instanceof SETControlFlowNode) && ((child instanceof SETUnconditionalWhileNode) == false)) {
SETControlFlowNode scfn = (SETControlFlowNode) child;
if ((scfn.get_CharacterizingStmt() == as) || ((as.cpreds.size() == 1) && (as.get_Stmt() instanceof GotoStmt)
&& (scfn.get_CharacterizingStmt() == as.cpreds.get(0)))) {
remove_AugmentedStmt(as);
}
}
}
}
return true;
}
}
}
return true;
}
}
| 7,062
| 30.391111
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETUnconditionalWhileNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.util.IterableSet;
public class SETUnconditionalWhileNode extends SETCycleNode {
public SETUnconditionalWhileNode(IterableSet body) {
super((AugmentedStmt) body.getFirst(), body);
add_SubBody(body);
}
public IterableSet get_NaturalExits() {
return new IterableSet();
}
public ASTNode emit_AST() {
return new ASTUnconditionalLoopNode(get_Label(), emit_ASTBody(body2childChain.get(subBodies.get(0))));
}
public AugmentedStmt get_EntryStmt() {
return get_CharacterizingStmt();
}
}
| 1,507
| 30.416667
| 106
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/SET/SETWhileNode.java
|
package soot.dava.internal.SET;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.jimple.ConditionExpr;
import soot.jimple.IfStmt;
import soot.util.IterableSet;
public class SETWhileNode extends SETCycleNode {
public SETWhileNode(AugmentedStmt characterizingStmt, IterableSet body) {
super(characterizingStmt, body);
IterableSet subBody = (IterableSet) body.clone();
subBody.remove(characterizingStmt);
add_SubBody(subBody);
}
public IterableSet get_NaturalExits() {
IterableSet c = new IterableSet();
c.add(get_CharacterizingStmt());
return c;
}
public ASTNode emit_AST() {
return new ASTWhileNode(get_Label(), (ConditionExpr) ((IfStmt) get_CharacterizingStmt().get_Stmt()).getCondition(),
emit_ASTBody(body2childChain.get(subBodies.get(0))));
}
public AugmentedStmt get_EntryStmt() {
return get_CharacterizingStmt();
}
}
| 1,786
| 29.810345
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/asg/AugmentedStmt.java
|
package soot.dava.internal.asg;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 2005 Nomair A. Naeem
* %%
* 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.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.dava.internal.SET.SETNode;
import soot.jimple.Stmt;
import soot.util.IterableSet;
public class AugmentedStmt {
private static final Logger logger = LoggerFactory.getLogger(AugmentedStmt.class);
public List<AugmentedStmt> bpreds, bsuccs, cpreds, csuccs;
public SETNode myNode;
private final IterableSet<AugmentedStmt> dominators;
private IterableSet<AugmentedStmt> reachers;
private Stmt s;
public AugmentedStmt(Stmt s) {
this.s = s;
dominators = new IterableSet<AugmentedStmt>();
reachers = new IterableSet<AugmentedStmt>();
reset_PredsSuccs();
}
public void set_Stmt(Stmt s) {
this.s = s;
}
public boolean add_BPred(AugmentedStmt bpred) {
if (add_CPred(bpred) == false) {
return false;
}
if (bpreds.contains(bpred)) {
cpreds.remove(bpred);
return false;
}
bpreds.add(bpred);
return true;
}
public boolean add_BSucc(AugmentedStmt bsucc) {
if (add_CSucc(bsucc) == false) {
return false;
}
if (bsuccs.contains(bsucc)) {
csuccs.remove(bsucc);
return false;
}
bsuccs.add(bsucc);
return true;
}
public boolean add_CPred(AugmentedStmt cpred) {
if (cpreds.contains(cpred) == false) {
cpreds.add(cpred);
return true;
}
return false;
}
public boolean add_CSucc(AugmentedStmt csucc) {
if (csuccs.contains(csucc) == false) {
csuccs.add(csucc);
return true;
}
return false;
}
public boolean remove_BPred(AugmentedStmt bpred) {
if (remove_CPred(bpred) == false) {
return false;
}
if (bpreds.contains(bpred)) {
bpreds.remove(bpred);
return true;
}
cpreds.add(bpred);
return false;
}
public boolean remove_BSucc(AugmentedStmt bsucc) {
if (remove_CSucc(bsucc) == false) {
return false;
}
if (bsuccs.contains(bsucc)) {
bsuccs.remove(bsucc);
return true;
}
csuccs.add(bsucc);
return false;
}
public boolean remove_CPred(AugmentedStmt cpred) {
if (cpreds.contains(cpred)) {
cpreds.remove(cpred);
return true;
}
return false;
}
public boolean remove_CSucc(AugmentedStmt csucc) {
if (csuccs.contains(csucc)) {
csuccs.remove(csucc);
return true;
}
return false;
}
public Stmt get_Stmt() {
return s;
}
public IterableSet<AugmentedStmt> get_Dominators() {
return dominators;
}
public IterableSet<AugmentedStmt> get_Reachers() {
return reachers;
}
public void set_Reachability(IterableSet<AugmentedStmt> reachers) {
this.reachers = reachers;
}
public void dump() {
logger.debug("" + toString());
}
public String toString() {
return "(" + s.toString() + " @ " + hashCode() + ")";
}
public void reset_PredsSuccs() {
bpreds = new LinkedList<AugmentedStmt>();
bsuccs = new LinkedList<AugmentedStmt>();
cpreds = new LinkedList<AugmentedStmt>();
csuccs = new LinkedList<AugmentedStmt>();
}
public Object clone() {
return new AugmentedStmt((Stmt) s.clone());
}
}
| 4,083
| 21.075676
| 84
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/asg/AugmentedStmtGraph.java
|
package soot.dava.internal.asg;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Unit;
import soot.dava.Dava;
import soot.jimple.IfStmt;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.Stmt;
import soot.jimple.TableSwitchStmt;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.PseudoTopologicalOrderer;
import soot.toolkits.graph.TrapUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.util.IterableSet;
public class AugmentedStmtGraph implements DirectedGraph<AugmentedStmt> {
private HashMap<Stmt, AugmentedStmt> binding;
private HashMap<AugmentedStmt, AugmentedStmt> original2clone;
private IterableSet<AugmentedStmt> aug_list;
private IterableSet<Stmt> stmt_list;
private List<AugmentedStmt> bheads, btails, cheads, ctails;
public AugmentedStmtGraph(AugmentedStmtGraph other) {
this();
HashMap<AugmentedStmt, AugmentedStmt> old2new = new HashMap<AugmentedStmt, AugmentedStmt>();
for (AugmentedStmt oas : other.aug_list) {
Stmt s = oas.get_Stmt();
AugmentedStmt nas = new AugmentedStmt(s);
aug_list.add(nas);
stmt_list.add(s);
binding.put(s, nas);
old2new.put(oas, nas);
}
for (AugmentedStmt oas : other.aug_list) {
AugmentedStmt nas = (AugmentedStmt) old2new.get(oas);
for (AugmentedStmt aug : oas.bpreds) {
nas.bpreds.add(old2new.get(aug));
}
if (nas.bpreds.isEmpty()) {
bheads.add(nas);
}
for (AugmentedStmt aug : oas.cpreds) {
nas.cpreds.add(old2new.get(aug));
}
if (nas.cpreds.isEmpty()) {
cheads.add(nas);
}
for (AugmentedStmt aug : oas.bsuccs) {
nas.bsuccs.add(old2new.get(aug));
}
if (nas.bsuccs.isEmpty()) {
btails.add(nas);
}
for (AugmentedStmt aug : oas.csuccs) {
nas.csuccs.add(old2new.get(aug));
}
if (nas.csuccs.isEmpty()) {
ctails.add(nas);
}
}
find_Dominators();
}
public AugmentedStmtGraph(BriefUnitGraph bug, TrapUnitGraph cug) {
this();
Dava.v().log("AugmentedStmtGraph::AugmentedStmtGraph() - cug.size() = " + cug.size());
// make the augmented statements
for (Unit u : cug) {
Stmt s = (Stmt) u;
add_StmtBinding(s, new AugmentedStmt(s));
}
// make the list of augmented statements in pseudo topological order!
List<Unit> cugList = (new PseudoTopologicalOrderer<Unit>()).newList(cug, false);
for (Unit u : cugList) {
Stmt s = (Stmt) u;
aug_list.add(get_AugStmt(s));
stmt_list.add(s);
}
// now that we've got all the augmented statements, mirror the statement
// graph
for (AugmentedStmt as : aug_list) {
mirror_PredsSuccs(as, bug);
mirror_PredsSuccs(as, cug);
}
find_Dominators();
}
public AugmentedStmtGraph() {
binding = new HashMap<Stmt, AugmentedStmt>();
original2clone = new HashMap<AugmentedStmt, AugmentedStmt>();
aug_list = new IterableSet<AugmentedStmt>();
stmt_list = new IterableSet<Stmt>();
bheads = new LinkedList<AugmentedStmt>();
btails = new LinkedList<AugmentedStmt>();
cheads = new LinkedList<AugmentedStmt>();
ctails = new LinkedList<AugmentedStmt>();
}
public void add_AugmentedStmt(AugmentedStmt as) {
Stmt s = as.get_Stmt();
aug_list.add(as);
stmt_list.add(s);
add_StmtBinding(s, as);
if (as.bpreds.isEmpty()) {
bheads.add(as);
}
if (as.cpreds.isEmpty()) {
cheads.add(as);
}
if (as.bsuccs.isEmpty()) {
btails.add(as);
}
if (as.csuccs.isEmpty()) {
ctails.add(as);
}
check_List(as.bpreds, btails);
check_List(as.bsuccs, bheads);
check_List(as.cpreds, ctails);
check_List(as.csuccs, cheads);
}
public boolean contains(Object o) {
return aug_list.contains(o);
}
public AugmentedStmt get_CloneOf(AugmentedStmt as) {
return original2clone.get(as);
}
@Override
public int size() {
return aug_list.size();
}
private <T> void check_List(List<T> psList, List<T> htList) {
for (T t : psList) {
if (htList.contains(t)) {
htList.remove(t);
}
}
}
public void calculate_Reachability(AugmentedStmt source, Set<AugmentedStmt> blockers, AugmentedStmt dominator) {
if (blockers == null) {
throw new RuntimeException("Tried to call AugmentedStmtGraph:calculate_Reachability() with null blockers.");
}
if (source == null) {
return;
}
LinkedList<AugmentedStmt> worklist = new LinkedList<AugmentedStmt>();
HashSet<AugmentedStmt> touchSet = new HashSet<AugmentedStmt>();
worklist.addLast(source);
touchSet.add(source);
while (!worklist.isEmpty()) {
AugmentedStmt as = worklist.removeFirst();
for (AugmentedStmt sas : as.csuccs) {
if (touchSet.contains(sas) || !sas.get_Dominators().contains(dominator)) {
continue;
}
touchSet.add(sas);
IterableSet<AugmentedStmt> reachers = sas.get_Reachers();
if (!reachers.contains(source)) {
reachers.add(source);
}
if (!blockers.contains(sas)) {
worklist.addLast(sas);
}
}
}
}
public void calculate_Reachability(Collection<AugmentedStmt> sources, Set<AugmentedStmt> blockers,
AugmentedStmt dominator) {
for (AugmentedStmt next : sources) {
calculate_Reachability(next, blockers, dominator);
}
}
public void calculate_Reachability(AugmentedStmt source, AugmentedStmt blocker, AugmentedStmt dominator) {
HashSet<AugmentedStmt> h = new HashSet<AugmentedStmt>();
h.add(blocker);
calculate_Reachability(source, h, dominator);
}
public void calculate_Reachability(Collection<AugmentedStmt> sources, AugmentedStmt blocker, AugmentedStmt dominator) {
HashSet<AugmentedStmt> h = new HashSet<AugmentedStmt>();
h.add(blocker);
calculate_Reachability(sources, h, dominator);
}
public void calculate_Reachability(AugmentedStmt source, AugmentedStmt dominator) {
calculate_Reachability(source, Collections.<AugmentedStmt>emptySet(), dominator);
}
public void calculate_Reachability(Collection<AugmentedStmt> sources, AugmentedStmt dominator) {
calculate_Reachability(sources, Collections.<AugmentedStmt>emptySet(), dominator);
}
public void calculate_Reachability(AugmentedStmt source) {
calculate_Reachability(source, null);
}
public void calculate_Reachability(Collection<AugmentedStmt> sources) {
calculate_Reachability(sources, null);
}
public void add_StmtBinding(Stmt s, AugmentedStmt as) {
binding.put(s, as);
}
public AugmentedStmt get_AugStmt(Stmt s) {
AugmentedStmt as = binding.get(s);
if (as == null) {
throw new RuntimeException("Could not find augmented statement for: " + s.toString());
}
return as;
}
// now put in the methods to satisfy the DirectedGraph interface
@Override
public List<AugmentedStmt> getHeads() {
return cheads;
}
@Override
public List<AugmentedStmt> getTails() {
return ctails;
}
@Override
public Iterator<AugmentedStmt> iterator() {
return aug_list.iterator();
}
@Override
public List<AugmentedStmt> getPredsOf(AugmentedStmt s) {
return s.cpreds;
}
public List<AugmentedStmt> getPredsOf(Stmt s) {
return get_AugStmt(s).cpreds;
}
@Override
public List<AugmentedStmt> getSuccsOf(AugmentedStmt s) {
return s.csuccs;
}
public List<AugmentedStmt> getSuccsOf(Stmt s) {
return get_AugStmt(s).csuccs;
}
// end of methods satisfying DirectedGraph
public List<AugmentedStmt> get_BriefHeads() {
return bheads;
}
public List<AugmentedStmt> get_BriefTails() {
return btails;
}
public IterableSet<AugmentedStmt> get_ChainView() {
return new IterableSet<AugmentedStmt>(aug_list);
}
@Override
public Object clone() {
return new AugmentedStmtGraph(this);
}
public boolean remove_AugmentedStmt(AugmentedStmt toRemove) {
if (!aug_list.contains(toRemove)) {
return false;
}
for (AugmentedStmt pas : toRemove.bpreds) {
if (pas.bsuccs.contains(toRemove)) {
pas.bsuccs.remove(toRemove);
}
}
for (AugmentedStmt pas : toRemove.cpreds) {
if (pas.csuccs.contains(toRemove)) {
pas.csuccs.remove(toRemove);
}
}
for (AugmentedStmt sas : toRemove.bsuccs) {
if (sas.bpreds.contains(toRemove)) {
sas.bpreds.remove(toRemove);
}
}
for (AugmentedStmt sas : toRemove.csuccs) {
if (sas.cpreds.contains(toRemove)) {
sas.cpreds.remove(toRemove);
}
}
aug_list.remove(toRemove);
stmt_list.remove(toRemove.get_Stmt());
bheads.remove(toRemove);
btails.remove(toRemove);
cheads.remove(toRemove);
ctails.remove(toRemove);
binding.remove(toRemove.get_Stmt());
return true;
// NOTE: we do *NOT* touch the underlying unit graphs.
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
String cr = "\n";
b.append("AugmentedStmtGraph (size: ").append(size()).append(" stmts)").append(cr);
for (AugmentedStmt as : aug_list) {
b.append("| .---").append(cr).append("| | AugmentedStmt ").append(as.toString()).append(cr).append("| |").append(cr)
.append("| | preds:");
for (AugmentedStmt pas : as.cpreds) {
b.append(" ").append(pas.toString());
}
b.append(cr).append("| |").append(cr).append("| | succs:");
for (AugmentedStmt sas : as.csuccs) {
b.append(" ").append(sas.toString());
}
b.append(cr).append("| |").append(cr).append("| | doms:");
for (AugmentedStmt das : as.get_Dominators()) {
b.append(" ").append(das.toString());
}
b.append(cr).append("| `---").append(cr);
}
b.append("-").append(cr);
return b.toString();
}
private void mirror_PredsSuccs(AugmentedStmt as, UnitGraph ug) {
Stmt s = as.get_Stmt();
LinkedList<AugmentedStmt> preds = new LinkedList<AugmentedStmt>(), succs = new LinkedList<AugmentedStmt>();
// mirror the predecessors
for (Unit u : ug.getPredsOf(s)) {
AugmentedStmt po = get_AugStmt((Stmt) u);
if (!preds.contains(po)) {
preds.add(po);
}
}
// mirror the successors
for (Unit u : ug.getSuccsOf(s)) {
AugmentedStmt so = get_AugStmt((Stmt) u);
if (!succs.contains(so)) {
succs.add(so);
}
}
// attach the mirrors properly to the AugmentedStmt
if (ug instanceof BriefUnitGraph) {
as.bpreds = preds;
as.bsuccs = succs;
if (preds.isEmpty()) {
bheads.add(as);
}
if (succs.isEmpty()) {
btails.add(as);
}
} else if (ug instanceof TrapUnitGraph) {
as.cpreds = preds;
as.csuccs = succs;
if (preds.isEmpty()) {
cheads.add(as);
}
if (succs.isEmpty()) {
ctails.add(as);
}
} else {
throw new RuntimeException("Unknown UnitGraph type: " + ug.getClass());
}
}
public IterableSet<AugmentedStmt> clone_Body(IterableSet<AugmentedStmt> oldBody) {
HashMap<AugmentedStmt, AugmentedStmt> old2new = new HashMap<AugmentedStmt, AugmentedStmt>();
HashMap<AugmentedStmt, AugmentedStmt> new2old = new HashMap<AugmentedStmt, AugmentedStmt>();
IterableSet<AugmentedStmt> newBody = new IterableSet<AugmentedStmt>();
for (AugmentedStmt as : oldBody) {
AugmentedStmt clone = (AugmentedStmt) as.clone();
original2clone.put(as, clone);
old2new.put(as, clone);
new2old.put(clone, as);
newBody.add(clone);
}
for (AugmentedStmt newAs : newBody) {
AugmentedStmt oldAs = new2old.get(newAs);
mirror_PredsSuccs(oldAs, oldAs.bpreds, newAs.bpreds, old2new);
mirror_PredsSuccs(oldAs, oldAs.cpreds, newAs.cpreds, old2new);
mirror_PredsSuccs(oldAs, oldAs.bsuccs, newAs.bsuccs, old2new);
mirror_PredsSuccs(oldAs, oldAs.csuccs, newAs.csuccs, old2new);
}
for (AugmentedStmt au : newBody) {
add_AugmentedStmt(au);
}
HashMap<Unit, Stmt> so2n = new HashMap<Unit, Stmt>();
for (AugmentedStmt as : oldBody) {
Stmt os = as.get_Stmt();
Stmt ns = old2new.get(as).get_Stmt();
so2n.put(os, ns);
}
for (AugmentedStmt nas : newBody) {
AugmentedStmt oas = new2old.get(nas);
Stmt ns = nas.get_Stmt(), os = oas.get_Stmt();
if (os instanceof IfStmt) {
Unit target = ((IfStmt) os).getTarget();
Unit newTgt = so2n.get(target);
((IfStmt) ns).setTarget(newTgt == null ? target : newTgt);
} else if (os instanceof TableSwitchStmt) {
TableSwitchStmt otss = (TableSwitchStmt) os, ntss = (TableSwitchStmt) ns;
Unit target = otss.getDefaultTarget();
Unit newTgt = so2n.get(target);
ntss.setDefaultTarget(newTgt == null ? target : newTgt);
LinkedList<Unit> new_target_list = new LinkedList<Unit>();
int target_count = otss.getHighIndex() - otss.getLowIndex() + 1;
for (int i = 0; i < target_count; i++) {
target = otss.getTarget(i);
newTgt = so2n.get(target);
new_target_list.add(newTgt == null ? target : newTgt);
}
ntss.setTargets(new_target_list);
} else if (os instanceof LookupSwitchStmt) {
LookupSwitchStmt olss = (LookupSwitchStmt) os, nlss = (LookupSwitchStmt) ns;
Unit target = olss.getDefaultTarget();
Unit newTgt = so2n.get(target);
nlss.setDefaultTarget(newTgt == null ? target : newTgt);
Unit[] new_target_list = new Unit[olss.getTargetCount()];
for (int i = 0; i < new_target_list.length; i++) {
target = olss.getTarget(i);
newTgt = so2n.get(target);
new_target_list[i] = newTgt == null ? target : newTgt;
}
nlss.setTargets(new_target_list);
nlss.setLookupValues(olss.getLookupValues());
}
}
return newBody;
}
private void mirror_PredsSuccs(AugmentedStmt originalAs, List<AugmentedStmt> oldList, List<AugmentedStmt> newList,
Map<AugmentedStmt, AugmentedStmt> old2new) {
for (AugmentedStmt oldAs : oldList) {
AugmentedStmt newAs = old2new.get(oldAs);
if (newAs != null) {
newList.add(newAs);
} else {
newList.add(oldAs);
AugmentedStmt clonedAs = old2new.get(originalAs);
if (oldList == originalAs.bpreds) {
oldAs.bsuccs.add(clonedAs);
} else if (oldList == originalAs.cpreds) {
oldAs.csuccs.add(clonedAs);
} else if (oldList == originalAs.bsuccs) {
oldAs.bpreds.add(clonedAs);
} else if (oldList == originalAs.csuccs) {
oldAs.cpreds.add(clonedAs);
} else {
throw new RuntimeException("Error mirroring preds and succs in Try block splitting.");
}
}
}
}
public void find_Dominators() {
// set up the dominator sets for all the nodes in the graph
for (AugmentedStmt as : aug_list) {
// Dominators:
// safe starting approximation for S(0) ... empty set
// unsafe starting approximation for S(i) .. full set
IterableSet<AugmentedStmt> doms = as.get_Dominators();
doms.clear();
if (!as.cpreds.isEmpty()) {
doms.addAll(aug_list);
}
}
// build the worklist
IterableSet<AugmentedStmt> worklist = new IterableSet<AugmentedStmt>();
worklist.addAll(aug_list);
// keep going until the worklist is empty
while (!worklist.isEmpty()) {
AugmentedStmt as = worklist.getFirst();
worklist.removeFirst();
IterableSet<AugmentedStmt> pred_intersection = new IterableSet<AugmentedStmt>();
boolean first_pred = true;
// run through all the predecessors and get their dominance
// intersection
for (AugmentedStmt pas : as.cpreds) {
if (first_pred) {
// for the first predecessor just take all its dominators
pred_intersection.addAll(pas.get_Dominators());
if (!pred_intersection.contains(pas)) {
pred_intersection.add(pas);
}
first_pred = false;
} else {
// for the subsequent predecessors remove the ones they do not
// have from the intersection
for (Iterator<AugmentedStmt> piit = pred_intersection.snapshotIterator(); piit.hasNext();) {
AugmentedStmt pid = piit.next();
if (!pas.get_Dominators().contains(pid) && (pas != pid)) {
pred_intersection.remove(pid);
}
}
}
}
// update dominance if we have a change
if (!as.get_Dominators().equals(pred_intersection)) {
for (AugmentedStmt o : as.csuccs) {
if (!worklist.contains(o)) {
worklist.add(o);
}
}
as.get_Dominators().clear();
as.get_Dominators().addAll(pred_intersection);
}
}
}
}
| 18,043
| 27.371069
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DAbruptStmt.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.dava.internal.SET.SETNodeLabel;
import soot.jimple.internal.AbstractStmt;
public class DAbruptStmt extends AbstractStmt {
private String command;
private SETNodeLabel label;
public boolean surpressDestinationLabel;
public DAbruptStmt(String command, SETNodeLabel label) {
this.command = command;
this.label = label;
label.set_Name();
surpressDestinationLabel = false;
}
public boolean fallsThrough() {
return false;
}
public boolean branches() {
return false;
}
public Object clone() {
return new DAbruptStmt(command, label);
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(command);
if ((surpressDestinationLabel == false) && (label.toString() != null)) {
b.append(" ");
b.append(label.toString());
}
return b.toString();
}
public void toString(UnitPrinter up) {
up.literal(command);
if ((surpressDestinationLabel == false) && (label.toString() != null)) {
up.literal(" ");
up.literal(label.toString());
}
}
public boolean is_Continue() {
return command.equals("continue");
}
public boolean is_Break() {
return command.equals("break");
}
/*
* Nomair A. Naeem 20-FEB-2005 getter and setter methods for the label are needed for the aggregators of the AST
* conditionals
*/
public void setLabel(SETNodeLabel label) {
this.label = label;
}
public SETNodeLabel getLabel() {
return label;
}
}
| 2,405
| 23.804124
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DArrayInitExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%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.List;
import soot.Type;
import soot.UnitPrinter;
import soot.Value;
import soot.ValueBox;
import soot.util.Switch;
/*
* TODO: Starting with a 1D array in mind will try to refactor for multi D arrays
* later
*/
public class DArrayInitExpr implements Value {
// an array of elements for the initialization
ValueBox[] elements;
// store the type of the array
Type type;
public DArrayInitExpr(ValueBox[] elements, Type type) {
this.elements = elements;
this.type = type;
}
/*
* go through the elements array return useBoxes of each value plus the valuebox itself
*/
public List<ValueBox> getUseBoxes() {
List<ValueBox> list = new ArrayList<ValueBox>();
for (ValueBox element : elements) {
list.addAll(element.getValue().getUseBoxes());
list.add(element);
}
return list;
}
/*
* TODO: Does not work
*/
public Object clone() {
return this;
}
public Type getType() {
return type;
}
public void toString(UnitPrinter up) {
up.literal("{");
for (int i = 0; i < elements.length; i++) {
elements[i].toString(up);
if (i + 1 < elements.length) {
up.literal(" , ");
}
}
up.literal("}");
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append("{");
for (int i = 0; i < elements.length; i++) {
b.append(elements[i].toString());
if (i + 1 < elements.length) {
b.append(" , ");
}
}
b.append("}");
return b.toString();
}
public void apply(Switch sw) {
// TODO Auto-generated method stub
}
public boolean equivTo(Object o) {
// TODO Auto-generated method stub
return false;
}
public int equivHashCode() {
int toReturn = 0;
for (ValueBox element : elements) {
toReturn += element.getValue().equivHashCode();
}
return toReturn;
}
public ValueBox[] getElements() {
return elements;
}
}
| 2,839
| 22.278689
| 89
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DArrayInitValueBox.java
|
package soot.dava.internal.javaRep;
/*-
* #%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 soot.AbstractValueBox;
import soot.Value;
public class DArrayInitValueBox extends AbstractValueBox {
public DArrayInitValueBox(Value value) {
setValue(value);
}
public boolean canContainValue(Value value) {
return (value instanceof DArrayInitExpr);
}
}
| 1,134
| 28.868421
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DAssignStmt.java
|
package soot.dava.internal.javaRep;
/*-
* #%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 soot.UnitPrinter;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AssignStmt;
import soot.jimple.internal.AbstractDefinitionStmt;
public class DAssignStmt extends AbstractDefinitionStmt implements AssignStmt {
public DAssignStmt(ValueBox left, ValueBox right) {
super(left, right);
}
public Object clone() {
return new DAssignStmt(leftBox, rightBox);
}
@Override
public void setLeftOp(Value variable) {
leftBox.setValue(variable);
}
@Override
public void setRightOp(Value rvalue) {
rightBox.setValue(rvalue);
}
public void toString(UnitPrinter up) {
leftBox.toString(up);
up.literal(" = ");
rightBox.toString(up);
}
public String toString() {
return leftBox.getValue().toString() + " = " + rightBox.getValue().toString();
}
}
| 1,668
| 25.919355
| 82
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DCmpExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.Type;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.internal.AbstractGrimpIntBinopExpr;
import soot.jimple.CmpExpr;
import soot.jimple.ExprSwitch;
import soot.util.Switch;
/*
* TODO
*/
public class DCmpExpr extends AbstractGrimpIntBinopExpr implements CmpExpr {
public DCmpExpr(Value op1, Value op2) {
super(op1, op2);
}
public final String getSymbol() {
return " - ";
}
public final int getPrecedence() {
return 700;
}
public void apply(Switch sw) {
((ExprSwitch) sw).caseCmpExpr(this);
}
public Object clone() {
return new DCmpExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2()));
}
public Type getType() {
if (getOp1().getType().equals(getOp2().getType())) {
return getOp1().getType();
}
return IntType.v();
}
}
| 1,697
| 24.727273
| 92
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DCmpgExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.Type;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.internal.AbstractGrimpIntBinopExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.ExprSwitch;
import soot.util.Switch;
public class DCmpgExpr extends AbstractGrimpIntBinopExpr implements CmpgExpr {
public DCmpgExpr(Value op1, Value op2) {
super(op1, op2);
}
public final String getSymbol() {
return " - ";
}
public final int getPrecedence() {
return 700;
}
public void apply(Switch sw) {
((ExprSwitch) sw).caseCmpgExpr(this);
}
public Object clone() {
return new DCmpgExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2()));
}
public Type getType() {
if (getOp1().getType().equals(getOp2().getType())) {
return getOp1().getType();
}
return IntType.v();
}
}
| 1,688
| 25.809524
| 93
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DCmplExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.Type;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.internal.AbstractGrimpIntBinopExpr;
import soot.jimple.CmplExpr;
import soot.jimple.ExprSwitch;
import soot.util.Switch;
public class DCmplExpr extends AbstractGrimpIntBinopExpr implements CmplExpr {
public DCmplExpr(Value op1, Value op2) {
super(op1, op2);
}
public final String getSymbol() {
return " - ";
}
public final int getPrecedence() {
return 700;
}
public void apply(Switch sw) {
((ExprSwitch) sw).caseCmplExpr(this);
}
public Object clone() {
return new DCmplExpr(Grimp.cloneIfNecessary(getOp1()), Grimp.cloneIfNecessary(getOp2()));
}
public Type getType() {
if (getOp1().getType().equals(getOp2().getType())) {
return getOp1().getType();
}
return IntType.v();
}
}
| 1,688
| 25.809524
| 93
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DDecrementStmt.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.internal.GAssignStmt;
public class DDecrementStmt extends GAssignStmt {
public DDecrementStmt(Value variable, Value rvalue) {
super(variable, rvalue);
}
public Object clone() {
return new DDecrementStmt(Grimp.cloneIfNecessary(getLeftOp()), Grimp.cloneIfNecessary(getRightOp()));
}
public String toString() {
return getLeftOpBox().getValue().toString() + "--";
}
public void toString(UnitPrinter up) {
getLeftOpBox().toString(up);
up.literal("--");
}
}
| 1,417
| 27.938776
| 105
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DIdentityStmt.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.UnitPrinter;
import soot.Value;
import soot.grimp.internal.GIdentityStmt;
public class DIdentityStmt extends GIdentityStmt {
public DIdentityStmt(Value local, Value identityValue) {
super(local, identityValue);
}
public void toString(UnitPrinter up) {
getLeftOpBox().toString(up);
up.literal(" := ");
getRightOpBox().toString(up);
}
public String toString() {
return getLeftOpBox().getValue().toString() + " = " + getRightOpBox().getValue().toString();
}
}
| 1,346
| 29.613636
| 96
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DIncrementStmt.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.UnitPrinter;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.internal.GAssignStmt;
public class DIncrementStmt extends GAssignStmt {
public DIncrementStmt(Value variable, Value rvalue) {
super(variable, rvalue);
}
public Object clone() {
return new DIncrementStmt(Grimp.cloneIfNecessary(getLeftOp()), Grimp.cloneIfNecessary(getRightOp()));
}
public String toString() {
return getLeftOpBox().getValue().toString() + "++";
}
public void toString(UnitPrinter up) {
getLeftOpBox().toString(up);
up.literal("++");
}
}
| 1,417
| 27.938776
| 105
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DInstanceFieldRef.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* 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.HashSet;
import soot.SootFieldRef;
import soot.UnitPrinter;
import soot.Value;
import soot.grimp.internal.GInstanceFieldRef;
public class DInstanceFieldRef extends GInstanceFieldRef {
private HashSet<Object> thisLocals;
public DInstanceFieldRef(Value base, SootFieldRef fieldRef, HashSet<Object> thisLocals) {
super(base, fieldRef);
this.thisLocals = thisLocals;
}
public void toString(UnitPrinter up) {
if (thisLocals.contains(getBase())) {
up.fieldRef(fieldRef);
} else {
super.toString(up);
}
}
public String toString() {
if (thisLocals.contains(getBase())) {
return fieldRef.name();
}
return super.toString();
}
public Object clone() {
return new DInstanceFieldRef(getBase(), fieldRef, thisLocals);
}
}
| 1,682
| 26.145161
| 91
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DIntConstant.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.Type;
import soot.jimple.IntConstant;
public class DIntConstant extends IntConstant {
public Type type;
private DIntConstant(int value, Type type) {
super(value);
this.type = type;
}
public static DIntConstant v(int value, Type type) {
return new DIntConstant(value, type);
}
@Override
public String toString() {
if (type != null) {
if (type instanceof BooleanType) {
return (value == 0) ? "false" : "true";
} else if (type instanceof CharType) {
String ch;
switch (value) {
case 0x08:
ch = "\\b";
break;
case 0x09:
ch = "\\t";
break;
case 0x0a:
ch = "\\n";
break;
case 0x0c:
ch = "\\f";
break;
case 0x0d:
ch = "\\r";
break;
case 0x22:
ch = "\\\"";
break;
case 0x27:
ch = "\\'";
break;
case 0x5c:
ch = "\\\\";
break;
default:
if ((value > 31) && (value < 127)) {
ch = new Character((char) value).toString();
} else {
ch = Integer.toHexString(value);
while (ch.length() < 4) {
ch = "0" + ch;
}
if (ch.length() > 4) {
ch = ch.substring(ch.length() - 4);
}
ch = "\\u" + ch;
}
}
return "'" + ch + "'";
} else if (type instanceof ByteType) {
return "(byte) " + Integer.toString(value);
}
}
return Integer.toString(value);
}
}
| 2,614
| 24.38835
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DInterfaceInvokeExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* 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 soot.NullType;
import soot.SootMethodRef;
import soot.UnitPrinter;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.Precedence;
import soot.grimp.PrecedenceTest;
import soot.grimp.internal.GInterfaceInvokeExpr;
public class DInterfaceInvokeExpr extends GInterfaceInvokeExpr {
public DInterfaceInvokeExpr(Value base, SootMethodRef methodRef, java.util.List args) {
super(base, methodRef, args);
}
public void toString(UnitPrinter up) {
if (getBase().getType() instanceof NullType) {
// OL: I don't know what this is for; I'm just refactoring the
// original code. An explanation here would be welcome.
up.literal("((");
up.type(getMethodRef().declaringClass().getType());
up.literal(") ");
if (PrecedenceTest.needsBrackets(baseBox, this)) {
up.literal("(");
}
baseBox.toString(up);
if (PrecedenceTest.needsBrackets(baseBox, this)) {
up.literal(")");
}
up.literal(")");
up.literal(".");
up.methodRef(methodRef);
up.literal("(");
if (argBoxes != null) {
for (int i = 0; i < argBoxes.length; i++) {
if (i != 0) {
up.literal(", ");
}
argBoxes[i].toString(up);
}
}
up.literal(")");
} else {
super.toString(up);
}
}
public String toString() {
if (getBase().getType() instanceof NullType) {
StringBuffer b = new StringBuffer();
b.append("((");
b.append(getMethodRef().declaringClass().getJavaStyleName());
b.append(") ");
String baseStr = (getBase()).toString();
if ((getBase() instanceof Precedence) && (((Precedence) getBase()).getPrecedence() < getPrecedence())) {
baseStr = "(" + baseStr + ")";
}
b.append(baseStr);
b.append(").");
b.append(getMethodRef().name());
b.append("(");
if (argBoxes != null) {
for (int i = 0; i < argBoxes.length; i++) {
if (i != 0) {
b.append(", ");
}
b.append((argBoxes[i].getValue()).toString());
}
}
b.append(")");
return b.toString();
}
return super.toString();
}
public Object clone() {
ArrayList clonedArgs = new ArrayList(getArgCount());
for (int i = 0; i < getArgCount(); i++) {
clonedArgs.add(i, Grimp.cloneIfNecessary(getArg(i)));
}
return new DInterfaceInvokeExpr(getBase(), methodRef, clonedArgs);
}
}
| 3,390
| 25.700787
| 110
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DLengthExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.UnitPrinter;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.Precedence;
import soot.grimp.PrecedenceTest;
import soot.jimple.internal.AbstractLengthExpr;
public class DLengthExpr extends AbstractLengthExpr implements Precedence {
public DLengthExpr(Value op) {
super(Grimp.v().newObjExprBox(op));
}
public int getPrecedence() {
return 950;
}
public Object clone() {
return new DLengthExpr(Grimp.cloneIfNecessary(getOp()));
}
public void toString(UnitPrinter up) {
if (PrecedenceTest.needsBrackets(getOpBox(), this)) {
up.literal("(");
}
getOpBox().toString(up);
if (PrecedenceTest.needsBrackets(getOpBox(), this)) {
up.literal(")");
}
up.literal(".");
up.literal("length");
}
public String toString() {
StringBuffer b = new StringBuffer();
if (PrecedenceTest.needsBrackets(getOpBox(), this)) {
b.append("(");
}
b.append(getOpBox().getValue().toString());
if (PrecedenceTest.needsBrackets(getOpBox(), this)) {
b.append(")");
}
b.append(".length");
return b.toString();
}
}
| 1,963
| 26.661972
| 75
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DNegExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.UnitPrinter;
import soot.Value;
import soot.grimp.Grimp;
import soot.jimple.internal.AbstractNegExpr;
public class DNegExpr extends AbstractNegExpr {
public DNegExpr(Value op) {
super(Grimp.v().newExprBox(op));
}
public Object clone() {
return new DNegExpr(Grimp.cloneIfNecessary(getOp()));
}
public void toString(UnitPrinter up) {
up.literal("(");
up.literal("-");
up.literal(" ");
up.literal("(");
getOpBox().toString(up);
up.literal(")");
up.literal(")");
}
public String toString() {
return "(- (" + (getOpBox().getValue()).toString() + "))";
}
}
| 1,465
| 26.660377
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DNewArrayExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.ArrayType;
import soot.Type;
import soot.UnitPrinter;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.Precedence;
import soot.jimple.internal.AbstractNewArrayExpr;
public class DNewArrayExpr extends AbstractNewArrayExpr implements Precedence {
public DNewArrayExpr(Type type, Value size) {
super(type, Grimp.v().newExprBox(size));
}
public int getPrecedence() {
return 850;
}
public Object clone() {
return new DNewArrayExpr(getBaseType(), Grimp.cloneIfNecessary(getSize()));
}
public void toString(UnitPrinter up) {
up.literal("new");
up.literal(" ");
Type type = getBaseType();
if (type instanceof ArrayType) {
ArrayType arrayType = (ArrayType) type;
up.type(arrayType.baseType);
up.literal("[");
getSizeBox().toString(up);
up.literal("]");
for (int i = 0; i < arrayType.numDimensions; i++) {
up.literal("[]");
}
} else {
up.type(getBaseType());
up.literal("[");
getSizeBox().toString(up);
up.literal("]");
}
}
public String toString() {
return "new " + getBaseType() + "[" + getSize() + "]";
}
}
| 2,007
| 26.888889
| 79
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DNewInvokeExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* 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 soot.RefType;
import soot.SootMethodRef;
import soot.grimp.Grimp;
import soot.grimp.internal.GNewInvokeExpr;
public class DNewInvokeExpr extends GNewInvokeExpr {
public DNewInvokeExpr(RefType type, SootMethodRef methodRef, java.util.List args) {
super(type, methodRef, args);
}
public Object clone() {
ArrayList clonedArgs = new ArrayList(getArgCount());
for (int i = 0; i < getArgCount(); i++) {
clonedArgs.add(i, Grimp.cloneIfNecessary(getArg(i)));
}
return new DNewInvokeExpr((RefType) getType(), methodRef, clonedArgs);
}
}
| 1,480
| 29.854167
| 85
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DNewMultiArrayExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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 soot.ArrayType;
import soot.UnitPrinter;
import soot.Value;
import soot.ValueBox;
import soot.grimp.Grimp;
import soot.jimple.internal.AbstractNewMultiArrayExpr;
public class DNewMultiArrayExpr extends AbstractNewMultiArrayExpr {
public DNewMultiArrayExpr(ArrayType type, List sizes) {
super(type, new ValueBox[sizes.size()]);
for (int i = 0; i < sizes.size(); i++) {
sizeBoxes[i] = Grimp.v().newExprBox((Value) sizes.get(i));
}
}
public Object clone() {
List clonedSizes = new ArrayList(getSizeCount());
for (int i = 0; i < getSizeCount(); i++) {
clonedSizes.add(i, Grimp.cloneIfNecessary(getSize(i)));
}
return new DNewMultiArrayExpr(getBaseType(), clonedSizes);
}
public void toString(UnitPrinter up) {
up.literal("new");
up.literal(" ");
up.type(getBaseType().baseType);
for (ValueBox element : sizeBoxes) {
up.literal("[");
element.toString(up);
up.literal("]");
}
for (int i = getSizeCount(); i < getBaseType().numDimensions; i++) {
up.literal("[]");
}
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("new " + getBaseType().baseType);
List sizes = getSizes();
Iterator it = getSizes().iterator();
while (it.hasNext()) {
buffer.append("[" + it.next().toString() + "]");
}
for (int i = getSizeCount(); i < getBaseType().numDimensions; i++) {
buffer.append("[]");
}
return buffer.toString();
}
}
| 2,432
| 26.647727
| 72
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DNotExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.ShortType;
import soot.Type;
import soot.UnitPrinter;
import soot.UnknownType;
import soot.Value;
import soot.grimp.Grimp;
import soot.jimple.internal.AbstractUnopExpr;
import soot.util.Switch;
//import soot.jimple.*;
public class DNotExpr extends AbstractUnopExpr {
public DNotExpr(Value op) {
super(Grimp.v().newExprBox(op));
}
public Object clone() {
return new DNotExpr(Grimp.cloneIfNecessary(getOpBox().getValue()));
}
public void toString(UnitPrinter up) {
up.literal(" ! (");
getOpBox().toString(up);
up.literal(")");
}
public String toString() {
return " ! (" + (getOpBox().getValue()).toString() + ")";
}
public Type getType() {
Value op = getOpBox().getValue();
if (op.getType().equals(IntType.v()) || op.getType().equals(ByteType.v()) || op.getType().equals(ShortType.v())
|| op.getType().equals(BooleanType.v()) || op.getType().equals(CharType.v())) {
return IntType.v();
} else if (op.getType().equals(LongType.v())) {
return LongType.v();
} else if (op.getType().equals(DoubleType.v())) {
return DoubleType.v();
} else if (op.getType().equals(FloatType.v())) {
return FloatType.v();
} else {
return UnknownType.v();
}
}
/*
* NOTE THIS IS AN EMPTY IMPLEMENTATION OF APPLY METHOD
*/
public void apply(Switch sw) {
}
/** Compares the specified object with this one for structural equality. */
public boolean equivTo(Object o) {
if (o instanceof DNotExpr) {
return getOpBox().getValue().equivTo(((DNotExpr) o).getOpBox().getValue());
}
return false;
}
/** Returns a hash code for this object, consistent with structural equality. */
public int equivHashCode() {
return getOpBox().getValue().equivHashCode();
}
}
| 2,796
| 27.540816
| 115
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DShortcutAssignStmt.java
|
package soot.dava.internal.javaRep;
/*-
* #%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 soot.Type;
import soot.UnitPrinter;
public class DShortcutAssignStmt extends DAssignStmt {
Type type;
public DShortcutAssignStmt(DAssignStmt assignStmt, Type type) {
super(assignStmt.getLeftOpBox(), assignStmt.getRightOpBox());
this.type = type;
}
public void toString(UnitPrinter up) {
up.type(type);
up.literal(" ");
super.toString(up);
}
public String toString() {
return type.toString() + " " + leftBox.getValue().toString() + " = " + rightBox.getValue().toString();
}
}
| 1,380
| 28.382979
| 106
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DShortcutIf.java
|
package soot.dava.internal.javaRep;
/*-
* #%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.List;
import soot.Type;
import soot.UnitPrinter;
import soot.ValueBox;
import soot.jimple.Expr;
import soot.util.Switch;
public class DShortcutIf implements Expr {
ValueBox testExprBox;
ValueBox trueExprBox;
ValueBox falseExprBox;
Type exprType;
public DShortcutIf(ValueBox test, ValueBox left, ValueBox right) {
testExprBox = test;
trueExprBox = left;
falseExprBox = right;
}
public Object clone() {
// does not work
return this;
}
public List getUseBoxes() {
List toReturn = new ArrayList();
toReturn.addAll(testExprBox.getValue().getUseBoxes());
toReturn.add(testExprBox);
toReturn.addAll(trueExprBox.getValue().getUseBoxes());
toReturn.add(trueExprBox);
toReturn.addAll(falseExprBox.getValue().getUseBoxes());
toReturn.add(falseExprBox);
return toReturn;
}
public Type getType() {
return exprType;
}
public String toString() {
String toReturn = "";
toReturn += testExprBox.getValue().toString();
toReturn += " ? ";
toReturn += trueExprBox.getValue().toString();
toReturn += " : ";
toReturn += falseExprBox.getValue().toString();
return toReturn;
}
public void toString(UnitPrinter up) {
testExprBox.getValue().toString(up);
up.literal(" ? ");
trueExprBox.getValue().toString(up);
up.literal(" : ");
falseExprBox.getValue().toString(up);
}
public void apply(Switch sw) {
// TODO Auto-generated method stub
}
public boolean equivTo(Object o) {
// TODO Auto-generated method stub
return false;
}
public int equivHashCode() {
int toReturn = 0;
toReturn += testExprBox.getValue().equivHashCode();
toReturn += trueExprBox.getValue().equivHashCode();
toReturn += falseExprBox.getValue().equivHashCode();
return toReturn;
}
}
| 2,715
| 25.368932
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DSpecialInvokeExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* 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 soot.NullType;
import soot.SootMethodRef;
import soot.UnitPrinter;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.Precedence;
import soot.grimp.PrecedenceTest;
import soot.grimp.internal.GSpecialInvokeExpr;
public class DSpecialInvokeExpr extends GSpecialInvokeExpr {
public DSpecialInvokeExpr(Value base, SootMethodRef methodRef, java.util.List args) {
super(base, methodRef, args);
}
public void toString(UnitPrinter up) {
if (getBase().getType() instanceof NullType) {
// OL: I don't know what this is for; I'm just refactoring the
// original code. An explanation here would be welcome.
up.literal("((");
up.type(methodRef.declaringClass().getType());
up.literal(") ");
if (PrecedenceTest.needsBrackets(baseBox, this)) {
up.literal("(");
}
baseBox.toString(up);
if (PrecedenceTest.needsBrackets(baseBox, this)) {
up.literal(")");
}
up.literal(")");
up.literal(".");
up.methodRef(methodRef);
up.literal("(");
if (argBoxes != null) {
for (int i = 0; i < argBoxes.length; i++) {
if (i != 0) {
up.literal(", ");
}
argBoxes[i].toString(up);
}
}
up.literal(")");
} else {
super.toString(up);
}
}
public String toString() {
if (getBase().getType() instanceof NullType) {
StringBuffer b = new StringBuffer();
b.append("((");
b.append(methodRef.declaringClass().getJavaStyleName());
b.append(") ");
String baseStr = (getBase()).toString();
if ((getBase() instanceof Precedence) && (((Precedence) getBase()).getPrecedence() < getPrecedence())) {
baseStr = "(" + baseStr + ")";
}
b.append(baseStr);
b.append(").");
b.append(methodRef.name());
b.append("(");
if (argBoxes != null) {
for (int i = 0; i < argBoxes.length; i++) {
if (i != 0) {
b.append(", ");
}
b.append((argBoxes[i].getValue()).toString());
}
}
b.append(")");
return b.toString();
}
return super.toString();
}
public Object clone() {
ArrayList clonedArgs = new ArrayList(getArgCount());
for (int i = 0; i < getArgCount(); i++) {
clonedArgs.add(i, Grimp.cloneIfNecessary(getArg(i)));
}
return new DSpecialInvokeExpr(getBase(), methodRef, clonedArgs);
}
}
| 3,365
| 25.503937
| 110
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DStaticFieldRef.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* 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 soot.SootFieldRef;
import soot.UnitPrinter;
import soot.jimple.StaticFieldRef;
public class DStaticFieldRef extends StaticFieldRef {
private boolean supressDeclaringClass;
public void toString(UnitPrinter up) {
if (!supressDeclaringClass) {
up.type(fieldRef.declaringClass().getType());
up.literal(".");
}
up.fieldRef(fieldRef);
}
public DStaticFieldRef(SootFieldRef fieldRef, String myClassName) {
super(fieldRef);
supressDeclaringClass = myClassName.equals(fieldRef.declaringClass().getName());
}
public DStaticFieldRef(SootFieldRef fieldRef, boolean supressDeclaringClass) {
super(fieldRef);
this.supressDeclaringClass = supressDeclaringClass;
}
public Object clone() {
return new DStaticFieldRef(fieldRef, supressDeclaringClass);
}
}
| 1,690
| 29.745455
| 84
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DStaticInvokeExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* 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 soot.SootMethodRef;
import soot.UnitPrinter;
import soot.grimp.Grimp;
import soot.grimp.internal.GStaticInvokeExpr;
public class DStaticInvokeExpr extends GStaticInvokeExpr {
public DStaticInvokeExpr(SootMethodRef methodRef, java.util.List args) {
super(methodRef, args);
}
public void toString(UnitPrinter up) {
up.type(methodRef.declaringClass().getType());
up.literal(".");
super.toString(up);
}
public Object clone() {
ArrayList clonedArgs = new ArrayList(getArgCount());
for (int i = 0; i < getArgCount(); i++) {
clonedArgs.add(i, Grimp.cloneIfNecessary(getArg(i)));
}
return new DStaticInvokeExpr(methodRef, clonedArgs);
}
}
| 1,600
| 28.648148
| 74
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DThisRef.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.RefType;
import soot.jimple.ThisRef;
public class DThisRef extends ThisRef {
public DThisRef(RefType thisType) {
super(thisType);
}
public String toString() {
return "this: " + getType();
}
public Object clone() {
return new DThisRef((RefType) getType());
}
}
| 1,141
| 26.853659
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DVariableDeclarationStmt.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 soot.AbstractUnit;
import soot.Local;
import soot.Type;
import soot.UnitPrinter;
import soot.Value;
import soot.ValueBox;
import soot.dava.DavaBody;
import soot.dava.DavaUnitPrinter;
import soot.dava.toolkits.base.renamer.RemoveFullyQualifiedName;
import soot.grimp.Grimp;
import soot.jimple.ArrayRef;
import soot.jimple.FieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
import soot.util.IterableSet;
public class DVariableDeclarationStmt extends AbstractUnit implements Stmt {
Type declarationType = null;
List declarations = null;
// added solely for the purpose of retrieving packages used when printing
DavaBody davaBody = null;
public DVariableDeclarationStmt(Type decType, DavaBody davaBody) {
if (declarationType != null) {
throw new RuntimeException("creating a VariableDeclaration which has already been created");
} else {
declarationType = decType;
declarations = new ArrayList();
this.davaBody = davaBody;
}
}
public List getDeclarations() {
return declarations;
}
public void addLocal(Local add) {
declarations.add(add);
}
public void removeLocal(Local remove) {
for (int i = 0; i < declarations.size(); i++) {
Local temp = (Local) declarations.get(i);
if (temp.getName().compareTo(remove.getName()) == 0) {
// this is the local to be removed
// System.out.println("REMOVED"+temp);
declarations.remove(i);
return;
}
}
}
public Type getType() {
return declarationType;
}
public boolean isOfType(Type type) {
if (type.toString().compareTo(declarationType.toString()) == 0) {
return true;
} else {
return false;
}
}
public Object clone() {
DVariableDeclarationStmt temp = new DVariableDeclarationStmt(declarationType, davaBody);
Iterator it = declarations.iterator();
while (it.hasNext()) {
Local obj = (Local) it.next();
Value temp1 = Grimp.cloneIfNecessary(obj);
if (temp1 instanceof Local) {
temp.addLocal((Local) temp1);
}
}
return temp;
}
public String toString() {
StringBuffer b = new StringBuffer();
if (declarations.size() == 0) {
return b.toString();
}
String type = declarationType.toString();
if (type.equals("null_type")) {
b.append("Object");
} else {
b.append(type);
}
b.append(" ");
Iterator decIt = declarations.iterator();
while (decIt.hasNext()) {
Local tempDec = (Local) decIt.next();
b.append(tempDec.getName());
if (decIt.hasNext()) {
b.append(", ");
}
}
return b.toString();
}
public void toString(UnitPrinter up) {
if (declarations.size() == 0) {
return;
}
if (!(up instanceof DavaUnitPrinter)) {
throw new RuntimeException("DavaBody should always be printed using the DavaUnitPrinter");
} else {
DavaUnitPrinter dup = (DavaUnitPrinter) up;
String type = declarationType.toString();
if (type.equals("null_type")) {
dup.printString("Object");
} else {
IterableSet importSet = davaBody.getImportList();
if (!importSet.contains(type)) {
davaBody.addToImportList(type);
}
type = RemoveFullyQualifiedName.getReducedName(davaBody.getImportList(), type, declarationType);
dup.printString(type);
}
dup.printString(" ");
Iterator decIt = declarations.iterator();
while (decIt.hasNext()) {
Local tempDec = (Local) decIt.next();
dup.printString(tempDec.getName());
if (decIt.hasNext()) {
dup.printString(", ");
}
}
}
}
/*
* Methods needed to satisfy all obligations due to extension from AbstractUnit and implementing Stmt
*
*/
public boolean fallsThrough() {
return true;
}
public boolean branches() {
return false;
}
public boolean containsInvokeExpr() {
return false;
}
public InvokeExpr getInvokeExpr() {
throw new RuntimeException("getInvokeExpr() called with no invokeExpr present!");
}
public ValueBox getInvokeExprBox() {
throw new RuntimeException("getInvokeExprBox() called with no invokeExpr present!");
}
public boolean containsArrayRef() {
return false;
}
public ArrayRef getArrayRef() {
throw new RuntimeException("getArrayRef() called with no ArrayRef present!");
}
public ValueBox getArrayRefBox() {
throw new RuntimeException("getArrayRefBox() called with no ArrayRef present!");
}
public boolean containsFieldRef() {
return false;
}
public FieldRef getFieldRef() {
throw new RuntimeException("getFieldRef() called with no FieldRef present!");
}
public ValueBox getFieldRefBox() {
throw new RuntimeException("getFieldRefBox() called with no FieldRef present!");
}
}
| 5,793
| 24.751111
| 104
|
java
|
soot
|
soot-master/src/main/java/soot/dava/internal/javaRep/DVirtualInvokeExpr.java
|
package soot.dava.internal.javaRep;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* 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.HashSet;
import soot.NullType;
import soot.SootMethodRef;
import soot.UnitPrinter;
import soot.Value;
import soot.grimp.Grimp;
import soot.grimp.Precedence;
import soot.grimp.PrecedenceTest;
import soot.grimp.internal.GVirtualInvokeExpr;
public class DVirtualInvokeExpr extends GVirtualInvokeExpr {
private HashSet<Object> thisLocals;
public DVirtualInvokeExpr(Value base, SootMethodRef methodRef, java.util.List args, HashSet<Object> thisLocals) {
super(base, methodRef, args);
this.thisLocals = thisLocals;
}
public void toString(UnitPrinter up) {
if (getBase().getType() instanceof NullType) {
// OL: I don't know what this is for; I'm just refactoring the
// original code. An explanation here would be welcome.
up.literal("((");
up.type(methodRef.declaringClass().getType());
up.literal(") ");
if (PrecedenceTest.needsBrackets(baseBox, this)) {
up.literal("(");
}
baseBox.toString(up);
if (PrecedenceTest.needsBrackets(baseBox, this)) {
up.literal(")");
}
up.literal(")");
up.literal(".");
up.methodRef(methodRef);
up.literal("(");
if (argBoxes != null) {
for (int i = 0; i < argBoxes.length; i++) {
if (i != 0) {
up.literal(", ");
}
argBoxes[i].toString(up);
}
}
up.literal(")");
} else {
super.toString(up);
}
}
public String toString() {
if (getBase().getType() instanceof NullType) {
StringBuffer b = new StringBuffer();
b.append("((");
b.append(methodRef.declaringClass().getJavaStyleName());
b.append(") ");
String baseStr = (getBase()).toString();
if ((getBase() instanceof Precedence) && (((Precedence) getBase()).getPrecedence() < getPrecedence())) {
baseStr = "(" + baseStr + ")";
}
b.append(baseStr);
b.append(").");
b.append(methodRef.name());
b.append("(");
if (argBoxes != null) {
for (int i = 0; i < argBoxes.length; i++) {
if (i != 0) {
b.append(", ");
}
b.append((argBoxes[i].getValue()).toString());
}
}
b.append(")");
return b.toString();
}
return super.toString();
}
public Object clone() {
ArrayList clonedArgs = new ArrayList(getArgCount());
for (int i = 0; i < getArgCount(); i++) {
clonedArgs.add(i, Grimp.cloneIfNecessary(getArg(i)));
}
return new DVirtualInvokeExpr(Grimp.cloneIfNecessary(getBase()), methodRef, clonedArgs, thisLocals);
}
}
| 3,529
| 25.742424
| 115
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/ASTAnalysis.java
|
package soot.dava.toolkits.base.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.dava.internal.AST.ASTNode;
import soot.jimple.ArrayRef;
import soot.jimple.BinopExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.Expr;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.Ref;
import soot.jimple.ReturnStmt;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UnopExpr;
public abstract class ASTAnalysis {
public static final int ANALYSE_AST = 0, ANALYSE_STMTS = 1, ANALYSE_VALUES = 2;
public abstract int getAnalysisDepth();
public void analyseASTNode(ASTNode n) {
}
public void analyseDefinitionStmt(DefinitionStmt s) {
}
public void analyseReturnStmt(ReturnStmt s) {
}
public void analyseInvokeStmt(InvokeStmt s) {
}
public void analyseThrowStmt(ThrowStmt s) {
}
public void analyseStmt(Stmt s) {
}
public void analyseBinopExpr(BinopExpr v) {
}
public void analyseUnopExpr(UnopExpr v) {
}
public void analyseNewArrayExpr(NewArrayExpr v) {
}
public void analyseNewMultiArrayExpr(NewMultiArrayExpr v) {
}
public void analyseInstanceOfExpr(InstanceOfExpr v) {
}
public void analyseInstanceInvokeExpr(InstanceInvokeExpr v) {
}
public void analyseInvokeExpr(InvokeExpr v) {
}
public void analyseExpr(Expr v) {
}
public void analyseArrayRef(ArrayRef v) {
}
public void analyseInstanceFieldRef(InstanceFieldRef v) {
}
public void analyseRef(Ref v) {
}
public void analyseValue(Value v) {
}
}
| 2,517
| 23.446602
| 81
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/ASTWalker.java
|
package soot.dava.toolkits.base.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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.G;
import soot.Singletons;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.Expr;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.Ref;
import soot.jimple.ReturnStmt;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UnopExpr;
public class ASTWalker {
public ASTWalker(Singletons.Global g) {
}
public static ASTWalker v() {
return G.v().soot_dava_toolkits_base_AST_ASTWalker();
}
public void walk_stmt(ASTAnalysis a, Stmt s) {
if (a.getAnalysisDepth() < ASTAnalysis.ANALYSE_STMTS) {
return;
}
if (s instanceof DefinitionStmt) {
DefinitionStmt ds = (DefinitionStmt) s;
walk_value(a, ds.getRightOp());
walk_value(a, ds.getLeftOp());
a.analyseDefinitionStmt(ds);
} else if (s instanceof ReturnStmt) {
ReturnStmt rs = (ReturnStmt) s;
walk_value(a, rs.getOp());
a.analyseReturnStmt(rs);
} else if (s instanceof InvokeStmt) {
InvokeStmt is = (InvokeStmt) s;
walk_value(a, is.getInvokeExpr());
a.analyseInvokeStmt(is);
} else if (s instanceof ThrowStmt) {
ThrowStmt ts = (ThrowStmt) s;
walk_value(a, ts.getOp());
a.analyseThrowStmt(ts);
} else {
a.analyseStmt(s);
}
}
public void walk_value(ASTAnalysis a, Value v) {
if (a.getAnalysisDepth() < ASTAnalysis.ANALYSE_VALUES) {
return;
}
if (v instanceof Expr) {
Expr e = (Expr) v;
if (e instanceof BinopExpr) {
BinopExpr be = (BinopExpr) e;
walk_value(a, be.getOp1());
walk_value(a, be.getOp2());
a.analyseBinopExpr(be);
} else if (e instanceof UnopExpr) {
UnopExpr ue = (UnopExpr) e;
walk_value(a, ue.getOp());
a.analyseUnopExpr(ue);
} else if (e instanceof CastExpr) {
CastExpr ce = (CastExpr) e;
walk_value(a, ce.getOp());
a.analyseExpr(ce);
} else if (e instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) e;
walk_value(a, nae.getSize());
a.analyseNewArrayExpr(nae);
} else if (e instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) e;
for (int i = 0; i < nmae.getSizeCount(); i++) {
walk_value(a, nmae.getSize(i));
}
a.analyseNewMultiArrayExpr(nmae);
} else if (e instanceof InstanceOfExpr) {
InstanceOfExpr ioe = (InstanceOfExpr) e;
walk_value(a, ioe.getOp());
a.analyseInstanceOfExpr(ioe);
} else if (e instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) e;
for (int i = 0; i < ie.getArgCount(); i++) {
walk_value(a, ie.getArg(i));
}
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
walk_value(a, iie.getBase());
a.analyseInstanceInvokeExpr(iie);
} else {
a.analyseInvokeExpr(ie);
}
} else {
a.analyseExpr(e);
}
} else if (v instanceof Ref) {
Ref r = (Ref) v;
if (r instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) r;
walk_value(a, ar.getBase());
walk_value(a, ar.getIndex());
a.analyseArrayRef(ar);
} else if (r instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) r;
walk_value(a, ifr.getBase());
a.analyseInstanceFieldRef(ifr);
} else {
a.analyseRef(r);
}
} else {
a.analyseValue(v);
}
}
}
| 4,671
| 27.144578
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/TryContentsFinder.java
|
package soot.dava.toolkits.base.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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 soot.G;
import soot.Local;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.Type;
import soot.Value;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.jimple.FieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.ThrowStmt;
import soot.util.IterableSet;
public class TryContentsFinder extends ASTAnalysis {
public TryContentsFinder(Singletons.Global g) {
}
public static TryContentsFinder v() {
return G.v().soot_dava_toolkits_base_AST_TryContentsFinder();
}
private IterableSet curExceptionSet = new IterableSet();
private final HashMap<Object, IterableSet> node2ExceptionSet = new HashMap<Object, IterableSet>();
public int getAnalysisDepth() {
return ANALYSE_VALUES;
}
public IterableSet remove_CurExceptionSet() {
IterableSet s = curExceptionSet;
set_CurExceptionSet(new IterableSet());
return s;
}
public void set_CurExceptionSet(IterableSet curExceptionSet) {
this.curExceptionSet = curExceptionSet;
}
public void analyseThrowStmt(ThrowStmt s) {
Value op = (s).getOp();
if (op instanceof Local) {
add_ThrownType(((Local) op).getType());
} else if (op instanceof FieldRef) {
add_ThrownType(((FieldRef) op).getType());
}
}
private void add_ThrownType(Type t) {
if (t instanceof RefType) {
curExceptionSet.add(((RefType) t).getSootClass());
}
}
public void analyseInvokeExpr(InvokeExpr ie) {
curExceptionSet.addAll(ie.getMethod().getExceptions());
}
public void analyseInstanceInvokeExpr(InstanceInvokeExpr iie) {
analyseInvokeExpr(iie);
}
public void analyseASTNode(ASTNode n) {
if (n instanceof ASTTryNode) {
ASTTryNode tryNode = (ASTTryNode) n;
ArrayList<Object> toRemove = new ArrayList<Object>();
IterableSet tryExceptionSet = node2ExceptionSet.get(tryNode.get_TryBodyContainer());
if (tryExceptionSet == null) {
tryExceptionSet = new IterableSet();
node2ExceptionSet.put(tryNode.get_TryBodyContainer(), tryExceptionSet);
}
List<Object> catchBodies = tryNode.get_CatchList();
List<Object> subBodies = tryNode.get_SubBodies();
Iterator<Object> cit = catchBodies.iterator();
while (cit.hasNext()) {
Object catchBody = cit.next();
SootClass exception = (SootClass) tryNode.get_ExceptionMap().get(catchBody);
if ((catches_Exception(tryExceptionSet, exception) == false) && (catches_RuntimeException(exception) == false)) {
toRemove.add(catchBody);
}
}
Iterator<Object> trit = toRemove.iterator();
while (trit.hasNext()) {
Object catchBody = trit.next();
subBodies.remove(catchBody);
catchBodies.remove(catchBody);
}
IterableSet passingSet = (IterableSet) tryExceptionSet.clone();
cit = catchBodies.iterator();
while (cit.hasNext()) {
passingSet.remove(tryNode.get_ExceptionMap().get(cit.next()));
}
cit = catchBodies.iterator();
while (cit.hasNext()) {
passingSet.addAll(get_ExceptionSet(cit.next()));
}
node2ExceptionSet.put(n, passingSet);
}
else {
Iterator<Object> sbit = n.get_SubBodies().iterator();
while (sbit.hasNext()) {
Iterator it = ((List) sbit.next()).iterator();
while (it.hasNext()) {
add_ExceptionSet(n, get_ExceptionSet(it.next()));
}
}
}
remove_CurExceptionSet();
}
public IterableSet get_ExceptionSet(Object node) {
IterableSet fullSet = node2ExceptionSet.get(node);
if (fullSet == null) {
fullSet = new IterableSet();
node2ExceptionSet.put(node, fullSet);
}
return fullSet;
}
public void add_ExceptionSet(Object node, IterableSet s) {
IterableSet fullSet = node2ExceptionSet.get(node);
if (fullSet == null) {
fullSet = new IterableSet();
node2ExceptionSet.put(node, fullSet);
}
fullSet.addAll(s);
}
private boolean catches_Exception(IterableSet tryExceptionSet, SootClass c) {
Iterator it = tryExceptionSet.iterator();
while (it.hasNext()) {
SootClass thrownException = (SootClass) it.next();
while (true) {
if (thrownException == c) {
return true;
}
if (thrownException.hasSuperclass() == false) {
break;
}
thrownException = thrownException.getSuperclass();
}
}
return false;
}
private boolean catches_RuntimeException(SootClass c) {
if ((c == Scene.v().getSootClass("java.lang.Throwable")) || (c == Scene.v().getSootClass("java.lang.Exception"))) {
return true;
}
SootClass caughtException = c, runtimeException = Scene.v().getSootClass("java.lang.RuntimeException");
while (true) {
if (caughtException == runtimeException) {
return true;
}
if (caughtException.hasSuperclass() == false) {
return false;
}
caughtException = caughtException.getSuperclass();
}
}
}
| 6,072
| 26.857798
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/UselessTryRemover.java
|
package soot.dava.toolkits.base.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* 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 soot.G;
import soot.Singletons;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTTryNode;
public class UselessTryRemover extends ASTAnalysis {
public UselessTryRemover(Singletons.Global g) {
}
public static UselessTryRemover v() {
return G.v().soot_dava_toolkits_base_AST_UselessTryRemover();
}
public int getAnalysisDepth() {
return ANALYSE_AST;
}
public void analyseASTNode(ASTNode n) {
Iterator<Object> sbit = n.get_SubBodies().iterator();
while (sbit.hasNext()) {
List<Object> subBody = null, toRemove = new ArrayList<Object>();
if (n instanceof ASTTryNode) {
subBody = (List<Object>) ((ASTTryNode.container) sbit.next()).o;
} else {
subBody = (List<Object>) sbit.next();
}
Iterator<Object> cit = subBody.iterator();
while (cit.hasNext()) {
Object child = cit.next();
if (child instanceof ASTTryNode) {
ASTTryNode tryNode = (ASTTryNode) child;
tryNode.perform_Analysis(TryContentsFinder.v());
if ((tryNode.get_CatchList().isEmpty()) || (tryNode.isEmpty())) {
toRemove.add(tryNode);
}
}
}
Iterator<Object> trit = toRemove.iterator();
while (trit.hasNext()) {
ASTTryNode tryNode = (ASTTryNode) trit.next();
subBody.addAll(subBody.indexOf(tryNode), tryNode.get_TryBody());
subBody.remove(tryNode);
}
if (toRemove.isEmpty() == false) {
G.v().ASTAnalysis_modified = true;
}
}
}
}
| 2,477
| 27.159091
| 75
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/analysis/Analysis.java
|
package soot.dava.toolkits.base.AST.analysis;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.Type;
import soot.Value;
import soot.dava.internal.AST.ASTAndCondition;
import soot.dava.internal.AST.ASTBinaryCondition;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTOrCondition;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.AST.ASTUnaryCondition;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.javaRep.DVariableDeclarationStmt;
import soot.jimple.ArrayRef;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.Expr;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.Ref;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UnopExpr;
public interface Analysis {
public void caseASTMethodNode(ASTMethodNode node);
public void caseASTSynchronizedBlockNode(ASTSynchronizedBlockNode node);
public void caseASTLabeledBlockNode(ASTLabeledBlockNode node);
public void caseASTUnconditionalLoopNode(ASTUnconditionalLoopNode node);
public void caseASTSwitchNode(ASTSwitchNode node);
public void caseASTIfNode(ASTIfNode node);
public void caseASTIfElseNode(ASTIfElseNode node);
public void caseASTWhileNode(ASTWhileNode node);
public void caseASTForLoopNode(ASTForLoopNode node);
public void caseASTDoWhileNode(ASTDoWhileNode node);
public void caseASTTryNode(ASTTryNode node);
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node);
public void caseASTUnaryCondition(ASTUnaryCondition uc);
public void caseASTBinaryCondition(ASTBinaryCondition bc);
public void caseASTAndCondition(ASTAndCondition ac);
public void caseASTOrCondition(ASTOrCondition oc);
public void caseType(Type t);
public void caseDefinitionStmt(DefinitionStmt s);
public void caseReturnStmt(ReturnStmt s);
public void caseInvokeStmt(InvokeStmt s);
public void caseThrowStmt(ThrowStmt s);
public void caseDVariableDeclarationStmt(DVariableDeclarationStmt s);
public void caseStmt(Stmt s);
public void caseValue(Value v);
public void caseExpr(Expr e);
public void caseRef(Ref r);
public void caseBinopExpr(BinopExpr be);
public void caseUnopExpr(UnopExpr ue);
public void caseNewArrayExpr(NewArrayExpr nae);
public void caseNewMultiArrayExpr(NewMultiArrayExpr nmae);
public void caseInstanceOfExpr(InstanceOfExpr ioe);
public void caseInvokeExpr(InvokeExpr ie);
public void caseInstanceInvokeExpr(InstanceInvokeExpr iie);
public void caseCastExpr(CastExpr ce);
public void caseArrayRef(ArrayRef ar);
public void caseInstanceFieldRef(InstanceFieldRef ifr);
public void caseStaticFieldRef(StaticFieldRef sfr);
}
| 4,237
| 29.489209
| 74
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/analysis/AnalysisAdapter.java
|
package soot.dava.toolkits.base.AST.analysis;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.Type;
import soot.Value;
import soot.dava.internal.AST.ASTAndCondition;
import soot.dava.internal.AST.ASTBinaryCondition;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTOrCondition;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.AST.ASTUnaryCondition;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.javaRep.DVariableDeclarationStmt;
import soot.jimple.ArrayRef;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.Expr;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.Ref;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UnopExpr;
public class AnalysisAdapter implements Analysis {
public void defaultCase(Object o) {
// do nothing
}
public void caseASTMethodNode(ASTMethodNode node) {
defaultCase(node);
}
public void caseASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
defaultCase(node);
}
public void caseASTLabeledBlockNode(ASTLabeledBlockNode node) {
defaultCase(node);
}
public void caseASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
defaultCase(node);
}
public void caseASTSwitchNode(ASTSwitchNode node) {
defaultCase(node);
}
public void caseASTIfNode(ASTIfNode node) {
defaultCase(node);
}
public void caseASTIfElseNode(ASTIfElseNode node) {
defaultCase(node);
}
public void caseASTWhileNode(ASTWhileNode node) {
defaultCase(node);
}
public void caseASTForLoopNode(ASTForLoopNode node) {
defaultCase(node);
}
public void caseASTDoWhileNode(ASTDoWhileNode node) {
defaultCase(node);
}
public void caseASTTryNode(ASTTryNode node) {
defaultCase(node);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
defaultCase(node);
}
public void caseASTUnaryCondition(ASTUnaryCondition uc) {
defaultCase(uc);
}
public void caseASTBinaryCondition(ASTBinaryCondition bc) {
defaultCase(bc);
}
public void caseASTAndCondition(ASTAndCondition ac) {
defaultCase(ac);
}
public void caseASTOrCondition(ASTOrCondition oc) {
defaultCase(oc);
}
public void caseType(Type t) {
defaultCase(t);
}
public void caseDefinitionStmt(DefinitionStmt s) {
defaultCase(s);
}
public void caseReturnStmt(ReturnStmt s) {
defaultCase(s);
}
public void caseInvokeStmt(InvokeStmt s) {
defaultCase(s);
}
public void caseThrowStmt(ThrowStmt s) {
defaultCase(s);
}
public void caseDVariableDeclarationStmt(DVariableDeclarationStmt s) {
defaultCase(s);
}
public void caseStmt(Stmt s) {
defaultCase(s);
}
public void caseValue(Value v) {
defaultCase(v);
}
public void caseExpr(Expr e) {
defaultCase(e);
}
public void caseRef(Ref r) {
defaultCase(r);
}
public void caseBinopExpr(BinopExpr be) {
defaultCase(be);
}
public void caseUnopExpr(UnopExpr ue) {
defaultCase(ue);
}
public void caseNewArrayExpr(NewArrayExpr nae) {
defaultCase(nae);
}
public void caseNewMultiArrayExpr(NewMultiArrayExpr nmae) {
defaultCase(nmae);
}
public void caseInstanceOfExpr(InstanceOfExpr ioe) {
defaultCase(ioe);
}
public void caseInvokeExpr(InvokeExpr ie) {
defaultCase(ie);
}
public void caseInstanceInvokeExpr(InstanceInvokeExpr iie) {
defaultCase(iie);
}
public void caseCastExpr(CastExpr ce) {
defaultCase(ce);
}
public void caseArrayRef(ArrayRef ar) {
defaultCase(ar);
}
public void caseInstanceFieldRef(InstanceFieldRef ifr) {
defaultCase(ifr);
}
public void caseStaticFieldRef(StaticFieldRef sfr) {
defaultCase(sfr);
}
}
| 5,304
| 23.447005
| 75
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/analysis/DepthFirstAdapter.java
|
package soot.dava.toolkits.base.AST.analysis;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.Immediate;
import soot.Local;
import soot.SootClass;
import soot.Type;
import soot.Value;
import soot.ValueBox;
import soot.dava.internal.AST.ASTAndCondition;
import soot.dava.internal.AST.ASTBinaryCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTOrCondition;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.AST.ASTUnaryCondition;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DInstanceFieldRef;
import soot.dava.internal.javaRep.DThisRef;
import soot.dava.internal.javaRep.DVariableDeclarationStmt;
import soot.jimple.ArrayRef;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.Expr;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.Ref;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UnopExpr;
/*
* CHANGE LOG: 18th MArch 2006: Need a reference to the ValueBox holding a BinOp for SimplifyExpressions
* Need to create a level of indirection i.e. instead of retrieving Values e.g. from stmts retrieve the valueBox
* and then apply on the value inside the valuebox
*/
public class DepthFirstAdapter extends AnalysisAdapter {
public boolean DEBUG = false;
boolean verbose = false;
public DepthFirstAdapter() {
}
public DepthFirstAdapter(boolean verbose) {
this.verbose = verbose;
}
public void inASTMethodNode(ASTMethodNode node) {
if (verbose) {
System.out.println("inASTMethodNode");
}
}
public void outASTMethodNode(ASTMethodNode node) {
if (verbose) {
System.out.println("outASTMethodNode");
}
}
public void caseASTMethodNode(ASTMethodNode node) {
inASTMethodNode(node);
normalRetrieving(node);
outASTMethodNode(node);
}
public void inASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
if (verbose) {
System.out.println("inASTSynchronizedBlockNode");
}
}
public void outASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
if (verbose) {
System.out.println("outASTSynchronizedBlockNode");
}
}
public void caseASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
inASTSynchronizedBlockNode(node);
/*
* apply on the local on which synchronization is done MArch 18th, 2006: since getLocal returns a local always dont need
* a valuebox for this
*/
Value local = node.getLocal();
decideCaseExprOrRef(local);
/*
* apply on the body of the synch block
*/
normalRetrieving(node);
outASTSynchronizedBlockNode(node);
}
public void inASTLabeledBlockNode(ASTLabeledBlockNode node) {
if (verbose) {
System.out.println("inASTLabeledBlockNode");
}
}
public void outASTLabeledBlockNode(ASTLabeledBlockNode node) {
if (verbose) {
System.out.println("outASTLabeledBlockNode");
}
}
public void caseASTLabeledBlockNode(ASTLabeledBlockNode node) {
inASTLabeledBlockNode(node);
normalRetrieving(node);
outASTLabeledBlockNode(node);
}
public void inASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
if (verbose) {
System.out.println("inASTUnconditionalWhileNode");
}
}
public void outASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
if (verbose) {
System.out.println("outASTUnconditionalWhileNode");
}
}
public void caseASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
inASTUnconditionalLoopNode(node);
normalRetrieving(node);
outASTUnconditionalLoopNode(node);
}
public void inASTSwitchNode(ASTSwitchNode node) {
if (verbose) {
System.out.println("inASTSwitchNode");
}
}
public void outASTSwitchNode(ASTSwitchNode node) {
if (verbose) {
System.out.println("outASTSwitchNode");
}
}
public void caseASTSwitchNode(ASTSwitchNode node) {
inASTSwitchNode(node);
/*
* apply on key of switchStatement
*/
/*
* March 18th 2006, added level of indirection to have access to value box Value key = node.get_Key();
* decideCaseExprOrRef(key);
*/
caseExprOrRefValueBox(node.getKeyBox());
/*
* Apply on bodies of switch cases
*/
normalRetrieving(node);
outASTSwitchNode(node);
}
public void inASTIfNode(ASTIfNode node) {
if (verbose) {
System.out.println("inASTIfNode");
}
}
public void outASTIfNode(ASTIfNode node) {
if (verbose) {
System.out.println("outASTIfNode");
}
}
public void caseASTIfNode(ASTIfNode node) {
inASTIfNode(node);
/*
* apply on the ASTCondition
*/
ASTCondition condition = node.get_Condition();
condition.apply(this);
/*
* Apply on the if body
*/
normalRetrieving(node);
outASTIfNode(node);
}
public void inASTIfElseNode(ASTIfElseNode node) {
if (verbose) {
System.out.println("inASTIfElseNode");
}
}
public void outASTIfElseNode(ASTIfElseNode node) {
if (verbose) {
System.out.println("outASTIfElseNode");
}
}
public void caseASTIfElseNode(ASTIfElseNode node) {
inASTIfElseNode(node);
/*
* apply on the ASTCondition
*/
ASTCondition condition = node.get_Condition();
condition.apply(this);
/*
* Apply on the if body followed by the else body
*/
normalRetrieving(node);
outASTIfElseNode(node);
}
public void inASTWhileNode(ASTWhileNode node) {
if (verbose) {
System.out.println("inASTWhileNode");
}
}
public void outASTWhileNode(ASTWhileNode node) {
if (verbose) {
System.out.println("outASTWhileNode");
}
}
public void caseASTWhileNode(ASTWhileNode node) {
inASTWhileNode(node);
/*
* apply on the ASTCondition
*/
ASTCondition condition = node.get_Condition();
condition.apply(this);
/*
* Apply on the while body
*/
normalRetrieving(node);
outASTWhileNode(node);
}
public void inASTForLoopNode(ASTForLoopNode node) {
if (verbose) {
System.out.println("inASTForLoopNode");
}
}
public void outASTForLoopNode(ASTForLoopNode node) {
if (verbose) {
System.out.println("outASTForLoopNode");
}
}
public void caseASTForLoopNode(ASTForLoopNode node) {
inASTForLoopNode(node);
/*
* Apply on init
*/
for (AugmentedStmt as : node.getInit()) {
Stmt s = as.get_Stmt();
if (s instanceof DefinitionStmt) {
caseDefinitionStmt((DefinitionStmt) s);
} else if (s instanceof ReturnStmt) {
caseReturnStmt((ReturnStmt) s);
} else if (s instanceof InvokeStmt) {
caseInvokeStmt((InvokeStmt) s);
} else if (s instanceof ThrowStmt) {
caseThrowStmt((ThrowStmt) s);
} else {
caseStmt(s);
}
}
/*
* apply on the ASTCondition
*/
ASTCondition condition = node.get_Condition();
condition.apply(this);
/*
* Apply on update
*/
for (AugmentedStmt as : node.getUpdate()) {
Stmt s = as.get_Stmt();
if (s instanceof DefinitionStmt) {
caseDefinitionStmt((DefinitionStmt) s);
} else if (s instanceof ReturnStmt) {
caseReturnStmt((ReturnStmt) s);
} else if (s instanceof InvokeStmt) {
caseInvokeStmt((InvokeStmt) s);
} else if (s instanceof ThrowStmt) {
caseThrowStmt((ThrowStmt) s);
} else {
caseStmt(s);
}
}
/*
* Apply on the for body
*/
normalRetrieving(node);
outASTForLoopNode(node);
}
public void inASTDoWhileNode(ASTDoWhileNode node) {
if (verbose) {
System.out.println("inASTDoWhileNode");
}
}
public void outASTDoWhileNode(ASTDoWhileNode node) {
if (verbose) {
System.out.println("outASTDoWhileNode");
}
}
public void caseASTDoWhileNode(ASTDoWhileNode node) {
inASTDoWhileNode(node);
/*
* apply on the ASTCondition
*/
ASTCondition condition = node.get_Condition();
condition.apply(this);
/*
* Apply on the while body
*/
normalRetrieving(node);
outASTDoWhileNode(node);
}
public void inASTTryNode(ASTTryNode node) {
if (verbose) {
System.out.println("inASTTryNode");
}
}
public void outASTTryNode(ASTTryNode node) {
if (verbose) {
System.out.println("outASTTryNode");
}
}
public void caseASTTryNode(ASTTryNode node) {
inASTTryNode(node);
// get try body
List<Object> tryBody = node.get_TryBody();
Iterator<Object> it = tryBody.iterator();
// go over the ASTNodes in this tryBody and apply
while (it.hasNext()) {
((ASTNode) it.next()).apply(this);
}
Map<Object, Object> exceptionMap = node.get_ExceptionMap();
Map<Object, Object> paramMap = node.get_ParamMap();
// get catch list and apply on the following
// a, type of exception caught
// b, local of exception
// c, catchBody
List<Object> catchList = node.get_CatchList();
Iterator itBody = null;
it = catchList.iterator();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container) it.next();
SootClass sootClass = ((SootClass) exceptionMap.get(catchBody));
Type type = sootClass.getType();
// apply on type of exception
caseType(type);
// apply on local of exception
Local local = (Local) paramMap.get(catchBody);
/*
* March 18th, 2006, Since these are always locals we dont have access to ValueBox
*/
decideCaseExprOrRef(local);
// apply on catchBody
List body = (List) catchBody.o;
itBody = body.iterator();
while (itBody.hasNext()) {
((ASTNode) itBody.next()).apply(this);
}
}
outASTTryNode(node);
}
public void inASTUnaryCondition(ASTUnaryCondition uc) {
if (verbose) {
System.out.println("inASTUnaryCondition");
}
}
public void outASTUnaryCondition(ASTUnaryCondition uc) {
if (verbose) {
System.out.println("outASTUnaryCondition");
}
}
public void caseASTUnaryCondition(ASTUnaryCondition uc) {
inASTUnaryCondition(uc);
// apply on the value
decideCaseExprOrRef(uc.getValue());
outASTUnaryCondition(uc);
}
public void inASTBinaryCondition(ASTBinaryCondition bc) {
if (verbose) {
System.out.println("inASTBinaryCondition");
}
}
public void outASTBinaryCondition(ASTBinaryCondition bc) {
if (verbose) {
System.out.println("outASTBinaryCondition");
}
}
public void caseASTBinaryCondition(ASTBinaryCondition bc) {
inASTBinaryCondition(bc);
ConditionExpr condition = bc.getConditionExpr();
// calling decideCaseExprOrRef although we know for sure this is an Expr but doesnt matter
decideCaseExprOrRef(condition);
outASTBinaryCondition(bc);
}
public void inASTAndCondition(ASTAndCondition ac) {
if (verbose) {
System.out.println("inASTAndCondition");
}
}
public void outASTAndCondition(ASTAndCondition ac) {
if (verbose) {
System.out.println("outASTAndCondition");
}
}
public void caseASTAndCondition(ASTAndCondition ac) {
inASTAndCondition(ac);
((ac.getLeftOp())).apply(this);
((ac.getRightOp())).apply(this);
outASTAndCondition(ac);
}
public void inASTOrCondition(ASTOrCondition oc) {
if (verbose) {
System.out.println("inASTOrCondition");
}
}
public void outASTOrCondition(ASTOrCondition oc) {
if (verbose) {
System.out.println("outASTOrCondition");
}
}
public void caseASTOrCondition(ASTOrCondition oc) {
inASTOrCondition(oc);
((oc.getLeftOp())).apply(this);
((oc.getRightOp())).apply(this);
outASTOrCondition(oc);
}
public void inType(Type t) {
if (verbose) {
System.out.println("inType");
}
}
public void outType(Type t) {
if (verbose) {
System.out.println("outType");
}
}
public void caseType(Type t) {
inType(t);
outType(t);
}
public void normalRetrieving(ASTNode node) {
// from the Node get the subBodes
Iterator<Object> sbit = node.get_SubBodies().iterator();
while (sbit.hasNext()) {
Object subBody = sbit.next();
Iterator it = ((List) subBody).iterator();
// go over the ASTNodes in this subBody and apply
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
temp.apply(this);
}
} // end of going over subBodies
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
if (verbose) {
System.out.println("inASTStatementSequenceNode");
}
}
public void outASTStatementSequenceNode(ASTStatementSequenceNode node) {
if (verbose) {
System.out.println("outASTStatementSequenceNode");
}
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
inASTStatementSequenceNode(node);
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
/*
* Do a case by case check of possible statements and invoke the case methods from within this method.
*
* cant use apply since the Statements are defined in some other package and dont want to change code all over the
* place
*/
if (s instanceof DefinitionStmt) {
caseDefinitionStmt((DefinitionStmt) s);
} else if (s instanceof ReturnStmt) {
caseReturnStmt((ReturnStmt) s);
} else if (s instanceof InvokeStmt) {
caseInvokeStmt((InvokeStmt) s);
} else if (s instanceof ThrowStmt) {
caseThrowStmt((ThrowStmt) s);
} else if (s instanceof DVariableDeclarationStmt) {
caseDVariableDeclarationStmt((DVariableDeclarationStmt) s);
} else {
caseStmt(s);
}
} // end of while going through the statement sequence
outASTStatementSequenceNode(node);
}
public void inDefinitionStmt(DefinitionStmt s) {
if (verbose) {
System.out.println("inDefinitionStmt" + s);
}
}
public void outDefinitionStmt(DefinitionStmt s) {
if (verbose) {
System.out.println("outDefinitionStmt");
}
}
public void caseDefinitionStmt(DefinitionStmt s) {
inDefinitionStmt(s);
/*
* March 18th, 2006 introducing level of indirection decideCaseExprOrRef(s.getRightOp());
* decideCaseExprOrRef(s.getLeftOp());
*/
caseExprOrRefValueBox(s.getRightOpBox());
caseExprOrRefValueBox(s.getLeftOpBox());
outDefinitionStmt(s);
}
public void inReturnStmt(ReturnStmt s) {
if (verbose) {
System.out.println("inReturnStmt");
// System.out.println("Return Stmt:"+s);
}
}
public void outReturnStmt(ReturnStmt s) {
if (verbose) {
System.out.println("outReturnStmt");
}
}
public void caseReturnStmt(ReturnStmt s) {
inReturnStmt(s);
/*
* MArch 18th 2006 decideCaseExprOrRef(s.getOp());
*/
caseExprOrRefValueBox(s.getOpBox());
outReturnStmt(s);
}
public void inInvokeStmt(InvokeStmt s) {
if (verbose) {
System.out.println("inInvokeStmt");
}
}
public void outInvokeStmt(InvokeStmt s) {
if (verbose) {
System.out.println("outInvokeStmt");
}
}
public void caseInvokeStmt(InvokeStmt s) {
inInvokeStmt(s);
caseExprOrRefValueBox(s.getInvokeExprBox());
// decideCaseExprOrRef(s.getInvokeExpr());
outInvokeStmt(s);
}
public void inThrowStmt(ThrowStmt s) {
if (verbose) {
System.out.println("\n\ninThrowStmt\n\n");
}
}
public void outThrowStmt(ThrowStmt s) {
if (verbose) {
System.out.println("outThrowStmt");
}
}
public void caseThrowStmt(ThrowStmt s) {
inThrowStmt(s);
caseExprOrRefValueBox(s.getOpBox());
// decideCaseExprOrRef(s.getOp());
outThrowStmt(s);
}
public void inDVariableDeclarationStmt(DVariableDeclarationStmt s) {
if (verbose) {
System.out.println("\n\ninDVariableDeclarationStmt\n\n" + s);
}
}
public void outDVariableDeclarationStmt(DVariableDeclarationStmt s) {
if (verbose) {
System.out.println("outDVariableDeclarationStmt");
}
}
public void caseDVariableDeclarationStmt(DVariableDeclarationStmt s) {
inDVariableDeclarationStmt(s);
// a variableDeclarationStmt has a type followed by a list of locals
Type type = s.getType();
caseType(type);
List listDeclared = s.getDeclarations();
Iterator it = listDeclared.iterator();
while (it.hasNext()) {
Local declared = (Local) it.next();
decideCaseExprOrRef(declared);
}
outDVariableDeclarationStmt(s);
}
public void inStmt(Stmt s) {
if (verbose) {
System.out.println("inStmt: " + s);
}
/*
* if(s instanceof DAbruptStmt) System.out.println("DAbruptStmt: "+s); if(s instanceof ReturnVoidStmt)
* System.out.println("ReturnVoidStmt: "+s);
*/
}
public void outStmt(Stmt s) {
if (verbose) {
System.out.println("outStmt");
}
}
public void caseStmt(Stmt s) {
inStmt(s);
outStmt(s);
}
/*
* March 18th 2006, Adding new indirection
*/
public void caseExprOrRefValueBox(ValueBox vb) {
inExprOrRefValueBox(vb);
decideCaseExprOrRef(vb.getValue());
outExprOrRefValueBox(vb);
}
public void inExprOrRefValueBox(ValueBox vb) {
if (verbose) {
System.out.println("inExprOrRefValueBox" + vb);
}
}
public void outExprOrRefValueBox(ValueBox vb) {
if (verbose) {
System.out.println("outExprOrRefValueBox" + vb);
}
}
public void decideCaseExprOrRef(Value v) {
if (v instanceof Expr) {
caseExpr((Expr) v);
} else if (v instanceof Ref) {
caseRef((Ref) v);
} else {
caseValue(v);
}
}
public void inValue(Value v) {
if (verbose) {
System.out.println("inValue" + v);
if (v instanceof DThisRef) {
System.out.println("DTHISREF.................");
} else if (v instanceof Immediate) {
System.out.println("\tIMMEDIATE");
if (v instanceof soot.jimple.internal.JimpleLocal) {
System.out.println("\t\tJimpleLocal...................." + v);
} else if (v instanceof Constant) {
System.out.println("\t\tconstant....................");
if (v instanceof IntConstant) {
System.out.println("\t\t INTconstant....................");
}
} else if (v instanceof soot.baf.internal.BafLocal) {
System.out.println("\t\tBafLocal....................");
} else {
System.out.println("\t\telse!!!!!!!!!!!!");
}
} else {
System.out.println("NEITHER................");
}
}
}
public void outValue(Value v) {
if (verbose) {
System.out.println("outValue");
}
}
public void caseValue(Value v) {
inValue(v);
outValue(v);
}
public void inExpr(Expr e) {
if (verbose) {
System.out.println("inExpr");
}
}
public void outExpr(Expr e) {
if (verbose) {
System.out.println("outExpr");
}
}
public void caseExpr(Expr e) {
inExpr(e);
decideCaseExpr(e);
outExpr(e);
}
public void inRef(Ref r) {
if (verbose) {
System.out.println("inRef");
}
}
public void outRef(Ref r) {
if (verbose) {
System.out.println("outRef");
}
}
public void caseRef(Ref r) {
inRef(r);
decideCaseRef(r);
outRef(r);
}
public void decideCaseExpr(Expr e) {
if (e instanceof BinopExpr) {
caseBinopExpr((BinopExpr) e);
} else if (e instanceof UnopExpr) {
caseUnopExpr((UnopExpr) e);
} else if (e instanceof NewArrayExpr) {
caseNewArrayExpr((NewArrayExpr) e);
} else if (e instanceof NewMultiArrayExpr) {
caseNewMultiArrayExpr((NewMultiArrayExpr) e);
} else if (e instanceof InstanceOfExpr) {
caseInstanceOfExpr((InstanceOfExpr) e);
} else if (e instanceof InvokeExpr) {
caseInvokeExpr((InvokeExpr) e);
} else if (e instanceof CastExpr) {
caseCastExpr((CastExpr) e);
}
}
public void inBinopExpr(BinopExpr be) {
if (verbose) {
System.out.println("inBinopExpr");
}
}
public void outBinopExpr(BinopExpr be) {
if (verbose) {
System.out.println("outBinopExpr");
}
}
public void caseBinopExpr(BinopExpr be) {
inBinopExpr(be);
caseExprOrRefValueBox(be.getOp1Box());
caseExprOrRefValueBox(be.getOp2Box());
// decideCaseExprOrRef(be.getOp1());
// decideCaseExprOrRef(be.getOp2());
outBinopExpr(be);
}
public void inUnopExpr(UnopExpr ue) {
if (verbose) {
System.out.println("inUnopExpr");
}
}
public void outUnopExpr(UnopExpr ue) {
if (verbose) {
System.out.println("outUnopExpr");
}
}
public void caseUnopExpr(UnopExpr ue) {
inUnopExpr(ue);
caseExprOrRefValueBox(ue.getOpBox());
// decideCaseExprOrRef(ue.getOp());
outUnopExpr(ue);
}
public void inNewArrayExpr(NewArrayExpr nae) {
if (verbose) {
System.out.println("inNewArrayExpr");
}
}
public void outNewArrayExpr(NewArrayExpr nae) {
if (verbose) {
System.out.println("outNewArrayExpr");
}
}
public void caseNewArrayExpr(NewArrayExpr nae) {
inNewArrayExpr(nae);
caseExprOrRefValueBox(nae.getSizeBox());
// decideCaseExprOrRef(nae.getSize());
outNewArrayExpr(nae);
}
public void inNewMultiArrayExpr(NewMultiArrayExpr nmae) {
if (verbose) {
System.out.println("inNewMultiArrayExpr");
}
}
public void outNewMultiArrayExpr(NewMultiArrayExpr nmae) {
if (verbose) {
System.out.println("outNewMultiArrayExpr");
}
}
public void caseNewMultiArrayExpr(NewMultiArrayExpr nmae) {
inNewMultiArrayExpr(nmae);
for (int i = 0; i < nmae.getSizeCount(); i++) {
caseExprOrRefValueBox(nmae.getSizeBox(i));
// decideCaseExprOrRef(nmae.getSize(i));
}
outNewMultiArrayExpr(nmae);
}
public void inInstanceOfExpr(InstanceOfExpr ioe) {
if (verbose) {
System.out.println("inInstanceOfExpr");
}
}
public void outInstanceOfExpr(InstanceOfExpr ioe) {
if (verbose) {
System.out.println("outInstanceOfExpr");
}
}
public void caseInstanceOfExpr(InstanceOfExpr ioe) {
inInstanceOfExpr(ioe);
caseExprOrRefValueBox(ioe.getOpBox());
// decideCaseExprOrRef(ioe.getOp());
outInstanceOfExpr(ioe);
}
public void inInvokeExpr(InvokeExpr ie) {
if (verbose) {
System.out.println("inInvokeExpr");
}
}
public void outInvokeExpr(InvokeExpr ie) {
if (verbose) {
System.out.println("outInvokeExpr");
}
}
public void caseInvokeExpr(InvokeExpr ie) {
inInvokeExpr(ie);
for (int i = 0; i < ie.getArgCount(); i++) {
caseExprOrRefValueBox(ie.getArgBox(i));
// decideCaseExprOrRef(ie.getArg(i));
}
if (ie instanceof InstanceInvokeExpr) {
caseInstanceInvokeExpr((InstanceInvokeExpr) ie);
}
outInvokeExpr(ie);
}
public void inInstanceInvokeExpr(InstanceInvokeExpr iie) {
if (verbose) {
System.out.println("inInstanceInvokeExpr");
}
}
public void outInstanceInvokeExpr(InstanceInvokeExpr iie) {
if (verbose) {
System.out.println("outInstanceInvokeExpr");
}
}
public void caseInstanceInvokeExpr(InstanceInvokeExpr iie) {
inInstanceInvokeExpr(iie);
caseExprOrRefValueBox(iie.getBaseBox());
// decideCaseExprOrRef(iie.getBase());
outInstanceInvokeExpr(iie);
}
public void inCastExpr(CastExpr ce) {
if (verbose) {
System.out.println("inCastExpr");
}
}
public void outCastExpr(CastExpr ce) {
if (verbose) {
System.out.println("outCastExpr");
}
}
public void caseCastExpr(CastExpr ce) {
inCastExpr(ce);
Type type = ce.getCastType();
caseType(type);
caseExprOrRefValueBox(ce.getOpBox());
// Value op = ce.getOp();
// decideCaseExprOrRef(op);
outCastExpr(ce);
}
public void decideCaseRef(Ref r) {
if (r instanceof ArrayRef) {
caseArrayRef((ArrayRef) r);
} else if (r instanceof InstanceFieldRef) {
caseInstanceFieldRef((InstanceFieldRef) r);
} else if (r instanceof StaticFieldRef) {
caseStaticFieldRef((StaticFieldRef) r);
}
}
public void inArrayRef(ArrayRef ar) {
if (verbose) {
System.out.println("inArrayRef");
}
}
public void outArrayRef(ArrayRef ar) {
if (verbose) {
System.out.println("outArrayRef");
}
}
public void caseArrayRef(ArrayRef ar) {
inArrayRef(ar);
caseExprOrRefValueBox(ar.getBaseBox());
caseExprOrRefValueBox(ar.getIndexBox());
// decideCaseExprOrRef(ar.getBase());
// decideCaseExprOrRef(ar.getIndex());
outArrayRef(ar);
}
public void inInstanceFieldRef(InstanceFieldRef ifr) {
if (verbose) {
System.out.println("inInstanceFieldRef");
if (ifr instanceof DInstanceFieldRef) {
System.out.println("...........DINSTANCEFIELDREF");
}
}
}
public void outInstanceFieldRef(InstanceFieldRef ifr) {
if (verbose) {
System.out.println("outInstanceFieldRef");
}
}
public void caseInstanceFieldRef(InstanceFieldRef ifr) {
inInstanceFieldRef(ifr);
caseExprOrRefValueBox(ifr.getBaseBox());
// decideCaseExprOrRef(ifr.getBase());
outInstanceFieldRef(ifr);
}
public void inStaticFieldRef(StaticFieldRef sfr) {
if (verbose) {
System.out.println("inStaticFieldRef");
}
}
public void outStaticFieldRef(StaticFieldRef sfr) {
if (verbose) {
System.out.println("outStaticFieldRef");
}
}
public void caseStaticFieldRef(StaticFieldRef sfr) {
inStaticFieldRef(sfr);
outStaticFieldRef(sfr);
}
public void debug(String className, String methodName, String debug) {
if (DEBUG) {
System.out.println("Analysis" + className + "..Method:" + methodName + " DEBUG: " + debug);
}
}
}
| 27,812
| 23.548102
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/interProcedural/ConstantFieldValueFinder.java
|
package soot.dava.toolkits.base.AST.interProcedural;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Nomair A. Naeem
* %%
* 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.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.PrimType;
import soot.ShortType;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.Value;
import soot.dava.DavaBody;
import soot.dava.DecompilationException;
import soot.dava.internal.AST.ASTNode;
import soot.dava.toolkits.base.AST.traversals.AllDefinitionsFinder;
import soot.jimple.DefinitionStmt;
import soot.jimple.DoubleConstant;
import soot.jimple.FieldRef;
import soot.jimple.FloatConstant;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.NumericConstant;
import soot.tagkit.DoubleConstantValueTag;
import soot.tagkit.FloatConstantValueTag;
import soot.tagkit.IntegerConstantValueTag;
import soot.tagkit.LongConstantValueTag;
import soot.util.Chain;
/*
* Deemed important because of obfuscation techniques which add crazy
* control flow under some condition which is never executed because
* it uses some field which is always false!!
*
* Goal:
* Prove that a field is never assigned a value or that if it is assigned a value
* we can statically tell this value
*
*
*/
public class ConstantFieldValueFinder {
public final boolean DEBUG = false;
public static String combiner = "_$p$g_";
private final HashMap<String, SootField> classNameFieldNameToSootFieldMapping = new HashMap<>();
private final HashMap<String, ArrayList<Value>> fieldToValues = new HashMap<>();
private final HashMap<String, Object> primTypeFieldValueToUse = new HashMap<>();
private final Chain<SootClass> appClasses;
public ConstantFieldValueFinder(Chain<SootClass> classes) {
appClasses = classes;
debug("ConstantFieldValueFinder -- applyAnalyses", "computing Method Summaries");
computeFieldToValuesAssignedList();
valuesForPrimTypeFields();
}
/*
* The hashMap returned contains a mapping of class + combiner + field ----> Double/Float/Long/Integer if there is no
* mapping for a particular field then that means we couldnt detect a constant value for it
*/
public HashMap<String, Object> getFieldsWithConstantValues() {
return primTypeFieldValueToUse;
}
public HashMap<String, SootField> getClassNameFieldNameToSootFieldMapping() {
return classNameFieldNameToSootFieldMapping;
}
/*
* This method gives values to all the fields in all the classes if they can be determined statically We only care about
* fields which have primitive types
*/
private void valuesForPrimTypeFields() {
// go through all the classes
for (SootClass s : appClasses) {
debug("\nvaluesforPrimTypeFields", "Processing class " + s.getName());
String declaringClass = s.getName();
// all fields of the class
for (SootField f : s.getFields()) {
Type fieldType = f.getType();
if (!(fieldType instanceof PrimType)) {
continue;
}
String combined = declaringClass + combiner + f.getName();
classNameFieldNameToSootFieldMapping.put(combined, f);
Object value = null;
// check for constant value tags
if (fieldType instanceof DoubleType) {
DoubleConstantValueTag t = (DoubleConstantValueTag) f.getTag(DoubleConstantValueTag.NAME);
if (t != null) {
value = t.getDoubleValue();
}
} else if (fieldType instanceof FloatType) {
FloatConstantValueTag t = (FloatConstantValueTag) f.getTag(FloatConstantValueTag.NAME);
if (t != null) {
value = t.getFloatValue();
}
} else if (fieldType instanceof LongType) {
LongConstantValueTag t = (LongConstantValueTag) f.getTag(LongConstantValueTag.NAME);
if (t != null) {
value = t.getLongValue();
}
} else if (fieldType instanceof CharType) {
IntegerConstantValueTag t = (IntegerConstantValueTag) f.getTag(IntegerConstantValueTag.NAME);
if (t != null) {
value = t.getIntValue();
}
} else if (fieldType instanceof BooleanType) {
IntegerConstantValueTag t = (IntegerConstantValueTag) f.getTag(IntegerConstantValueTag.NAME);
if (t != null) {
value = (t.getIntValue() != 0);
}
} else if (fieldType instanceof IntType || fieldType instanceof ByteType || fieldType instanceof ShortType) {
IntegerConstantValueTag t = (IntegerConstantValueTag) f.getTag(IntegerConstantValueTag.NAME);
if (t != null) {
value = t.getIntValue();
}
}
// if there was a constant value tag we have its value now
if (value != null) {
debug("TAGGED value found for field: " + combined);
primTypeFieldValueToUse.put(combined, value);
// continue with next field
continue;
}
// see if the field was never assigned in which case it gets default values
ArrayList<Value> values = fieldToValues.get(combined);
if (values == null) {
// no value list found is good
// add default value to primTypeFieldValueToUse hashmap
if (fieldType instanceof DoubleType) {
value = 0.0d;
} else if (fieldType instanceof FloatType) {
value = 0.0f;
} else if (fieldType instanceof LongType) {
value = 0L;
} else if (fieldType instanceof BooleanType) {
value = false;
} else if (fieldType instanceof IntType || fieldType instanceof ByteType || fieldType instanceof ShortType
|| fieldType instanceof CharType) {
value = 0;
} else {
throw new DecompilationException("Unknown primitive type...please report to developer");
}
primTypeFieldValueToUse.put(combined, value);
debug("DEFAULT value for field: " + combined);
// continue with next field
continue;
}
// haven't got a tag with value and havent use default since SOME method did define the field atleast once
// there was some value assigned!!!!!!!!!
debug("CHECKING USER ASSIGNED VALUES FOR: " + combined);
// check if they are all constants and that too the same constant
NumericConstant tempConstant = null;
for (Value val : values) {
if (!(val instanceof NumericConstant)) {
tempConstant = null;
debug("Not numeric constant hence giving up");
break;
}
if (tempConstant == null) {
tempConstant = (NumericConstant) val;
} else {
// check that this value is the same as previous
if (!tempConstant.equals(val)) {
tempConstant = null;
break;
}
}
}
if (tempConstant == null) {
// continue with next field cant do anything about this one
continue;
}
// agreed on a unique constant value
/*
* Since these are fields are we are doing CONTEXT INSENSITIVE WE need to make sure that the agreed unique constant
* value is the default value
*
* I KNOW IT SUCKS BUT HEY WHAT CAN I DO!!!
*/
if (tempConstant instanceof LongConstant) {
long tempVal = ((LongConstant) tempConstant).value;
if (Long.compare(tempVal, 0L) == 0) {
primTypeFieldValueToUse.put(combined, tempVal);
} else {
debug("Not assigning the agreed value since that is not the default value for " + combined);
}
} else if (tempConstant instanceof DoubleConstant) {
double tempVal = ((DoubleConstant) tempConstant).value;
if (Double.compare(tempVal, 0.0d) == 0) {
primTypeFieldValueToUse.put(combined, tempVal);
} else {
debug("Not assigning the agreed value since that is not the default value for " + combined);
}
} else if (tempConstant instanceof FloatConstant) {
float tempVal = ((FloatConstant) tempConstant).value;
if (Float.compare(tempVal, 0.0f) == 0) {
primTypeFieldValueToUse.put(combined, tempVal);
} else {
debug("Not assigning the agreed value since that is not the default value for " + combined);
}
} else if (tempConstant instanceof IntConstant) {
int tempVal = ((IntConstant) tempConstant).value;
if (Integer.compare(tempVal, 0) == 0) {
SootField tempField = classNameFieldNameToSootFieldMapping.get(combined);
if (tempField.getType() instanceof BooleanType) {
primTypeFieldValueToUse.put(combined, false);
// System.out.println("puttingvalue false for"+combined);
} else {
primTypeFieldValueToUse.put(combined, tempVal);
// System.out.println("puttingvalue 0 for"+combined);
}
} else {
debug("Not assigning the agreed value since that is not the default value for " + combined);
}
} else {
throw new DecompilationException("Un handled Numberic Constant....report to programmer");
}
}
} // all classes
}
/*
* Go through all the methods in the application and make a mapping of className+methodName ---> values assigned There can
* obviously be more than one value assigned to each field
*/
private void computeFieldToValuesAssignedList() {
// go through all the classes
for (SootClass s : appClasses) {
debug("\ncomputeMethodSummaries", "Processing class " + s.getName());
// go though all the methods
for (Iterator<SootMethod> methodIt = s.methodIterator(); methodIt.hasNext();) {
SootMethod m = methodIt.next();
if (!m.hasActiveBody()) {
continue;
}
DavaBody body = (DavaBody) m.getActiveBody();
ASTNode AST = (ASTNode) body.getUnits().getFirst();
// find all definitions in the program
AllDefinitionsFinder defFinder = new AllDefinitionsFinder();
AST.apply(defFinder);
// go through each definition
for (DefinitionStmt stmt : defFinder.getAllDefs()) {
// debug("DefinitionStmt")
Value left = stmt.getLeftOp();
/*
* Only care if we have fieldRef on the left
*/
if (!(left instanceof FieldRef)) {
continue;
}
// we know definition is to a field
debug("computeMethodSummaries method: " + m.getName(), "Field ref is: " + left);
// Information we want to store is class of field and name of field and the right op
FieldRef ref = (FieldRef) left;
SootField field = ref.getField();
/*
* Only care about fields with primtype
*/
if (!(field.getType() instanceof PrimType)) {
continue;
}
String fieldName = field.getName();
String declaringClass = field.getDeclaringClass().getName();
debug("\tField Name: " + fieldName);
debug("\tField DeclaringClass: " + declaringClass);
// get the valueList for this class+field combo
String combined = declaringClass + combiner + fieldName;
ArrayList<Value> valueList = fieldToValues.get(combined);
if (valueList == null) {
// no value of this field was yet assigned
valueList = new ArrayList<>();
fieldToValues.put(combined, valueList);
}
valueList.add(stmt.getRightOp());
} // going through all the definitions
} // going through methods of class s
}
}
public void printConstantValueFields() {
System.out.println("\n\n Printing Constant Value Fields (method: printConstantValueFields)");
for (String combined : primTypeFieldValueToUse.keySet()) {
int temp = combined.indexOf(combiner, 0);
if (temp > 0) {
System.out.println("Class: " + combined.substring(0, temp) + " Field: "
+ combined.substring(temp + combiner.length()) + " Value: " + primTypeFieldValueToUse.get(combined));
}
}
}
public void debug(String methodName, String debug) {
if (DEBUG) {
System.out.println(methodName + " DEBUG: " + debug);
}
}
public void debug(String debug) {
if (DEBUG) {
System.out.println("DEBUG: " + debug);
}
}
}
| 13,531
| 35.572973
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/interProcedural/InterProceduralAnalyses.java
|
package soot.dava.toolkits.base.AST.interProcedural;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Nomair A. Naeem
* %%
* 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 soot.PhaseOptions;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.dava.DavaBody;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.toolkits.base.AST.transformations.CPApplication;
import soot.dava.toolkits.base.AST.transformations.EliminateConditions;
import soot.dava.toolkits.base.AST.transformations.LocalVariableCleaner;
import soot.dava.toolkits.base.AST.transformations.SimplifyConditions;
import soot.dava.toolkits.base.AST.transformations.SimplifyExpressions;
import soot.dava.toolkits.base.AST.transformations.UnreachableCodeEliminator;
import soot.dava.toolkits.base.AST.transformations.UselessLabelFinder;
import soot.dava.toolkits.base.AST.transformations.VoidReturnRemover;
import soot.dava.toolkits.base.renamer.Renamer;
import soot.dava.toolkits.base.renamer.infoGatheringAnalysis;
import soot.util.Chain;
public class InterProceduralAnalyses {
public static boolean DEBUG = false;
/*
* Method is invoked by postProcessDava in PackManager if the transformations flag is true
*
* All interproceduralAnalyses should be applied in here
*/
public static void applyInterProceduralAnalyses() {
Chain<SootClass> classes = Scene.v().getApplicationClasses();
if (DEBUG) {
System.out.println("\n\nInvoking redundantFielduseEliminator");
}
ConstantFieldValueFinder finder = new ConstantFieldValueFinder(classes);
HashMap<String, Object> constantValueFields = finder.getFieldsWithConstantValues();
if (DEBUG) {
finder.printConstantValueFields();
}
/*
* The code above this gathers interprocedural information the code below this USES the interprocedural results
*/
for (SootClass s : classes) {
// go though all the methods
for (Iterator<SootMethod> methodIt = s.methodIterator(); methodIt.hasNext();) {
SootMethod m = methodIt.next();
if (!m.hasActiveBody()) {
continue;
}
DavaBody body = (DavaBody) m.getActiveBody();
ASTNode AST = (ASTNode) body.getUnits().getFirst();
if (!(AST instanceof ASTMethodNode)) {
continue;
}
boolean deobfuscate = PhaseOptions.getBoolean(PhaseOptions.v().getPhaseOptions("db.deobfuscate"), "enabled");
if (deobfuscate) {
if (DEBUG) {
System.out.println("\nSTART CP Class:" + s.getName() + " Method: " + m.getName());
}
AST.apply(
new CPApplication((ASTMethodNode) AST, constantValueFields, finder.getClassNameFieldNameToSootFieldMapping()));
if (DEBUG) {
System.out.println("DONE CP for " + m.getName());
}
}
// expression simplification
// SimplifyExpressions.DEBUG=true;
AST.apply(new SimplifyExpressions());
// SimplifyConditions.DEBUG=true;
AST.apply(new SimplifyConditions());
// condition elimination
// EliminateConditions.DEBUG=true;
AST.apply(new EliminateConditions((ASTMethodNode) AST));
// the above should ALWAYS be followed by an unreachable code eliminator
AST.apply(new UnreachableCodeEliminator(AST));
// local variable cleanup
AST.apply(new LocalVariableCleaner(AST));
// VERY EXPENSIVE STAGE of redoing all analyses!!!!
if (deobfuscate) {
if (DEBUG) {
System.out.println("reinvoking analyzeAST");
}
UselessLabelFinder.DEBUG = false;
body.analyzeAST();
}
// renaming should be applied as the last stage
if (PhaseOptions.getBoolean(PhaseOptions.v().getPhaseOptions("db.renamer"), "enabled")) {
applyRenamerAnalyses(AST, body);
}
// remove returns from void methods
VoidReturnRemover.cleanClass(s);
}
}
}
/*
* If there is any interprocedural information required it should be passed as argument to this method and then the renamer
* can make use of it.
*/
private static void applyRenamerAnalyses(ASTNode AST, DavaBody body) {
// intra procedural heuristic gathering
infoGatheringAnalysis info = new infoGatheringAnalysis(body);
AST.apply(info);
Renamer renamer = new Renamer(info.getHeuristicSet(), (ASTMethodNode) AST);
renamer.rename();
}
private InterProceduralAnalyses() {
}
}
| 5,297
| 34.086093
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/CP.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%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.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.PrimType;
import soot.ShortType;
import soot.SootField;
import soot.Type;
import soot.Value;
import soot.dava.DavaFlowAnalysisException;
import soot.dava.internal.AST.ASTBinaryCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTUnaryBinaryCondition;
import soot.dava.internal.AST.ASTUnaryCondition;
import soot.dava.internal.javaRep.DNotExpr;
import soot.dava.toolkits.base.AST.interProcedural.ConstantFieldValueFinder;
import soot.jimple.BinopExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.Stmt;
public class CP extends StructuredAnalysis {
/*
* Constant Propagation:
*
* Step 1: Sets of CPTuple (className, CPVariable, value) where: CPVariable contains a local or SootField
*
* Step 2: A local or SootField has a constant value at a program point p if on all program paths from the start of the
* method to point p the local or Sootfield has only been assigned this constant value.
*
* Step 3: Forward Analysis
*
* Step 4: Intersection (See intersection method in CPFlowSet)
*
* Step 5: See method processStatement
*
* Step 6: out(start) = all locals set to bottom(they shouldnt be present in the initialSet all formals set to Top, all
* constant fields set to constant values
*
* newInitialFlow: all locals and formals set to Top, all constant fields set to constant values remember new InitialFlow
* is ONLY used for input to catchBodies
*
* Any local or field which is not in the flow set at any time is necessarily bottom
*
*
* knowing how a condition evaluates can give us useful insight to the values of variables Handle this for a == b where
* both a and b are primtype and special case handle it for A where A is a unary boolean condition
*
* See following over-riden methods:
*
* public Object processASTIfElseNode(ASTIfElseNode node,Object input) public Object processASTIfNode(ASTIfNode node,Object
* input) public Object processASTSwitchNode(ASTSwitchNode node,Object input)
*/
ArrayList<CPTuple> constantFieldTuples = null; // VariableTuples of
// constantFields
ArrayList<CPTuple> formals = null; // VariableTuples for formals initially
// set to T
ArrayList<CPTuple> locals = null; // VariableTuples for locals initially set
// to default
ArrayList<CPTuple> initialInput = null; // VariableTuples of constantFields,
// locals set to 0 and formals set
// to T
ASTMethodNode methodNode = null;
String localClassName = null;
/*
* The start of the analysis takes place whenever this constructor is invoked
*/
public CP(ASTMethodNode analyze, HashMap<String, Object> constantFields,
HashMap<String, SootField> classNameFieldNameToSootFieldMapping) {
super();
/*
* DEBUG = true; DEBUG_IF = true; DEBUG_WHILE = true; DEBUG_STATEMENTS = true;
*/
this.methodNode = analyze;
localClassName = analyze.getDavaBody().getMethod().getDeclaringClass().getName();
// Create a list of VariableValueTuples for all the constantFields
createConstantFieldsList(constantFields, classNameFieldNameToSootFieldMapping);
// Create the complete list of vars to go into constant propagation
createInitialInput();
// input to constant propagation should not be an empty flow set it is
// the set of all constant fields, locals assigned 0 and formals
// assigned T
CPFlowSet initialSet = new CPFlowSet();
Iterator<CPTuple> it = initialInput.iterator();
while (it.hasNext()) {
initialSet.add(it.next());
}
// System.out.println("Initial set"+initialSet.toString());
CPFlowSet result = (CPFlowSet) process(analyze, initialSet);
// System.out.println("Last result :"+result.toString());
}
/*
* constant fields added with KNOWN CONSTANT VALUE formals added with TOP locals added with 0 other fields IGNORED
*/
public void createInitialInput() {
initialInput = new ArrayList<CPTuple>();
// adding constant fields
initialInput.addAll(constantFieldTuples);
// String className =
// analyze.getDavaBody().getMethod().getDeclaringClass().getName();
// adding formals
formals = new ArrayList<CPTuple>();
// System.out.println("Adding following formals: with TOP");
Collection col = methodNode.getDavaBody().get_ParamMap().values();
Iterator it = col.iterator();
while (it.hasNext()) {
Object temp = it.next();
if (temp instanceof Local) {
Local tempLocal = (Local) temp;
if (!(tempLocal.getType() instanceof PrimType)) {
continue;
}
CPVariable newVar = new CPVariable(tempLocal);
// new tuple set to top since this is a formal and we dont know
// what value we will get into it
CPTuple newTuple = new CPTuple(localClassName, newVar, true);
initialInput.add(newTuple);
formals.add(newTuple);
// System.out.print("\t"+tempLocal.getName());
}
}
// System.out.println();
// adding locals
List decLocals = methodNode.getDeclaredLocals();
it = decLocals.iterator();
locals = new ArrayList<CPTuple>();
// System.out.println("Adding following locals with default values:");
while (it.hasNext()) {
Object temp = it.next();
if (temp instanceof Local) {
Local tempLocal = (Local) temp;
Type localType = tempLocal.getType();
if (!(localType instanceof PrimType)) {
continue;
}
CPVariable newVar = new CPVariable(tempLocal);
// store the default value into this object
Object value;
// locals value is set to the default value that it can have
// depending on its type
if (localType instanceof BooleanType) {
value = new Boolean(false);
} else if (localType instanceof ByteType) {
value = new Integer(0);
} else if (localType instanceof CharType) {
value = new Integer(0);
} else if (localType instanceof DoubleType) {
value = new Double(0);
} else if (localType instanceof FloatType) {
value = new Float(0);
} else if (localType instanceof IntType) {
value = new Integer(0);
} else if (localType instanceof LongType) {
value = new Long(0);
} else if (localType instanceof ShortType) {
value = new Integer(0);
} else {
throw new DavaFlowAnalysisException("Unknown PrimType");
}
CPTuple newTuple = new CPTuple(localClassName, newVar, value);
/*
* Commenting the next line since we dont want initial Input to have any locals in it all locals are considered
* bottom initially
*/
// initialInput.add(newTuple);
locals.add(newTuple);
// System.out.print("\t"+tempLocal.getName());
} // was a local
}
// System.out.println();
}
/*
* Uses the results of the ConstantValueFinder to create a list of constantField CPTuple
*/
private void createConstantFieldsList(HashMap<String, Object> constantFields,
HashMap<String, SootField> classNameFieldNameToSootFieldMapping) {
constantFieldTuples = new ArrayList<CPTuple>();
Iterator<String> it = constantFields.keySet().iterator();
// System.out.println("Adding constant fields to initial set: ");
while (it.hasNext()) {
String combined = it.next();
int temp = combined.indexOf(ConstantFieldValueFinder.combiner, 0);
if (temp > 0) {
String className = combined.substring(0, temp);
// String fieldName = combined.substring(temp+
// ConstantFieldValueFinder.combiner.length());
SootField field = classNameFieldNameToSootFieldMapping.get(combined);
// String fieldName = field.getName();
if (!(field.getType() instanceof PrimType)) {
// we only care about PrimTypes
continue;
}
// object type is double float long boolean or integer
Object value = constantFields.get(combined);
CPVariable var = new CPVariable(field);
CPTuple newTuples = new CPTuple(className, var, value);
constantFieldTuples.add(newTuples);
// System.out.print("Class: "+className +
// " Field: "+fieldName+" Value: "+value+" ");
} else {
throw new DavaFlowAnalysisException("Second argument of VariableValuePair not a variable");
}
}
// System.out.println("");
}
@Override
public DavaFlowSet emptyFlowSet() {
return new CPFlowSet();
}
/*
* Setting the mergetype to intersection but since we are going to have constantpropagation flow sets the intersection
* method for this flow set will be invoked which defines the correct semantics of intersection for the case of constant
* propagation
*/
public void setMergeType() {
MERGETYPE = INTERSECTION;
}
/*
* newInitialFlow is invoked for the input set of the catchBodies
*
* formals initialized to top since we dont know what has happened so far in the body locals initialized to top since we
* dont know what has happened so far in the method body constant fields present with their constant value since that never
* changes
*/
@Override
public DavaFlowSet newInitialFlow() {
CPFlowSet flowSet = new CPFlowSet();
// formals and locals should be both initialized to top since we dont
// know what has happened so far in the body
ArrayList<CPTuple> localsAndFormals = new ArrayList<CPTuple>();
localsAndFormals.addAll(formals);
localsAndFormals.addAll(locals);
Iterator<CPTuple> it = localsAndFormals.iterator();
while (it.hasNext()) {
CPTuple tempTuple = (CPTuple) it.next().clone();
// just making sure all are set to Top
if (!tempTuple.isTop()) {
tempTuple.setTop();
}
flowSet.add(tempTuple);
}
// constant fields should be present with their constant value since
// that never changes
it = constantFieldTuples.iterator();
while (it.hasNext()) {
flowSet.add(it.next());
}
return flowSet;
}
@Override
public DavaFlowSet cloneFlowSet(DavaFlowSet flowSet) {
if (flowSet instanceof CPFlowSet) {
return ((CPFlowSet) flowSet).clone();
} else {
throw new RuntimeException("cloneFlowSet not implemented for other flowSet types" + flowSet.toString());
}
}
/*
* Since we are only keeping track of constant fields now there will be no kill if we were keeping track of fields then we
* woul dneed to kill all non constant fields if there was an invokeExpr
*/
@Override
public DavaFlowSet processUnaryBinaryCondition(ASTUnaryBinaryCondition cond, DavaFlowSet input) {
if (!(input instanceof CPFlowSet)) {
throw new RuntimeException("processCondition is not implemented for other flowSet types" + input.toString());
}
CPFlowSet inSet = (CPFlowSet) input;
return inSet;
}
/*
* Has no effect whatsoever on the analysis
*/
@Override
public DavaFlowSet processSynchronizedLocal(Local local, DavaFlowSet input) {
if (!(input instanceof CPFlowSet)) {
throw new RuntimeException("processSynchronized is not implemented for other flowSet types" + input.toString());
}
DavaFlowSet inSet = (DavaFlowSet) input;
return inSet;
}
/*
* no effect on the analysis since we are keeping track of non constant fields only if we were tracking other fields then
* If the value contained an invoke expr top all non constant fields similar to as done for unarybinary condition
*/
@Override
public DavaFlowSet processSwitchKey(Value key, DavaFlowSet input) {
if (!(input instanceof CPFlowSet)) {
throw new RuntimeException("processCondition is not implemented for other flowSet types" + input.toString());
}
CPFlowSet inSet = (CPFlowSet) input;
return inSet;
}
/*
* x = expr;
*
* expr is a constant
*
* epr is a local (Note we are not going to worry about fieldRefs)
*
* expr is a Unary op with neg followed by a local or field
*
* expr is actually exp1 op expr2 ..... ( x = x+1, y = i * 3, x = 3 *0
*
* expr contains an invokeExpr
*/
@Override
public DavaFlowSet processStatement(Stmt s, DavaFlowSet input) {
if (!(input instanceof CPFlowSet)) {
throw new RuntimeException("processStatement is not implemented for other flowSet types");
}
CPFlowSet inSet = (CPFlowSet) input;
if (inSet == NOPATH) {
return inSet;
}
if (!(s instanceof DefinitionStmt)) {
return inSet;
}
DefinitionStmt defStmt = (DefinitionStmt) s;
// x = expr;
// confirm that the left side is a local with a primitive type
Value left = defStmt.getLeftOp();
if (!(left instanceof Local && ((Local) left).getType() instanceof PrimType)) {
return inSet;
}
// left is a primitive primitive local
CPFlowSet toReturn = (CPFlowSet) cloneFlowSet(inSet);
/*
* KILL ANY PREVIOUS VALUE OF this local as this is an assignment Remember the returned value can be null if the element
* was not found or it was TOP
*/
Object killedValue = killButGetValueForUse((Local) left, toReturn);
Value right = defStmt.getRightOp();
Object value = CPHelper.isAConstantValue(right);
if (value != null) {
// EXPR IS A CONSTANT
if (left.getType() instanceof BooleanType) {
Integer tempValue = (Integer) value;
if (tempValue.intValue() == 0) {
value = new Boolean(false);
} else {
value = new Boolean(true);
}
}
addOrUpdate(toReturn, (Local) left, value);
} else {
// EXPR IS NOT A CONSTANT
handleMathematical(toReturn, (Local) left, right, killedValue);
}
return toReturn;
}
/*
* The returned value is the current constant associated with left. Integer/Long/Double/Float/Boolean The returned value
* can also be null if the element was not found or it was TOP
*/
public Object killButGetValueForUse(Local left, CPFlowSet toReturn) {
for (CPTuple tempTuple : toReturn) {
if (!(tempTuple.getSootClassName().equals(localClassName))) {
continue;
}
// className is the same check if the variable is the same or not
if (tempTuple.containsLocal()) { // remmeber the sets contain
// constant fields also
Local tempLocal = tempTuple.getVariable().getLocal();
if (left.getName().equals(tempLocal.getName())) {
// KILL THIS SUCKA!!!
Object killedValue = tempTuple.getValue();
tempTuple.setTop();
return killedValue;
}
}
} // going through all elements of the flow set
// if this element was no where enter it with top
CPVariable newVar = new CPVariable(left);
// create the CPTuple
// System.out.println("trying to kill something which was not present so added with TOP");
CPTuple newTuple = new CPTuple(localClassName, newVar, false);
toReturn.add(newTuple);
return null;
}
/*
* Create a CPTuple for left with the val and update the toReturn set
*/
private void addOrUpdate(CPFlowSet toReturn, Local left, Object val) {
CPVariable newVar = new CPVariable(left);
CPTuple newTuple = new CPTuple(localClassName, newVar, val);
toReturn.addIfNotPresent(newTuple);
// System.out.println("DefinitionStmt checked right expr for constants"+toReturn.toString());
}
/*
* x = b where b is in the before set of the statement as a constant then we can simply say x = that constant also
*
* TODO: DONT WANT TO DO IT:::: If right expr is a unary expression see if the stuff inside is a Local
*
* x = exp1 op exp2 (check if both exp1 and exp2 are int constants
*
* killedValuse is either the constant value which left had before this assignment stmt or null if left was Top or not in
* the set
*
* handle the special case when the inputset could not find a value because its the killed value //eg. x = x+1 since we top
* x first we will never get a match IMPORTANT
*/
private void handleMathematical(CPFlowSet toReturn, Local left, Value right, Object killedValue) {
// if right expr is a local or field
Object value = isANotTopConstantInInputSet(toReturn, right);
if (value != null) {
// right was a local or field with a value other than top
// dont send value SEND A CLONE OF VALUE.....IMPORTANT!!!!
Object toSend = CPHelper.wrapperClassCloner(value);
if (toSend != null) {
addOrUpdate(toReturn, left, toSend);
}
// return if value was != null as this means that the left was a
// primitive local assigned some value from the right
return;
}
// if we get here we know that right is not a local or field whose value
// we could find in the set
if (right instanceof BinopExpr) {
Value op1 = ((BinopExpr) right).getOp1();
Value op2 = ((BinopExpr) right).getOp2();
Object op1Val = CPHelper.isAConstantValue(op1);
Object op2Val = CPHelper.isAConstantValue(op2);
if (op1Val == null) {
op1Val = isANotTopConstantInInputSet(toReturn, op1);
}
if (op2Val == null) {
op2Val = isANotTopConstantInInputSet(toReturn, op2);
}
if (op1 == left) {
// System.out.println("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>OP1 is the same as LHS");
op1Val = killedValue;
}
if (op2 == left) {
// System.out.println("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>OP2 is the same as LHS");
op2Val = killedValue;
}
if (op1Val != null && op2Val != null) {
// System.out.println("found constant values for both operands of binary expression");
if (left.getType() instanceof IntType && op1Val instanceof Integer && op2Val instanceof Integer) {
// only caring about operations on two integers and result
// is an integer
int op1IntValue = ((Integer) op1Val).intValue();
int op2IntValue = ((Integer) op2Val).intValue();
String tempStr = ((BinopExpr) right).getSymbol();
if (tempStr.length() > 1) {
char symbol = tempStr.charAt(1);
// System.out.println("found symbol "+symbol+" for the operands of binary expression");
int newValue = 0;
boolean set = false;
switch (symbol) {
case '+':
// System.out.println("Adding");
newValue = op1IntValue + op2IntValue;
set = true;
break;
case '-':
// System.out.println("Subtracting");
newValue = op1IntValue - op2IntValue;
set = true;
break;
case '*':
// System.out.println("Multiplying");
newValue = op1IntValue * op2IntValue;
set = true;
break;
}
if (set) {
// we have our new value
Integer newValueObject = new Integer(newValue);
addOrUpdate(toReturn, left, newValueObject);
return;
}
}
}
} else {
// System.out.println("atleast one value is not constant so cant simplify expression");
}
}
// System.out.println("DefinitionStmt checked right expr for mathematical stuff"+toReturn.toString());
}
/*
* Check whether it is a local or field which has a constant value (could be top) in the current inSet
*
* The method returns null if its not found or its TOP Otherwise it will return the constant value
*/
private Object isANotTopConstantInInputSet(CPFlowSet set, Value toCheck) {
if (toCheck instanceof Local || toCheck instanceof FieldRef) {
String toCheckClassName = null;
if (toCheck instanceof Local) {
toCheckClassName = localClassName;
} else {
toCheckClassName = ((FieldRef) toCheck).getField().getDeclaringClass().getName();
}
for (CPTuple tempTuple : set) {
// check that the classNames are the same
if (!(tempTuple.getSootClassName().equals(toCheckClassName))) {
// classNames are not the same no point in continuing with
// checks
continue;
}
boolean tupleFound = false;
if (tempTuple.containsLocal() && toCheck instanceof Local) {
// check they are the same Local
Local tempLocal = tempTuple.getVariable().getLocal();
if (tempLocal.getName().equals(((Local) toCheck).getName())) {
// the set does have a constant value for this local
tupleFound = true;
}
} else if (tempTuple.containsField() && toCheck instanceof FieldRef) {
SootField toCheckField = ((FieldRef) toCheck).getField();
SootField tempField = tempTuple.getVariable().getSootField();
if (tempField.getName().equals(toCheckField.getName())) {
// the set contains a constant value for this field
tupleFound = true;
}
}
if (tupleFound) {
if (tempTuple.isTop()) {
return null;
} else {
return tempTuple.getValue();
}
}
}
}
return null;
}
/*
* over-riding the StructuredFlow Analysis implementation because we want to be able to gather information about the truth
* value in the condition
*/
@Override
public DavaFlowSet processASTIfNode(ASTIfNode node, DavaFlowSet input) {
if (DEBUG_IF) {
System.out.println("Processing if node using over-ridden process if method" + input.toString());
}
;
input = processCondition(node.get_Condition(), input);
if (!(input instanceof CPFlowSet)) {
throw new DavaFlowAnalysisException("not a flow set");
}
CPFlowSet inputToBody = ((CPFlowSet) input).clone();
CPTuple tuple = checkForValueHints(node.get_Condition(), inputToBody, false);
if (tuple != null) {
// if not null, is a belief going into the if branch simply add it
// into the input set
// System.out.println(">>>>>Adding tuple because of condition"+tuple.toString());
inputToBody.addIfNotPresentButDontUpdate(tuple);
}
DavaFlowSet output1 = processSingleSubBodyNode(node, inputToBody);
if (DEBUG_IF) {
System.out.println("\n\nINPUTS TO MERGE ARE input (original):" + input.toString() + "processingBody output:"
+ output1.toString() + "\n\n\n");
}
// merge with input which tells if the cond did not evaluate to true
DavaFlowSet output2 = merge(input, output1);
// handle break
String label = getLabel(node);
DavaFlowSet temp = handleBreak(label, output2, node);
if (DEBUG_IF) {
System.out.println("Exiting if node" + temp.toString());
}
;
return temp;
}
@Override
public DavaFlowSet processASTIfElseNode(ASTIfElseNode node, DavaFlowSet input) {
if (DEBUG_IF) {
System.out.println("Processing IF-ELSE node using over-ridden process if method" + input.toString());
}
;
if (!(input instanceof CPFlowSet)) {
throw new DavaFlowAnalysisException("not a flow set");
}
// get the subBodies
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 2) {
throw new RuntimeException("processASTIfElseNode called with a node without two subBodies");
}
// we know there is only two subBodies
List subBodyOne = (List) subBodies.get(0);
List subBodyTwo = (List) subBodies.get(1);
// process Condition
input = processCondition(node.get_Condition(), input);
// the current input flowset is sent to both branches
DavaFlowSet clonedInput = cloneFlowSet(input);
CPTuple tuple = checkForValueHints(node.get_Condition(), (CPFlowSet) clonedInput, false);
if (tuple != null) {
// if not null, is a belief going into the if branch simply add it
// into the input set
// System.out.println(">>>>>Adding tuple because of condition into if branch"+tuple.toString());
((CPFlowSet) clonedInput).addIfNotPresentButDontUpdate(tuple);
}
DavaFlowSet output1 = process(subBodyOne, clonedInput);
clonedInput = cloneFlowSet(input);
CPTuple tuple1 = checkForValueHints(node.get_Condition(), (CPFlowSet) clonedInput, true);
if (tuple1 != null) {
// if not null, is a belief going into the else branch simply add it
// into the input set
// System.out.println(">>>>>Adding tuple because of condition into else branch"+tuple1.toString());
((CPFlowSet) clonedInput).addIfNotPresentButDontUpdate(tuple1);
}
DavaFlowSet output2 = process(subBodyTwo, clonedInput);
if (DEBUG_IF) {
System.out.println(
"\n\n IF-ELSE INPUTS TO MERGE ARE input (if):" + output1.toString() + " else:" + output2.toString() + "\n\n\n");
}
DavaFlowSet temp = merge(output1, output2);
// notice we handle breaks only once since these are breaks to the same
// label or same node
String label = getLabel(node);
output1 = handleBreak(label, temp, node);
if (DEBUG_IF) {
System.out.println("Exiting ifelse node" + output1.toString());
;
}
return output1;
}
/*
* The isElseBranch flag is true if the caller is the else branch of the ifelse statement. In that case we might be able to
* send something for the else branch
*/
public CPTuple checkForValueHints(ASTCondition cond, CPFlowSet input, boolean isElseBranch) {
if (cond instanceof ASTUnaryCondition) {
// check for lone boolean if(notDone)
ASTUnaryCondition unary = (ASTUnaryCondition) cond;
Value unaryValue = unary.getValue();
boolean NOTTED = false;
// Get the real value if this is a notted expression
if (unaryValue instanceof DNotExpr) {
unaryValue = ((DNotExpr) unaryValue).getOp();
NOTTED = true;
}
if (!(unaryValue instanceof Local)) {
// since we only track locals we cant possibly add info to the
// inset
return null;
}
// the unary value is a local add the value to the inset which woul
// dbe present in the if branch
CPVariable variable = new CPVariable((Local) unaryValue);
// since NOTTED true means the if branch has variable with value
// false and vice verse
if (!isElseBranch) {
// we are in the if branch hence notted true would mean the
// variable is actually false here
Boolean boolVal = new Boolean(!NOTTED);
return new CPTuple(localClassName, variable, boolVal);
} else {
// in the else branch NOTTED true means the variable is true
Boolean boolVal = new Boolean(NOTTED);
return new CPTuple(localClassName, variable, boolVal);
}
} else if (cond instanceof ASTBinaryCondition) {
ASTBinaryCondition binary = (ASTBinaryCondition) cond;
ConditionExpr expr = binary.getConditionExpr();
Boolean equal = null;
String symbol = expr.getSymbol();
if (symbol.indexOf("==") > -1) {
// System.out.println("!!!!!!!!!1 FOUND == in binary comparison operaiton");
equal = new Boolean(true);
} else if (symbol.indexOf("!=") > -1) {
equal = new Boolean(false);
// System.out.println("!!!!!!!!!!!!!! FOUND != in binary comparison operaiton");
} else {
// a symbol we are not interested in
// System.out.println("symbol is"+symbol);
return null;
}
// we have a comparison the truth value of equal tells whether we
// are doing == or !=
Value a = expr.getOp1();
Value b = expr.getOp2();
// see if its possible to deduce a hint from these values
CPTuple tuple = createCPTupleIfPossible(a, b, input);
// if the tuple is not created
if (tuple == null) {
return null;
}
// we have to make sure is that the == and != are taken into account
if (equal.booleanValue()) {
// using equality comparison a == b this then means in the if
// branch a is in fact equal to b
if (!isElseBranch) {
return tuple;
} else {
return null;
}
} else {
if (isElseBranch) {
return tuple;
} else {
return null;
}
}
}
return null;
}
/*
* Should create the final tuple to add
*
* a == b
*
* case 1 a is constant b is constant dont give a damm case 2 a is constant b is a local useful case 3 a is a local b is a
* constant useful case 4 a is a local or sootfield b is a local or sootfield useful if one of them is in the inset
*/
public CPTuple createCPTupleIfPossible(Value a, Value b, CPFlowSet input) {
Object aVal = CPHelper.isAConstantValue(a);
Object bVal = CPHelper.isAConstantValue(b);
if (aVal != null && bVal != null) {
// both are constants dont want to do anything..case 1
return null;
}
CPVariable cpVar = null;
Object constantToUse = null;
if (aVal == null && bVal == null) {
// both are not constants but one of their values could be known in
// the inset ... case 4
// System.out.println("a:"+a+" is not a constant b:"+b+" is not");
// check the input set to see if either a or b have known beliefs.
// its useful if one and only one of the two has a known belief
Object av1 = isANotTopConstantInInputSet(input, a);
Object av2 = isANotTopConstantInInputSet(input, b);
if (av1 == null && av2 == null) {
// either top or not present hence useless
return null;
} else if (av1 == null && av2 != null) {
// no value of a found but value of b was found <classname, a,b>
// System.out.println("From INSET: a:"+a+" is not a constant b "+b+" is"
// );
if (!(a instanceof Local && ((Local) a).getType() instanceof PrimType)) {
// we only hanlde primitive locals
return null;
}
cpVar = new CPVariable((Local) a);
constantToUse = av2;
} else if (av1 != null && av2 == null) {
// no value of b found but value of a was found <classname, b,a>
// System.out.println("From INSET: a:"+a+" is a constant b "+b+" is not"
// );
if (!(b instanceof Local && ((Local) b).getType() instanceof PrimType)) {
// we only hanlde primitive locals
return null;
}
cpVar = new CPVariable((Local) b);
constantToUse = av1;
}
} else if (aVal != null && bVal == null) {
// CASE 2: a is a constant and b is not so we have a chance of
// entering a tuple <className,b,a> maybe
// System.out.println("a:"+a+" is a constant b:"+b+" is not");
if (!(b instanceof Local && ((Local) b).getType() instanceof PrimType)) {
// we only hanlde primitive locals
return null;
}
// able to create cpVar
cpVar = new CPVariable((Local) b);
constantToUse = aVal;
} else if (aVal == null && bVal != null) {
// CASE 3: a is not a constant but b is a constant so we have a
// chance of entering a tuple <className,a,b>
// System.out.println("a:"+a+" is not a constant b:"+b+" is ");
if (!(a instanceof Local && ((Local) a).getType() instanceof PrimType)) {
// we only hanlde primitive locals
return null;
}
// able to create cpVar
cpVar = new CPVariable((Local) a);
constantToUse = bVal;
}
// if cpVar is not null and constantToUse is not null thats good
if (cpVar != null && constantToUse != null) {
// create a CPTuple which contains the belief for cpVar with
// constantToUse we will for sure have going into the if branch
// we know cpVar is always a local since we create it only for
// locals
// need to see if constant is supposed to be a boolean
// (isAConstantValue returns an Integer for a boolean)
if (cpVar.getLocal().getType() instanceof BooleanType) {
if (!(constantToUse instanceof Integer)) {
// booleans are represented by Integeres in the
// isConstantValue method what happened here???
return null;
}
Integer tempValue = (Integer) constantToUse;
if (tempValue.intValue() == 0) {
constantToUse = new Boolean(false);
} else {
constantToUse = new Boolean(true);
}
}
// ready to create the CPTuple
return new CPTuple(localClassName, cpVar, constantToUse);
}
return null;
}
/*
* TODO some other time
*
* public Object processASTSwitchNode(ASTSwitchNode node,Object input){
*
* }
*/
}
| 34,275
| 33.904277
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/CPFlowSet.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%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.io.Serializable;
import java.util.HashMap;
import java.util.List;
import soot.dava.DecompilationException;
import soot.toolkits.scalar.FlowSet;
/*
* Really the only reason for needing a specialized flow set is that
* intersection is done differently for constant propagation
*/
public class CPFlowSet extends DavaFlowSet<CPTuple> {
public CPFlowSet() {
super();
}
/*
* invoked by the clone method
*
* This is not as simple as one would think cloning is
*
* We have to make sure that certain important things.....like the bloody constant value inside the the variablevaluetuple
* is being cloned!!!
*/
public CPFlowSet(CPFlowSet other) {
numElements = other.numElements;
maxElements = other.maxElements;
elements = new CPTuple[other.getElementCount()];
for (int i = 0; i < other.getElementCount(); i++) {
if (other.getElementAt(i) != null) {
elements[i] = other.getElementAt(i).clone();
} else {
elements[i] = null;
}
}
// elements = (Object[]) other.elements.clone();
/*
* Reason about the fact whether we need deep cloning of these shits or not anything which is in these lists is not being
* cloned so care should be taken to not modify any value... c
*/
breakList = (HashMap<Serializable, List<DavaFlowSet<CPTuple>>>) other.breakList.clone();
continueList = (HashMap<Serializable, List<DavaFlowSet<CPTuple>>>) other.continueList.clone();
implicitBreaks = (HashMap<Serializable, List<DavaFlowSet<CPTuple>>>) other.implicitBreaks.clone();
implicitContinues = (HashMap<Serializable, List<DavaFlowSet<CPTuple>>>) other.implicitContinues.clone();
}
/*
* helper method to be invoked by CPApplication when trying to do transformation
*
* returns a non null if the local or field is contained and has a constant value returns a null if the local or field is
* eithe rnot present or is trop
*/
public Object contains(String className, String localOrField) {
for (int i = 0; i < this.numElements; i++) {
CPTuple current = getElementAt(i);
if (!(current.getSootClassName().equals(className))) {
continue;
}
if (current.containsField()) {
if (!current.getVariable().getSootField().getName().equals(localOrField)) {
continue;
} else {
return current.getValue();
}
} else if (current.containsLocal()) {
if (!current.getVariable().getLocal().getName().equals(localOrField)) {
continue;
} else {
return current.getValue();
}
}
}
return null;
}
/*
* This is more of an update method than an add method.
*
* Go through all the elements in the flowSet See if we can find an element (CPTuple with the same className and same
* CPVariable) if we dont find one: add this to the flowset if we find one: update the Value with the value of the newTuple
*/
public void addIfNotPresent(CPTuple newTuple) {
// System.out.println("addIfnotPresent invoked");
// going through all the elements in the set
for (int i = 0; i < this.numElements; i++) {
CPTuple current = (CPTuple) elements[i];
if (!(current.getSootClassName().equals(newTuple.getSootClassName()))) {
// different classNAmes
continue;
}
// same class names
CPVariable curVar = current.getVariable();
CPVariable newTupleVar = newTuple.getVariable();
if (!(curVar.equals(newTupleVar))) {
// different variable
continue;
}
// same class and same variable
// UPDATE this elements VALUE
// System.out.println("got here"+newTuple.getValue());
current.setValue(newTuple.getValue());
// since the tuple was present no need to ADD since we updated
return;
}
// if we get to this part we know that we need to add
// System.out.println("no got here");
this.add(newTuple);
}
/*
* Specialized method for handling conditionals this is used to add a belief derived from the condition of an if or ifelse
*
* The belief is only added if the current belief about the variable is top since later on when leaving the conditional our
* new belief intersected with top will give top and we would not have added anything incorrect or presumptuous into our
* flow set (LAURIE)
*/
public void addIfNotPresentButDontUpdate(CPTuple newTuple) {
// System.out.println("addIfnotPresent invoked");
// going through all the elements in the set
for (int i = 0; i < this.numElements; i++) {
CPTuple current = (CPTuple) elements[i];
if (!(current.getSootClassName().equals(newTuple.getSootClassName()))) {
// different classNAmes
continue;
}
// same class names
CPVariable curVar = current.getVariable();
CPVariable newTupleVar = newTuple.getVariable();
if (!(curVar.equals(newTupleVar))) {
// different variable
continue;
}
/*
* We only assign value if there is one not already present
*/
if (current.isTop()) {
current.setValue(newTuple.getValue());
}
return;
}
// if we get to this part we know that we need to add
/*
* DO NOT ADD IF NOT FOUND SINCE THAT MEANS IT IS BOTTOM and we dont want the following to occur
*
* if( bla ){
*
* if a var is bottom before the loop and we add something because of bla } then the merge rules will cause the after set
* of if to have the something Body A since bottom merged with something is that something THIS WOULD BE INCORRECT
*/
// this.add(newTuple);
}
/*
* The intersection method is called by the object whose set is to be intersected with otherFlow and the result to be
* stored in destFlow
*
* So we will be intersecting elements of "this" and otherFlow
*
* Definition of Intersection: If an element e belongs to Set A then Set A ^ B contains e if B contains an element such
* that the constantpropagationFlowSet equals method returns true (this will happen if they have the same variable and the
* same value which better not be TOP)
*
* If the element e is not added to set A ^ B then element e should be changed to hold TOP as the value is unknown and that
* value should be added to the set A ^ B
*
*
*/
public void intersection(FlowSet otherFlow, FlowSet destFlow) {
// System.out.println("In specialized intersection for CopyPropagation");
if (!(otherFlow instanceof CPFlowSet && destFlow instanceof CPFlowSet)) {
super.intersection(otherFlow, destFlow);
return;
}
CPFlowSet other = (CPFlowSet) otherFlow;
CPFlowSet dest = (CPFlowSet) destFlow;
CPFlowSet workingSet;
if (dest == other || dest == this) {
workingSet = new CPFlowSet();
} else {
workingSet = dest;
workingSet.clear();
}
/*
* HERE IS THE MERGE TABLE
*
*
* THIS OTHER RESULT
*
* 1 BOTTOM BOTTOM WHO CARES 2 BOTTOM C C (Laurie Convinced me) 3 BOTTOM TOP TOP 4 C BOTTOM C (Laurie Convinced me) 5 C1
* C2 C if C1 == C2 else TOP 6 C TOP TOP 7 TOP BOTTOM TOP 8 TOP C TOP 9 TOP TOP TOP
*/
for (int i = 0; i < this.numElements; i++) {
CPTuple thisTuple = this.getElementAt(i);
String className = thisTuple.getSootClassName();
CPVariable thisVar = thisTuple.getVariable();
CPTuple matchFound = null;
/*
* Find a matching tuple if one exists
*/
CPTuple otherTuple = null;
for (int j = 0; j < other.numElements; j++) {
otherTuple = other.getElementAt(j);
/*
* wont use the CPTuple equal method since that ignores tops we want to implement the intersection rules given in the
* merge table
*/
// check that the two tuples have the same class
String tempClass = otherTuple.getSootClassName();
if (!tempClass.equals(className)) {
continue;
}
// Check that the variable contained is the same name and type (local or sootfield)
if (!otherTuple.getVariable().equals(thisVar)) {
continue;
}
// match of sootClass and Variable have to use merge table on matchFound and elements[i]
matchFound = otherTuple;
break;
} // end looking for a match in other set
if (matchFound != null) {
// cases 5 6 8 and 9 are the ones in which both sets have a value for this variable
if (thisTuple.isTop()) {
// cases 8 and 9
workingSet.add(thisTuple.clone());
} else if (matchFound.isTop()) {
// case 6
workingSet.add(matchFound.clone());
} else if (!matchFound.isTop() && !thisTuple.isTop()) {
// this has to be case 5 since there is no other case possible
Object matchedValue = matchFound.getValue();
Object thisValue = thisTuple.getValue();
// using the equals method of Boolean/Float/Integer etc
if (matchedValue.equals(thisValue)) {
workingSet.add(thisTuple.clone());
} else {
// if we get here either the types dont match or the values didnt match just add top
workingSet.add(new CPTuple(className, thisVar, true));
}
} else {
throw new DecompilationException("Ran out of cases in CPVariable values...report bug to developer");
}
} // if match was found
else {
// could not find a match for element[i] in other hence its bottom in other
// CASE 4 and 7 (cant be case 1 since element[i]s presence means its not bottom
// add CLONE OF element[i] to working set unchanged
/*
* TODO: why should a field be turned to TOP... a field is only a constant value field and hence should never be
* changed!!!!!
*
* BUG FOUND DUE TO CHROMOSOME benchmark if(Debug.flag) was not being detected as it was being set to top
*
* April 3rd 2006
*/
/*
* if(thisTuple.containsField()){ //add top workingSet.add(new
* CPTuple(thisTuple.getSootClassName(),thisTuple.getVariable(),true)); } else if(thisTuple.containsLocal()){
*/
workingSet.add(thisTuple.clone());
/*
* } else throw new DecompilationException("CPVariable is not local and not field");
*/
}
} // end going through all elements of this flowset
/*
* havent covered cases 2 and 3 in which case this has bottom (a.k.a variable is not present) and the other has the
* elements
*/
for (int i = 0; i < other.numElements; i++) {
CPTuple otherTuple = other.getElementAt(i);
String otherClassName = otherTuple.getSootClassName();
CPVariable otherVar = otherTuple.getVariable();
// System.out.print("\t Other:"+otherVar.toString());
boolean inBoth = false;
for (int j = 0; j < this.numElements; j++) {
CPTuple thisTuple = this.getElementAt(j);
String thisClassName = thisTuple.getSootClassName();
CPVariable thisVar = thisTuple.getVariable();
if (!otherClassName.equals(thisClassName)) {
continue;
}
if (!thisVar.equals(otherVar)) {
continue;
}
// if we get here we know both sets have this variable so this is not case 2 or 3
// System.out.println(">>>> FOUND"+thisVar.toString());
inBoth = true;
break;
}
if (!inBoth) {
// System.out.println("....NOT FOUND ....SET IS:"+this.toString());
// not in both so this is case 2 or 3
/*
* clone and add if its local
*
* if field then add top
*/
/*
* TODO why should a field be converted to TOP when all the fiels are only constant value fields
*//*
* if(otherTuple.containsField()){ //add top workingSet.add(new
* CPTuple(otherTuple.getSootClassName(),otherTuple.getVariable(),true)); } else if(otherTuple.containsLocal()){
*/
workingSet.add(otherTuple.clone());
/*
* } else throw new DecompilationException("CPVariable is not local and not field");
*/
}
} // end going through other elements
}
public CPFlowSet clone() {
return new CPFlowSet(this);
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append("Printing CPFlowSet: ");
for (int i = 0; i < this.numElements; i++) {
b.append("\n" + ((CPTuple) elements[i]).toString());
}
b.append("\n");
return b.toString();
}
}
| 13,617
| 33.388889
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/CPHelper.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%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 soot.BooleanType;
import soot.Value;
import soot.dava.internal.javaRep.DIntConstant;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
public class CPHelper {
/*
* The helper class just checks the type of the data being sent and create a clone of it
*
* If it is not a data of interest a null is send back
*/
public static Object wrapperClassCloner(Object value) {
if (value instanceof Double) {
return new Double(((Double) value).doubleValue());
} else if (value instanceof Float) {
return new Float(((Float) value).floatValue());
} else if (value instanceof Long) {
return new Long(((Long) value).longValue());
} else if (value instanceof Boolean) {
return new Boolean(((Boolean) value).booleanValue());
} else if (value instanceof Integer) {
return new Integer(((Integer) value).intValue());
} else {
return null;
}
}
/*
* isAConstantValue(Value toCheck) it will check whether toCheck is one of the interesting Constants IntConstant
* FloatConstant etc etc if yes return the Integer/Long/float/Double
*
* Notice for integer the callee has to check whether what is required is a Boolean!!!!
*/
public static Object isAConstantValue(Value toCheck) {
Object value = null;
if (toCheck instanceof LongConstant) {
value = new Long(((LongConstant) toCheck).value);
} else if (toCheck instanceof DoubleConstant) {
value = new Double(((DoubleConstant) toCheck).value);
} else if (toCheck instanceof FloatConstant) {
value = new Float(((FloatConstant) toCheck).value);
} else if (toCheck instanceof IntConstant) {
int val = ((IntConstant) toCheck).value;
value = new Integer(val);
}
return value;
}
public static Value createConstant(Object toConvert) {
if (toConvert instanceof Long) {
return LongConstant.v(((Long) toConvert).longValue());
} else if (toConvert instanceof Double) {
return DoubleConstant.v(((Double) toConvert).doubleValue());
} else if (toConvert instanceof Boolean) {
boolean val = ((Boolean) toConvert).booleanValue();
if (val) {
return DIntConstant.v(1, BooleanType.v());
} else {
return DIntConstant.v(0, BooleanType.v());
}
} else if (toConvert instanceof Float) {
return FloatConstant.v(((Float) toConvert).floatValue());
} else if (toConvert instanceof Integer) {
return IntConstant.v(((Integer) toConvert).intValue());
} else {
return null;
}
}
}
| 3,502
| 34.03
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/CPTuple.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%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 soot.dava.DavaFlowAnalysisException;
/********** START LOCAL CLASS DECLARATION *******************/
public class CPTuple {
private String sootClass; // hold the name of the class to which the val belongs .... needed for interprocedural constant
// Fields info
/*
*
*/
private CPVariable variable;
// Double Float Long Boolean Integer
private Object constant; // the known constant value for the local or field
/*
* false means not top true mean TOP
*/
private Boolean TOP = new Boolean(false);
/*
* Dont care about className and variable but the CONSTANT VALUE HAS TO BE A NEW ONE otherwise the clone of the flowset
* keeps pointing to the same bloody constant value
*/
public CPTuple clone() {
if (isTop()) {
return new CPTuple(sootClass, variable, true);
} else if (isValueADouble()) {
return new CPTuple(sootClass, variable, new Double(((Double) constant).doubleValue()));
} else if (isValueAFloat()) {
return new CPTuple(sootClass, variable, new Float(((Float) constant).floatValue()));
} else if (isValueALong()) {
return new CPTuple(sootClass, variable, new Long(((Long) constant).longValue()));
} else if (isValueABoolean()) {
return new CPTuple(sootClass, variable, new Boolean(((Boolean) constant).booleanValue()));
} else if (isValueAInteger()) {
return new CPTuple(sootClass, variable, new Integer(((Integer) constant).intValue()));
} else {
throw new RuntimeException("illegal Constant Type...report to developer" + constant);
}
}
public CPTuple(String sootClass, CPVariable variable, Object constant) {
if (!(constant instanceof Float || constant instanceof Double || constant instanceof Long || constant instanceof Boolean
|| constant instanceof Integer)) {
throw new DavaFlowAnalysisException(
"Third argument of VariableValuePair not an acceptable constant value...report to developer");
}
this.sootClass = sootClass;
this.variable = variable;
this.constant = constant;
TOP = new Boolean(false);
}
public CPTuple(String sootClass, CPVariable variable, boolean top) {
this.sootClass = sootClass;
this.variable = variable;
// notice we dont really care whether the argument top was true or false
setTop();
}
public boolean containsLocal() {
return variable.containsLocal();
}
public boolean containsField() {
return variable.containsSootField();
}
/*
* If TOP is non null then that means it is set to TOP
*/
public boolean isTop() {
return TOP.booleanValue();
}
public void setTop() {
constant = null;
TOP = new Boolean(true);
}
public boolean isValueADouble() {
return (constant instanceof Double);
}
public boolean isValueAFloat() {
return (constant instanceof Float);
}
public boolean isValueALong() {
return (constant instanceof Long);
}
public boolean isValueABoolean() {
return (constant instanceof Boolean);
}
public boolean isValueAInteger() {
return (constant instanceof Integer);
}
public Object getValue() {
return constant;
}
public void setValue(Object constant) {
// System.out.println("here currently valued as"+this.constant);
if (!(constant instanceof Float || constant instanceof Double || constant instanceof Long || constant instanceof Boolean
|| constant instanceof Integer)) {
throw new DavaFlowAnalysisException("argument to setValue not an acceptable constant value...report to developer");
}
this.constant = constant;
TOP = new Boolean(false);
}
public String getSootClassName() {
return sootClass;
}
public CPVariable getVariable() {
return variable;
}
public boolean equals(Object other) {
if (other instanceof CPTuple) {
CPTuple var = (CPTuple) other;
// if both are top thats all right
if (sootClass.equals(var.getSootClassName()) && variable.equals(var.getVariable()) && isTop() & var.isTop()) {
return true;
}
// if any one is top thats no good
if (isTop() || var.isTop()) {
return false;
}
if (sootClass.equals(var.getSootClassName()) && variable.equals(var.getVariable())
&& constant.equals(var.getValue())) {
// System.out.println("constant value "+constant.toString() + " is equal to "+ var.toString());
return true;
}
}
return false;
}
public String toString() {
StringBuffer b = new StringBuffer();
if (isTop()) {
b.append("<" + sootClass + ", " + variable.toString() + ", TOP>");
} else {
b.append("<" + sootClass + ", " + variable.toString() + "," + constant.toString() + ">");
}
return b.toString();
}
}
/********** END LOCAL CLASS DECLARATION *******************/
| 5,740
| 29.700535
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/CPVariable.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%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 soot.Local;
import soot.PrimType;
import soot.SootField;
import soot.dava.DavaFlowAnalysisException;
/*
* Needed since we want to track locals and SootFields (not FieldRefs)
*/
public class CPVariable {
private Local local;
private SootField field;
public CPVariable(SootField field) {
this.field = field;
this.local = null;
if (!(field.getType() instanceof PrimType)) {
throw new DavaFlowAnalysisException("Variables managed for CP should only be primitives");
}
}
public CPVariable(Local local) {
this.field = null;
this.local = local;
if (!(local.getType() instanceof PrimType)) {
throw new DavaFlowAnalysisException("Variables managed for CP should only be primitives");
}
}
public boolean containsLocal() {
return (local != null);
}
public boolean containsSootField() {
return (field != null);
}
public SootField getSootField() {
if (containsSootField()) {
return field;
} else {
throw new DavaFlowAnalysisException("getsootField invoked when variable is not a sootfield!!!");
}
}
public Local getLocal() {
if (containsLocal()) {
return local;
} else {
throw new DavaFlowAnalysisException("getLocal invoked when variable is not a local");
}
}
/*
* VERY IMPORTANT METHOD: invoked from ConstantPropagationTuple equals method which is invoked from the main merge
* intersection method of CPFlowSet
*/
public boolean equals(CPVariable var) {
// check they have the same type Local or SootField
if (this.containsLocal() && var.containsLocal()) {
// both locals and same name
if (this.getLocal().getName().equals(var.getLocal().getName())) {
return true;
}
}
if (this.containsSootField() && var.containsSootField()) {
// both SootFields check they have same name
if (this.getSootField().getName().equals(var.getSootField().getName())) {
return true;
}
}
return false;
}
public String toString() {
if (containsLocal()) {
return "Local: " + getLocal().getName();
} else if (containsSootField()) {
return "SootField: " + getSootField().getName();
} else {
return "UNKNOWN CONSTANT_PROPAGATION_VARIABLE";
}
}
}
| 3,161
| 26.982301
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/DavaFlowSet.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.internal.javaRep.DAbruptStmt;
import soot.dava.toolkits.base.AST.traversals.ClosestAbruptTargetFinder;
import soot.toolkits.scalar.AbstractFlowSet;
import soot.toolkits.scalar.FlowSet;
public class DavaFlowSet<T> extends AbstractFlowSet<T> {
static final int DEFAULT_SIZE = 8;
int numElements;
int maxElements;
protected T[] elements;
/**
* Whenever in a structured flow analysis a break or continue stmt is encountered the current DavaFlowSet is stored in the
* break/continue list with the appropriate label for the target code. This is how explicit breaks and continues are
* handled by the analysis framework
*/
HashMap<Serializable, List<DavaFlowSet<T>>> breakList;
HashMap<Serializable, List<DavaFlowSet<T>>> continueList;
/**
* To handle implicit breaks and continues the following HashMaps store the DavaFlowSets as value with the key being the
* targeted piece of code (an ASTNode)
*/
HashMap<Serializable, List<DavaFlowSet<T>>> implicitBreaks; // map a node
// and all the
// dataflowsets
// due to
// implicit
// breaks
// targetting it
HashMap<Serializable, List<DavaFlowSet<T>>> implicitContinues; // map a node
// and all
// the
// dataflowsets
// due to
// implicit
// continues
// targetting
// it
public DavaFlowSet() {
maxElements = DEFAULT_SIZE;
elements = (T[]) new Object[DEFAULT_SIZE];
numElements = 0;
breakList = new HashMap<Serializable, List<DavaFlowSet<T>>>();
continueList = new HashMap<Serializable, List<DavaFlowSet<T>>>();
implicitBreaks = new HashMap<Serializable, List<DavaFlowSet<T>>>();
implicitContinues = new HashMap<Serializable, List<DavaFlowSet<T>>>();
}
public DavaFlowSet(DavaFlowSet<T> other) {
numElements = other.numElements;
maxElements = other.maxElements;
elements = other.elements.clone();
breakList = (HashMap<Serializable, List<DavaFlowSet<T>>>) other.breakList.clone();
continueList = (HashMap<Serializable, List<DavaFlowSet<T>>>) other.continueList.clone();
implicitBreaks = (HashMap<Serializable, List<DavaFlowSet<T>>>) other.implicitBreaks.clone();
implicitContinues = (HashMap<Serializable, List<DavaFlowSet<T>>>) other.implicitContinues.clone();
}
/** Returns true if flowSet is the same type of flow set as this. */
private boolean sameType(Object flowSet) {
return (flowSet instanceof DavaFlowSet);
}
public DavaFlowSet<T> clone() {
return new DavaFlowSet<T>(this);
}
public FlowSet<T> emptySet() {
return new DavaFlowSet<T>();
}
public void clear() {
numElements = 0;
}
public int size() {
return numElements;
}
public boolean isEmpty() {
return numElements == 0;
}
/** Returns a unbacked list of elements in this set. */
public List<T> toList() {
@SuppressWarnings("unchecked")
T[] copiedElements = (T[]) new Object[numElements];
System.arraycopy(elements, 0, copiedElements, 0, numElements);
return Arrays.asList(copiedElements);
}
/*
* Expand array only when necessary, pointed out by Florian Loitsch March 08, 2002
*/
@Override
public void add(T e) {
/* Expand only if necessary! and removes one if too:) */
// Add element
if (!contains(e)) {
// Expand array if necessary
if (numElements == maxElements) {
doubleCapacity();
}
elements[numElements++] = e;
}
}
private void doubleCapacity() {
int newSize = maxElements * 2;
@SuppressWarnings("unchecked")
T[] newElements = (T[]) new Object[newSize];
System.arraycopy(elements, 0, newElements, 0, numElements);
elements = newElements;
maxElements = newSize;
}
@Override
public void remove(Object obj) {
for (int i = 0; i < numElements; i++) {
if (elements[i].equals(obj)) {
remove(i);
break;
}
}
}
public void remove(int idx) {
elements[idx] = elements[--numElements];
}
/**
* Notice that the union method only merges the elements of the flow set DavaFlowSet also contains information regarding
* abrupt control flow This should also be merged using the copyInternalDataFrom method
*/
public void union(FlowSet<T> otherFlow, FlowSet<T> destFlow) {
if (sameType(otherFlow) && sameType(destFlow)) {
DavaFlowSet<T> other = (DavaFlowSet<T>) otherFlow;
DavaFlowSet<T> dest = (DavaFlowSet<T>) destFlow;
// For the special case that dest == other
if (dest == other) {
for (int i = 0; i < this.numElements; i++) {
dest.add(this.elements[i]);
}
}
// Else, force that dest starts with contents of this
else {
if (this != dest) {
copy(dest);
}
for (int i = 0; i < other.numElements; i++) {
dest.add(other.elements[i]);
}
}
} else {
super.union(otherFlow, destFlow);
}
}
/**
* Notice that the intersection method only merges the elements of the flow set DavaFlowSet also contains information
* regarding abrupt control flow This should also be merged using the copyInternalDataFrom method
*/
public void intersection(FlowSet<T> otherFlow, FlowSet<T> destFlow) {
// System.out.println("DAVA FLOWSET INTERSECTION INVOKED!!!");
if (sameType(otherFlow) && sameType(destFlow)) {
DavaFlowSet<T> other = (DavaFlowSet<T>) otherFlow;
DavaFlowSet<T> dest = (DavaFlowSet<T>) destFlow;
DavaFlowSet<T> workingSet;
if (dest == other || dest == this) {
workingSet = new DavaFlowSet<T>();
} else {
workingSet = dest;
workingSet.clear();
}
for (int i = 0; i < this.numElements; i++) {
if (other.contains(this.elements[i])) {
workingSet.add(this.elements[i]);
}
}
if (workingSet != dest) {
workingSet.copy(dest);
}
} else {
super.intersection(otherFlow, destFlow);
}
}
public void difference(FlowSet<T> otherFlow, FlowSet<T> destFlow) {
if (sameType(otherFlow) && sameType(destFlow)) {
DavaFlowSet<T> other = (DavaFlowSet<T>) otherFlow;
DavaFlowSet<T> dest = (DavaFlowSet<T>) destFlow;
DavaFlowSet<T> workingSet;
if (dest == other || dest == this) {
workingSet = new DavaFlowSet<T>();
} else {
workingSet = dest;
workingSet.clear();
}
for (int i = 0; i < this.numElements; i++) {
if (!other.contains(this.elements[i])) {
workingSet.add(this.elements[i]);
}
}
if (workingSet != dest) {
workingSet.copy(dest);
}
} else {
super.difference(otherFlow, destFlow);
}
}
public boolean contains(Object obj) {
for (int i = 0; i < numElements; i++) {
if (elements[i].equals(obj)) {
return true;
}
}
return false;
}
/**
* Notice that the equals method only checks the equality of the elements of the flow set DavaFlowSet also contains
* information regarding abrupt control flow This should also be checked by invoking the internalDataMatchesTo method
*/
public boolean equals(Object otherFlow) {
if (sameType(otherFlow)) {
@SuppressWarnings("unchecked")
DavaFlowSet<T> other = (DavaFlowSet<T>) otherFlow;
if (other.numElements != this.numElements) {
return false;
}
int size = this.numElements;
// Make sure that thisFlow is contained in otherFlow
for (int i = 0; i < size; i++) {
if (!other.contains(this.elements[i])) {
return false;
}
}
/*
* both arrays have the same size, no element appears twice in one array, all elements of ThisFlow are in otherFlow ->
* they are equal! we don't need to test again! // Make sure that otherFlow is contained in ThisFlow for(int i = 0; i <
* size; i++) if(!this.contains(other.elements[i])) return false;
*/
return true;
} else {
return super.equals(otherFlow);
}
}
public void copy(FlowSet<T> destFlow) {
if (this == destFlow) {
return;
}
if (sameType(destFlow)) {
DavaFlowSet<T> dest = (DavaFlowSet<T>) destFlow;
while (dest.maxElements < this.maxElements) {
dest.doubleCapacity();
}
dest.numElements = this.numElements;
System.arraycopy(this.elements, 0, dest.elements, 0, this.numElements);
} else {
super.copy(destFlow);
}
}
/**
* A private method used to add an element into a List if it is NOT a duplicate
*/
private List<DavaFlowSet<T>> addIfNotDuplicate(List<DavaFlowSet<T>> into, DavaFlowSet<T> addThis) {
// if set is not already present in the labelsBreakList then add it
Iterator<DavaFlowSet<T>> it = into.iterator();
boolean found = false;
while (it.hasNext()) {
DavaFlowSet<T> temp = it.next();
if (temp.equals(addThis) && temp.internalDataMatchesTo(addThis)) {
found = true;
break;
}
}
if (!found) {
into.add(addThis);
}
return into;
}
/**
* When an explicit break statement is encountered this method should be called to store the current davaflowset
*/
public void addToBreakList(String labelBroken, DavaFlowSet<T> set) {
List<DavaFlowSet<T>> labelsBreakList = breakList.get(labelBroken);
if (labelsBreakList == null) {
labelsBreakList = new ArrayList<DavaFlowSet<T>>();
labelsBreakList.add(set);
breakList.put(labelBroken, labelsBreakList);
// System.out.println("ADDED"+labelBroken+" with"+set.toString());
} else {
// add set into this list if its not a duplicate and update the
// hashMap
breakList.put(labelBroken, addIfNotDuplicate(labelsBreakList, set));
}
}
/**
* When an explicit continue statement is encountered this method should be called to store the current davaflowset
*/
public void addToContinueList(String labelContinued, DavaFlowSet<T> set) {
List<DavaFlowSet<T>> labelsContinueList = continueList.get(labelContinued);
if (labelsContinueList == null) {
labelsContinueList = new ArrayList<DavaFlowSet<T>>();
labelsContinueList.add(set);
continueList.put(labelContinued, labelsContinueList);
} else {
continueList.put(labelContinued, addIfNotDuplicate(labelsContinueList, set));
}
}
/**
* Checks whether the input stmt is an implicit break/continue A abrupt stmt is implicit if the SETLabelNode is null or the
* label.toString results in null
*/
private boolean checkImplicit(DAbruptStmt ab) {
SETNodeLabel label = ab.getLabel();
if (label == null) {
return true;
}
if (label.toString() == null) {
return true;
}
return false;
}
/**
* The next two methods take an abruptStmt as input along with a flowSet. It should be only invoked for abrupt stmts which
* do not have explicit labels
*
* The node being targeted by this implicit stmt should be found Then the flow set should be added to the list within the
* appropriate hashmap
*/
public void addToImplicitBreaks(DAbruptStmt ab, DavaFlowSet<T> set) {
if (!checkImplicit(ab)) {
throw new RuntimeException("Tried to add explicit break statement in the implicit list in");
}
if (!ab.is_Break()) {
throw new RuntimeException("Tried to add continue statement in the break list in DavaFlowSet.addToImplicitBreaks");
}
// okkay so its an implicit break
// get the targetted node, use the ClosestAbruptTargetFinder
ASTNode node = ClosestAbruptTargetFinder.v().getTarget(ab);
// get the list of flow sets already stored for this node
List<DavaFlowSet<T>> listSets = implicitBreaks.get(node);
if (listSets == null) {
listSets = new ArrayList<DavaFlowSet<T>>();
}
// if set is not already present in listSets add it and update hashMap
implicitBreaks.put(node, addIfNotDuplicate(listSets, set));
}
public void addToImplicitContinues(DAbruptStmt ab, DavaFlowSet<T> set) {
if (!checkImplicit(ab)) {
throw new RuntimeException("Tried to add explicit continue statement in the implicit list ");
}
if (!ab.is_Continue()) {
throw new RuntimeException("Tried to add break statement in the continue list");
}
// okkay so its an implicit continue
// get the targetted node, use the ClosestAbruptTargetFinder
ASTNode node = ClosestAbruptTargetFinder.v().getTarget(ab);
// get the list of flow sets already stored for this node
List<DavaFlowSet<T>> listSets = implicitContinues.get(node);
if (listSets == null) {
listSets = new ArrayList<DavaFlowSet<T>>();
}
// if set is not already present in listSets add it and update hashMap
implicitContinues.put(node, addIfNotDuplicate(listSets, set));
}
private HashMap<Serializable, List<DavaFlowSet<T>>> getBreakList() {
return breakList;
}
private HashMap<Serializable, List<DavaFlowSet<T>>> getContinueList() {
return continueList;
}
public HashMap<Serializable, List<DavaFlowSet<T>>> getImplicitBreaks() {
return implicitBreaks;
}
public HashMap<Serializable, List<DavaFlowSet<T>>> getImplicitContinues() {
return implicitContinues;
}
public List<DavaFlowSet<T>> getImplicitlyBrokenSets(ASTNode node) {
List<DavaFlowSet<T>> toReturn = implicitBreaks.get(node);
if (toReturn != null) {
return toReturn;
}
return null;
}
public List<DavaFlowSet<T>> getImplicitlyContinuedSets(ASTNode node) {
List<DavaFlowSet<T>> toReturn = implicitContinues.get(node);
if (toReturn != null) {
return toReturn;
}
return null;
}
/**
* An internal method used to copy non-duplicate entries from the temp list into the currentList
*/
private List<DavaFlowSet<T>> copyDavaFlowSetList(List<DavaFlowSet<T>> currentList, List<DavaFlowSet<T>> temp) {
Iterator<DavaFlowSet<T>> tempIt = temp.iterator();
while (tempIt.hasNext()) {
DavaFlowSet<T> check = tempIt.next();
Iterator<DavaFlowSet<T>> currentListIt = currentList.iterator();
boolean found = false;
while (currentListIt.hasNext()) {
// see if currentList has check
DavaFlowSet<T> currentSet = currentListIt.next();
if (check.equals(currentSet) && check.internalDataMatchesTo(currentSet)) {
found = true;
break;
}
}
if (!found) {
currentList.add(check);
}
}
return currentList;
}
public void copyInternalDataFrom(DavaFlowSet<T> fromThis) {
if (!sameType(fromThis)) {
return;
}
// copy elements of breaklist
{
Map<Serializable, List<DavaFlowSet<T>>> fromThisBreakList = fromThis.getBreakList();
Iterator<Serializable> keys = fromThisBreakList.keySet().iterator();
while (keys.hasNext()) {
String labelBroken = (String) keys.next();
List<DavaFlowSet<T>> temp = fromThisBreakList.get(labelBroken);
List<DavaFlowSet<T>> currentList = breakList.get(labelBroken);
if (currentList == null) {
breakList.put(labelBroken, temp);
} else {
List<DavaFlowSet<T>> complete = copyDavaFlowSetList(currentList, temp);
breakList.put(labelBroken, complete);
}
}
}
// copy elements of continuelist
{
HashMap<Serializable, List<DavaFlowSet<T>>> fromThisContinueList = fromThis.getContinueList();
Iterator<Serializable> keys = fromThisContinueList.keySet().iterator();
while (keys.hasNext()) {
String labelContinued = (String) keys.next();
List<DavaFlowSet<T>> temp = fromThisContinueList.get(labelContinued);
List<DavaFlowSet<T>> currentList = continueList.get(labelContinued);
if (currentList == null) {
continueList.put(labelContinued, temp);
} else {
List<DavaFlowSet<T>> complete = copyDavaFlowSetList(currentList, temp);
continueList.put(labelContinued, complete);
}
}
}
// copy elements of implicitBreaks
// this hashMap contains a mapping of ASTNodes to DavaFlowSets due to
// impicit breaks
{
HashMap<Serializable, List<DavaFlowSet<T>>> copyThis = fromThis.getImplicitBreaks();
Iterator<Serializable> it = copyThis.keySet().iterator();
while (it.hasNext()) { // going through all nodes in the other
// objects implicitBreaks hashMap
// each is a node
ASTNode node = (ASTNode) it.next();
// get list of dava flow sets targetting this node implicitly
List<DavaFlowSet<T>> fromDavaFlowSets = copyThis.get(node);
// Have copy non duplicates in this to the implicitbreak hashMap
// the current dava flow set has
List<DavaFlowSet<T>> toDavaFlowSets = implicitBreaks.get(node);
if (toDavaFlowSets == null) {
// there was no dava flow set currently targetting this node
// implicitly
// put the fromDavaFlowSets into the hashMap
implicitBreaks.put(node, fromDavaFlowSets);
} else {
List<DavaFlowSet<T>> complete = copyDavaFlowSetList(toDavaFlowSets, fromDavaFlowSets);
implicitBreaks.put(node, complete);
}
}
}
// copy elements of implicitContinues
// this hashMap contains a mapping of ASTNodes to DavaFlowSets due to
// impicit continues
{
HashMap<Serializable, List<DavaFlowSet<T>>> copyThis = fromThis.getImplicitContinues();
Iterator<Serializable> it = copyThis.keySet().iterator();
while (it.hasNext()) { // going through all nodes in the other
// objects implicitcontinues hashMap
// each is a node
ASTNode node = (ASTNode) it.next();
// get list of dava flow sets targetting this node implicitly
List<DavaFlowSet<T>> fromDavaFlowSets = copyThis.get(node);
// Have copy non duplicates in this to the implicitContinue
// hashMap the current dava flow set has
List<DavaFlowSet<T>> toDavaFlowSets = implicitContinues.get(node);
if (toDavaFlowSets == null) {
// there was no dava flow set currently targetting this node
// implicitly
// put the fromDavaFlowSets into the hashMap
implicitContinues.put(node, fromDavaFlowSets);
} else {
List<DavaFlowSet<T>> complete = copyDavaFlowSetList(toDavaFlowSets, fromDavaFlowSets);
implicitContinues.put(node, complete);
}
}
}
}
private <X> boolean compareLists(List<X> listOne, List<X> listTwo) {
if (listOne == null && listTwo == null) {
return true;
}
if (listOne == null || listTwo == null) {
return false;
}
// compare elements of the list
if (listOne.size() != listTwo.size()) {
// size has to be same for lists to match
return false;
}
Iterator<X> listOneIt = listOne.iterator();
boolean found = false;
while (listOneIt.hasNext()) {
// going through the first list
Object listOneObj = listOneIt.next();
Iterator<X> listTwoIt = listTwo.iterator();
while (listTwoIt.hasNext()) {
// find the object in the second list
Object listTwoObj = listTwoIt.next();
if (listOneObj.equals(listTwoObj)) {
// if object is found stop search
found = true;
break;
}
}
if (!found) {
// if didnt find object return false
return false;
}
found = false;
}
return true;
}
public boolean internalDataMatchesTo(Object otherObj) {
if (!(otherObj instanceof DavaFlowSet)) {
return false;
}
@SuppressWarnings("unchecked")
DavaFlowSet<T> other = (DavaFlowSet<T>) otherObj;
// check if same break list
HashMap<Serializable, List<DavaFlowSet<T>>> otherMap = other.getBreakList();
if (!compareHashMaps(breakList, otherMap)) {
return false;
}
// check if same continue list
otherMap = other.getContinueList();
if (!compareHashMaps(continueList, otherMap)) {
return false;
}
// check implicitBreaks match
otherMap = other.getImplicitBreaks();
if (!compareHashMaps(implicitBreaks, otherMap)) {
return false;
}
// check implicitContinues match
otherMap = other.getImplicitContinues();
if (!compareHashMaps(implicitContinues, otherMap)) {
return false;
}
return true;
}
private boolean compareHashMaps(HashMap<Serializable, List<DavaFlowSet<T>>> thisMap,
HashMap<Serializable, List<DavaFlowSet<T>>> otherMap) {
List<String> otherKeyList = new ArrayList<String>();
Iterator<Serializable> keys = otherMap.keySet().iterator();
while (keys.hasNext()) {
String otherKey = (String) keys.next();
otherKeyList.add(otherKey);
List<DavaFlowSet<T>> listOther = otherMap.get(otherKey);
List<DavaFlowSet<T>> listThis = thisMap.get(otherKey);
// compare the two lists
if (!compareLists(listOther, listThis)) {
// if lists dont match internalData doesnt match
return false;
}
}
// have gone through otherMap
// going through thisMap
keys = thisMap.keySet().iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
Iterator<String> keyListIt = otherKeyList.iterator();
boolean alreadyDone = false;
while (keyListIt.hasNext()) {
String doneKey = keyListIt.next();
if (key.equals(doneKey)) {
alreadyDone = true;
break;
}
}
if (!alreadyDone) {
/*
* we have come across a label which was not done by the first hashmap meaning it was NOT in the first hashMap
*/
return false;
}
}
return true;
}
public List<DavaFlowSet<T>> getContinueSet(String label) {
return continueList.remove(label);
}
public List<DavaFlowSet<T>> getBreakSet(String label) {
return breakList.remove(label);
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append(" SET={");
for (int i = 0; i < this.numElements; i++) {
if (i != 0) {
b.append(" , ");
}
b.append(this.elements[i].toString());
}
b.append(" }");
return b.toString();
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
int lastIdx = 0;
@Override
public boolean hasNext() {
return lastIdx < numElements;
}
@Override
public T next() {
return elements[lastIdx++];
}
@Override
public void remove() {
DavaFlowSet.this.remove(--lastIdx);
}
};
}
/*
* public String toString(){ StringBuffer b = new StringBuffer(); b.append("\nSETTTTT\n"); for(int i = 0; i <
* this.numElements; i++){ b.append("\t"+this.elements[i]+"\n"); } b.append("BREAK LIST\n");
* b.append("\t"+breakList.toString()+"\n");
*
*
* b.append("CONTINUE LIST\n"); b.append("\t"+continueList.toString()+"\n");
*
* b.append("EXCEPTION LIST\n"); b.append("\t"+exceptionList.toString()+"\n"); return b.toString(); }
*/
public int getElementCount() {
return elements.length;
}
public T getElementAt(int idx) {
return elements[idx];
}
}
| 24,435
| 30.168367
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/MustMayInitialize.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Nomair A. Naeem (nomair.naeem@mail.mcgill.ca)
* %%
* 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 soot.Local;
import soot.SootField;
import soot.Value;
import soot.dava.DavaFlowAnalysisException;
import soot.dava.internal.AST.ASTUnaryBinaryCondition;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.Stmt;
//import soot.dava.internal.javaRep.*;
/*
* The analysis stores all defs of Locals/SootField. The user can then ask whether a local or SootField
isMustInitialized or isMayInitialized
*
MustInitialize/MayInitialize
Step 1:
Set of initialized locals/SootField
Step 2:
A local or SootField is MUST initialized at a program point p if on all paths from the start to this
point the local or SootField is assigned a value.
Similarly a local or SootField is MAY initialized at a program point p if there is a path from the start
to this point on wich the local or SootField is assigned
Step 3:
Forward Analysis
Step 4:
Intersection/Union
Step 5:
x = expr
kill = {}
if x is a local or SootField, gen(x) = {x}
Step 6:
out(start) = {}
newInitialFlow: No copies are available. an empty flow set
remember new InitialFlow is ONLY used for input to catchBodies
*
*
*/
public class MustMayInitialize extends StructuredAnalysis {
HashMap<Object, List> mapping;
DavaFlowSet finalResult;
public static final int MUST = 0;
public static final int MAY = 1;
int MUSTMAY;
public MustMayInitialize(Object analyze, int MUSTorMAY) {
super();
mapping = new HashMap<Object, List>();
MUSTMAY = MUSTorMAY;
// System.out.println("MustOrMay value is"+MUSTorMAY);
setMergeType();
// the input to the process method is an empty DavaFlow Set meaning
// out(start) ={} (no var initialized)
finalResult = (DavaFlowSet) process(analyze, new DavaFlowSet());
// finalResult contains the flowSet of having processed the whole of the
// method
}
public DavaFlowSet emptyFlowSet() {
return new DavaFlowSet();
}
public void setMergeType() {
// System.out.println("here"+MUSTMAY);
if (MUSTMAY == MUST) {
MERGETYPE = INTERSECTION;
// System.out.println("MERGETYPE set to intersection");
} else if (MUSTMAY == MAY) {
MERGETYPE = UNION;
// System.out.println("MERGETYPE set to union");
} else {
throw new DavaFlowAnalysisException("Only allowed 0 or 1 for MUST or MAY values");
}
}
/*
* newInitialFlow set is used only for start of catch bodies and here we assume that no var is ever being initialized
*/
@Override
public DavaFlowSet newInitialFlow() {
return new DavaFlowSet();
}
@Override
public DavaFlowSet cloneFlowSet(DavaFlowSet flowSet) {
return ((DavaFlowSet) flowSet).clone();
}
/*
* By construction conditions never have assignment statements. Hence processing a condition has no effect on this analysis
*/
@Override
public DavaFlowSet processUnaryBinaryCondition(ASTUnaryBinaryCondition cond, DavaFlowSet input) {
return input;
}
/*
* By construction the synchronized Local is a Value and can definetly not have an assignment stmt Processing a synch local
* has no effect on this analysis
*/
@Override
public DavaFlowSet processSynchronizedLocal(Local local, DavaFlowSet input) {
return input;
}
/*
* The switch key is stored as a value and hence can never have an assignment stmt Processing the switch key has no effect
* on the analysis
*/
@Override
public DavaFlowSet processSwitchKey(Value key, DavaFlowSet input) {
return input;
}
/*
* This method internally invoked by the process method decides which Statement specialized method to call
*/
@Override
public DavaFlowSet processStatement(Stmt s, DavaFlowSet inSet) {
/*
* If this path will not be taken return no path straightaway
*/
if (inSet == NOPATH) {
return inSet;
}
if (s instanceof DefinitionStmt) {
DavaFlowSet toReturn = (DavaFlowSet) cloneFlowSet(inSet);
// x = expr;
Value leftOp = ((DefinitionStmt) s).getLeftOp();
SootField field = null;
;
if (leftOp instanceof Local) {
toReturn.add(leftOp);
/*
* Gather more information just in case someone might need the def points
*/
Object temp = mapping.get(leftOp);
List<Stmt> defs;
if (temp == null) {
// first definition
defs = new ArrayList<Stmt>();
} else {
defs = (ArrayList<Stmt>) temp;
}
defs.add(s);
mapping.put(leftOp, defs);
} else if (leftOp instanceof FieldRef) {
field = ((FieldRef) leftOp).getField();
toReturn.add(field);
/*
* Gather more information just in case someone might need the def points
*/
Object temp = mapping.get(field);
List<Stmt> defs;
if (temp == null) {
// first definition
defs = new ArrayList<Stmt>();
} else {
defs = (ArrayList<Stmt>) temp;
}
defs.add(s);
mapping.put(field, defs);
}
return toReturn;
}
return inSet;
}
public boolean isMayInitialized(SootField field) {
if (MUSTMAY == MAY) {
Object temp = mapping.get(field);
if (temp == null) {
return false;
} else {
List list = (List) temp;
if (list.size() == 0) {
return false;
} else {
return true;
}
}
} else {
throw new RuntimeException("Cannot invoke isMayInitialized for a MUST analysis");
}
}
public boolean isMayInitialized(Value local) {
if (MUSTMAY == MAY) {
Object temp = mapping.get(local);
if (temp == null) {
return false;
} else {
List list = (List) temp;
if (list.size() == 0) {
return false;
} else {
return true;
}
}
} else {
throw new RuntimeException("Cannot invoke isMayInitialized for a MUST analysis");
}
}
public boolean isMustInitialized(SootField field) {
if (MUSTMAY == MUST) {
if (finalResult.contains(field)) {
return true;
}
return false;
} else {
throw new RuntimeException("Cannot invoke isMustinitialized for a MAY analysis");
}
}
public boolean isMustInitialized(Value local) {
if (MUSTMAY == MUST) {
if (finalResult.contains(local)) {
return true;
}
return false;
} else {
throw new RuntimeException("Cannot invoke isMustinitialized for a MAY analysis");
}
}
/*
* Given a local ask for all def positions Notice this could be null in the case there was no definition
*/
public List getDefs(Value local) {
Object temp = mapping.get(local);
if (temp == null) {
return null;
} else {
return (List) temp;
}
}
/*
* Given a field ask for all def positions Notice this could be null in the case there was no definition
*/
public List getDefs(SootField field) {
Object temp = mapping.get(field);
if (temp == null) {
return null;
} else {
return (List) temp;
}
}
}
| 8,076
| 26.287162
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/ReachingCopies.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.Local;
import soot.Value;
import soot.dava.internal.AST.ASTUnaryBinaryCondition;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
/*
ReachingCopies
Step 1:
Set of pairs where each pair has the form (a,b) indicating a statement a=b
Step 2:
A copy statement (a=b) reaches a statement s if all paths leading to s have a copy
statemet a=b and the values of a and b are not changed between the copy statement and the statement s.
Step 3:
Forward Analysis
Step 4:
Intersection
Step 5:
x = expr
kill = { all pairs containing x in left or right position}
if expr is a local , y
gen = (x,y)
Step 6:
out(start) = {}
newInitialFlow: No copies are available. an empty flow set
remember new InitialFlow is ONLY used for input to catchBodies
In ordinary flow analyses one has to assume that out(Si) is the universal set
for reaching copies. However the way structured flow analysis works
there is no need for such an assumption since it is never used in the structured flow analysis code
*/
public class ReachingCopies extends StructuredAnalysis {
/***************** DEFINIING LOCAL PAIR CLASS ************************/
public class LocalPair {
private final Local leftLocal;
private final Local rightLocal;
public LocalPair(Local left, Local right) {
leftLocal = left;
rightLocal = right;
}
public Local getLeftLocal() {
return leftLocal;
}
public Local getRightLocal() {
return rightLocal;
}
public boolean equals(Object other) {
if (other instanceof LocalPair) {
if (this.leftLocal.toString().equals(((LocalPair) other).getLeftLocal().toString())) {
if (this.rightLocal.toString().equals(((LocalPair) other).getRightLocal().toString())) {
return true;
}
}
}
return false;
}
/**
* Method checks whether local occurs in the left or right side of the localpair different semantics than the usual
* contains method which checks something in a list
*/
public boolean contains(Local local) {
if (leftLocal.toString().equals(local.toString()) || rightLocal.toString().equals(local.toString())) {
return true;
}
return false;
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append("<" + leftLocal.toString() + "," + rightLocal.toString() + ">");
return b.toString();
}
}
/****************************** END OF LOCAL PAIR CLASS ***********************/
public ReachingCopies(Object analyze) {
super();
// the input to the process method is an empty DavaFlow Set meaning
// out(start) ={}
DavaFlowSet temp = (DavaFlowSet) process(analyze, new DavaFlowSet());
}
public DavaFlowSet emptyFlowSet() {
return new DavaFlowSet();
}
public void setMergeType() {
MERGETYPE = INTERSECTION;
}
@Override
public DavaFlowSet newInitialFlow() {
return new DavaFlowSet();
}
@Override
public DavaFlowSet cloneFlowSet(DavaFlowSet flowSet) {
return ((DavaFlowSet) flowSet).clone();
}
/*
* By construction conditions never have assignment statements. Hence processing a condition has no effect on this analysis
*/
@Override
public DavaFlowSet processUnaryBinaryCondition(ASTUnaryBinaryCondition cond, DavaFlowSet input) {
return input;
}
/*
* By construction the synchronized Local is a Value and can definetly not have an assignment stmt Processing a synch local
* has no effect on this analysis
*/
@Override
public DavaFlowSet processSynchronizedLocal(Local local, DavaFlowSet input) {
return input;
}
/*
* The switch key is stored as a value and hence can never have an assignment stmt Processing the switch key has no effect
* on the analysis
*/
@Override
public DavaFlowSet processSwitchKey(Value key, DavaFlowSet input) {
return input;
}
/*
* This method internally invoked by the process method decides which Statement specialized method to call
*/
@Override
public DavaFlowSet processStatement(Stmt s, DavaFlowSet input) {
DavaFlowSet inSet = (DavaFlowSet) input;
/*
* If this path will not be taken return no path straightaway
*/
if (inSet == NOPATH) {
return inSet;
}
if (s instanceof DefinitionStmt) {
DavaFlowSet toReturn = (DavaFlowSet) cloneFlowSet(inSet);
// x = expr;
// check if expr is a local in which case this is a copy
Value leftOp = ((DefinitionStmt) s).getLeftOp();
Value rightOp = ((DefinitionStmt) s).getRightOp();
if (leftOp instanceof Local) {
// KILL any available copy with local since it has been
// redefined
kill(toReturn, (Local) leftOp);
} // leftop is a local
if (leftOp instanceof Local && rightOp instanceof Local) {
// this is a copy statement
// GEN
gen(toReturn, (Local) leftOp, (Local) rightOp);
}
return toReturn;
} else {
return input;
}
}
public void gen(DavaFlowSet in, Local left, Local right) {
// adding localpair
// no need to check for duplicates as the DavaFlowSet checks that
LocalPair localp = new LocalPair(left, right);
in.add(localp);
}
public void kill(DavaFlowSet<LocalPair> in, Local redefined) {
// kill any previous localpairs which have the redefined Local in the
// left OR right position
for (Iterator<LocalPair> listIt = in.iterator(); listIt.hasNext();) {
LocalPair tempPair = listIt.next();
if (tempPair.contains(redefined)) {
// need to kill this from the list
listIt.remove();
}
}
}
/*
* Wrapper method to get before set of an ASTNode or Statement which gives us the reaching copies at this point
*/
public DavaFlowSet getReachingCopies(Object node) {
// get the before set for this node
DavaFlowSet beforeSet = getBeforeSet(node);
if (beforeSet == null) {
throw new RuntimeException("Could not get reaching copies of node/stmt");
}
// Get all reachingCopies
/*
* the list that toList of this object contains elements of type LocalPair (a,b) which means this is a copy stmt of the
* form a=b
*/
return beforeSet;
}
}
| 7,170
| 28.755187
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/ReachingDefs.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 soot.Local;
import soot.Value;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTUnaryBinaryCondition;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.toolkits.base.AST.traversals.AllDefinitionsFinder;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
//import soot.dava.internal.javaRep.*;
//import soot.dava.internal.SET.*;
/**
* CHANGE LOG: * November 21st Added support for implicit breaks and continues Tested code for reaching defs within
* switch/try/if/while/for
*
* * November 22nd Refactored code to make structure flow analysis framework handle breaks and returns.
*
* * November 24th newInitialFlow ERROR............initialFlow should be the set of all defs........since there needs to
* exist SOME path
*/
/*
* Reaching Defs Step 1: Set of definitions (a definition is a Stmt within a StatementSequenceNode) Step 2: A definition d: x
* = ... reaches a point p in the program if there exists a path from p such that there is no other definition of x between d
* and p. Step 3: Forward Analysis Step 4: Union Step 5: d: x = expr kill = { all existing defs of x}
*
* gen = (d)
*
* Step 6: newInitialFlow: No definitions reach (safe) (Catch bodies) //November 24th.........changing above to be the
* universal set of all definitions
*
*
* out(start) = {} since there has been no definition so far
*
* out(Si) not needed for structured flow analysis
*/
public class ReachingDefs extends StructuredAnalysis<Stmt> {
Object toAnalyze;
public ReachingDefs(Object analyze) {
super();
toAnalyze = analyze;
process(analyze, new DavaFlowSet<Stmt>());
}
@Override
public DavaFlowSet<Stmt> emptyFlowSet() {
return new DavaFlowSet<Stmt>();
}
/*
* Initial flow into catch statements is empty meaning no definition reaches
*/
@Override
public DavaFlowSet<Stmt> newInitialFlow() {
DavaFlowSet<Stmt> initial = new DavaFlowSet<Stmt>();
// find all definitions in the program
AllDefinitionsFinder defFinder = new AllDefinitionsFinder();
((ASTNode) toAnalyze).apply(defFinder);
List<DefinitionStmt> allDefs = defFinder.getAllDefs();
// all defs is the list of all augmented stmts which contains
// DefinitionStmts
for (DefinitionStmt def : allDefs) {
initial.add(def);
}
// initial is not the universal set of all definitions
return initial;
}
/*
* Using union
*/
public void setMergeType() {
MERGETYPE = UNION;
}
@Override
public DavaFlowSet<Stmt> cloneFlowSet(DavaFlowSet<Stmt> flowSet) {
return flowSet.clone();
}
/*
* In the case of reachingDefs the evaluation of a condition has no effect on the reachingDefs
*/
@Override
public DavaFlowSet<Stmt> processUnaryBinaryCondition(ASTUnaryBinaryCondition cond, DavaFlowSet<Stmt> inSet) {
return inSet;
}
/*
* In the case of reachingDefs the use of a local has no effect on reachingDefs
*/
@Override
public DavaFlowSet<Stmt> processSynchronizedLocal(Local local, DavaFlowSet<Stmt> inSet) {
return inSet;
}
/*
* In the case of reachingDefs a value has no effect on reachingDefs
*/
@Override
public DavaFlowSet<Stmt> processSwitchKey(Value key, DavaFlowSet<Stmt> inSet) {
return inSet;
}
/*
* This method internally invoked by the process method decides which Statement specialized method to call
*/
@Override
public DavaFlowSet<Stmt> processStatement(Stmt s, DavaFlowSet<Stmt> inSet) {
/*
* If this path will not be taken return no path straightaway
*/
if (inSet == NOPATH) {
return inSet;
}
if (s instanceof DefinitionStmt) {
DavaFlowSet<Stmt> toReturn = cloneFlowSet(inSet);
// d:x = expr
// gen is x
// kill is all previous defs of x
Value leftOp = ((DefinitionStmt) s).getLeftOp();
if (leftOp instanceof Local) {
// KILL any reaching defs of leftOp
kill(toReturn, (Local) leftOp);
// GEN
gen(toReturn, (DefinitionStmt) s);
return toReturn;
} // leftop is a local
}
return inSet;
}
public void gen(DavaFlowSet<Stmt> in, DefinitionStmt s) {
// System.out.println("Adding Definition Stmt: "+s);
in.add(s);
}
public void kill(DavaFlowSet<Stmt> in, Local redefined) {
String redefinedLocalName = redefined.getName();
// kill any previous localpairs which have the redefined Local in the
// left i.e. previous definitions
for (Iterator<Stmt> listIt = in.iterator(); listIt.hasNext();) {
DefinitionStmt tempStmt = (DefinitionStmt) listIt.next();
Value leftOp = tempStmt.getLeftOp();
if (leftOp instanceof Local) {
String storedLocalName = ((Local) leftOp).getName();
if (redefinedLocalName.compareTo(storedLocalName) == 0) {
// need to kill this from the list
// System.out.println("Killing "+tempStmt);
listIt.remove();
}
}
}
}
public List<DefinitionStmt> getReachingDefs(Local local, Object node) {
ArrayList<DefinitionStmt> toReturn = new ArrayList<DefinitionStmt>();
// get the reaching defs of this node
DavaFlowSet<Stmt> beforeSet = null;
/*
* If this object is some sort of loop while, for dowhile, unconditional then return after set
*/
if (node instanceof ASTWhileNode || node instanceof ASTDoWhileNode || node instanceof ASTUnconditionalLoopNode
|| node instanceof ASTForLoopNode) {
beforeSet = getAfterSet(node);
} else {
beforeSet = getBeforeSet(node);
}
if (beforeSet == null) {
throw new RuntimeException("Could not get reaching defs of node");
}
// find all reachingdefs matching this local
for (Object temp : beforeSet) {
// checking each def to see if it is a def of local
if (!(temp instanceof DefinitionStmt)) {
throw new RuntimeException("Not an instanceof DefinitionStmt" + temp);
}
DefinitionStmt stmt = (DefinitionStmt) temp;
Value leftOp = stmt.getLeftOp();
if (leftOp.toString().compareTo(local.toString()) == 0) {
toReturn.add(stmt);
}
}
return toReturn;
}
public void reachingDefsToString(Object node) {
// get the reaching defs of this node
DavaFlowSet<Stmt> beforeSet = null;
/*
* If this object is some sort of loop while, for dowhile, unconditional then return after set
*/
if (node instanceof ASTWhileNode || node instanceof ASTDoWhileNode || node instanceof ASTUnconditionalLoopNode
|| node instanceof ASTForLoopNode) {
beforeSet = getAfterSet(node);
} else {
beforeSet = getBeforeSet(node);
}
if (beforeSet == null) {
throw new RuntimeException("Could not get reaching defs of node");
}
// find all reachingdefs matching this local
for (Object o : beforeSet) {
System.out.println("Reaching def:" + o);
}
}
}
| 8,023
| 30.84127
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/StructuredAnalysis.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.Local;
import soot.Value;
import soot.dava.internal.AST.ASTAggregatedCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTLabeledNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.AST.ASTUnaryBinaryCondition;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DAbruptStmt;
import soot.jimple.RetStmt;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
/*
* This class is meant to be extended to write structred analyses.
* The analysis is invoked by invoking the process method sending it
* the body to be analyzed and the input flowset
* Currently support is available only for a forward flow analysis.
* This should soon be refactored to include backwards flow analysis
* (Nomair 16th November 2005)
*/
public abstract class StructuredAnalysis<E> {
public static boolean DEBUG = false;
public static boolean DEBUG_IF = false;
public static boolean DEBUG_WHILE = false;
public static boolean DEBUG_STATEMENTS = false;
public static boolean DEBUG_TRY = false;
/*
* public static boolean DEBUG = true; public static boolean DEBUG_IF = true; public static boolean DEBUG_WHILE = true;
* public static boolean DEBUG_STATEMENTS = true; public static boolean DEBUG_TRY = true; /* /** Whenever an abrupt edge is
* encountered the flow set is added into a the break or continue list and a NOPATH object is returned
*/
DavaFlowSet<E> NOPATH = emptyFlowSet();
public int MERGETYPE; // the confluence operator
// the three types of operators
final int UNDEFINED = 0;
final int UNION = 1;
final int INTERSECTION = 2;
// storing before and after sets for each stmt or ASTNode
HashMap<Object, DavaFlowSet<E>> beforeSets, afterSets;
public StructuredAnalysis() {
beforeSets = new HashMap<Object, DavaFlowSet<E>>();
afterSets = new HashMap<Object, DavaFlowSet<E>>();
MERGETYPE = UNDEFINED;
// invoke user defined function which makes sure that you have the merge
// operator set
setMergeType();
// System.out.println("MergeType is"+MERGETYPE);
if (MERGETYPE == UNDEFINED) {
throw new RuntimeException("MERGETYPE UNDEFINED");
}
}
/*
* This method should be used to set the variable MERGETYPE use StructuredAnalysis.UNION for union use
* StructuredAnalysis.INTERSECTION for intersection
*/
public abstract void setMergeType();
/*
* Returns the flow object corresponding to the initial values for the catch statements
*/
public abstract DavaFlowSet<E> newInitialFlow();
/*
* Returns an empty flow set object Notice this has to be a DavaFlowSet or a set extending DavaFlowSet (hopefully
* constantpropagationFlowSET??)
*/
public abstract DavaFlowSet<E> emptyFlowSet();
/**
* Make a clone of the flowset The implementor should know when they want a shallow or deep clone
*/
public abstract DavaFlowSet<E> cloneFlowSet(DavaFlowSet<E> flowSet);
/**
* Specific stmts within AST Constructs are processed through this method. It will be invoked everytime a stmt is
* encountered
*/
public abstract DavaFlowSet<E> processStatement(Stmt s, DavaFlowSet<E> input);
/**
* To have maximum flexibility in analyzing conditions the analysis API breaks down the aggregated conditions to simple
* unary or binary conditions user defined code can then deal with each condition separately. To be able to deal with
* entire aggregated conditions the user should wite their own implementation of the method processCondition
*/
public abstract DavaFlowSet<E> processUnaryBinaryCondition(ASTUnaryBinaryCondition cond, DavaFlowSet<E> input);
/**
* To deal with the local used for synch blocks
*/
public abstract DavaFlowSet<E> processSynchronizedLocal(Local local, DavaFlowSet<E> input);
/**
* Deal with the key in the switch construct
*/
public abstract DavaFlowSet<E> processSwitchKey(Value key, DavaFlowSet<E> input);
public void print(Object toPrint) {
System.out.println(toPrint.toString());
}
/**
* This implementation breaks down the aggregated condition to the terminal conditions which all have type
* ASTUnaryBinaryCondition. Once these are obtained the abstract method processUnaryBinaryCondition is invoked. For
* aggregated conditions the merging is done in a depth first order of the condition tree.
*/
public DavaFlowSet<E> processCondition(ASTCondition cond, DavaFlowSet<E> input) {
if (cond instanceof ASTUnaryBinaryCondition) {
return processUnaryBinaryCondition((ASTUnaryBinaryCondition) cond, input);
} else if (cond instanceof ASTAggregatedCondition) {
ASTCondition left = ((ASTAggregatedCondition) cond).getLeftOp();
DavaFlowSet<E> output1 = processCondition(left, input);
ASTCondition right = ((ASTAggregatedCondition) cond).getRightOp();
DavaFlowSet<E> output2 = processCondition(right, output1);
return merge(output1, output2);
} else {
throw new RuntimeException("Unknown ASTCondition found in structred flow analysis");
}
}
/*
* The parameter body contains the body to be analysed It can be an ASTNode, a Stmt, an augmentedStmt or a list of ASTNodes
* The input is any data that is gathered plus any info needed for making decisions during the analysis
*/
public DavaFlowSet<E> process(Object body, DavaFlowSet<E> input) {
if (body instanceof ASTNode) {
beforeSets.put(body, input);
DavaFlowSet<E> temp = processASTNode((ASTNode) body, input);
afterSets.put(body, temp);
return temp;
} else if (body instanceof Stmt) {
beforeSets.put(body, input);
DavaFlowSet<E> result = processAbruptStatements((Stmt) body, input);
afterSets.put(body, result);
return result;
} else if (body instanceof AugmentedStmt) {
AugmentedStmt as = (AugmentedStmt) body;
Stmt s = as.get_Stmt();
beforeSets.put(s, input);
DavaFlowSet<E> result = processAbruptStatements(s, input);
afterSets.put(s, result);
return result;
} else if (body instanceof List) {
// this should always be a list of ASTNodes
Iterator it = ((List) body).iterator();
DavaFlowSet<E> result = input;
while (it.hasNext()) {
Object temp = it.next();
if (!(temp instanceof ASTNode)) {
throw new RuntimeException(
"Body sent to be processed by " + "StructuredAnalysis contains a list which does not have ASTNodes");
} else {
/*
* As we are simply going through a list of ASTNodes The output of the previous becomes the input of the next
*/
beforeSets.put(temp, result);
result = processASTNode((ASTNode) temp, result);
afterSets.put(temp, result);
}
} // end of going through list
// at this point the result var contains the result of processing
// the List
return result;
} else {
throw new RuntimeException("Body sent to be processed by " + "StructuredAnalysis is not a valid body");
}
}
/*
* This method internally invoked by the process method decides which ASTNode specialized method to call
*/
public DavaFlowSet<E> processASTNode(ASTNode node, DavaFlowSet<E> input) {
if (node instanceof ASTDoWhileNode) {
return processASTDoWhileNode((ASTDoWhileNode) node, input);
} else if (node instanceof ASTForLoopNode) {
return processASTForLoopNode((ASTForLoopNode) node, input);
} else if (node instanceof ASTIfElseNode) {
return processASTIfElseNode((ASTIfElseNode) node, input);
} else if (node instanceof ASTIfNode) {
return processASTIfNode((ASTIfNode) node, input);
} else if (node instanceof ASTLabeledBlockNode) {
return processASTLabeledBlockNode((ASTLabeledBlockNode) node, input);
} else if (node instanceof ASTMethodNode) {
return processASTMethodNode((ASTMethodNode) node, input);
} else if (node instanceof ASTStatementSequenceNode) {
return processASTStatementSequenceNode((ASTStatementSequenceNode) node, input);
} else if (node instanceof ASTSwitchNode) {
return processASTSwitchNode((ASTSwitchNode) node, input);
} else if (node instanceof ASTSynchronizedBlockNode) {
return processASTSynchronizedBlockNode((ASTSynchronizedBlockNode) node, input);
} else if (node instanceof ASTTryNode) {
return processASTTryNode((ASTTryNode) node, input);
} else if (node instanceof ASTWhileNode) {
return processASTWhileNode((ASTWhileNode) node, input);
} else if (node instanceof ASTUnconditionalLoopNode) {
return processASTUnconditionalLoopNode((ASTUnconditionalLoopNode) node, input);
} else {
throw new RuntimeException("processASTNode called using unknown node type");
}
}
/**
* This method is called from the specialized ASTNodes. The purpose was to deal with different ASTNodes with similar
* structure in one go. The method will deal with retrieve the body of the ASTNode which are known to have only one subBody
*/
public final DavaFlowSet<E> processSingleSubBodyNode(ASTNode node, DavaFlowSet<E> input) {
// get the subBodies
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 1) {
throw new RuntimeException("processSingleSubBodyNode called with a node without one subBody");
}
// we know there is only one
List subBody = (List) subBodies.get(0);
return process(subBody, input);
}
/**
* returns label on the ASTNode null if the ASTNode cannot hold a label or if the label is null
*/
public String getLabel(ASTNode node) {
if (node instanceof ASTLabeledNode) {
Object temp = ((ASTLabeledNode) node).get_Label();
if (temp != null) {
return temp.toString();
}
}
return null;
}
/**
* Whenever a statement has to be processed the first step is to invoke this method. This is to remove the tedious work of
* adding code to deal with abrupt control flow from the programmer of the analysis. The method invokes the
* processStatement method for all other statements
*
* A programmer can decide to override this method if they want to do something specific
*/
public DavaFlowSet<E> processAbruptStatements(Stmt s, DavaFlowSet<E> input) {
if (s instanceof ReturnStmt || s instanceof RetStmt || s instanceof ReturnVoidStmt) {
// dont need to remember this path
return NOPATH;
} else if (s instanceof DAbruptStmt) {
DAbruptStmt abStmt = (DAbruptStmt) s;
// see if its a break or continue
if (!(abStmt.is_Continue() || abStmt.is_Break())) {
// DAbruptStmt is of only two kinds
throw new RuntimeException("Found a DAbruptStmt which is neither break nor continue!!");
}
DavaFlowSet<E> temp = NOPATH;
SETNodeLabel nodeLabel = abStmt.getLabel();
// System.out.println("here");
if (nodeLabel != null && nodeLabel.toString() != null) {
// explicit abrupt stmt
if (abStmt.is_Continue()) {
temp.addToContinueList(nodeLabel.toString(), input);
} else if (abStmt.is_Break()) {
temp.addToBreakList(nodeLabel.toString(), input);
} else {
throw new RuntimeException("Found abruptstmt which is neither break nor continue");
}
} else {
// found implicit break/continue
if (abStmt.is_Continue()) {
temp.addToImplicitContinues(abStmt, input);
} else if (abStmt.is_Break()) {
temp.addToImplicitBreaks(abStmt, input);
} else {
throw new RuntimeException("Found abruptstmt which is neither break nor continue");
}
}
return temp;
} else {
/**************************************************************/
/****** ALL OTHER STATEMENTS HANDLED BY PROGRAMMER **************/
/**************************************************************/
return processStatement(s, input);
}
}
/*
* Notice Right now the output of the processing of method bodies is returned as the output. This only works for INTRA
* procedural Analysis. For accomodating INTER procedural analysis one needs to have a return list of all possible returns
* (stored in the flowset) And merge Returns with the output of normal execution of the body
*/
// reasoned about this....seems right!!
public DavaFlowSet<E> processASTMethodNode(ASTMethodNode node, DavaFlowSet<E> input) {
DavaFlowSet<E> temp = processSingleSubBodyNode(node, input);
return temp;
}
public DavaFlowSet<E> processASTStatementSequenceNode(ASTStatementSequenceNode node, DavaFlowSet<E> input) {
DavaFlowSet<E> output = cloneFlowSet(input);// needed if there are no stmts
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
/*
* Since we are processing a list of statements the output of previous is input of next
*/
output = process(s, output);
if (DEBUG_STATEMENTS) {
System.out.println("After Processing statement " + s + output.toString());
;
}
}
return output;
}
// reasoned about this....seems right!!
public DavaFlowSet<E> processASTLabeledBlockNode(ASTLabeledBlockNode node, DavaFlowSet<E> input) {
DavaFlowSet<E> output1 = processSingleSubBodyNode(node, input);
// handle break
String label = getLabel(node);
return handleBreak(label, output1, node);
}
public DavaFlowSet<E> processASTSynchronizedBlockNode(ASTSynchronizedBlockNode node, DavaFlowSet<E> input) {
input = processSynchronizedLocal(node.getLocal(), input);
DavaFlowSet<E> output = processSingleSubBodyNode(node, input);
String label = getLabel(node);
return handleBreak(label, output, node);
}
// reasoned about this....seems right!!
public DavaFlowSet<E> processASTIfNode(ASTIfNode node, DavaFlowSet<E> input) {
input = processCondition(node.get_Condition(), input);
DavaFlowSet<E> output1 = processSingleSubBodyNode(node, input);
// merge with input which tells if the cond did not evaluate to true
DavaFlowSet<E> output2 = merge(input, output1);
// handle break
String label = getLabel(node);
DavaFlowSet<E> temp = handleBreak(label, output2, node);
if (DEBUG_IF) {
System.out.println("Exiting if node" + temp.toString());
}
return temp;
}
public DavaFlowSet<E> processASTIfElseNode(ASTIfElseNode node, DavaFlowSet<E> input) {
// get the subBodies
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 2) {
throw new RuntimeException("processASTIfElseNode called with a node without two subBodies");
}
// we know there is only two subBodies
List subBodyOne = (List) subBodies.get(0);
List subBodyTwo = (List) subBodies.get(1);
// process Condition
input = processCondition(node.get_Condition(), input);
// the current input flowset is sent to both branches
DavaFlowSet<E> clonedInput = cloneFlowSet(input);
DavaFlowSet<E> output1 = process(subBodyOne, clonedInput);
clonedInput = cloneFlowSet(input);
DavaFlowSet<E> output2 = process(subBodyTwo, clonedInput);
DavaFlowSet<E> temp = merge(output1, output2);
// notice we handle breaks only once since these are breaks to the same
// label or same node
String label = getLabel(node);
output1 = handleBreak(label, temp, node);
return output1;
}
public DavaFlowSet<E> processASTWhileNode(ASTWhileNode node, DavaFlowSet<E> input) {
DavaFlowSet<E> lastin = null;
DavaFlowSet<E> initialInput = cloneFlowSet(input);
String label = getLabel(node);
DavaFlowSet<E> output = null;
input = processCondition(node.get_Condition(), input);
if (DEBUG_WHILE) {
System.out.println("Going int while (condition processed): " + input.toString());
}
do {
lastin = cloneFlowSet(input);
output = processSingleSubBodyNode(node, input);
// handle continue
output = handleContinue(label, output, node);
// merge with the initial input
input = merge(initialInput, output);
input = processCondition(node.get_Condition(), input);
} while (isDifferent(lastin, input));
// input contains the result of the fixed point
DavaFlowSet<E> temp = handleBreak(label, input, node);
if (DEBUG_WHILE) {
System.out.println("Going out of while: " + temp.toString());
}
return temp;
}
public DavaFlowSet<E> processASTDoWhileNode(ASTDoWhileNode node, DavaFlowSet<E> input) {
DavaFlowSet<E> lastin = null, output = null;
DavaFlowSet<E> initialInput = cloneFlowSet(input);
String label = getLabel(node);
if (DEBUG_WHILE) {
System.out.println("Going into do-while: " + initialInput.toString());
}
do {
lastin = cloneFlowSet(input);
output = processSingleSubBodyNode(node, input);
// handle continue
output = handleContinue(label, output, node);
output = processCondition(node.get_Condition(), output);
// merge with the initial input
input = merge(initialInput, output);
} while (isDifferent(lastin, input));
// output contains the result of the fixed point since do-while breaks
// of at the processing of cond
DavaFlowSet<E> temp = handleBreak(label, output, node);
if (DEBUG_WHILE) {
System.out.println("Going out of do-while: " + temp.toString());
}
return temp;
}
public DavaFlowSet<E> processASTUnconditionalLoopNode(ASTUnconditionalLoopNode node, DavaFlowSet<E> input) {
// an unconditional loop behaves almost like a conditional While loop
DavaFlowSet<E> initialInput = cloneFlowSet(input);
DavaFlowSet<E> lastin = null;
if (DEBUG_WHILE) {
System.out.println("Going into while(true): " + initialInput.toString());
}
String label = getLabel(node);
DavaFlowSet<E> output = null;
do {
lastin = cloneFlowSet(input);
output = processSingleSubBodyNode(node, input);
// handle continue
output = handleContinue(label, output, node);
// merge this with the initial input
input = merge(initialInput, output);
} while (isDifferent(lastin, input));
// the output is not part of the set returned
// it is just used to retrieve the set of breaklists stored for this
// label
DavaFlowSet<E> temp = getMergedBreakList(label, output, node);
if (DEBUG_WHILE) {
System.out.println("Going out of while(true): " + temp.toString());
}
return temp;
}
public DavaFlowSet<E> processASTForLoopNode(ASTForLoopNode node, DavaFlowSet<E> input) {
for (AugmentedStmt as : node.getInit()) {
Stmt s = as.get_Stmt();
input = process(s, input);
}
// finished processing the init part of the for loop
DavaFlowSet<E> initialInput = cloneFlowSet(input);
input = processCondition(node.get_Condition(), input);
DavaFlowSet<E> lastin = null;
String label = getLabel(node);
DavaFlowSet<E> output2 = null;
do {
lastin = cloneFlowSet(input);
// process body
DavaFlowSet<E> output1 = processSingleSubBodyNode(node, input);
// handle continues (Notice this is done before update!!!)
output1 = handleContinue(label, output1, node);
// notice that we dont merge with the initial output1 from
// processing singleSubBody
// the handlecontinue function takes care of it
// handle update
output2 = cloneFlowSet(output1);// if there is nothing in update
for (AugmentedStmt as : node.getUpdate()) {
Stmt s = as.get_Stmt();
/*
* Since we are just going over a list of statements the output of each statement is the input of the next
*/
output2 = process(s, output2);
}
// output2 is the final result
// merge this with the input
input = merge(initialInput, output2);
input = processCondition(node.get_Condition(), input);
} while (isDifferent(lastin, input));
// handle break
return handleBreak(label, input, node);
}
/*
* Notice ASTSwitch is horribly conservative....eg. if all cases break properly it will still merge with defaultOut which
* will be a NOPATH and bound to have empty or full sets
*/
public DavaFlowSet<E> processASTSwitchNode(ASTSwitchNode node, DavaFlowSet<E> input) {
if (DEBUG) {
System.out.println("Going into switch: " + input.toString());
}
List<Object> indexList = node.getIndexList();
Map<Object, List<Object>> index2BodyList = node.getIndex2BodyList();
Iterator<Object> it = indexList.iterator();
input = processSwitchKey(node.get_Key(), input);
DavaFlowSet<E> initialIn = cloneFlowSet(input);
DavaFlowSet<E> out = null;
DavaFlowSet<E> defaultOut = null;
List<DavaFlowSet<E>> toMergeBreaks = new ArrayList<DavaFlowSet<E>>();
while (it.hasNext()) {
// going through all the cases of the switch
// statement
Object currentIndex = it.next();
List body = index2BodyList.get(currentIndex);
// BUG FIX if body is null (fall through we shouldnt invoke process
// Reported by Steffen Pingel 14th Jan 2006 on the soot mailing list
if (body != null) {
out = process(body, input);
// System.out.println("Breaklist for this out is"+out.getBreakList());
toMergeBreaks.add(cloneFlowSet(out));
if (currentIndex instanceof String) {
// this is the default
defaultOut = out;
}
// the input to the next can be a fall through or directly input
input = merge(out, initialIn);
} // body was non null
}
// have to handle the case when no case matches. The input is the output
DavaFlowSet<E> output = null;
if (out != null) {
// just to make sure that there were some cases
// present
/*
* January 30th 2006, FOUND BUG The initialIn should only be merge with the out if there is no default in the list of
* switch cases If there is a default then there is no way that the initialIn is the actual result. Then its either the
* default or one of the outs!!!
*/
if (defaultOut != null) {
// there was a default
// System.out.println("DEFAULTSET");
// System.out.println("defaultOut is"+defaultOut);
// System.out.println("out is"+out);
output = merge(defaultOut, out);
} else {
// there was no default so no case might match
output = merge(initialIn, out);
}
} else {
output = initialIn;
}
// handle break
String label = getLabel(node);
// have to handleBreaks for all the different cases
List<DavaFlowSet<E>> outList = new ArrayList<DavaFlowSet<E>>();
// handling breakLists of each of the toMergeBreaks
for (DavaFlowSet<E> mset : toMergeBreaks) {
outList.add(handleBreak(label, mset, node));
}
// merge all outList elements. since these are the outputs with breaks
// handled
DavaFlowSet<E> finalOut = output;
for (DavaFlowSet<E> outIt : outList) {
finalOut = merge(finalOut, outIt);
}
if (DEBUG) {
System.out.println("Going out of switch: " + finalOut.toString());
}
return finalOut;
}
public DavaFlowSet<E> processASTTryNode(ASTTryNode node, DavaFlowSet<E> input) {
if (DEBUG_TRY) {
System.out.println("TRY START is:" + input);
}
// System.out.println("SET beginning of tryBody is:"+input);
List<Object> tryBody = node.get_TryBody();
DavaFlowSet<E> tryBodyOutput = process(tryBody, input);
// System.out.println("SET end of tryBody is:"+tryBodyOutput);
/*
* By default take either top or bottom as the input to the catch statements Which goes in depends on the type of
* analysis.
*/
DavaFlowSet<E> inputCatch = newInitialFlow();
if (DEBUG_TRY) {
System.out.println("TRY initialFLOW is:" + inputCatch);
}
List<Object> catchList = node.get_CatchList();
Iterator<Object> it = catchList.iterator();
List<DavaFlowSet<E>> catchOutput = new ArrayList<DavaFlowSet<E>>();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container) it.next();
List<E> body = (List<E>) catchBody.o;
// list of ASTNodes
// result because of going through the catchBody
DavaFlowSet<E> tempResult = process(body, cloneFlowSet(inputCatch));
// System.out.println("TempResult going through body"+tempResult);
catchOutput.add(tempResult);
}
// handle breaks
String label = getLabel(node);
/*
* 30th Jan 2005, Found bug in handling out breaks what was being done was that handleBreak was invoked using just
* handleBreak(label,tryBodyoutput,node) Now what it does is that it looks for the breakList stored in the tryBodyOutput
* node What might happen is that there might be some breaks in the catchOutput which would have gotten stored in the
* breakList of the respective catchoutput
*
* The correct way to handle this is create a list of handledBreak objects (in the outList) And then to merge them
*/
List<DavaFlowSet<E>> outList = new ArrayList<DavaFlowSet<E>>();
// handle breaks out of tryBodyOutput
outList.add(handleBreak(label, tryBodyOutput, node));
// System.out.println("After handling break from tryBodyOutput"+outList.get(0));
// handling breakLists of each of the catchOutputs
for (DavaFlowSet<E> co : catchOutput) {
DavaFlowSet<E> temp = handleBreak(label, co, node);
if (DEBUG_TRY) {
System.out.println("TRY handling breaks is:" + temp);
}
outList.add(temp);
}
// merge all outList elements. since these are the outputs with breaks
// handled
DavaFlowSet<E> out = tryBodyOutput;
for (DavaFlowSet<E> co : outList) {
out = merge(out, co);
}
if (DEBUG_TRY) {
System.out.println("TRY after merge outList is:" + out);
}
// System.out.println("After handling break"+out);
for (DavaFlowSet<E> co : catchOutput) {
out = merge(out, co);
}
if (DEBUG_TRY) {
System.out.println("TRY END RESULT is:" + out);
}
return out;
}
/*
* MERGETYPE var has to be set 0, means no type set 1, means union 2, means intersection
*/
public DavaFlowSet<E> merge(DavaFlowSet<E> in1, DavaFlowSet<E> in2) {
if (MERGETYPE == 0) {
throw new RuntimeException("Use the setMergeType method to set the type of merge used in the analysis");
}
DavaFlowSet<E> out;
if (in1 == NOPATH && in2 != NOPATH) {
out = in2.clone();
out.copyInternalDataFrom(in1);
return out;
} else if (in1 != NOPATH && in2 == NOPATH) {
out = in1.clone();
out.copyInternalDataFrom(in2);
return out;
} else if (in1 == NOPATH && in2 == NOPATH) {
out = in1.clone();
out.copyInternalDataFrom(in2);
return out; // meaning return NOPATH
} else {
// both are not NOPATH
out = emptyFlowSet();
if (MERGETYPE == 1) {
in1.union(in2, out);
} else if (MERGETYPE == 2) {
in1.intersection(in2, out);
} else {
throw new RuntimeException("Merge type value" + MERGETYPE + " not recognized");
}
out.copyInternalDataFrom(in1);
out.copyInternalDataFrom(in2);
return out;
}
}
public DavaFlowSet<E> mergeExplicitAndImplicit(String label, DavaFlowSet<E> output, List<DavaFlowSet<E>> explicitSet,
List<DavaFlowSet<E>> implicitSet) {
DavaFlowSet<E> toReturn = output.clone();
if (label != null) {
// use the explicit list
/*
* If there is no list associated with this label or the list is empty there no explicit merging to be done
*/
if (explicitSet != null && explicitSet.size() != 0) {
// explicitSet is a list of DavaFlowSets
Iterator<DavaFlowSet<E>> it = explicitSet.iterator();
// we know there is atleast one element
toReturn = merge(output, it.next());
while (it.hasNext()) {
// merge this with toReturn
toReturn = merge(toReturn, it.next());
}
} // a non empty explicitSet was found
} // label not null could have explicit sets
// toReturn contains result of dealing with explicit stmts
// dealing with implicit set now
if (implicitSet != null) {
// implicitSet is a list of DavaFlowSets
Iterator<DavaFlowSet<E>> it = implicitSet.iterator();
while (it.hasNext()) {
// merge this with toReturn
toReturn = merge(toReturn, it.next());
}
}
return toReturn;
}
/**
* Need to handleBreak stmts There can be explicit breaks (in which case label is non null) There can always be implicit
* breaks ASTNode is non null
*/
public DavaFlowSet<E> handleBreak(String label, DavaFlowSet<E> out, ASTNode node) {
// get the explicit list with this label from the breakList
List<DavaFlowSet<E>> explicitSet = out.getBreakSet(label);
// System.out.println("\n\nExplicit set is"+explicitSet);
// getting the implicit list now
if (node == null) {
throw new RuntimeException("ASTNode sent to handleBreak was null");
}
List<DavaFlowSet<E>> implicitSet = out.getImplicitlyBrokenSets(node);
// System.out.println("\n\nImplicit set is"+implicitSet);
// invoke mergeExplicitAndImplicit
return mergeExplicitAndImplicit(label, out, explicitSet, implicitSet);
}
/**
* Need to handleContinue stmts There can be explicit continues (in which case label is non null) There can always be
* implicit continues ASTNode is non null
*/
public DavaFlowSet<E> handleContinue(String label, DavaFlowSet<E> out, ASTNode node) {
// get the explicit list with this label from the continueList
List<DavaFlowSet<E>> explicitSet = out.getContinueSet(label);
// getting the implicit list now
if (node == null) {
throw new RuntimeException("ASTNode sent to handleContinue was null");
}
List<DavaFlowSet<E>> implicitSet = out.getImplicitlyContinuedSets(node);
// invoke mergeExplicitAndImplicit
return mergeExplicitAndImplicit(label, out, explicitSet, implicitSet);
}
/**
* Invoked from within the UnconditionalWhile processing method Need to handle both explicit and implicit breaks
*/
private DavaFlowSet<E> getMergedBreakList(String label, DavaFlowSet<E> output, ASTNode node) {
List<DavaFlowSet<E>> breakSet = output.getBreakSet(label);
DavaFlowSet<E> toReturn = null;
if (breakSet == null) {
// there is no list associated with this label hence no merging to
// be done
// since this is a call from unconditional this means there should
// have been an implicit break
toReturn = NOPATH;
} else if (breakSet.size() == 0) {
// list is empty for this label hence no merging to be done
// since this is a call from unconditional this means there should
// have been an implicit break
toReturn = NOPATH;
} else {
// breakSet is a list of DavaFlowSets
Iterator<DavaFlowSet<E>> it = breakSet.iterator();
// we know there is atleast one element
// making sure we dont send NOPATH
toReturn = it.next();
while (it.hasNext()) {
// merge this with toReturn
toReturn = merge(toReturn, it.next());
}
} // a non empty breakSet was found
// dealing with implicit set now
List<DavaFlowSet<E>> implicitSet = output.getImplicitlyBrokenSets(node);
if (implicitSet != null) {
// implicitSet is a list of DavaFlowSets
Iterator<DavaFlowSet<E>> it = implicitSet.iterator();
// making sure that we dont send NOPATH
if (implicitSet.size() > 0) {
toReturn = it.next();
}
while (it.hasNext()) {
// merge this with toReturn
toReturn = merge(toReturn, it.next());
}
}
return toReturn;
}
public boolean isDifferent(DavaFlowSet<E> oldObj, DavaFlowSet<E> newObj) {
if (oldObj.equals(newObj) && oldObj.internalDataMatchesTo(newObj)) {
// set matches and breaks and continues also match
// System.out.println("NOT DIFFERENT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
return false;
} else {
// System.out.println(oldObj);
// System.out.println(newObj);
// System.out.println("DIFFERENT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
return true;
}
}
/*
* The before set contains the before set of an ASTNode , a Stmt , and AugmentedStmt, Notice for instance for a for loop we
* will get a before set before the loop and an after set after the loop
*
* we dont have info about before set before executing a particular stmt that kind of info is available if you know which
* stmt u want e.g. the update stmt
*/
public DavaFlowSet<E> getBeforeSet(Object beforeThis) {
return beforeSets.get(beforeThis);
}
public DavaFlowSet<E> getAfterSet(Object afterThis) {
return afterSets.get(afterThis);
}
public void debug(String methodName, String debug) {
if (DEBUG) {
System.out.println("Class: StructuredAnalysis MethodName: " + methodName + " DEBUG: " + debug);
}
}
public void debug(String debug) {
if (DEBUG) {
System.out.println("Class: StructuredAnalysis DEBUG: " + debug);
}
}
}
| 35,131
| 35.481828
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/structuredAnalysis/UnreachableCodeFinder.java
|
package soot.dava.toolkits.base.AST.structuredAnalysis;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Nomair A. Naeem
* %%
* 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.Local;
import soot.Value;
import soot.dava.DecompilationException;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.AST.ASTUnaryBinaryCondition;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.internal.javaRep.DAbruptStmt;
import soot.jimple.RetStmt;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
import soot.toolkits.scalar.FlowSet;
/*
* Sort of the mark phase of a mark and sweep dead code eliminator.
* Carry NOPATH information through the flowsets
*
* Will need to over ride the processAbruptStatement method of parent
* class since we plan to do something special with abrupt stmts
*
* ONLY PROCESS A CONSTRUCT IF ITS INSET HOLDS TRUE i.e. it is REACHABLE otherwise
* simply pass on the inset
*
* TODO:
* 1, The child after any loop is always reachable (even for a while(true) which returns)
* Will probably have to override loop process methods, invoke the super process method and then change the outset
* 2, handleBreak would need to see if there is any break stmt then set the out to contain true
*/
public class UnreachableCodeFinder extends StructuredAnalysis {
public static boolean DEBUG = false;
public class UnreachableCodeFlowSet extends DavaFlowSet {
public UnreachableCodeFlowSet clone() {
if (this.size() != 1) {
throw new DecompilationException("unreachableCodeFlow set size should always be 1");
}
Boolean temp = (Boolean) this.elements[0];
UnreachableCodeFlowSet toReturn = new UnreachableCodeFlowSet();
toReturn.add(new Boolean(temp.booleanValue()));
toReturn.copyInternalDataFrom(this);
return toReturn;
}
@Override
public void intersection(FlowSet otherFlow, FlowSet destFlow) {
if (DEBUG) {
System.out.println("In intersection");
}
if (!(otherFlow instanceof UnreachableCodeFlowSet) || !(destFlow instanceof UnreachableCodeFlowSet)) {
super.intersection(otherFlow, destFlow);
return;
}
UnreachableCodeFlowSet other = (UnreachableCodeFlowSet) otherFlow;
UnreachableCodeFlowSet dest = (UnreachableCodeFlowSet) destFlow;
UnreachableCodeFlowSet workingSet;
if (dest == other || dest == this) {
workingSet = new UnreachableCodeFlowSet();
} else {
workingSet = dest;
workingSet.clear();
}
if (other.size() != 1 || this.size() != 1) {
System.out.println("Other size = " + other.size());
System.out.println("This size = " + this.size());
throw new DecompilationException("UnreachableCodeFlowSet size should always be one");
}
Boolean thisPath = (Boolean) this.elements[0];
Boolean otherPath = (Boolean) other.elements[0];
if (!thisPath.booleanValue() && !otherPath.booleanValue()) {
// both say there is no path
workingSet.add((new Boolean(false)));
} else {
workingSet.add((new Boolean(true)));
}
(workingSet).copyInternalDataFrom(this);
if (otherFlow instanceof DavaFlowSet) {
(workingSet).copyInternalDataFrom((DavaFlowSet) otherFlow);
}
if (workingSet != dest) {
workingSet.copy(dest);
}
if (DEBUG) {
System.out.println("destFlow contains size:" + ((UnreachableCodeFlowSet) destFlow).size());
}
}
} // end UnreachableCodeFlowSet
public UnreachableCodeFinder(Object analyze) {
super();
// the input to the process method is newInitialFlow
DavaFlowSet temp = (DavaFlowSet) process(analyze, newInitialFlow());
}
/*
* Merge is intersection but our SPECIALIZED intersection hence creating our own specialize flow set with overriding the
* intersection method
*/
public void setMergeType() {
MERGETYPE = INTERSECTION;
}
/*
* For catch bodies.
*
* If you are processing the catch body that means you can reach to the try Since you can always come to a catchbody the
* inset to the catch body to should be that there is a path
*/
public DavaFlowSet newInitialFlow() {
DavaFlowSet newSet = emptyFlowSet();
newSet.add(new Boolean(true));
return newSet;
}
public DavaFlowSet emptyFlowSet() {
return new UnreachableCodeFlowSet();
}
@Override
public UnreachableCodeFlowSet cloneFlowSet(DavaFlowSet flowSet) {
if (flowSet instanceof UnreachableCodeFlowSet) {
return ((UnreachableCodeFlowSet) flowSet).clone();
}
throw new RuntimeException("Clone only implemented for UnreachableCodeFlowSet");
}
@Override
public DavaFlowSet processUnaryBinaryCondition(ASTUnaryBinaryCondition cond, DavaFlowSet input) {
return input;
}
@Override
public DavaFlowSet processSynchronizedLocal(Local local, DavaFlowSet input) {
return input;
}
@Override
public DavaFlowSet processSwitchKey(Value key, DavaFlowSet input) {
return input;
}
@Override
public DavaFlowSet processStatement(Stmt s, DavaFlowSet input) {
return input;
}
@Override
public DavaFlowSet processAbruptStatements(Stmt s, DavaFlowSet input) {
if (DEBUG) {
System.out.println("processing stmt " + s);
}
if (s instanceof ReturnStmt || s instanceof RetStmt || s instanceof ReturnVoidStmt) {
// dont need to remember this path
UnreachableCodeFlowSet toReturn = new UnreachableCodeFlowSet();
toReturn.add(new Boolean(false));
toReturn.copyInternalDataFrom(input);
// false indicates NOPATH
if (DEBUG) {
System.out.println("\tstmt is a return stmt. Hence sending forward false");
}
return toReturn;
} else if (s instanceof DAbruptStmt) {
DAbruptStmt abStmt = (DAbruptStmt) s;
// see if its a break or continue
if (!(abStmt.is_Continue() || abStmt.is_Break())) {
// DAbruptStmt is of only two kinds
throw new RuntimeException("Found a DAbruptStmt which is neither break nor continue!!");
}
DavaFlowSet temp = new UnreachableCodeFlowSet();
SETNodeLabel nodeLabel = abStmt.getLabel();
// notice we ignore continues for this analysis
if (abStmt.is_Break()) {
if (nodeLabel != null && nodeLabel.toString() != null) {
// explicit break stmt
temp.addToBreakList(nodeLabel.toString(), input);
} else {
// found implicit break
temp.addToImplicitBreaks(abStmt, input);
}
}
temp.add(new Boolean(false));
temp.copyInternalDataFrom(input);
if (DEBUG) {
System.out.println("\tstmt is an abrupt stmt. Hence sending forward false");
}
return temp;
} else {
if (DEBUG) {
System.out.println("\tstmt is not an abrupt stmt.");
}
return processStatement(s, input);
}
}
/*
* If a particular node is targeted by a break statement then that means there is always a path to it Hence if there is
* even a single entry in the implicit or explicit break set return a flow set which contains true since there is a path to
* this point
*/
@Override
public DavaFlowSet handleBreak(String label, DavaFlowSet output, ASTNode node) {
if (DEBUG) {
System.out.println("Handling break. Output contains" + ((UnreachableCodeFlowSet) output).size());
}
if (!(output instanceof UnreachableCodeFlowSet)) {
throw new RuntimeException("handleBreak is only implemented for UnreachableCodeFlowSet type");
}
DavaFlowSet out = (DavaFlowSet) output;
// get the explicit list with this label from the breakList
List explicitSet = out.getBreakSet(label);
// getting the implicit list now
if (node == null) {
throw new RuntimeException("ASTNode sent to handleBreak was null");
}
List implicitSet = out.getImplicitlyBrokenSets(node);
// System.out.println("\n\nImplicit set is"+implicitSet);
DavaFlowSet toReturn = emptyFlowSet();
toReturn.copyInternalDataFrom(output);
if ((explicitSet != null && explicitSet.size() > 0) || (implicitSet != null && implicitSet.size() > 0)) {
if (DEBUG) {
System.out.println("\tBreak sets (implicit and explicit are nonempty hence forwarding true");
}
// some break targets node
toReturn.add(new Boolean(true));
return toReturn;
} else {
// no break targets node, maybe output was true though hence use merge
toReturn.add(new Boolean(false));
if (DEBUG) {
System.out.println("\tBreak sets (implicit and explicit are empty hence forwarding merge of false with inset");
}
return merge(toReturn, output);
}
}
public boolean isReachable(Object input) {
if (!(input instanceof UnreachableCodeFlowSet)) {
throw new DecompilationException("Implemented only for UnreachableCodeFlowSet");
}
UnreachableCodeFlowSet checking = (UnreachableCodeFlowSet) input;
if (checking.size() != 1) {
throw new DecompilationException("unreachableCodeFlow set size should always be 1");
}
if (((Boolean) checking.elements[0]).booleanValue()) {
// it is reachable
if (DEBUG) {
System.out.println("\t Reachable");
}
return true;
} else {
if (DEBUG) {
System.out.println("\t NOT Reachable");
}
return false;
}
}
@Override
public DavaFlowSet processASTStatementSequenceNode(ASTStatementSequenceNode node, DavaFlowSet input) {
if (DEBUG) {
System.out.println("Processing statement sequence node");
}
if (!isReachable(input)) {
// this sequence is not reachable hence simply return inset
return input;
} else {
return super.processASTStatementSequenceNode(node, input);
}
}
@Override
public DavaFlowSet processASTLabeledBlockNode(ASTLabeledBlockNode node, DavaFlowSet input) {
if (DEBUG) {
System.out.println("Processing labeled block node node");
}
if (!isReachable(input)) {
// this sequence is not reachable hence simply return inset
return input;
} else {
return super.processASTLabeledBlockNode(node, input);
}
}
@Override
public DavaFlowSet processASTSynchronizedBlockNode(ASTSynchronizedBlockNode node, DavaFlowSet input) {
if (DEBUG) {
System.out.println("Processing synchronized block node");
}
if (!isReachable(input)) {
// this sequence is not reachable hence simply return inset
return input;
} else {
return super.processASTSynchronizedBlockNode(node, input);
}
}
@Override
public DavaFlowSet processASTIfElseNode(ASTIfElseNode node, DavaFlowSet input) {
if (DEBUG) {
System.out.println("Processing ifelse node");
}
if (!isReachable(input)) {
// this sequence is not reachable hence simply return inset
return input;
} else {
// the output will be false if both branches are abrupt
// and also there is no break targetting this construct
return super.processASTIfElseNode(node, input);
}
}
public DavaFlowSet ifNotReachableReturnInputElseProcessBodyAndReturnTrue(ASTNode node, DavaFlowSet input) {
if (DEBUG) {
System.out.println("Processing " + node.getClass() + " node");
}
if (!isReachable(input)) {
// this sequence is not reachable hence simply return inset
return input;
} else {
DavaFlowSet output = processSingleSubBodyNode(node, input);
UnreachableCodeFlowSet toReturn = new UnreachableCodeFlowSet();
toReturn.add(new Boolean(true));
toReturn.copyInternalDataFrom(output);
return toReturn;
}
}
/*
* If the if stmt is reachable the outset if always reachable
*/
@Override
public DavaFlowSet processASTIfNode(ASTIfNode node, DavaFlowSet input) {
return ifNotReachableReturnInputElseProcessBodyAndReturnTrue(node, input);
}
/*
* No need to process Condition No need to do fixed point No need to handleContinues since they dont change reachability
*/
@Override
public DavaFlowSet processASTWhileNode(ASTWhileNode node, DavaFlowSet input) {
return ifNotReachableReturnInputElseProcessBodyAndReturnTrue(node, input);
}
/*
* Same as while loop
*/
@Override
public DavaFlowSet processASTDoWhileNode(ASTDoWhileNode node, DavaFlowSet input) {
return ifNotReachableReturnInputElseProcessBodyAndReturnTrue(node, input);
}
@Override
public DavaFlowSet processASTUnconditionalLoopNode(ASTUnconditionalLoopNode node, DavaFlowSet input) {
return ifNotReachableReturnInputElseProcessBodyAndReturnTrue(node, input);
}
/*
* No need to process Init No need to process Condition No need to process Update No need to handle continue
*/
@Override
public DavaFlowSet processASTForLoopNode(ASTForLoopNode node, DavaFlowSet input) {
return ifNotReachableReturnInputElseProcessBodyAndReturnTrue(node, input);
}
/*
* No need to process SwitchKey TODO test and reason
*/
@Override
public DavaFlowSet processASTSwitchNode(ASTSwitchNode node, DavaFlowSet input) {
if (DEBUG) {
System.out.println("Processing switch node");
}
if (!isReachable(input)) {
// this sequence is not reachable hence simply return inset
return input;
}
// if reachable
List<Object> indexList = node.getIndexList();
Map<Object, List<Object>> index2BodyList = node.getIndex2BodyList();
DavaFlowSet initialIn = cloneFlowSet(input);
DavaFlowSet out = null;
DavaFlowSet defaultOut = null;
List<DavaFlowSet> toMergeBreaks = new ArrayList<DavaFlowSet>();
Iterator<Object> it = indexList.iterator();
while (it.hasNext()) {
// going through all the cases of the switch statement
Object currentIndex = it.next();
List body = index2BodyList.get(currentIndex);
if (body == null) {
continue;
}
// although the input is usually the merge of the out of previous
// but since we know this case is always reachable as switch is reachable
// there is no need to merge
out = process(body, cloneFlowSet(initialIn));
toMergeBreaks.add(cloneFlowSet(out));
if (currentIndex instanceof String) {
// this is the default
defaultOut = out;
}
}
// have to handle the case when no case matches. The input is the output
DavaFlowSet output = initialIn;
if (out != null) {
// just to make sure that there were some cases present
if (defaultOut != null) {
output = merge(defaultOut, out);
} else {
output = merge(initialIn, out);
}
}
// handle break
String label = getLabel(node);
// have to handleBreaks for all the different cases
List<DavaFlowSet> outList = new ArrayList<DavaFlowSet>();
// handling breakLists of each of the toMergeBreaks
for (DavaFlowSet tmb : toMergeBreaks) {
outList.add(handleBreak(label, tmb, node));
}
// merge all outList elements. since these are the outputs with breaks handled
DavaFlowSet finalOut = output;
for (DavaFlowSet fo : outList) {
finalOut = merge(finalOut, fo);
}
return finalOut;
}
@Override
public DavaFlowSet processASTTryNode(ASTTryNode node, DavaFlowSet input) {
if (DEBUG) {
System.out.println("Processing try node");
}
if (!isReachable(input)) {
// this sequence is not reachable hence simply return inset
return input;
}
// if reachable
List<Object> tryBody = node.get_TryBody();
DavaFlowSet tryBodyOutput = process(tryBody, input);
// catch is always reachable if try is reachable
DavaFlowSet inputCatch = newInitialFlow();
List<Object> catchList = node.get_CatchList();
Iterator<Object> it = catchList.iterator();
List<DavaFlowSet> catchOutput = new ArrayList<DavaFlowSet>();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container) it.next();
List body = (List) catchBody.o;
// list of ASTNodes
// result because of going through the catchBody
DavaFlowSet tempResult = process(body, cloneFlowSet(inputCatch));
// System.out.println("TempResult going through body"+tempResult);
catchOutput.add(tempResult);
}
// handle breaks
String label = getLabel(node);
List<DavaFlowSet> outList = new ArrayList<DavaFlowSet>();
// handle breaks out of tryBodyOutput
outList.add(handleBreak(label, tryBodyOutput, node));
// handling breakLists of each of the catchOutputs
for (DavaFlowSet co : catchOutput) {
DavaFlowSet temp = handleBreak(label, co, node);
outList.add(temp);
}
// merge all outList elements. since these are the outputs with breaks handled
DavaFlowSet out = tryBodyOutput;
for (DavaFlowSet oe : outList) {
out = merge(out, oe);
}
for (DavaFlowSet ce : catchOutput) {
out = merge(out, ce);
}
return out;
}
public boolean isConstructReachable(Object construct) {
Object temp = getBeforeSet(construct);
if (temp == null) {
return true;
} else {
if (DEBUG) {
System.out.println("Have before set");
}
Boolean reachable = (Boolean) ((UnreachableCodeFlowSet) temp).elements[0];
return reachable.booleanValue();
}
}
}
| 18,772
| 31.935088
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/ASTCleaner.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.G;
import soot.Local;
import soot.SootClass;
import soot.Type;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
/*
Nomair A. Naeem 21-FEB-2005
In the depthFirstAdaptor children of a ASTNode
are gotten in three ways
a, ASTStatementSequenceNode uses one way see caseASTStatementSequenceNode in DepthFirstAdapter
b, ASTTryNode uses another way see caseASTTryNode in DepthFirstAdapter
c, All other nodes use normalRetrieving method to retrieve the children
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
Current tasks of the cleaner
Invoke UselessLabeledBlockRemover
Invoke EmptyElseRemover
Apply OrAggregatorThree
*/
public class ASTCleaner extends DepthFirstAdapter {
public ASTCleaner() {
}
public ASTCleaner(boolean verbose) {
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
}
/*
* Note the ASTNode in this case can be any of the following: ASTMethodNode ASTSwitchNode ASTIfNode ASTIfElseNode
* ASTUnconditionalWhileNode ASTWhileNode ASTDoWhileNode ASTForLoopNode ASTLabeledBlockNode ASTSynchronizedBlockNode
*/
public void normalRetrieving(ASTNode node) {
if (node instanceof ASTSwitchNode) {
dealWithSwitchNode((ASTSwitchNode) node);
return;
}
// from the Node get the subBodes
Iterator<Object> sbit = node.get_SubBodies().iterator();
// onlyASTIfElseNode has 2 subBodies but we need to deal with that
int subBodyNumber = 0;
while (sbit.hasNext()) {
Object subBody = sbit.next();
Iterator it = ((List) subBody).iterator();
int nodeNumber = 0;
// go over the ASTNodes in this subBody and apply
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
if (temp instanceof ASTLabeledBlockNode) {
// check if the label is null
ASTLabeledBlockNode labelBlock = (ASTLabeledBlockNode) temp;
SETNodeLabel label = labelBlock.get_Label();
if (label.toString() == null) {
// uselessLabeledBlock Found REMOVE IT
UselessLabeledBlockRemover.removeLabeledBlock(node, labelBlock, subBodyNumber, nodeNumber);
if (G.v().ASTTransformations_modified) {
return;
}
}
} else if (temp instanceof ASTIfElseNode) {
// check if there is an empty else body
List<Object> elseBody = ((ASTIfElseNode) temp).getElseBody();
if (elseBody.size() == 0) {
EmptyElseRemover.removeElseBody(node, (ASTIfElseNode) temp, subBodyNumber, nodeNumber);
}
} else if (temp instanceof ASTIfNode) {
// check if the next node in the subBody is also an ASTIfNode in which case invoke OrAggregatorThree
if (it.hasNext()) {
// means we can get the nodeNumber+1
ASTNode nextNode = (ASTNode) ((List) subBody).get(nodeNumber + 1);
if (nextNode instanceof ASTIfNode) {
// found an If followed by another if might match Patter 3.
OrAggregatorThree.checkAndTransform(node, (ASTIfNode) temp, (ASTIfNode) nextNode, nodeNumber, subBodyNumber);
if (G.v().ASTTransformations_modified) {
// if we modified something we want to stop since the tree is stale
// System.out.println("here");
return;
}
}
}
}
temp.apply(this);
nodeNumber++;
}
subBodyNumber++;
} // end of going over subBodies
}
public void caseASTTryNode(ASTTryNode node) {
inASTTryNode(node);
// get try body
List<Object> tryBody = node.get_TryBody();
Iterator<Object> it = tryBody.iterator();
int nodeNumber = 0;
// go over the ASTNodes and apply
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
if (temp instanceof ASTLabeledBlockNode) {
// check if the label is null
ASTLabeledBlockNode labelBlock = (ASTLabeledBlockNode) temp;
SETNodeLabel label = labelBlock.get_Label();
if (label.toString() == null) {
// uselessLabeledBlock Found REMOVE IT
List<Object> newBody = UselessLabeledBlockRemover.createNewSubBody(tryBody, nodeNumber, labelBlock);
if (newBody != null) {
// something did not go wrong
node.replaceTryBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL from within trybody");
}
}
} else if (temp instanceof ASTIfElseNode) {
// check if there is an empty else body
List<Object> elseBody = ((ASTIfElseNode) temp).getElseBody();
if (elseBody.size() == 0) {
// System.out.println("Empty else body found"+temp);
List<Object> newBody = EmptyElseRemover.createNewNodeBody(tryBody, nodeNumber, (ASTIfElseNode) temp);
if (newBody != null) {
// something did not go wrong
node.replaceTryBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSEBODY from within trybody");
return;
}
}
} else if (temp instanceof ASTIfNode) {
// check if the next node in the subBody is also an ASTIfNode in which case invoke OrAggregatorThree
if (it.hasNext()) {
// means we can get the nodeNumber+1
ASTNode nextNode = (ASTNode) tryBody.get(nodeNumber + 1);
if (nextNode instanceof ASTIfNode) {
// found an If followed by another if might match Patter 3.
List<Object> newBody
= OrAggregatorThree.createNewNodeBody(tryBody, nodeNumber, (ASTIfNode) temp, (ASTIfNode) nextNode);
if (newBody != null) {
// something did not go wrong and pattern was matched
node.replaceTryBody(newBody);
G.v().ASTTransformations_modified = true;
// we modified something we want to stop since the tree is stale
// System.out.println("here");
return;
// System.out.println("OR AGGREGATOR THREE");
}
}
}
}
temp.apply(this);
nodeNumber++;
}
Map<Object, Object> exceptionMap = node.get_ExceptionMap();
Map<Object, Object> paramMap = node.get_ParamMap();
// get catch list and apply on the following
// a, type of exception caught
// b, local of exception
// c, catchBody
List<Object> catchList = node.get_CatchList();
Iterator<Object> itBody = null;
it = catchList.iterator();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container) it.next();
SootClass sootClass = ((SootClass) exceptionMap.get(catchBody));
Type type = sootClass.getType();
// apply on type of exception
caseType(type);
// apply on local of exception
Local local = (Local) paramMap.get(catchBody);
decideCaseExprOrRef(local);
// apply on catchBody
List<Object> body = (List<Object>) catchBody.o;
itBody = body.iterator();
nodeNumber = 0;
// go over the ASTNodes and apply
while (itBody.hasNext()) {
ASTNode temp = (ASTNode) itBody.next();
if (temp instanceof ASTLabeledBlockNode) {
// check if the label is null
ASTLabeledBlockNode labelBlock = (ASTLabeledBlockNode) temp;
SETNodeLabel label = labelBlock.get_Label();
if (label.toString() == null) {
// uselessLabeledBlock Found REMOVE IT
List<Object> newBody = UselessLabeledBlockRemover.createNewSubBody(body, nodeNumber, labelBlock);
if (newBody != null) {
// something did not go wrong
catchBody.replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL from within catchlist");
}
}
} else if (temp instanceof ASTIfElseNode) {
// check if there is an empty else body
List<Object> elseBody = ((ASTIfElseNode) temp).getElseBody();
if (elseBody.size() == 0) {
// System.out.println("Empty else body found"+temp);
List<Object> newBody = EmptyElseRemover.createNewNodeBody(body, nodeNumber, (ASTIfElseNode) temp);
if (newBody != null) {
// something did not go wrong
catchBody.replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSEBODY FROm within catchlist");
return;
}
}
} else if (temp instanceof ASTIfNode) {
// check if the next node in the subBody is also an ASTIfNode in which case invoke OrAggregatorThree
if (itBody.hasNext()) {
// means we can get the nodeNumber+1
ASTNode nextNode = (ASTNode) body.get(nodeNumber + 1);
if (nextNode instanceof ASTIfNode) {
// found an If followed by another if might match Patter 3.
List<Object> newBody
= OrAggregatorThree.createNewNodeBody(body, nodeNumber, (ASTIfNode) temp, (ASTIfNode) nextNode);
if (newBody != null) {
// something did not go wrong and pattern was matched
catchBody.replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATOR THREE");
return;
}
}
}
}
temp.apply(this);
nodeNumber++;
}
}
outASTTryNode(node);
}
private void dealWithSwitchNode(ASTSwitchNode node) {
// do a depthfirst on elements of the switchNode
List<Object> indexList = node.getIndexList();
Map<Object, List<Object>> index2BodyList = node.getIndex2BodyList();
Iterator<Object> it = indexList.iterator();
while (it.hasNext()) {
// going through all the cases of the switch statement
Object currentIndex = it.next();
List<Object> body = index2BodyList.get(currentIndex);
if (body != null) {
// this body is a list of ASTNodes
Iterator<Object> itBody = body.iterator();
int nodeNumber = 0;
// go over the ASTNodes and apply
while (itBody.hasNext()) {
ASTNode temp = (ASTNode) itBody.next();
if (temp instanceof ASTLabeledBlockNode) {
// check if the label is null
ASTLabeledBlockNode labelBlock = (ASTLabeledBlockNode) temp;
SETNodeLabel label = labelBlock.get_Label();
if (label.toString() == null) {
// uselessLabeledBlock Found REMOVE IT
List<Object> newBody = UselessLabeledBlockRemover.createNewSubBody(body, nodeNumber, labelBlock);
if (newBody != null) {
// something did not go wrong
// put this body in the Map
index2BodyList.put(currentIndex, newBody);
// replace in actual switchNode
node.replaceIndex2BodyList(index2BodyList);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL From Within Switch");
}
}
} else if (temp instanceof ASTIfElseNode) {
// check if there is an empty else body
List<Object> elseBody = ((ASTIfElseNode) temp).getElseBody();
if (elseBody.size() == 0) {
// System.out.println("Empty else body found"+temp);
List<Object> newBody = EmptyElseRemover.createNewNodeBody(body, nodeNumber, (ASTIfElseNode) temp);
if (newBody != null) {
// something did not go wrong
// put this body in the Map
index2BodyList.put(currentIndex, newBody);
// replace in actual switchNode
node.replaceIndex2BodyList(index2BodyList);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSEBODY FROM WITHIN SWITCH");
return;
}
}
} else if (temp instanceof ASTIfNode) {
// check if the next node in the subBody is also an ASTIfNode in which case invoke OrAggregatorThree
if (itBody.hasNext()) {
// means we can get the nodeNumber+1
ASTNode nextNode = (ASTNode) body.get(nodeNumber + 1);
if (nextNode instanceof ASTIfNode) {
// found an If followed by another if might match Patter 3.
List<Object> newBody
= OrAggregatorThree.createNewNodeBody(body, nodeNumber, (ASTIfNode) temp, (ASTIfNode) nextNode);
if (newBody != null) {
// something did not go wrong and pattern was matched
// put this body in the Map
index2BodyList.put(currentIndex, newBody);
// replace in actual switchNode
node.replaceIndex2BodyList(index2BodyList);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATOR THREE");
return;
}
}
}
}
temp.apply(this);
nodeNumber++;
}
}
}
}
}
| 14,861
| 38.421751
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/ASTCleanerTwo.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair Naeem
* %%
* 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.G;
import soot.Local;
import soot.SootClass;
import soot.Type;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
/*
Nomair A. Naeem 21-FEB-2005
In the depthFirstAdaptor children of a ASTNode
are gotten in three ways
a, ASTStatementSequenceNode uses one way see caseASTStatementSequenceNode in DepthFirstAdapter
b, ASTTryNode uses another way see caseASTTryNode in DepthFirstAdapter
c, All other nodes use normalRetrieving method to retrieve the children
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
Current tasks of the cleaner
Invoke IfElsebreaker
*/
public class ASTCleanerTwo extends DepthFirstAdapter {
public ASTCleanerTwo() {
}
public ASTCleanerTwo(boolean verbose) {
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
}
/*
* Note the ASTNode in this case can be any of the following: ASTMethodNode ASTSwitchNode ASTIfNode ASTIfElseNode
* ASTUnconditionalWhileNode ASTWhileNode ASTDoWhileNode ASTForLoopNode ASTLabeledBlockNode ASTSynchronizedBlockNode
*/
public void normalRetrieving(ASTNode node) {
if (node instanceof ASTSwitchNode) {
dealWithSwitchNode((ASTSwitchNode) node);
return;
}
// from the Node get the subBodes
Iterator<Object> sbit = node.get_SubBodies().iterator();
// onlyASTIfElseNode has 2 subBodies but we need to deal with that
int subBodyNumber = 0;
while (sbit.hasNext()) {
List<Object> subBody = (List<Object>) sbit.next();
Iterator<Object> it = subBody.iterator();
int nodeNumber = 0;
// go over the ASTNodes in this subBody and apply
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
if (temp instanceof ASTIfElseNode) {
IfElseBreaker breaker = new IfElseBreaker();
boolean success = false;
if (breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode) temp)) {
success = true;
} else if (breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode) temp)) {
success = true;
}
// if(G.v().ASTTransformations_modified)
// return;
if (!success) {
// System.out.println("not successful");
}
if (success) {
List<Object> newBody = breaker.createNewBody(subBody, nodeNumber);
if (newBody != null) {
if (node instanceof ASTIfElseNode) {
if (subBodyNumber == 0) {
// the if body was modified
List<Object> subBodies = node.get_SubBodies();
List<Object> ifElseBody = (List<Object>) subBodies.get(1);
((ASTIfElseNode) node).replaceBody(newBody, ifElseBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 1");
return;
} else if (subBodyNumber == 1) {
// else body was modified
List<Object> subBodies = node.get_SubBodies();
List<Object> ifBody = (List<Object>) subBodies.get(0);
((ASTIfElseNode) node).replaceBody(ifBody, newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 2");
return;
} else {
throw new RuntimeException("Please report benchmark to programmer");
}
} else {
if (node instanceof ASTMethodNode) {
((ASTMethodNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 3");
return;
} else if (node instanceof ASTSynchronizedBlockNode) {
((ASTSynchronizedBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 4");
return;
} else if (node instanceof ASTLabeledBlockNode) {
((ASTLabeledBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 5");
return;
} else if (node instanceof ASTUnconditionalLoopNode) {
((ASTUnconditionalLoopNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 6");
return;
} else if (node instanceof ASTIfNode) {
((ASTIfNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 7");
return;
} else if (node instanceof ASTWhileNode) {
((ASTWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 8");
return;
} else if (node instanceof ASTDoWhileNode) {
((ASTDoWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 9");
return;
} else if (node instanceof ASTForLoopNode) {
((ASTForLoopNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 11");
return;
} else {
throw new RuntimeException("Please report benchmark to programmer");
}
}
} // newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
subBodyNumber++;
} // end of going over subBodies
}
public void caseASTTryNode(ASTTryNode node) {
inASTTryNode(node);
// get try body
List<Object> tryBody = node.get_TryBody();
Iterator<Object> it = tryBody.iterator();
int nodeNumber = 0;
// go over the ASTNodes and apply
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
if (temp instanceof ASTIfElseNode) {
IfElseBreaker breaker = new IfElseBreaker();
boolean success = false;
if (breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode) temp)) {
success = true;
} else if (breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode) temp)) {
success = true;
}
if (G.v().ASTTransformations_modified) {
return;
}
if (success) {
List<Object> newBody = breaker.createNewBody(tryBody, nodeNumber);
if (newBody != null) {
// something did not go wrong
node.replaceTryBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 10");
return;
} // newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
Map<Object, Object> exceptionMap = node.get_ExceptionMap();
Map<Object, Object> paramMap = node.get_ParamMap();
// get catch list and apply on the following
// a, type of exception caught
// b, local of exception
// c, catchBody
List<Object> catchList = node.get_CatchList();
Iterator<Object> itBody = null;
it = catchList.iterator();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container) it.next();
SootClass sootClass = ((SootClass) exceptionMap.get(catchBody));
Type type = sootClass.getType();
// apply on type of exception
caseType(type);
// apply on local of exception
Local local = (Local) paramMap.get(catchBody);
decideCaseExprOrRef(local);
// apply on catchBody
List<Object> body = (List<Object>) catchBody.o;
itBody = body.iterator();
nodeNumber = 0;
// go over the ASTNodes and apply
while (itBody.hasNext()) {
ASTNode temp = (ASTNode) itBody.next();
if (temp instanceof ASTIfElseNode) {
IfElseBreaker breaker = new IfElseBreaker();
boolean success = false;
if (breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode) temp)) {
success = true;
} else if (breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode) temp)) {
success = true;
}
if (G.v().ASTTransformations_modified) {
return;
}
if (success) {
List<Object> newBody = breaker.createNewBody(body, nodeNumber);
if (newBody != null) {
// something did not go wrong
catchBody.replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 11");
return;
} // newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
}
outASTTryNode(node);
}
private void dealWithSwitchNode(ASTSwitchNode node) {
// do a depthfirst on elements of the switchNode
List<Object> indexList = node.getIndexList();
Map<Object, List<Object>> index2BodyList = node.getIndex2BodyList();
Iterator<Object> it = indexList.iterator();
while (it.hasNext()) {
// going through all the cases of the switch statement
Object currentIndex = it.next();
List<Object> body = index2BodyList.get(currentIndex);
if (body != null) {
// this body is a list of ASTNodes
Iterator<Object> itBody = body.iterator();
int nodeNumber = 0;
// go over the ASTNodes and apply
while (itBody.hasNext()) {
ASTNode temp = (ASTNode) itBody.next();
if (temp instanceof ASTIfElseNode) {
IfElseBreaker breaker = new IfElseBreaker();
boolean success = false;
if (breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode) temp)) {
success = true;
} else if (breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode) temp)) {
success = true;
}
if (G.v().ASTTransformations_modified) {
return;
}
if (success) {
List<Object> newBody = breaker.createNewBody(body, nodeNumber);
if (newBody != null) {
// put this body in the Map
index2BodyList.put(currentIndex, newBody);
// replace in actual switchNode
node.replaceIndex2BodyList(index2BodyList);
G.v().ASTTransformations_modified = true;
// System.out.println("BROKE IFELSE 12");
return;
} // newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
}
}
}
}
| 12,712
| 35.956395
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/AndAggregator.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 soot.G;
import soot.dava.internal.AST.ASTAndCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DAbruptStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.Stmt;
/*
Nomair A. Naeem 18-FEB-2005
The class is responsible to do the following transformation on the AST
if(A){ if(A && B){
if(B){ Body1
Body1 -----> }
} Body2
}
Body2
The most important thing to check is that there is only one If Statement inside the
outer if and that there is NO other statement.
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
*/
public class AndAggregator extends DepthFirstAdapter {
public AndAggregator() {
}
public AndAggregator(boolean verbose) {
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
}
public void outASTIfNode(ASTIfNode node) {
List<Object> bodies = node.get_SubBodies();
if (bodies.size() == 1) { // this should always be one since there is
// only one body of an if statement
List body = (List) bodies.get(0);
// this is the if body check to see if this is a single if Node
if (body.size() == 1) {
// size is good
ASTNode bodyNode = (ASTNode) body.get(0);
if (bodyNode instanceof ASTIfNode) {
/*
* We can do AndAggregation at this point node contains the outer if (ASTIfNode)bodyNode is the inner if
*/
ASTCondition outerCond = node.get_Condition();
ASTCondition innerCond = ((ASTIfNode) bodyNode).get_Condition();
SETNodeLabel outerLabel = (node).get_Label();
SETNodeLabel innerLabel = ((ASTIfNode) bodyNode).get_Label();
SETNodeLabel newLabel = null;
if (outerLabel.toString() == null && innerLabel.toString() == null) {
newLabel = outerLabel;
} else if (outerLabel.toString() != null && innerLabel.toString() == null) {
newLabel = outerLabel;
} else if (outerLabel.toString() == null && innerLabel.toString() != null) {
newLabel = innerLabel;
} else if (outerLabel.toString() != null && innerLabel.toString() != null) {
newLabel = outerLabel;
// however we have to change all occurance of inner
// label to point to that
// of outerlabel now
changeUses(outerLabel.toString(), innerLabel.toString(), bodyNode);
}
// aggregate the conditions
ASTCondition newCond = new ASTAndCondition(outerCond, innerCond);
// Get the body of the inner Node that will be the overall
// body
List<Object> newBodyList = ((ASTIfNode) bodyNode).get_SubBodies();
// retireve the actual body List
if (newBodyList.size() == 1) {
// should always be one since
// this is body of IF
List<Object> newBody = (List<Object>) newBodyList.get(0);
node.replace(newLabel, newCond, newBody);
// System.out.println("ANDDDDDD AGGREGATING !!!");
G.v().ASTTransformations_modified = true;
}
} else {
// not an if node
}
} else { // IfBody has more than 1 nodes cant do AND aggregation
}
}
}
private void changeUses(String to, String from, ASTNode node) {
// remember this method is only called when "to" and "from" are both non
// null
List<Object> subBodies = node.get_SubBodies();
Iterator<Object> it = subBodies.iterator();
while (it.hasNext()) {
// going over all subBodies
if (node instanceof ASTStatementSequenceNode) {
// check for abrupt stmts
ASTStatementSequenceNode stmtSeq = (ASTStatementSequenceNode) node;
for (AugmentedStmt as : stmtSeq.getStatements()) {
Stmt s = as.get_Stmt();
if (s instanceof DAbruptStmt) {
DAbruptStmt abStmt = (DAbruptStmt) s;
if (abStmt.is_Break() || abStmt.is_Continue()) {
SETNodeLabel label = abStmt.getLabel();
String labelBroken = label.toString();
if (labelBroken != null) {
// stmt breaks some label
if (labelBroken.compareTo(from) == 0) {
// have to replace the "from" label to "to"
// label
label.set_Name(to);
}
}
}
}
}
} else {
// need to recursively call changeUses
List subBodyNodes = null;
if (node instanceof ASTTryNode) {
ASTTryNode.container subBody = (ASTTryNode.container) it.next();
subBodyNodes = (List) subBody.o;
} else {
subBodyNodes = (List) it.next();
}
Iterator nodesIt = subBodyNodes.iterator();
while (nodesIt.hasNext()) {
changeUses(to, from, (ASTNode) nodesIt.next());
}
}
} // going through subBodies
}
}
| 6,318
| 33.71978
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/BooleanConditionSimplification.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.BooleanType;
import soot.Type;
import soot.Value;
import soot.dava.internal.AST.ASTBinaryCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTUnaryCondition;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.javaRep.DIntConstant;
import soot.dava.internal.javaRep.DNotExpr;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.ConditionExpr;
import soot.jimple.EqExpr;
import soot.jimple.NeExpr;
/*
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
*/
public class BooleanConditionSimplification extends DepthFirstAdapter {
public BooleanConditionSimplification(boolean verbose) {
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
}
public BooleanConditionSimplification() {
}
/*
* The method checks whether a particular ASTBinaryCondition is a comparison of a local with a boolean If so the
* ASTBinaryCondition is replaced by a ASTUnaryCondition
*/
public void outASTIfNode(ASTIfNode node) {
ASTCondition condition = node.get_Condition();
if (condition instanceof ASTBinaryCondition) {
ConditionExpr condExpr = ((ASTBinaryCondition) condition).getConditionExpr();
Value unary = checkBooleanUse(condExpr);
if (unary != null) {
node.set_Condition(new ASTUnaryCondition(unary));
}
}
}
public void outASTIfElseNode(ASTIfElseNode node) {
ASTCondition condition = node.get_Condition();
if (condition instanceof ASTBinaryCondition) {
ConditionExpr condExpr = ((ASTBinaryCondition) condition).getConditionExpr();
Value unary = checkBooleanUse(condExpr);
if (unary != null) {
node.set_Condition(new ASTUnaryCondition(unary));
}
}
}
public void outASTWhileNode(ASTWhileNode node) {
ASTCondition condition = node.get_Condition();
if (condition instanceof ASTBinaryCondition) {
ConditionExpr condExpr = ((ASTBinaryCondition) condition).getConditionExpr();
Value unary = checkBooleanUse(condExpr);
if (unary != null) {
node.set_Condition(new ASTUnaryCondition(unary));
}
}
}
public void outASTDoWhileNode(ASTDoWhileNode node) {
ASTCondition condition = node.get_Condition();
if (condition instanceof ASTBinaryCondition) {
ConditionExpr condExpr = ((ASTBinaryCondition) condition).getConditionExpr();
Value unary = checkBooleanUse(condExpr);
if (unary != null) {
node.set_Condition(new ASTUnaryCondition(unary));
}
}
}
private Value checkBooleanUse(ConditionExpr condition) {
// check whether the condition qualifies as a boolean use
if (condition instanceof NeExpr || condition instanceof EqExpr) {
Value op1 = condition.getOp1();
Value op2 = condition.getOp2();
if (op1 instanceof DIntConstant) {
Type op1Type = ((DIntConstant) op1).type;
if (op1Type instanceof BooleanType) {
return decideCondition(op2, ((DIntConstant) op1).toString(), condition);
}
} else if (op2 instanceof DIntConstant) {
Type op2Type = ((DIntConstant) op2).type;
if (op2Type instanceof BooleanType) {
return decideCondition(op1, ((DIntConstant) op2).toString(), condition);
}
} else {
return null;// meaning no Value used as boolean found
}
}
return null; // meaning no local used as boolean found
}
/*
* Used to decide what the condition should be if we are converting from ConditionExpr to Value A != false/0 --> A A !=
* true/1 --> !A A == false/0 --> !A A == true/1 --> A
*/
private Value decideCondition(Value A, String truthString, ConditionExpr condition) {
int truthValue = 0;
boolean notEqual = false;
// find out whether we are dealing with a false or true
if (truthString.compareTo("false") == 0) {
truthValue = 0;
} else if (truthString.compareTo("true") == 0) {
truthValue = 1;
} else {
throw new RuntimeException();
}
// find out whether the comparison operator is != or ==
if (condition instanceof NeExpr) {
notEqual = true;
} else if (condition instanceof EqExpr) {
notEqual = false;
} else {
throw new RuntimeException();
}
// decide and return
if (notEqual && truthValue == 0) { // A != false -->A
return A;
} else if (notEqual && truthValue == 1) {
// A != true --> !A
if (A instanceof DNotExpr) {
// A is actually !B
return ((DNotExpr) A).getOp();
} else {
return (new DNotExpr(A));
}
} else if (!notEqual && truthValue == 0) {
// A == false --> !A
if (A instanceof DNotExpr) {
// A is actually !B
return ((DNotExpr) A).getOp();
} else {
return new DNotExpr(A);
}
} else if (!notEqual && truthValue == 1) {
// A == true --> A
return A;
} else {
throw new RuntimeException();
}
}
}
| 6,137
| 32.540984
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/CPApplication.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%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.HashMap;
import java.util.Iterator;
import java.util.List;
import soot.Local;
import soot.SootField;
import soot.Value;
import soot.ValueBox;
import soot.dava.internal.AST.ASTAggregatedCondition;
import soot.dava.internal.AST.ASTBinaryCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTUnaryCondition;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.dava.toolkits.base.AST.structuredAnalysis.CP;
import soot.dava.toolkits.base.AST.structuredAnalysis.CPFlowSet;
import soot.dava.toolkits.base.AST.structuredAnalysis.CPHelper;
import soot.jimple.FieldRef;
import soot.jimple.Stmt;
/*
* The traversal utilizes the results of the CP (constant propagation analysis) to substitute uses
* of locals where ever possible. Note we also have information about the constant fields in the program but
* we are not going to de-inline those fields because it is thought that refereing to the field as a TYPE-DEF
* gives more info than the actual value
*
*
Need to be very clear when a local can be used
It can be used in the following places:
a, a conditional in if, ifelse,
a1 while , do while, for condition (after set of these will be used since those are the vars true at the start of the loop
i.e. when the loop has not executed and also true at the end of the loop
b, in the for init or update
c, in a switch choice
d, in a syncrhnoized block //wont do dont think we need to since this is a local
and synching is always done on objects and we are not tracking objects
d, in a statement
*
*/
public class CPApplication extends DepthFirstAdapter {
CP cp = null;
String className = null;
public CPApplication(ASTMethodNode AST, HashMap<String, Object> constantValueFields,
HashMap<String, SootField> classNameFieldNameToSootFieldMapping) {
className = AST.getDavaBody().getMethod().getDeclaringClass().getName();
cp = new CP(AST, constantValueFields, classNameFieldNameToSootFieldMapping);
}
public CPApplication(boolean verbose, ASTMethodNode AST, HashMap<String, Object> constantValueFields,
HashMap<String, SootField> classNameFieldNameToSootFieldMapping) {
super(verbose);
className = AST.getDavaBody().getMethod().getDeclaringClass().getName();
cp = new CP(AST, constantValueFields, classNameFieldNameToSootFieldMapping);
}
public void inASTSwitchNode(ASTSwitchNode node) {
Object obj = cp.getBeforeSet(node);
if (obj == null) {
return;
}
if (!(obj instanceof CPFlowSet)) {
return;
}
// before set is a non null CPFlowSet
CPFlowSet beforeSet = (CPFlowSet) obj;
Value key = node.get_Key();
if (key instanceof Local) {
Local useLocal = (Local) key;
// System.out.println("switch key is a local: "+useLocal);
Object value = beforeSet.contains(className, useLocal.toString());
if (value != null) {
// System.out.println("switch key Local "+useLocal+"is present in before set with value"+value);
// create constant value for the value and replace this local
// use with the constant value use
Value newValue = CPHelper.createConstant(value);
if (newValue != null) {
// System.out.println("Substituted the switch key local use with the constant value"+newValue);
node.set_Key(newValue);
} else {
// System.out.println("FAILED TO Substitute the local use with the constant value");
}
}
} else if (key instanceof FieldRef) {
FieldRef useField = (FieldRef) key;
// System.out.println("switch key is a FieldRef which is: "+useField);
SootField usedSootField = useField.getField();
Object value = beforeSet.contains(usedSootField.getDeclaringClass().getName(), usedSootField.getName().toString());
if (value != null) {
// System.out.println("FieldRef "+usedSootField+"is present in before set with value"+value);
// create constant value for the value and replace this local
// use with the constant value use
Value newValue = CPHelper.createConstant(value);
if (newValue != null) {
// System.out.println("Substituted the constant field ref use with the constant value"+newValue);
node.set_Key(newValue);
} else {
// System.out.println("FAILED TO Substitute the constant field ref use with the constant value");
}
}
}
}
public void inASTForLoopNode(ASTForLoopNode node) {
/*
* For the init part we should actually use the before set for each init stmt
*/
for (AugmentedStmt as : node.getInit()) {
Stmt s = as.get_Stmt();
List useBoxes = s.getUseBoxes();
Object obj = cp.getBeforeSet(s);
if (obj == null) {
continue;
}
if (!(obj instanceof CPFlowSet)) {
continue;
}
// before set is a non null CPFlowSet
CPFlowSet beforeSet = (CPFlowSet) obj;
// System.out.println("Init Statement: "+s);
// System.out.println("Before set is: "+beforeSet.toString());
/*
* get all use boxes see if their value is determined from the before set if yes replace them
*/
substituteUses(useBoxes, beforeSet);
}
// get after set for the condition and update
Object obj = cp.getAfterSet(node);
if (obj == null) {
return;
}
if (!(obj instanceof CPFlowSet)) {
return;
}
// after set is a non null CPFlowSet
CPFlowSet afterSet = (CPFlowSet) obj;
// conditon
ASTCondition cond = node.get_Condition();
// System.out.println("For Loop with condition: "+cond);
// System.out.println("After set is: "+afterSet.toString());
changedCondition(cond, afterSet);
// update
for (AugmentedStmt as : node.getUpdate()) {
Stmt s = as.get_Stmt();
List useBoxes = s.getUseBoxes();
// System.out.println("For update Statement: "+s);
// System.out.println("After set is: "+afterSet.toString());
/*
* get all use boxes see if their value is determined from the before set if yes replace them
*/
substituteUses(useBoxes, afterSet);
}
}
public void inASTWhileNode(ASTWhileNode node) {
Object obj = cp.getAfterSet(node);
if (obj == null) {
return;
}
if (!(obj instanceof CPFlowSet)) {
return;
}
// after set is a non null CPFlowSet
CPFlowSet afterSet = (CPFlowSet) obj;
ASTCondition cond = node.get_Condition();
// System.out.println("While Statement with condition: "+cond);
// System.out.println("After set is: "+afterSet.toString());
changedCondition(cond, afterSet);
}
public void inASTDoWhileNode(ASTDoWhileNode node) {
Object obj = cp.getAfterSet(node);
if (obj == null) {
return;
}
if (!(obj instanceof CPFlowSet)) {
return;
}
// after set is a non null CPFlowSet
CPFlowSet afterSet = (CPFlowSet) obj;
ASTCondition cond = node.get_Condition();
// System.out.println("Do While Statement with condition: "+cond);
// System.out.println("After set is: "+afterSet.toString());
changedCondition(cond, afterSet);
}
public void inASTIfNode(ASTIfNode node) {
// System.out.println(node);
Object obj = cp.getBeforeSet(node);
if (obj == null) {
return;
}
if (!(obj instanceof CPFlowSet)) {
return;
}
// before set is a non null CPFlowSet
CPFlowSet beforeSet = (CPFlowSet) obj;
// System.out.println("Printing before Set for IF"+beforeSet.toString());
ASTCondition cond = node.get_Condition();
// System.out.println("If Statement with condition: "+cond);
// System.out.println("Before set is: "+beforeSet.toString());
changedCondition(cond, beforeSet);
}
public void inASTIfElseNode(ASTIfElseNode node) {
Object obj = cp.getBeforeSet(node);
if (obj == null) {
return;
}
if (!(obj instanceof CPFlowSet)) {
return;
}
// before set is a non null CPFlowSet
CPFlowSet beforeSet = (CPFlowSet) obj;
ASTCondition cond = node.get_Condition();
// System.out.println("IfElse Statement with condition: "+cond);
// System.out.println("Before set is: "+beforeSet.toString());
changedCondition(cond, beforeSet);
}
/*
* Given a unary/binary or aggregated condition this method is used to find all the useBoxes or locals or fieldref in the
* case of unary conditions and then the set is checked for appropriate substitutions
*/
public ASTCondition changedCondition(ASTCondition cond, CPFlowSet set) {
if (cond instanceof ASTAggregatedCondition) {
ASTCondition left = changedCondition(((ASTAggregatedCondition) cond).getLeftOp(), set);
ASTCondition right = changedCondition(((ASTAggregatedCondition) cond).getRightOp(), set);
((ASTAggregatedCondition) cond).setLeftOp(left);
((ASTAggregatedCondition) cond).setRightOp(right);
// System.out.println("New condition is: "+cond);
return cond;
} else if (cond instanceof ASTUnaryCondition) {
Value val = ((ASTUnaryCondition) cond).getValue();
if (val instanceof Local) {
Object value = set.contains(className, ((Local) val).toString());
if (value != null) {
// System.out.println("if Condition Local "+((Local)val)+"is present in before set with value"+value);
// create constant value for the value and replace this
// local use with the constant value use
Value newValue = CPHelper.createConstant(value);
if (newValue != null) {
// System.out.println("Substituted the local use with the constant value"+newValue);
((ASTUnaryCondition) cond).setValue(newValue);
} else {
// System.out.println("FAILED TO Substitute the local use with the constant value");
}
}
} else if (val instanceof FieldRef) {
FieldRef useField = (FieldRef) val;
SootField usedSootField = useField.getField();
Object value = set.contains(usedSootField.getDeclaringClass().getName(), usedSootField.getName().toString());
if (value != null) {
// System.out.println("if condition FieldRef "+usedSootField+"is present in before set with value"+value);
// create constant value for the value and replace this
// field use with the constant value use
Value newValue = CPHelper.createConstant(value);
if (newValue != null) {
// System.out.println("Substituted the constant field ref use with the constant value"+newValue);
((ASTUnaryCondition) cond).setValue(newValue);
} else {
// System.out.println("FAILED TO Substitute the constant field ref use with the constant value");
}
}
} else {
substituteUses(val.getUseBoxes(), set);
}
// System.out.println("New condition is: "+cond);
return cond;
} else if (cond instanceof ASTBinaryCondition) {
// get uses from binaryCondition
Value val = ((ASTBinaryCondition) cond).getConditionExpr();
substituteUses(val.getUseBoxes(), set);
// System.out.println("New condition is: "+cond);
return cond;
} else {
throw new RuntimeException("Method getUseList in ASTUsesAndDefs encountered unknown condition type");
}
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
List useBoxes = s.getUseBoxes();
Object obj = cp.getBeforeSet(s);
if (obj == null) {
continue;
}
if (!(obj instanceof CPFlowSet)) {
continue;
}
// before set is a non null CPFlowSet
CPFlowSet beforeSet = (CPFlowSet) obj;
// System.out.println("Statement: "+s);
// System.out.println("Before set is: "+beforeSet.toString());
/*
* get all use boxes see if their value is determined from the before set if yes replace them
*/
substituteUses(useBoxes, beforeSet);
}
}
public void substituteUses(List useBoxes, CPFlowSet beforeSet) {
Iterator useIt = useBoxes.iterator();
while (useIt.hasNext()) {
Object useObj = useIt.next();
Value use = ((ValueBox) useObj).getValue();
if (use instanceof Local) {
Local useLocal = (Local) use;
// System.out.println("local is: "+useLocal);
Object value = beforeSet.contains(className, useLocal.toString());
if (value != null) {
// System.out.println("Local "+useLocal+"is present in before set with value"+value);
// create constant value for the value and replace this
// local use with the constant value use
Value newValue = CPHelper.createConstant(value);
if (newValue != null) {
// System.out.println("Substituted the local use with the constant value"+newValue);
((ValueBox) useObj).setValue(newValue);
} else {
// System.out.println("FAILED TO Substitute the local use with the constant value");
}
}
} else if (use instanceof FieldRef) {
FieldRef useField = (FieldRef) use;
// System.out.println("FieldRef is: "+useField);
SootField usedSootField = useField.getField();
Object value = beforeSet.contains(usedSootField.getDeclaringClass().getName(), usedSootField.getName().toString());
if (value != null) {
// System.out.println("FieldRef "+usedSootField+"is present in before set with value"+value);
// create constant value for the value and replace this
// local use with the constant value use
Value newValue = CPHelper.createConstant(value);
if (newValue != null) {
// System.out.println("Substituted the constant field ref use with the constant value"+newValue);
((ValueBox) useObj).setValue(newValue);
} else {
// System.out.println("FAILED TO Substitute the constant field ref use with the constant value");
}
}
}
}
}
}
| 15,479
| 35.252927
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/DeInliningFinalFields.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Nomair A. Naeem (nomair.naeem@mail.mcgill.ca)
* %%
* 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 soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.Scene;
import soot.ShortType;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.Value;
import soot.ValueBox;
import soot.dava.internal.AST.ASTAggregatedCondition;
import soot.dava.internal.AST.ASTBinaryCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DStaticFieldRef;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.tagkit.DoubleConstantValueTag;
import soot.tagkit.FloatConstantValueTag;
import soot.tagkit.IntegerConstantValueTag;
import soot.tagkit.LongConstantValueTag;
import soot.tagkit.StringConstantValueTag;
/**
* Maintained by: Nomair A. Naeem
*/
/**
* CHANGE LOG: 2nd February 2006:
*
*/
/**
* Both static and non-static BUT FINAL fields if initialized with constants get inlined A final initialized with an object
* (even if its a string) is NOT inlined e.g. public static final String temp = "hello"; //use of temp will get inlined
* public static final String temp1 = new String("hello"); //use of temp will NOT get inlined
*
*
* If its a static field we can get the info from a tag in the case of a non static we cant decide since the field is
* initialized inside a constructor and depending on different constructors there coul dbe different
* values...conservative....
*
*
* Need to be very clear when a SootField can be used It can be used in the following places:
*
* a, NOT used inside a Synchronized Block ........ HOWEVER ADD IT SINCE I DONT SEE WHY THIS RESTRICTION EXISTS!!! TICK b,
* CAN BE USED in a condition TICK c, CAN BE USED in the for init for update TICK d, CAN BE USED in a switch TICK e, CAN BE
* USED in a stmt TICK
*
* These are the exact places to look for constants...a constant is StringConstant DoubleConstant FloatConstant IntConstant
* (shortype, booltype, charType intType, byteType LongConstant
*/
public class DeInliningFinalFields extends DepthFirstAdapter {
private SootClass sootClass = null;
private SootMethod sootMethod = null;
private HashMap<Comparable, SootField> finalFields;
// ASTParentNodeFinder parentFinder;
public DeInliningFinalFields() {
}
public DeInliningFinalFields(boolean verbose) {
super(verbose);
}
@Override
public void inASTMethodNode(ASTMethodNode node) {
this.sootMethod = node.getDavaBody().getMethod();
this.sootClass = sootMethod.getDeclaringClass();
this.finalFields = new HashMap<Comparable, SootField>();
// System.out.println("Deiniling method: "+sootMethod.getName());
ArrayList<SootField> fieldChain = new ArrayList<>();
for (SootClass tempClass : Scene.v().getApplicationClasses()) {
for (SootField next : tempClass.getFields()) {
fieldChain.add(next);
}
}
// going through fields
for (SootField f : fieldChain) {
if (f.isFinal()) {
// check for constant value tags
Type fieldType = f.getType();
if (fieldType instanceof DoubleType && f.hasTag(DoubleConstantValueTag.NAME)) {
double val = ((DoubleConstantValueTag) f.getTag(DoubleConstantValueTag.NAME)).getDoubleValue();
finalFields.put(val, f);
} else if (fieldType instanceof FloatType && f.hasTag(FloatConstantValueTag.NAME)) {
float val = ((FloatConstantValueTag) f.getTag(FloatConstantValueTag.NAME)).getFloatValue();
finalFields.put(val, f);
} else if (fieldType instanceof LongType && f.hasTag(LongConstantValueTag.NAME)) {
long val = ((LongConstantValueTag) f.getTag(LongConstantValueTag.NAME)).getLongValue();
finalFields.put(val, f);
} else if (fieldType instanceof CharType && f.hasTag(IntegerConstantValueTag.NAME)) {
int val = ((IntegerConstantValueTag) f.getTag(IntegerConstantValueTag.NAME)).getIntValue();
finalFields.put(val, f);
} else if (fieldType instanceof BooleanType && f.hasTag(IntegerConstantValueTag.NAME)) {
int val = ((IntegerConstantValueTag) f.getTag(IntegerConstantValueTag.NAME)).getIntValue();
if (val == 0) {
finalFields.put(false, f);
} else {
finalFields.put(true, f);
}
} else if ((fieldType instanceof IntType || fieldType instanceof ByteType || fieldType instanceof ShortType)
&& f.hasTag(IntegerConstantValueTag.NAME)) {
int val = ((IntegerConstantValueTag) f.getTag(IntegerConstantValueTag.NAME)).getIntValue();
finalFields.put(val, f);
} else if (f.hasTag(StringConstantValueTag.NAME)) {
String val = ((StringConstantValueTag) f.getTag(StringConstantValueTag.NAME)).getStringValue();
// System.out.println("adding string constant"+val);
finalFields.put(val, f);
}
} // end if final
}
}
/*
* StringConstant DoubleConstant FloatConstant IntConstant (shortype, booltype, charType intType, byteType LongConstant
*/
private boolean isConstant(Value val) {
return val instanceof StringConstant || val instanceof DoubleConstant || val instanceof FloatConstant
|| val instanceof IntConstant || val instanceof LongConstant;
}
/*
* Notice as things stand synchblocks cant have the use of a SootField
*/
@Override
public void inASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
// hence nothing is implemented here
}
public void checkAndSwitch(ValueBox valBox) {
Value val = valBox.getValue();
Object finalField = check(val);
if (finalField != null) {
// System.out.println("Final field with this value exists"+finalField);
/*
* If the final field belongs to the same class then we should supress declaring class
*/
SootField field = (SootField) finalField;
if (sootClass.declaresField(field.getName(), field.getType())) {
// this field is of this class so supress the declaring class
if (valBox.canContainValue(new DStaticFieldRef(field.makeRef(), true))) {
valBox.setValue(new DStaticFieldRef(field.makeRef(), true));
}
} else {
if (valBox.canContainValue(new DStaticFieldRef(field.makeRef(), true))) {
valBox.setValue(new DStaticFieldRef(field.makeRef(), false));
}
}
}
// else
// System.out.println("Final field not found");
}
public Object check(Value val) {
Object finalField = null;
if (isConstant(val)) {
// System.out.println("Found constant in code"+val);
// can be a byte or short or char......or an int ...in the case of
// int you also have to check for Booleans
if (val instanceof StringConstant) {
String myString = ((StringConstant) val).toString();
myString = myString.substring(1, myString.length() - 1);
finalField = finalFields.get(myString);
} else if (val instanceof DoubleConstant) {
finalField = finalFields.get(((DoubleConstant) val).value);
} else if (val instanceof FloatConstant) {
finalField = finalFields.get(((FloatConstant) val).value);
} else if (val instanceof LongConstant) {
finalField = finalFields.get(((LongConstant) val).value);
} else if (val instanceof IntConstant) {
String myString = ((IntConstant) val).toString();
if (myString.length() == 0) {
return null;
}
Integer myInt;
try {
if (myString.charAt(0) == '\'') {
// character
if (myString.length() < 2) {
return null;
}
myInt = Integer.valueOf(myString.charAt(1));
} else {
myInt = Integer.valueOf(myString);
}
} catch (Exception e) {
// System.out.println("exception occured...gracefully exitting method..string was"+myString);
return finalField;
}
Type valType = ((IntConstant) val).getType();
if (valType instanceof ByteType) {
finalField = finalFields.get(myInt);
} else if (valType instanceof IntType) {
switch (myString) {
case "false":
finalField = finalFields.get(false);
break;
case "true":
finalField = finalFields.get(true);
break;
default:
finalField = finalFields.get(myInt);
break;
}
} else if (valType instanceof ShortType) {
finalField = finalFields.get(myInt);
}
}
}
return finalField;
}
/*
* The key in a switch stmt can be a local or a SootField or a value which can contain constant
*
* Hence the some what indirect approach........notice we will work with valueBoxes so that by changing the value in the
* value box we can deInline any field
*/
@Override
public void inASTSwitchNode(ASTSwitchNode node) {
Value val = node.get_Key();
if (isConstant(val)) {
// find if there is a SootField with this constant
// System.out.println("Found constant as key to switch");
checkAndSwitch(node.getKeyBox());
return;
}
// val is not a constant but it might have other constants in it
for (ValueBox tempBox : val.getUseBoxes()) {
// System.out.println("Checking useBox of switch key");
checkAndSwitch(tempBox);
}
}
@Override
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
for (ValueBox tempBox : s.getUseBoxes()) {
// System.out.println("Checking useBox of stmt");
checkAndSwitch(tempBox);
}
}
}
@Override
public void inASTForLoopNode(ASTForLoopNode node) {
// checking uses in init
for (AugmentedStmt as : node.getInit()) {
Stmt s = as.get_Stmt();
for (ValueBox tempBox : s.getUseBoxes()) {
// System.out.println("Checking useBox of init stmt");
checkAndSwitch(tempBox);
}
}
// checking uses in condition
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
// checking uses in update
for (AugmentedStmt as : node.getUpdate()) {
Stmt s = as.get_Stmt();
for (ValueBox tempBox : s.getUseBoxes()) {
// System.out.println("Checking useBox of update stmt");
checkAndSwitch(tempBox);
}
}
}
/*
* checking for unary conditions doesnt matter since this was definetly lost.
*/
public void checkConditionalUses(Object cond, ASTNode node) {
if (cond instanceof ASTAggregatedCondition) {
checkConditionalUses((((ASTAggregatedCondition) cond).getLeftOp()), node);
checkConditionalUses(((ASTAggregatedCondition) cond).getRightOp(), node);
return;
} else if (cond instanceof ASTBinaryCondition) {
// get uses from binaryCondition
Value val = ((ASTBinaryCondition) cond).getConditionExpr();
for (ValueBox tempBox : val.getUseBoxes()) {
// System.out.println("Checking useBox of binary condition");
checkAndSwitch(tempBox);
}
}
}
/*
* The condition of an if node can use a local
*/
@Override
public void inASTIfNode(ASTIfNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The condition of an ifElse node can use a local
*/
@Override
public void inASTIfElseNode(ASTIfElseNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The condition of a while node can use a local
*/
@Override
public void inASTWhileNode(ASTWhileNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The condition of a doWhile node can use a local
*/
@Override
public void inASTDoWhileNode(ASTDoWhileNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
}
| 13,749
| 35.089239
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/DecrementIncrementStmtCreation.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DDecrementStmt;
import soot.dava.internal.javaRep.DIncrementStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.AddExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.IntConstant;
import soot.jimple.Stmt;
import soot.jimple.SubExpr;
/*
* CHANGELOG: Nomair 9th Feb (For some reason only AddExpr was being checked for i++
* Added SubExpr for i--
*/
public class DecrementIncrementStmtCreation extends DepthFirstAdapter {
public DecrementIncrementStmtCreation() {
}
public DecrementIncrementStmtCreation(boolean verbose) {
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
for (AugmentedStmt as : node.getStatements()) {
// System.out.println(temp);
Stmt s = as.get_Stmt();
if (!(s instanceof DefinitionStmt)) {
continue;
}
// check if its i= i+1
Value left = ((DefinitionStmt) s).getLeftOp();
Value right = ((DefinitionStmt) s).getRightOp();
if (right instanceof SubExpr) {
Value op1 = ((SubExpr) right).getOp1();
Value op2 = ((SubExpr) right).getOp2();
if (left.toString().compareTo(op1.toString()) != 0) {
// not the same
continue;
}
// if they are the same
// check if op2 is a constant with value 1 or -1
if (op2 instanceof IntConstant) {
if (((IntConstant) op2).value == 1) {
// this is i = i-1
DDecrementStmt newStmt = new DDecrementStmt(left, right);
as.set_Stmt(newStmt);
} else if (((IntConstant) op2).value == -1) {
// this is i = i+1
DIncrementStmt newStmt = new DIncrementStmt(left, right);
as.set_Stmt(newStmt);
}
}
} else if (right instanceof AddExpr) {
Value op1 = ((AddExpr) right).getOp1();
Value op2 = ((AddExpr) right).getOp2();
if (left.toString().compareTo(op1.toString()) != 0) {
continue;
}
// check if op2 is a constant with value 1 or -1
if (op2 instanceof IntConstant) {
if (((IntConstant) op2).value == 1) {
// this is i = i+1
DIncrementStmt newStmt = new DIncrementStmt(left, right);
as.set_Stmt(newStmt);
} else if (((IntConstant) op2).value == -1) {
// this is i = i-1
DDecrementStmt newStmt = new DDecrementStmt(left, right);
as.set_Stmt(newStmt);
}
}
} // right expr was addExpr
} // going through statements
}
}
| 3,616
| 33.122642
| 84
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/EliminateConditions.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Nomair A. Naeem
* %%
* 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.BooleanType;
import soot.Value;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTControlFlowNode;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTLabeledNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.AST.ASTUnaryCondition;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.javaRep.DIntConstant;
import soot.dava.internal.javaRep.DNotExpr;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.dava.toolkits.base.AST.traversals.ASTParentNodeFinder;
/*
* if (true) ---> remove conditional copy ifbody to parent
*
* if(false) eliminate in all entirety
*
* if(true)
* bla1
* else
* bla2 remove conditional copy bla1 to parent
*
* if(false)
* bla1
* else
* bla2 remoce conditional copy bla2 to parent
*
*
* while(false) eliminate in entirety... notice this is not an Uncondition loop but a ASTWhileNode
*
* do{ .... } while(false) eliminate loop copy body to parent
*
* for(int i =0;false;i++) remove for . copy init stmts to parent
*/
public class EliminateConditions extends DepthFirstAdapter {
public static boolean DEBUG = false;
public boolean modified = false;
ASTParentNodeFinder finder;
ASTMethodNode AST;
List<Object> bodyContainingNode = null;
public EliminateConditions(ASTMethodNode AST) {
super();
finder = new ASTParentNodeFinder();
this.AST = AST;
}
public EliminateConditions(boolean verbose, ASTMethodNode AST) {
super(verbose);
finder = new ASTParentNodeFinder();
this.AST = AST;
}
public void normalRetrieving(ASTNode node) {
modified = false;
if (node instanceof ASTSwitchNode) {
do {
modified = false;
dealWithSwitchNode((ASTSwitchNode) node);
} while (modified);
return;
}
// from the Node get the subBodes
Iterator<Object> sbit = node.get_SubBodies().iterator();
while (sbit.hasNext()) {
List subBody = (List) sbit.next();
Iterator it = subBody.iterator();
ASTNode temp = null;
Boolean returned = null;
while (it.hasNext()) {
temp = (ASTNode) it.next();
// only check condition if this is a control flow node
if (temp instanceof ASTControlFlowNode) {
bodyContainingNode = null;
returned = eliminate(temp);
if (returned != null && canChange(returned, temp)) {
break;
} else {
if (DEBUG) {
System.out.println("returned is null" + temp.getClass());
}
bodyContainingNode = null;
}
}
temp.apply(this);
} // end while going through nodes in subBody
boolean changed = change(returned, temp);
if (changed) {
modified = true;
}
} // end of going over subBodies
if (modified) {
// repeat the whole thing
normalRetrieving(node);
}
}
public Boolean eliminate(ASTNode node) {
ASTCondition cond = null;
if (node instanceof ASTControlFlowNode) {
cond = ((ASTControlFlowNode) node).get_Condition();
} else {
return null;
}
if (cond == null || !(cond instanceof ASTUnaryCondition)) {
return null;
}
ASTUnaryCondition unary = (ASTUnaryCondition) cond;
Value unaryValue = unary.getValue();
boolean notted = false;
if (unaryValue instanceof DNotExpr) {
notted = true;
unaryValue = ((DNotExpr) unaryValue).getOp();
}
Boolean isBoolean = isBooleanConstant(unaryValue);
if (isBoolean == null) {
// not a constant
return null;
}
boolean trueOrFalse = isBoolean.booleanValue();
if (notted) {
// since it is notted we reverse the booleans
trueOrFalse = !trueOrFalse;
}
AST.apply(finder);
Object temp = finder.getParentOf(node);
if (temp == null) {
return null;
}
ASTNode parent = (ASTNode) temp;
List<Object> subBodies = parent.get_SubBodies();
Iterator<Object> it = subBodies.iterator();
int index = -1;
while (it.hasNext()) {
bodyContainingNode = (List<Object>) it.next();
index = bodyContainingNode.indexOf(node);
if (index < 0) {
bodyContainingNode = null;
} else {
// bound the body containing Node
return new Boolean(trueOrFalse);
}
}
return null;
}
/*
* Method returns null if the Value is not a constant or not a boolean constant return true if the constant is true return
* false if the constant is false
*/
public Boolean isBooleanConstant(Value internal) {
if (!(internal instanceof DIntConstant)) {
return null;
}
if (DEBUG) {
System.out.println("Found Constant");
}
DIntConstant intConst = (DIntConstant) internal;
if (!(intConst.type instanceof BooleanType)) {
return null;
}
// either true or false
if (DEBUG) {
System.out.println("Found Boolean Constant");
}
if (intConst.value == 1) {
return new Boolean(true);
} else if (intConst.value == 0) {
return new Boolean(false);
} else {
throw new RuntimeException("BooleanType found with value different than 0 or 1");
}
}
public Boolean eliminateForTry(ASTNode node) {
ASTCondition cond = null;
if (node instanceof ASTControlFlowNode) {
cond = ((ASTControlFlowNode) node).get_Condition();
} else {
return null;
}
if (cond == null || !(cond instanceof ASTUnaryCondition)) {
return null;
}
ASTUnaryCondition unary = (ASTUnaryCondition) cond;
Value unaryValue = unary.getValue();
boolean notted = false;
if (unaryValue instanceof DNotExpr) {
notted = true;
unaryValue = ((DNotExpr) unaryValue).getOp();
}
Boolean isBoolean = isBooleanConstant(unaryValue);
if (isBoolean == null) {
// not a constant
return null;
}
boolean trueOrFalse = isBoolean.booleanValue();
if (notted) {
// since it is notted we reverse the booleans
trueOrFalse = !trueOrFalse;
}
AST.apply(finder);
Object temp = finder.getParentOf(node);
if (temp == null) {
return null;
}
if (!(temp instanceof ASTTryNode)) {
throw new RuntimeException("eliminateTry called when parent was not a try node");
}
ASTTryNode parent = (ASTTryNode) temp;
List<Object> tryBody = parent.get_TryBody();
int index = tryBody.indexOf(node);
if (index >= 0) {
// bound the body containing Node
bodyContainingNode = tryBody;
return new Boolean(trueOrFalse);
}
List<Object> catchList = parent.get_CatchList();
Iterator<Object> it = catchList.iterator();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container) it.next();
List<Object> body = (List<Object>) catchBody.o;
index = body.indexOf(node);
if (index >= 0) {
// bound the body containing Node
bodyContainingNode = body;
return new Boolean(trueOrFalse);
}
}
return null;
}
public void caseASTTryNode(ASTTryNode node) {
modified = false;
inASTTryNode(node);
// get try body iterator
Iterator<Object> it = node.get_TryBody().iterator();
Boolean returned = null;
ASTNode temp = null;
while (it.hasNext()) {
temp = (ASTNode) it.next();
// only check condition if this is a control flow node
if (temp instanceof ASTControlFlowNode) {
bodyContainingNode = null;
returned = eliminateForTry(temp);
if (returned != null && canChange(returned, temp)) {
break;
} else {
bodyContainingNode = null;
}
}
temp.apply(this);
} // end while
boolean changed = change(returned, temp);
if (changed) {
modified = true;
}
// get catch list and apply on the following
// a, type of exception caught ......... NO NEED
// b, local of exception ............... NO NEED
// c, catchBody
List<Object> catchList = node.get_CatchList();
Iterator itBody = null;
it = catchList.iterator();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container) it.next();
List body = (List) catchBody.o;
itBody = body.iterator();
returned = null;
temp = null;
// go over the ASTNodes and apply
while (itBody.hasNext()) {
temp = (ASTNode) itBody.next();
// System.out.println("Next node is "+temp);
// only check condition if this is a control flow node
if (temp instanceof ASTControlFlowNode) {
bodyContainingNode = null;
returned = eliminateForTry(temp);
if (returned != null && canChange(returned, temp)) {
break;
} else {
bodyContainingNode = null;
}
}
temp.apply(this);
}
changed = change(returned, temp);
if (changed) {
modified = true;
}
}
outASTTryNode(node);
if (modified) {
// repeat the whole thing
caseASTTryNode(node);
}
}
public boolean canChange(Boolean returned, ASTNode temp) {
return true;
}
public boolean change(Boolean returned, ASTNode temp) {
if (bodyContainingNode != null && returned != null && temp != null) {
int index = bodyContainingNode.indexOf(temp);
if (DEBUG) {
System.out.println("in change");
}
if (temp instanceof ASTIfNode) {
bodyContainingNode.remove(temp);
if (returned.booleanValue()) {
// if statement and value was true put the body of if into
// the code
// if its a labeled stmt we need a labeled block instead
// notice that its okkay to put a labeled block since other
// transformations might remove it
String label = ((ASTLabeledNode) temp).get_Label().toString();
if (label != null) {
ASTLabeledBlockNode labeledNode
= new ASTLabeledBlockNode(((ASTLabeledNode) temp).get_Label(), (List<Object>) temp.get_SubBodies().get(0));
bodyContainingNode.add(index, labeledNode);
} else {
bodyContainingNode.addAll(index, (List) temp.get_SubBodies().get(0));
}
}
if (DEBUG) {
System.out.println("Removed if" + temp);
}
return true;
} else if (temp instanceof ASTIfElseNode) {
bodyContainingNode.remove(temp);
if (returned.booleanValue()) {
// true so the if branch's body has to be added
// if its a labeled stmt we need a labeled block instead
// notice that its okkay to put a labeled block since other
// transformations might remove it
String label = ((ASTLabeledNode) temp).get_Label().toString();
if (label != null) {
ASTLabeledBlockNode labeledNode
= new ASTLabeledBlockNode(((ASTLabeledNode) temp).get_Label(), (List<Object>) temp.get_SubBodies().get(0));
bodyContainingNode.add(index, labeledNode);
} else {
bodyContainingNode.addAll(index, (List) temp.get_SubBodies().get(0));
}
} else {
// if its a labeled stmt we need a labeled block instead
// notice that its okkay to put a labeled block since other
// transformations might remove it
String label = ((ASTLabeledNode) temp).get_Label().toString();
if (label != null) {
ASTLabeledBlockNode labeledNode
= new ASTLabeledBlockNode(((ASTLabeledNode) temp).get_Label(), (List<Object>) temp.get_SubBodies().get(1));
bodyContainingNode.add(index, labeledNode);
} else {
bodyContainingNode.addAll(index, (List) temp.get_SubBodies().get(1));
}
}
return true;
} else if (temp instanceof ASTWhileNode && returned.booleanValue() == false) {
// notice we only remove if ASTWhileNode has false condition
bodyContainingNode.remove(temp);
return true;
} else if (temp instanceof ASTDoWhileNode && returned.booleanValue() == false) {
// System.out.println("in try dowhile false");
// remove the loop copy the body out since it gets executed once
bodyContainingNode.remove(temp);
bodyContainingNode.addAll(index, (List) temp.get_SubBodies().get(0));
return true;
} else if (temp instanceof ASTForLoopNode && returned.booleanValue() == false) {
bodyContainingNode.remove(temp);
ASTStatementSequenceNode newNode = new ASTStatementSequenceNode(((ASTForLoopNode) temp).getInit());
bodyContainingNode.add(index, newNode);
return true;
}
}
return false;
}
public void dealWithSwitchNode(ASTSwitchNode node) {
List<Object> indexList = node.getIndexList();
Map<Object, List<Object>> index2BodyList = node.getIndex2BodyList();
Iterator<Object> it = indexList.iterator();
while (it.hasNext()) {
// going through all the cases of the switch statement
Object currentIndex = it.next();
List body = index2BodyList.get(currentIndex);
if (body != null) {
// this body is a list of ASTNodes
Iterator itBody = body.iterator();
Boolean returned = null;
ASTNode temp = null;
while (itBody.hasNext()) {
temp = (ASTNode) itBody.next();
if (temp instanceof ASTControlFlowNode) {
bodyContainingNode = null;
returned = eliminate(temp);
if (returned != null && canChange(returned, temp)) {
break;
} else {
bodyContainingNode = null;
}
}
temp.apply(this);
}
boolean changed = change(returned, temp);
if (changed) {
modified = true;
}
} // end while changed
}
}
}
| 15,305
| 29.921212
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/EmptyElseRemover.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 soot.G;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
/*
Nomair A. Naeem 21-FEB-2005
*/
public class EmptyElseRemover {
public static void removeElseBody(ASTNode node, ASTIfElseNode ifElseNode, int subBodyNumber, int nodeNumber) {
if (!(node instanceof ASTIfElseNode)) {
// these are the nodes which always have one subBody
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 1) {
// there is something wrong
throw new RuntimeException("Please report this benchmark to the programmer");
}
List<Object> onlySubBody = (List<Object>) subBodies.get(0);
/*
* The onlySubBody contains the ASTIfElseNode whose elsebody has to be removed at location given by the nodeNumber
* variable
*/
List<Object> newBody = createNewNodeBody(onlySubBody, nodeNumber, ifElseNode);
if (newBody == null) {
// something went wrong
return;
}
if (node instanceof ASTMethodNode) {
((ASTMethodNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSE BODY");
} else if (node instanceof ASTSynchronizedBlockNode) {
((ASTSynchronizedBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSE BODY");
} else if (node instanceof ASTLabeledBlockNode) {
((ASTLabeledBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSE BODY");
} else if (node instanceof ASTUnconditionalLoopNode) {
((ASTUnconditionalLoopNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSE BODY");
} else if (node instanceof ASTIfNode) {
((ASTIfNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSE BODY");
} else if (node instanceof ASTWhileNode) {
((ASTWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSE BODY");
} else if (node instanceof ASTDoWhileNode) {
((ASTDoWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED ELSE BODY");
} else {
// there is no other case something is wrong if we get here
return;
}
} else {
// its an ASTIfElseNode
// if its an ASIfElseNode then check which Subbody has the labeledBlock
if (subBodyNumber != 0 && subBodyNumber != 1) {
// something bad is happening dont do nothin
// System.out.println("Error-------not modifying AST");
return;
}
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 2) {
// there is something wrong
throw new RuntimeException("Please report this benchmark to the programmer");
}
List<Object> toModifySubBody = (List<Object>) subBodies.get(subBodyNumber);
/*
* The toModifySubBody contains the ASTIfElseNode to be removed at location given by the nodeNumber variable
*/
List<Object> newBody = createNewNodeBody(toModifySubBody, nodeNumber, ifElseNode);
if (newBody == null) {
// something went wrong
return;
}
if (subBodyNumber == 0) {
// the if body was modified
// System.out.println("REMOVED ELSE BODY");
G.v().ASTTransformations_modified = true;
((ASTIfElseNode) node).replaceBody(newBody, (List<Object>) subBodies.get(1));
} else if (subBodyNumber == 1) {
// else body was modified
// System.out.println("REMOVED ELSE BODY");
G.v().ASTTransformations_modified = true;
((ASTIfElseNode) node).replaceBody((List<Object>) subBodies.get(0), newBody);
} else {
// realllly shouldnt come here
// something bad is happening dont do nothin
// System.out.println("Error-------not modifying AST");
return;
}
} // end of ASTIfElseNode
}
public static List<Object> createNewNodeBody(List<Object> oldSubBody, int nodeNumber, ASTIfElseNode ifElseNode) {
// create a new SubBody
List<Object> newSubBody = new ArrayList<Object>();
// this is an iterator of ASTNodes
Iterator<Object> it = oldSubBody.iterator();
// copy to newSubBody all nodes until you get to nodeNumber
int index = 0;
while (index != nodeNumber) {
if (!it.hasNext()) {
return null;
}
newSubBody.add(it.next());
index++;
}
// at this point the iterator is pointing to the ASTIfElseNode to be removed
// just to make sure check this
ASTNode toRemove = (ASTNode) it.next();
if (!(toRemove instanceof ASTIfElseNode)) {
// something is wrong
return null;
} else {
ASTIfElseNode toRemoveNode = (ASTIfElseNode) toRemove;
// just double checking that this is a empty else node
List<Object> elseBody = toRemoveNode.getElseBody();
if (elseBody.size() != 0) {
// something is wrong we cant remove a non empty elsebody
return null;
}
// so this is the ElseBody to remove
// need to create an ASTIfNode from the ASTIfElseNode
ASTIfNode newNode = new ASTIfNode(toRemoveNode.get_Label(), toRemoveNode.get_Condition(), toRemoveNode.getIfBody());
// add this node to the newSubBody
newSubBody.add(newNode);
}
// add any remaining nodes in the oldSubBody to the new one
while (it.hasNext()) {
newSubBody.add(it.next());
}
// newSubBody is ready return it
return newSubBody;
}
}
| 7,130
| 35.948187
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/ExtraLabelNamesRemover.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
public class ExtraLabelNamesRemover extends DepthFirstAdapter {
/*
* label_0: while(cond){ if(cond1) NO NEED for break label_0 break label_0 Use just break; }
*
* label_0: switch(cond){ case 0: Body break label_0; NO NEED for break label_0 case 1: Use just break Body break label_0;
*
* IDEA: In gerneral store the current label name Go through the tree rooted at this label name and find all breaks if any
* break targets the current label name and not some previous one the label name can be removed from the break statement
* since it is the most recent break....TEST IT ON CASES AND SEE IF THIS IS TRUE THE JAVA LANGUAGE SAYS IT SHOULD BE TRUE
*
*/
public ExtraLabelNamesRemover() {
}
public ExtraLabelNamesRemover(boolean verbose) {
super(verbose);
}
}
| 1,720
| 35.617021
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/FinalFieldDefinition.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Nomair A. Naeem (nomair.naeem@mail.mcgill.ca)
* %%
* 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.HashSet;
import java.util.List;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.RefType;
import soot.ShortType;
import soot.SootClass;
import soot.SootField;
import soot.SootFieldRef;
import soot.SootMethod;
import soot.Type;
import soot.Value;
import soot.dava.DavaBody;
import soot.dava.DecompilationException;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DInstanceFieldRef;
import soot.dava.internal.javaRep.DIntConstant;
import soot.dava.internal.javaRep.DStaticFieldRef;
import soot.dava.internal.javaRep.DVariableDeclarationStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.dava.toolkits.base.AST.structuredAnalysis.MustMayInitialize;
import soot.dava.toolkits.base.AST.traversals.AllVariableUses;
import soot.grimp.internal.GAssignStmt;
import soot.jimple.DefinitionStmt;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.LongConstant;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.jimple.internal.JimpleLocal;
import soot.tagkit.DoubleConstantValueTag;
import soot.tagkit.FloatConstantValueTag;
import soot.tagkit.IntegerConstantValueTag;
import soot.tagkit.LongConstantValueTag;
import soot.tagkit.StringConstantValueTag;
/**
* Maintained by: Nomair A. Naeem
*/
/**
* CHANGE LOG: 30th January 2006: Class was created to get rid of the field might not be initialized error that used to show
* up when recompiling decompiled code Will be throughly covered in "Programmer Friendly Code" Sable Tech Report (2006)
*
*/
/**
* This class makes sure there is an initialization of all final variables (static or non static). If we cant guarantee
* initialization (may be initialized on multiple paths but not all) then we remove the final keyword
*/
public class FinalFieldDefinition {
// extends DepthFirstAdapter{
SootClass sootClass;
SootMethod sootMethod;
DavaBody davaBody;
List<SootField> cancelFinalModifier;
public FinalFieldDefinition(ASTMethodNode node) {
davaBody = node.getDavaBody();
sootMethod = davaBody.getMethod();
sootClass = sootMethod.getDeclaringClass();
String subSignature = sootMethod.getName();
if (subSignature.compareTo("<clinit>") != 0 && subSignature.compareTo("<init>") != 0) {
// dont care about these since we want only static block and
// constructors
// System.out.println("\n\nName"+sootMethod.getName()+"
// SubSignature:"+sootMethod.getSubSignature());
return;
}
// create a list of interesting vars
ArrayList<SootField> interesting = findFinalFields();
if (interesting.isEmpty()) {
// no final fields of interest
return;
}
cancelFinalModifier = new ArrayList<SootField>();
analyzeMethod(node, interesting);
for (SootField field : cancelFinalModifier) {
field.setModifiers((soot.Modifier.FINAL ^ 0xFFFF) & field.getModifiers());
}
}
/*
* this method finds all the final fields in this class and assigns them to the finalFields list
*
* Note this stores a list of SootFields!!!
*
* Fields which are initialized in their declaration should not be added
*/
public ArrayList<SootField> findFinalFields() {
// first thing is to get a list of all final fields in the class
ArrayList<SootField> interestingFinalFields = new ArrayList<SootField>();
for (SootField tempField : sootClass.getFields()) {
if (tempField.isFinal()) {
// if its static final and method is static add
if (tempField.isStatic() && sootMethod.getName().compareTo("<clinit>") == 0) {
interestingFinalFields.add(tempField);
}
// if its non static and final and method is constructor add
if (!tempField.isStatic() && sootMethod.getName().compareTo("<init>") == 0) {
interestingFinalFields.add(tempField);
}
}
}
return interestingFinalFields;
}
public void analyzeMethod(ASTMethodNode node, List<SootField> varsOfInterest) {
MustMayInitialize must = new MustMayInitialize(node, MustMayInitialize.MUST);
for (SootField interest : varsOfInterest) {
// check for constant value tags
Type fieldType = interest.getType();
if (fieldType instanceof DoubleType && interest.hasTag(DoubleConstantValueTag.NAME)) {
continue;
} else if (fieldType instanceof FloatType && interest.hasTag(FloatConstantValueTag.NAME)) {
continue;
} else if (fieldType instanceof LongType && interest.hasTag(LongConstantValueTag.NAME)) {
continue;
} else if (fieldType instanceof CharType && interest.hasTag(IntegerConstantValueTag.NAME)) {
continue;
} else if (fieldType instanceof BooleanType && interest.hasTag(IntegerConstantValueTag.NAME)) {
continue;
} else if ((fieldType instanceof IntType || fieldType instanceof ByteType || fieldType instanceof ShortType)
&& interest.hasTag(IntegerConstantValueTag.NAME)) {
continue;
} else if (interest.hasTag(StringConstantValueTag.NAME)) {
continue;
}
if (must.isMustInitialized(interest)) {
// was initialized on all paths couldnt ask for more
continue;
}
// System.out.println("SootField: "+interest+" not initialized.
// checking may analysis");
MustMayInitialize may = new MustMayInitialize(node, MustMayInitialize.MAY);
if (may.isMayInitialized(interest)) {
// System.out.println("It is initialized on some path just not
// all paths\n");
List defs = must.getDefs(interest);
if (defs == null) {
throw new RuntimeException("Sootfield: " + interest + " is mayInitialized but the defs is null");
}
handleAssignOnSomePaths(node, interest, defs);
} else {
// not initialized on any path., assign default
// System.out.println("Final field is not initialized on any
// path--------ASSIGN DEFAULT VALUE");
assignDefault(node, interest);
}
}
}
/*
* One gets to this method only if there was NO definition of a static final field in the static body At the same time no
* TAG with a constant value matched, so we know the static final was not initialized at declaration time If this happens:
* though it shouldnt unless u come from non-java compilers...insert default value initialization into the static
* method...right at the end to make things easy
*/
public void assignDefault(ASTMethodNode node, SootField f) {
// create initialization stmt
AugmentedStmt defaultStmt = createDefaultStmt(f);
if (defaultStmt == null) {
return;
}
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 1) {
throw new RuntimeException("SubBodies size of method node not equal to 1");
}
List<Object> body = (List<Object>) subBodies.get(0);
// check if the bodys last node is an ASTStatementSequenceNode where we
// might be able to add
boolean done = false;
if (!body.isEmpty()) {
ASTNode lastNode = (ASTNode) body.get(body.size() - 1);
if (lastNode instanceof ASTStatementSequenceNode) {
List<AugmentedStmt> stmts = ((ASTStatementSequenceNode) lastNode).getStatements();
if (!stmts.isEmpty()) {
Stmt s = stmts.get(0).get_Stmt();
if (!(s instanceof DVariableDeclarationStmt)) {
// can add statement here
stmts.add(defaultStmt);
ASTStatementSequenceNode newNode = new ASTStatementSequenceNode(stmts);
// replace this node with the original node
body.remove(body.size() - 1);
body.add(newNode);
node.replaceBody(body);
done = true;
}
}
}
}
if (!done) {
List<AugmentedStmt> newBody = new ArrayList<AugmentedStmt>();
newBody.add(defaultStmt);
ASTStatementSequenceNode newNode = new ASTStatementSequenceNode(newBody);
body.add(newNode);
node.replaceBody(body);
}
}
public AugmentedStmt createDefaultStmt(Object field) {
Value ref = null;
Type fieldType = null;
if (field instanceof SootField) {
// have to make a static field ref
SootFieldRef tempFieldRef = ((SootField) field).makeRef();
fieldType = ((SootField) field).getType();
if (((SootField) field).isStatic()) {
ref = new DStaticFieldRef(tempFieldRef, true);
} else {
ref = new DInstanceFieldRef(new JimpleLocal("this", fieldType), tempFieldRef, new HashSet<Object>());
}
} else if (field instanceof Local) {
ref = (Local) field;
fieldType = ((Local) field).getType();
}
GAssignStmt assignStmt = null;
if (fieldType instanceof RefType) {
assignStmt = new GAssignStmt(ref, NullConstant.v());
} else if (fieldType instanceof DoubleType) {
assignStmt = new GAssignStmt(ref, DoubleConstant.v(0));
} else if (fieldType instanceof FloatType) {
assignStmt = new GAssignStmt(ref, FloatConstant.v(0));
} else if (fieldType instanceof LongType) {
assignStmt = new GAssignStmt(ref, LongConstant.v(0));
} else if (fieldType instanceof IntType || fieldType instanceof ByteType || fieldType instanceof ShortType
|| fieldType instanceof CharType || fieldType instanceof BooleanType) {
assignStmt = new GAssignStmt(ref, DIntConstant.v(0, fieldType));
}
if (assignStmt != null) {
// System.out.println("AssignStmt is"+assignStmt);
AugmentedStmt as = new AugmentedStmt(assignStmt);
return as;
} else {
return null;
}
}
/*
* A sootfield gets to this method if it was an interesting field i.e static final for clinit and only final but non static
* for init and there was atleast one place that this var was defined but it was not defined on all paths and hence the
* recompilation will result in an error
*
* try{ staticFinal = defined; } catch(Exception e){}
*/
public void handleAssignOnSomePaths(ASTMethodNode node, SootField field, List defs) {
if (defs.size() != 1) {
// give up by removing "final" if there are more than one defs
cancelFinalModifier.add(field);
} else {
// if there is only one definition
// see if there is no use of def
AllVariableUses varUses = new AllVariableUses(node);
node.apply(varUses);
List allUses = varUses.getUsesForField(field);
if (allUses != null && !allUses.isEmpty()) {
/*
* if the number of uses is not 0 then we dont want to get into trying to delay initialization just before
* assignment. Easier to remove "final"
*/
cancelFinalModifier.add(field);
} else {
/*
* we have a final field with 1 def and 0 uses but is not initialized on all paths we can try to delay initialization
* using an indirect approach STMT0 TYPE DavaTemp_fieldName; STMT1 DavaTemp_fieldname = DEFAULT try{ try{ field = ...
* STMT2 DavaTemp_fieldname = ... } X catch(...){ }catch(..){ .... .... } } STMT3 field = Dava_tempVar
*
* Notice the following code will try to place the field assignment as close to the original assignment as possible.
*
* TODO: However there might still be issues with delaying this assignment e.g. what if the place marked by X (more
* specifically between the original def and the new def includes a method invocation which access the delayed field.
*
* Original Comment February 2nd, 2006: Laurie mentioned that apart from direct uses we also have to be conservative
* about method calls since we are dealing with fields here What if some method was invoked and it tried to use a
* field whose initialization we are about to delay. This can be done by implementing a small analysis. (See end of
* this class file.
*
* TODO: SHOULD BE CHECKED FOR CODE BETWEEN THE OLD DEF AND THE NEW ASSIGNMENT Currently checks from some point till
* end of method
*
* MethodCallFinder myMethodCallFinder = new MethodCallFinder( (GAssignStmt) defs.get(0));
* node.apply(myMethodCallFinder); if (myMethodCallFinder.anyMethodCalls()) { // there was some method call after the
* definition stmt so // we cant continue // remove the final modifier and leave //System.out.println(
* "Method invoked somewhere after definition"); cancelFinalModifier.add(field); return; }
*/
// Creating STMT0
Type localType = field.getType();
Local newLocal = new JimpleLocal("DavaTemp_" + field.getName(), localType);
DVariableDeclarationStmt varStmt = new DVariableDeclarationStmt(localType, davaBody);
varStmt.addLocal(newLocal);
AugmentedStmt as = new AugmentedStmt(varStmt);
// System.out.println("Var Decl stmt"+as);
// STORE IT IN Methods Declaration Node
ASTStatementSequenceNode declNode = node.getDeclarations();
List<AugmentedStmt> stmts = declNode.getStatements();
stmts.add(as);
declNode = new ASTStatementSequenceNode(stmts);
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 1) {
throw new DecompilationException("ASTMethodNode does not have one subBody");
}
List<Object> body = (List<Object>) subBodies.get(0);
body.remove(0);
body.add(0, declNode);
node.replaceBody(body);
node.setDeclarations(declNode);
// STMT1 initialization
AugmentedStmt initialization = createDefaultStmt(newLocal);
/*
* The first node in a method is the declarations we know there is a second node because originaly the field was
* initialized on some path
*/
if (body.size() < 2) {
throw new RuntimeException("Size of body is less than 1");
}
/*
* If the second node is a stmt seq we put STMT1 there otherwise we create a new stmt seq node
*/
ASTNode nodeSecond = (ASTNode) body.get(1);
if (nodeSecond instanceof ASTStatementSequenceNode) {
// the second node is a stmt seq node just add the stmt here
List<AugmentedStmt> stmts1 = ((ASTStatementSequenceNode) nodeSecond).getStatements();
stmts1.add(initialization);
nodeSecond = new ASTStatementSequenceNode(stmts1);
// System.out.println("Init added in exisiting node");
body.remove(1);
} else {
// System.out.println("had to add new node");
List<AugmentedStmt> tempList = new ArrayList<AugmentedStmt>();
tempList.add(initialization);
nodeSecond = new ASTStatementSequenceNode(tempList);
}
body.add(1, nodeSecond);
node.replaceBody(body);
// STMT2
// done by simply replacing the leftop in the original stmt
((GAssignStmt) defs.get(0)).setLeftOp(newLocal);
// STMT3
// have to make a field ref
SootFieldRef tempFieldRef = (field).makeRef();
Value ref;
if (field.isStatic()) {
ref = new DStaticFieldRef(tempFieldRef, true);
} else {
ref = new DInstanceFieldRef(new JimpleLocal("this", field.getType()), tempFieldRef, new HashSet<Object>());
// throw new RuntimeException("STOPPED");
}
GAssignStmt assignStmt = new GAssignStmt(ref, newLocal);
AugmentedStmt assignStmt1 = new AugmentedStmt(assignStmt);
/*
* 14th February 2006 Should add this statement to the first place in the code where we will have a mustInitialize
* satisfied
*/
// the def is at (GAssignStmt) defs.get(0)
// its parent is ASTStatementSequence and its parent is now needed
soot.dava.toolkits.base.AST.traversals.ASTParentNodeFinder parentFinder =
new soot.dava.toolkits.base.AST.traversals.ASTParentNodeFinder();
node.apply(parentFinder);
Object parent = parentFinder.getParentOf(defs.get(0));
if (!(parent instanceof ASTStatementSequenceNode)) {
throw new DecompilationException("Parent of stmt was not a stmt seq node");
}
Object grandParent = parentFinder.getParentOf(parent);
if (grandParent == null) {
throw new DecompilationException("Parent of stmt seq node was null");
}
// so we have the parent stmt seq node and the grandparent node
// so it is the grandparent which is causing the error in MUSTINitialize
// we should move our assign right after the grandParent is done
MustMayInitialize must = new MustMayInitialize(node, MustMayInitialize.MUST);
while (!must.isMustInitialized(field)) {
// System.out.println("not must initialized");
Object parentOfGrandParent = parentFinder.getParentOf(grandParent);
if (!(grandParent instanceof ASTMethodNode) && parentOfGrandParent == null) {
throw new DecompilationException("Parent of non method node was null");
}
boolean notResolved = false;
// look for grandParent in parentOfGrandParent
ASTNode ancestor = (ASTNode) parentOfGrandParent;
for (Object next : ancestor.get_SubBodies()) {
List<ASTStatementSequenceNode> ancestorSubBody;
if (ancestor instanceof ASTTryNode) {
ancestorSubBody = (List<ASTStatementSequenceNode>) ((ASTTryNode.container) next).o;
} else {
ancestorSubBody = (List<ASTStatementSequenceNode>) next;
}
if (ancestorSubBody.indexOf(grandParent) > -1) {
// grandParent is present in this body
int index = ancestorSubBody.indexOf(grandParent);
// check the next index
if (index + 1 < ancestorSubBody.size() && ancestorSubBody.get(index + 1) instanceof ASTStatementSequenceNode) {
// there is an stmt seq node node after the grandParent
ASTStatementSequenceNode someNode = ancestorSubBody.get(index + 1);
// add the assign stmt here
List<AugmentedStmt> stmtsLast = (someNode).getStatements();
List<AugmentedStmt> newStmts = new ArrayList<AugmentedStmt>();
newStmts.add(assignStmt1);
newStmts.addAll(stmtsLast);
someNode.setStatements(newStmts);
// System.out.println("here1");
// check if problem is solved else remove the assign and change parents
must = new MustMayInitialize(node, MustMayInitialize.MUST);
if (!must.isMustInitialized(field)) {
// problem not solved remove the stmt just added
someNode.setStatements(stmtsLast);
notResolved = true;
}
} else {
// create a new stmt seq node and add it here
List<AugmentedStmt> tempList = new ArrayList<AugmentedStmt>();
tempList.add(assignStmt1);
ASTStatementSequenceNode lastNode = new ASTStatementSequenceNode(tempList);
ancestorSubBody.add(index + 1, lastNode);
// node.replaceBody(body);
// System.out.println("here2");
// check if problem is solved else remove the assign and change parents
must = new MustMayInitialize(node, MustMayInitialize.MUST);
if (!must.isMustInitialized(field)) {
// problem not solved remove the stmt just added
ancestorSubBody.remove(index + 1);
notResolved = true;
}
}
break;// break the loop going through subBodies
} // if ancestor was found
} // next subBody
if (notResolved) {
// meaning we still dont have must initialization
// we should put assign in one level above than current
grandParent = parentFinder.getParentOf(grandParent);
// System.out.println("Going one level up");
}
} // while ! ismustinitialized
}
}
}
}
/*
* TODO: Change the analysis below to find method calls between GAssignStmt def and the new Assign Stmt.
*/
class MethodCallFinder extends DepthFirstAdapter {
GAssignStmt def;
boolean foundIt = false;
boolean anyMethodCalls = false;
public MethodCallFinder(GAssignStmt def) {
this.def = def;
}
public MethodCallFinder(boolean verbose, GAssignStmt def) {
super(verbose);
this.def = def;
}
@Override
public void outDefinitionStmt(DefinitionStmt s) {
if (s instanceof GAssignStmt) {
if (((GAssignStmt) s).equals(def)) {
foundIt = true;
// System.out.println("Found it" + s);
}
}
}
@Override
public void inInvokeExpr(InvokeExpr ie) {
// System.out.println("In invoke Expr");
if (foundIt) {
// System.out.println("oops invoking something after definition");
anyMethodCalls = true;
}
}
/*
* Method will return false if there were no method calls made after the definition stmt
*/
public boolean anyMethodCalls() {
return anyMethodCalls;
// return false;
}
}
| 22,708
| 37.489831
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/ForLoopCreationHelper.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.Value;
import soot.dava.internal.AST.ASTAggregatedCondition;
import soot.dava.internal.AST.ASTBinaryCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTLabeledNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTUnaryCondition;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.internal.asg.AugmentedStmt;
import soot.jimple.ConditionExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
public class ForLoopCreationHelper {
ASTStatementSequenceNode stmtSeqNode;
ASTWhileNode whileNode;
ASTStatementSequenceNode newStmtSeqNode;
ASTForLoopNode forNode;
Map<String, Integer> varToStmtMap;
/*
* Bug Reported by Steffen Pingel on the soot mailing list (january 2006) Fixed by Nomair February 6th, 2006
*
* There was a bug in the getUpdate method since it removed the update statement whenver it found one Later on if the
* ForLoop Creation terminated the update stmt had been removed We delay the removal of the update stmt until we are sure
* that the for loop is being created This is done by storing the list of stmts from which to remove the update statement
* in the following field. The boolean (although redundant) indicates when such an update stmt should be removed
*/
List<AugmentedStmt> myStmts;// stores the statementseq list of statements whose
// last stmt has to be removed
boolean removeLast = false;// the last stmt in the above stmts is removed if
// this boolean is true
public ForLoopCreationHelper(ASTStatementSequenceNode stmtSeqNode, ASTWhileNode whileNode) {
this.stmtSeqNode = stmtSeqNode;
this.whileNode = whileNode;
varToStmtMap = new HashMap<String, Integer>();
}
/*
* The purpose of this method is to replace the statement sequence node given by the var nodeNumber with the new statement
* sequence node and to replace the next node (which sould be a while node with the for loop node
*
* The new body is then returned;
*/
public List<Object> createNewBody(List<Object> oldSubBody, int nodeNumber) {
List<Object> newSubBody = new ArrayList<Object>();
if (oldSubBody.size() <= nodeNumber) {
// something is wrong since the oldSubBody has lesser nodes than
// nodeNumber
return null;
}
Iterator<Object> oldIt = oldSubBody.iterator();
int index = 0;
while (index != nodeNumber) {
newSubBody.add(oldIt.next());
index++;
}
// check to see that the next is a stmtseq and the one afteris while
// node
ASTNode temp = (ASTNode) oldIt.next();
if (!(temp instanceof ASTStatementSequenceNode)) {
return null;
}
temp = (ASTNode) oldIt.next();
if (!(temp instanceof ASTWhileNode)) {
return null;
}
// add new stmtseqnode to the newSubBody
if (newStmtSeqNode != null) {
newSubBody.add(newStmtSeqNode);
} else {
// System.out.println("Stmt seq was empty hence not putting a node in");
}
// add new For Loop Node
newSubBody.add(forNode);
// copy any remaining nodes
while (oldIt.hasNext()) {
newSubBody.add(oldIt.next());
}
return newSubBody;
}
/*
* Go through the stmtseq node and collect all defs
*
* Important: if a def is followed by a non def stmt clear def list and continue
*
* i.e. we are conservatively checking when a def can be moved into a for loop body
*/
private List<String> getDefs() {
if (stmtSeqNode == null) {
return null;
}
List<String> toReturn = new ArrayList<String>();
int stmtNum = 0;
for (AugmentedStmt as : stmtSeqNode.getStatements()) {
Stmt s = as.get_Stmt();
// check if this is a def
if (s instanceof DefinitionStmt) {
Value left = ((DefinitionStmt) s).getLeftOp();
toReturn.add(left.toString());
varToStmtMap.put(left.toString(), new Integer(stmtNum));
} else {
toReturn = new ArrayList<String>();
varToStmtMap = new HashMap<String, Integer>();
}
stmtNum++;
} // going through all statements
return toReturn;
}
/*
* Go through the ASTCondition of the whileNode Make a list of all vars being uses in the conditions Since any of them
* could be being used to drive the loop
*/
private List<String> getCondUses() {
if (whileNode == null) {
return null;
}
ASTCondition cond = whileNode.get_Condition();
return getCond(cond);
}
private List<String> getCond(ASTCondition cond) {
List<String> toReturn = new ArrayList<String>();
if (cond instanceof ASTUnaryCondition) {
toReturn.add(((ASTUnaryCondition) cond).toString());
} else if (cond instanceof ASTBinaryCondition) {
ConditionExpr condExpr = ((ASTBinaryCondition) cond).getConditionExpr();
toReturn.add(condExpr.getOp1().toString());
toReturn.add(condExpr.getOp2().toString());
} else if (cond instanceof ASTAggregatedCondition) {
toReturn.addAll(getCond(((ASTAggregatedCondition) cond).getLeftOp()));
toReturn.addAll(getCond(((ASTAggregatedCondition) cond).getRightOp()));
}
return toReturn;
}
private List<String> getCommonVars(List<String> defs, List<String> condUses) {
List<String> toReturn = new ArrayList<String>();
Iterator<String> defIt = defs.iterator();
while (defIt.hasNext()) {
String defString = defIt.next();
Iterator<String> condIt = condUses.iterator();
while (condIt.hasNext()) {
String condString = condIt.next();
if (condString.compareTo(defString) == 0) {
// match
toReturn.add(defString);
break;
}
}
}
return toReturn;
}
/*
* Given the StmtSequenceNode and the while Node Check if the while can be converted to a for
*
* If this can be done. create the replacement stmt sequence node and the new for loop and return TRUE;
*
* else return FALSE;
*/
public boolean checkPattern() {
List<String> defs = getDefs();
if (defs == null) {
return false;
}
if (defs.size() == 0) {
return false;
}
List<String> condUses = getCondUses();
if (condUses == null) {
return false;
}
if (condUses.size() == 0) {
return false;
}
/*
* find common vars between the defs and the condition
*/
List<String> commonVars = getCommonVars(defs, condUses);
/*
* Find the update list Also at the same time see if the update list has some update stmt whose var should be added to
* commonVars
*/
List<AugmentedStmt> update = getUpdate(defs, condUses, commonVars);
if (update == null || update.size() == 0) {
// System.out.println("Aborting because of update");
return false;
}
if (commonVars == null || commonVars.size() == 0) {
// System.out.println("Aborting because of commonVars");
return false;
}
// there are some vars which are
// 1, defined in the stmtseq node
// 2, used in the condition
// System.out.println(commonVars);
// create new stmtSeqNode and get the init list for the for loop
List<AugmentedStmt> init = createNewStmtSeqNodeAndGetInit(commonVars);
if (init.size() == 0) {
// System.out.println("Aborting because of init size");
return false;
}
ASTCondition condition = whileNode.get_Condition();
List<Object> body = (List<Object>) whileNode.get_SubBodies().get(0);
SETNodeLabel label = ((ASTLabeledNode) whileNode).get_Label();
/*
* Check that anything in init is not a first time initialization if it is and it is not used outside the for loop then
* we need to declare it as int i = bla bla instead of i = bla bla
*/
// init=analyzeInit(init);
// about to create loop make sure to remove the update stmt
if (removeLast) {
// System.out.println("Removing"+myStmts.get(myStmts.size()-1));
myStmts.remove(myStmts.size() - 1);
removeLast = false;
}
forNode = new ASTForLoopNode(label, init, condition, update, body);
return true;
}
private List<AugmentedStmt> getUpdate(List<String> defs, List<String> condUses, List<String> commonUses) {
List<AugmentedStmt> toReturn = new ArrayList<AugmentedStmt>();
// most naive approach
List<Object> subBodies = whileNode.get_SubBodies();
if (subBodies.size() != 1) {
// whileNode should always have oneSubBody
return toReturn;
}
List subBody = (List) subBodies.get(0);
Iterator it = subBody.iterator();
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
if (it.hasNext()) {
// not the last node in the loop body
continue;
}
// this is the last node in the loop body
if (!(temp instanceof ASTStatementSequenceNode)) {
// not a statementsequence node
// System.out.println("Aborting because last node is not a stmtseqnode");
return null;
}
List<AugmentedStmt> stmts = ((ASTStatementSequenceNode) temp).getStatements();
AugmentedStmt last = stmts.get(stmts.size() - 1);
Stmt lastStmt = last.get_Stmt();
if (!(lastStmt instanceof DefinitionStmt)) {
// not a definition stmt
// System.out.println("Aborting because last stmt is not definition stmt");
return null;
}
// check if it assigns to a def
Value left = ((DefinitionStmt) lastStmt).getLeftOp();
Iterator<String> defIt = defs.iterator();
while (defIt.hasNext()) {
String defString = defIt.next();
if (left.toString().compareTo(defString) == 0) {
// match
toReturn.add(last);
myStmts = stmts;
removeLast = true;
// stmts.remove(stmts.size()-1);
// see if commonUses has this otherwise add it
Iterator<String> coIt = commonUses.iterator();
boolean matched = false;
while (coIt.hasNext()) {
if (defString.compareTo(coIt.next()) == 0) {
matched = true;
}
}
if (!matched) {
// it is not in commonUses
commonUses.add(defString);
}
return toReturn;
}
}
// the code gets here only in the case when none of the def strings
// matched the updated variable
Iterator<String> condIt = condUses.iterator();
while (condIt.hasNext()) {
String condString = condIt.next();
if (left.toString().compareTo(condString) == 0) {
// match
toReturn.add(last);
myStmts = stmts;
removeLast = true;
// stmts.remove(stmts.size()-1);
// see if commonUses has this otherwise add it
Iterator<String> coIt = commonUses.iterator();
boolean matched = false;
while (coIt.hasNext()) {
if (condString.compareTo(coIt.next()) == 0) {
matched = true;
}
}
if (!matched) {
// it is not in commonUses
commonUses.add(condString);
}
return toReturn;
}
}
} // going through ASTNodes
return toReturn;
}
private List<AugmentedStmt> createNewStmtSeqNodeAndGetInit(List<String> commonVars) {
// get stmt number of each def of commonVar keeping the lowest
int currentLowestPosition = 999;
for (String temp : commonVars) {
Integer tempInt = varToStmtMap.get(temp);
if (tempInt != null) {
if (tempInt.intValue() < currentLowestPosition) {
currentLowestPosition = tempInt.intValue();
}
}
}
List<AugmentedStmt> stmts = new ArrayList<AugmentedStmt>();
List<AugmentedStmt> statements = stmtSeqNode.getStatements();
Iterator<AugmentedStmt> stmtIt = statements.iterator();
int stmtNum = 0;
while (stmtNum < currentLowestPosition && stmtIt.hasNext()) {
stmts.add(stmtIt.next());
stmtNum++;
}
if (stmts.size() > 0) {
newStmtSeqNode = new ASTStatementSequenceNode(stmts);
} else {
newStmtSeqNode = null;
}
List<AugmentedStmt> init = new ArrayList<AugmentedStmt>();
while (stmtIt.hasNext()) {
init.add(stmtIt.next());
}
return init;
}
/*
* private List analyzeInit(List init){ Iterator it = init.iterator(); while(it.hasNext()){ AugmentedStmt as =
* (AugmentedStmt)it.next(); Stmt s = as.get_Stmt(); if(!(s instanceof DefinitionStmt)){ //there is something wrong so dont
* do anything fancy return init; } else{ //get the local being initialized Value left = ((DefinitionStmt)s).getLeftOp();
*
* } } return init; }
*/
}
| 13,842
| 30.822989
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/ForLoopCreator.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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.G;
import soot.Local;
import soot.SootClass;
import soot.Type;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTTryNode;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
/*
Nomair A. Naeem 21-FEB-2005
In the depthFirstAdaptor children of a ASTNode
are gotten in three ways
a, ASTStatementSequenceNode uses one way see caseASTStatementSequenceNode in DepthFirstAdapter
b, ASTTryNode uses another way see caseASTTryNode in DepthFirstAdapter
c, All other nodes use normalRetrieving method to retrieve the children
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
*/
public class ForLoopCreator extends DepthFirstAdapter {
public ForLoopCreator() {
}
public ForLoopCreator(boolean verbose) {
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
}
/*
* Note the ASTNode in this case can be any of the following:
*
* ASTMethodNode ASTSwitchNode ASTIfNode ASTIfElseNode ASTUnconditionalWhileNode ASTWhileNode ASTDoWhileNode ASTForLoopNode
* ASTLabeledBlockNode ASTSynchronizedBlockNode
*/
public void normalRetrieving(ASTNode node) {
if (node instanceof ASTSwitchNode) {
dealWithSwitchNode((ASTSwitchNode) node);
return;
}
// from the Node get the subBodes
Iterator<Object> sbit = node.get_SubBodies().iterator();
// onlyASTIfElseNode has 2 subBodies but we need to deal with that
int subBodyNumber = 0;
while (sbit.hasNext()) {
List<Object> subBody = (List<Object>) sbit.next();
Iterator<Object> it = subBody.iterator();
int nodeNumber = 0;
// go over the ASTNodes in this subBody and apply
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
if (temp instanceof ASTStatementSequenceNode) {
// need to check if this is followed by a while node
if (it.hasNext()) {
// there is a next node
ASTNode temp1 = (ASTNode) subBody.get(nodeNumber + 1);
if (temp1 instanceof ASTWhileNode) {
// a statement sequence node followed by a while node
ForLoopCreationHelper helper
= new ForLoopCreationHelper((ASTStatementSequenceNode) temp, (ASTWhileNode) temp1);
if (helper.checkPattern()) {
// pattern matched
List<Object> newBody = helper.createNewBody(subBody, nodeNumber);
if (newBody != null) {
if (node instanceof ASTIfElseNode) {
if (subBodyNumber == 0) {
// the if body was modified
List<Object> subBodies = node.get_SubBodies();
List<Object> ifElseBody = (List<Object>) subBodies.get(1);
((ASTIfElseNode) node).replaceBody(newBody, ifElseBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else if (subBodyNumber == 1) {
// else body was modified
List<Object> subBodies = node.get_SubBodies();
List<Object> ifBody = (List<Object>) subBodies.get(0);
((ASTIfElseNode) node).replaceBody(ifBody, newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else {
throw new RuntimeException("Please report benchmark to programmer.");
}
} else {
if (node instanceof ASTMethodNode) {
((ASTMethodNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else if (node instanceof ASTSynchronizedBlockNode) {
((ASTSynchronizedBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else if (node instanceof ASTLabeledBlockNode) {
((ASTLabeledBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else if (node instanceof ASTUnconditionalLoopNode) {
((ASTUnconditionalLoopNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else if (node instanceof ASTIfNode) {
((ASTIfNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else if (node instanceof ASTWhileNode) {
((ASTWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else if (node instanceof ASTDoWhileNode) {
((ASTDoWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else if (node instanceof ASTForLoopNode) {
((ASTForLoopNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} else {
throw new RuntimeException("Please report benchmark to programmer.");
}
}
} // newBody was not null
} // for loop creation pattern matched
} // the next node was a whilenode
} // there is a next node
} // temp is a stmtSeqNode
temp.apply(this);
nodeNumber++;
} // end of going over nodes
subBodyNumber++;
} // end of going over subBodies
}
public void caseASTTryNode(ASTTryNode node) {
inASTTryNode(node);
// get try body
List<Object> tryBody = node.get_TryBody();
Iterator<Object> it = tryBody.iterator();
int nodeNumber = 0;
// go over the ASTNodes and apply
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
if (temp instanceof ASTStatementSequenceNode) {
// need to check if this is followed by a while node
if (it.hasNext()) {
// there is a next node
ASTNode temp1 = (ASTNode) tryBody.get(nodeNumber + 1);
if (temp1 instanceof ASTWhileNode) {
// a statement sequence node followed by a while node
ForLoopCreationHelper helper = new ForLoopCreationHelper((ASTStatementSequenceNode) temp, (ASTWhileNode) temp1);
if (helper.checkPattern()) {
// pattern matched
List<Object> newBody = helper.createNewBody(tryBody, nodeNumber);
if (newBody != null) {
// something did not go wrong
node.replaceTryBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} // newBody was not null
} // for loop creation pattern matched
} // the next node was a whilenode
} // there is a next node
} // temp is a stmtSeqNode
temp.apply(this);
nodeNumber++;
} // end of while going through tryBody
Map<Object, Object> exceptionMap = node.get_ExceptionMap();
Map<Object, Object> paramMap = node.get_ParamMap();
// get catch list and apply on the following
// a, type of exception caught
// b, local of exception
// c, catchBody
List<Object> catchList = node.get_CatchList();
Iterator<Object> itBody = null;
it = catchList.iterator();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container) it.next();
SootClass sootClass = ((SootClass) exceptionMap.get(catchBody));
Type type = sootClass.getType();
// apply on type of exception
caseType(type);
// apply on local of exception
Local local = (Local) paramMap.get(catchBody);
decideCaseExprOrRef(local);
// apply on catchBody
List<Object> body = (List<Object>) catchBody.o;
itBody = body.iterator();
nodeNumber = 0;
// go over the ASTNodes and apply
while (itBody.hasNext()) {
ASTNode temp = (ASTNode) itBody.next();
if (temp instanceof ASTStatementSequenceNode) {
// need to check if this is followed by a while node
if (itBody.hasNext()) {
// there is a next node
ASTNode temp1 = (ASTNode) body.get(nodeNumber + 1);
if (temp1 instanceof ASTWhileNode) {
// a statement sequence node followed by a while node
ForLoopCreationHelper helper
= new ForLoopCreationHelper((ASTStatementSequenceNode) temp, (ASTWhileNode) temp1);
if (helper.checkPattern()) {
// pattern matched
List<Object> newBody = helper.createNewBody(body, nodeNumber);
if (newBody != null) {
// something did not go wrong
catchBody.replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} // newBody was not null
} // for loop creation pattern matched
} // the next node was a whilenode
} // there is a next node
} // temp is a stmtSeqNode
temp.apply(this);
nodeNumber++;
}
}
outASTTryNode(node);
}
private void dealWithSwitchNode(ASTSwitchNode node) {
// do a depthfirst on elements of the switchNode
List<Object> indexList = node.getIndexList();
Map<Object, List<Object>> index2BodyList = node.getIndex2BodyList();
Iterator<Object> it = indexList.iterator();
while (it.hasNext()) {
// going through all the cases of the switch statement
Object currentIndex = it.next();
List<Object> body = index2BodyList.get(currentIndex);
if (body != null) {
// this body is a list of ASTNodes
Iterator<Object> itBody = body.iterator();
int nodeNumber = 0;
// go over the ASTNodes and apply
while (itBody.hasNext()) {
ASTNode temp = (ASTNode) itBody.next();
if (temp instanceof ASTStatementSequenceNode) {
// need to check if this is followed by a while node
if (itBody.hasNext()) {
// there is a next node
ASTNode temp1 = (ASTNode) body.get(nodeNumber + 1);
if (temp1 instanceof ASTWhileNode) {
// a statement sequence node followed by a while node
ForLoopCreationHelper helper
= new ForLoopCreationHelper((ASTStatementSequenceNode) temp, (ASTWhileNode) temp1);
if (helper.checkPattern()) {
// pattern matched
List<Object> newBody = helper.createNewBody(body, nodeNumber);
if (newBody != null) {
// something did not go wrong
// put this body in the Map
index2BodyList.put(currentIndex, newBody);
// replace in actual switchNode
node.replaceIndex2BodyList(index2BodyList);
G.v().ASTTransformations_modified = true;
// System.out.println("FOR LOOP CREATED");
return;
} // newBody was not null
} // for loop creation pattern matched
} // the next node was a whilenode
} // there is a next node
} // temp is a stmtSeqNode
temp.apply(this);
nodeNumber++;
}
}
}
}
}
| 14,136
| 38.488827
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/IfElseBreaker.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Nomair A. Naeem
* %%
* 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 soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.SET.SETNodeLabel;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DAbruptStmt;
import soot.jimple.Stmt;
/*
Nomair A. Naeem 03-MARCH-2005
PATTERN 1:
if(cond1){ if(cond1){
break label_1 break label_1
} -----> }
else{ Body1
Body1
}
PATTERN 2:
if(!cond1){ if(cond1){
Body1 break label_1
} -----> }
else{ Body1
break label_1
}
The assumption is that if cond1 is true there is an abrupt edge and Body1
will not be executed. So this works only if the else in the original
has an abrupt control flow. This can be break/continue/return
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
*/
public class IfElseBreaker {
ASTIfNode newIfNode;
List<Object> remainingBody;
public IfElseBreaker() {
newIfNode = null;
remainingBody = null;
}
public boolean isIfElseBreakingPossiblePatternOne(ASTIfElseNode node) {
List<Object> ifBody = node.getIfBody();
if (ifBody.size() != 1) {
// we are only interested if size is one
return false;
}
ASTNode onlyNode = (ASTNode) ifBody.get(0);
boolean check = checkStmt(onlyNode, node);
if (!check) {
return false;
}
// breaking is possible
// break and store
newIfNode = new ASTIfNode(((ASTLabeledNode) node).get_Label(), node.get_Condition(), ifBody);
remainingBody = node.getElseBody();
return true;
}
public boolean isIfElseBreakingPossiblePatternTwo(ASTIfElseNode node) {
List<Object> elseBody = node.getElseBody();
if (elseBody.size() != 1) {
// we are only interested if size is one
return false;
}
ASTNode onlyNode = (ASTNode) elseBody.get(0);
boolean check = checkStmt(onlyNode, node);
if (!check) {
return false;
}
// breaking is possible
ASTCondition cond = node.get_Condition();
// flip
cond.flip();
newIfNode = new ASTIfNode(((ASTLabeledNode) node).get_Label(), cond, elseBody);
remainingBody = node.getIfBody();
return true;
}
private boolean checkStmt(ASTNode onlyNode, ASTIfElseNode node) {
if (!(onlyNode instanceof ASTStatementSequenceNode)) {
// only interested in StmtSeq nodes
return false;
}
ASTStatementSequenceNode stmtNode = (ASTStatementSequenceNode) onlyNode;
List<AugmentedStmt> statements = stmtNode.getStatements();
if (statements.size() != 1) {
// need one stmt only
return false;
}
AugmentedStmt as = statements.get(0);
Stmt stmt = as.get_Stmt();
if (!(stmt instanceof DAbruptStmt)) {
// interested in abrupt stmts only
return false;
}
DAbruptStmt abStmt = (DAbruptStmt) stmt;
if (!(abStmt.is_Break() || abStmt.is_Continue())) {
// interested in breaks and continues only
return false;
}
// make sure that the break is not that of the if
// unliekly but good to check
SETNodeLabel ifLabel = ((ASTLabeledNode) node).get_Label();
if (ifLabel != null) {
if (ifLabel.toString() != null) {
if (abStmt.is_Break()) {
String breakLabel = abStmt.getLabel().toString();
if (breakLabel != null) {
if (breakLabel.compareTo(ifLabel.toString()) == 0) {
// is a break of this label
return false;
}
}
}
}
}
return true;
}
/*
* The purpose of this method is to replace the ASTIfElseNode given by the var nodeNumber with the new ASTIfNode and to add
* the remianing list of bodies after this ASTIfNode
*
* The new body is then returned;
*
*/
public List<Object> createNewBody(List<Object> oldSubBody, int nodeNumber) {
if (newIfNode == null) {
return null;
}
List<Object> newSubBody = new ArrayList<Object>();
if (oldSubBody.size() <= nodeNumber) {
// something is wrong since the oldSubBody has lesser nodes than nodeNumber
return null;
}
Iterator<Object> oldIt = oldSubBody.iterator();
int index = 0;
while (index != nodeNumber) {
newSubBody.add(oldIt.next());
index++;
}
// check to see that the next is an ASTIfElseNode
ASTNode temp = (ASTNode) oldIt.next();
if (!(temp instanceof ASTIfElseNode)) {
return null;
}
newSubBody.add(newIfNode);
newSubBody.addAll(remainingBody);
// copy any remaining nodes
while (oldIt.hasNext()) {
newSubBody.add(oldIt.next());
}
return newSubBody;
}
}
| 5,965
| 27.141509
| 125
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.