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/toolkits/base/AST/transformations/IfElseSplitter.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.Iterator;
import java.util.List;
import soot.G;
import soot.dava.DecompilationException;
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.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.dava.toolkits.base.AST.traversals.ASTParentNodeFinder;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
/*
* look for patterns of the form
* if(cond1){ if(cond1){
* BodyA BodyA
* abrupt ----> abrupt
* } }
* else{ BodyB
* BodyB
* }
*
* Things to ensure:
* If abrupt then check BodyA does not target a label on the ifelse
*
* ALWAYS Make sure BodyB does not target a label on the ifelse
*
* If the pattern is NOT matched check the reverse i.e. maybe BodyB
* has the abrupt statement in that case we just negated the condition
*/
public class IfElseSplitter extends DepthFirstAdapter {
public static boolean DEBUG = false;
boolean targeted = false;
ASTMethodNode methodNode;
ASTNode parent;
ASTIfElseNode toReplace;
ASTIfNode toInsert;
List<Object> bodyAfterInsert;
boolean transform = false;
public IfElseSplitter() {
}
public IfElseSplitter(boolean verbose) {
super(verbose);
}
public void inASTMethodNode(ASTMethodNode node) {
methodNode = node;
}
public void outASTMethodNode(ASTMethodNode a) {
if (!transform) {
return;
}
List<Object> parentBodies = parent.get_SubBodies();
Iterator<Object> it = parentBodies.iterator();
while (it.hasNext()) {
List<Object> subBody = null;
if (parent instanceof ASTTryNode) {
subBody = (List<Object>) ((ASTTryNode.container) it.next()).o;
} else {
subBody = (List<Object>) it.next();
}
if (subBody.indexOf(toReplace) > -1) {
// in the subBody list the node is present
subBody.add(subBody.indexOf(toReplace), toInsert);
subBody.addAll(subBody.indexOf(toReplace), bodyAfterInsert);
subBody.remove(toReplace);
G.v().ASTTransformations_modified = true;
}
}
}
public void outASTIfElseNode(ASTIfElseNode node) {
// if some pattern has already matched cant do another one in this go
if (transform) {
return;
}
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 2) {
throw new DecompilationException("IfelseNode without two subBodies. report to developer");
}
List<Object> ifBody = (List<Object>) subBodies.get(0);
List<Object> elseBody = (List<Object>) subBodies.get(1);
boolean patternMatched = tryBodyPattern(ifBody, node.get_Label(), elseBody);
List<Object> newIfBody = null;
List<Object> outerScopeBody = null;
boolean negateIfCondition = false;
if (patternMatched) {
if (DEBUG) {
System.out.println("First pattern matched");
}
newIfBody = ifBody;
outerScopeBody = elseBody;
negateIfCondition = false;
} else {
patternMatched = tryBodyPattern(elseBody, node.get_Label(), ifBody);
if (patternMatched) {
if (DEBUG) {
System.out.println("Second pattern matched");
}
newIfBody = elseBody;
outerScopeBody = ifBody;
negateIfCondition = true;
}
}
// if at this point newIfBody and outerScopeBody are non null we got ourselves a transformation :)
if (newIfBody != null && outerScopeBody != null) {
ASTCondition cond = node.get_Condition();
if (negateIfCondition) {
cond.flip();
}
ASTIfNode newNode = new ASTIfNode(node.get_Label(), cond, newIfBody);
if (DEBUG) {
System.out.println("New IF Node is: " + newNode.toString());
System.out.println("Outer scope body list is:\n");
for (int i = 0; i < outerScopeBody.size(); i++) {
System.out.println("\n\n " + outerScopeBody.get(i).toString());
}
}
ASTParentNodeFinder finder = new ASTParentNodeFinder();
methodNode.apply(finder);
Object returned = finder.getParentOf(node);
if (returned == null) {
// coundnt find parent so cant do anything
return;
}
/*
* Setting globals since everything is ready for transformation BECAUSE we cant modify the parent here we are going to
* do some bad coding style store the information needed for this into globals set a flag and the outASTMethod checks
* for this
*/
parent = (ASTNode) returned;
toReplace = node;
toInsert = newNode;
bodyAfterInsert = outerScopeBody;
transform = true;
}
}
public boolean tryBodyPattern(List<Object> body, SETNodeLabel label, List<Object> otherBody) {
Stmt lastStmt = getLastStmt(body);
if (lastStmt == null) {
// dont have a last stmt so cant match pattern
return false;
}
if (!(lastStmt instanceof ReturnStmt || lastStmt instanceof ReturnVoidStmt || lastStmt instanceof DAbruptStmt)) {
// lastStmt is not an abrupt stmt
return false;
}
if (bodyTargetsLabel(label, body) || bodyTargetsLabel(label, otherBody)) {
// one of the bodies targets the label on the ifelse cant match pattern
return false;
}
// pattern matched
return true;
}
/*
* Check that label is non null and the string inside is non null... if yes return false Check that the given list
* (sequeneof ASTNodes have no abrupt edge targeting the label.
*
*/
public boolean bodyTargetsLabel(SETNodeLabel label, List<Object> body) {
// no SETNodeLabel is good
if (label == null) {
return false;
}
// SETNodeLabel but with no string is also good
if (label.toString() == null) {
return false;
}
final String strLabel = label.toString();
// go through the body use traversal to find whether there is an abrupt stmt targeting this
Iterator<Object> it = body.iterator();
targeted = false;
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
temp.apply(new DepthFirstAdapter() {
// set targeted to true if DAbruptStmt targets it
public void inStmt(Stmt s) {
// only interested in abrupt stmts
if (!(s instanceof DAbruptStmt)) {
return;
}
DAbruptStmt abrupt = (DAbruptStmt) s;
SETNodeLabel label = abrupt.getLabel();
if (label != null && label.toString() != null && label.toString().equals(strLabel)) {
targeted = true;
}
}
});
if (targeted) {
break;
}
}
return targeted;
}
/*
* Given a list of ASTNodes see if the last astnode is a StatementSequenceNode if not return null else, return the last
* statement in this node
*/
public Stmt getLastStmt(List<Object> body) {
if (body.size() == 0) {
return null;
}
ASTNode lastNode = (ASTNode) body.get(body.size() - 1);
if (!(lastNode instanceof ASTStatementSequenceNode)) {
return null;
}
ASTStatementSequenceNode stmtNode = (ASTStatementSequenceNode) lastNode;
List<AugmentedStmt> stmts = stmtNode.getStatements();
if (stmts.size() == 0) {
return null;
}
AugmentedStmt lastStmt = stmts.get(stmts.size() - 1);
return lastStmt.get_Stmt();
}
}
| 8,690
| 29.602113
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/LocalVariableCleaner.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.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import soot.Local;
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.asg.AugmentedStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.dava.toolkits.base.AST.traversals.ASTParentNodeFinder;
import soot.dava.toolkits.base.AST.traversals.ASTUsesAndDefs;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
//import soot.dava.internal.javaRep.*;
//import soot.dava.toolkits.base.AST.structuredAnalysis.*;
/**
* The class is aimed to target cleaning up of unused local variables. Should be invoked after executing CopyPropagation
*
* Another thing that this class does which perhaps should have been implemented separately is to check whether there is an
* assignment which never gets used later on. If there exists such an assignment this assignment is removed first and then
* all the useless locals checks should be reapplied (until a fixed point)
*/
public class LocalVariableCleaner extends DepthFirstAdapter {
public final boolean DEBUG = false;
ASTNode AST;
ASTUsesAndDefs useDefs;
ASTParentNodeFinder parentOf;
public LocalVariableCleaner(ASTNode AST) {
super();
this.AST = AST;
parentOf = new ASTParentNodeFinder();
AST.apply(parentOf);
}
public LocalVariableCleaner(boolean verbose, ASTNode AST) {
super(verbose);
this.AST = AST;
parentOf = new ASTParentNodeFinder();
AST.apply(parentOf);
}
/*
* Get all locals declared in the method If the local is never defined (and hence never used) remove it If the local is
* defined BUT never used then you may remove it IF AND ONLY IF The definition is either a copy stmt or an assignment of a
* constant (i.e. no side effects)
*/
public void outASTMethodNode(ASTMethodNode node) {
boolean redo = false;
useDefs = new ASTUsesAndDefs(AST); // create the uD and dU chains
AST.apply(useDefs);
// get all local variables declared in this method
Iterator decIt = node.getDeclaredLocals().iterator();
ArrayList<Local> removeList = new ArrayList<Local>();
while (decIt.hasNext()) {
// going through each local declared
Local var = (Local) decIt.next();
List<DefinitionStmt> defs = getDefs(var);
// if defs is 0 it means var never got defined
if (defs.size() == 0) {
// var is never defined and hence is certainly not used anywhere
removeList.add(var);
} else {
// if a var is defined but not used then in some conditions we can remove it
// check that each def is removable
Iterator<DefinitionStmt> defIt = defs.iterator();
while (defIt.hasNext()) {
DefinitionStmt ds = defIt.next();
if (canRemoveDef(ds)) {
// if removeStmt is successful since something change we need to redo
// everything hoping something else might be removed....
// in this case method returns true
redo = removeStmt(ds);
}
} // while going through defs
} // end else defs was not zero
} // going through each stmt
// go through the removeList and remove all locals
Iterator<Local> remIt = removeList.iterator();
while (remIt.hasNext()) {
Local removeLocal = remIt.next();
node.removeDeclaredLocal(removeLocal);
/*
* Nomair A. Naeem 7th Feb 2005 these have to be removed from the legacy lists in DavaBody also
*
*/
// retrieve DavaBody
if (AST instanceof ASTMethodNode) {
// this should always be true but whatever
DavaBody body = ((ASTMethodNode) AST).getDavaBody();
if (DEBUG) {
System.out.println("body information");
System.out.println("Control local is: " + body.get_ControlLocal());
System.out.println("his locals are: " + body.get_ThisLocals());
System.out.println("Param Map is: " + body.get_ParamMap());
System.out.println("Locals are:" + body.getLocals());
}
Collection<Local> localChain = body.getLocals();
if (removeLocal != null && localChain != null) {
localChain.remove(removeLocal);
}
} else {
throw new DecompilationException("found AST which is not a methodNode");
}
if (DEBUG) {
System.out.println("Removed" + removeLocal);
}
redo = true;
}
if (redo) {
// redo the whole function
outASTMethodNode(node);
}
}
/*
* A def can be removed if and only if: 1, there are no uses of this definition 2, the right hand size is either a local or
* a constant i.e. no need to worry about side effects
*/
public boolean canRemoveDef(DefinitionStmt ds) {
List uses = useDefs.getDUChain(ds);
if (uses.size() != 0) {
return false;
}
// there is no use of this def, we can remove it if it is copy stmt or a constant assignment
if (ds.getRightOp() instanceof Local || ds.getRightOp() instanceof Constant) {
return true;
}
return false;
}
/*
* This method looks up all defs and returns those of this local
*/
public List<DefinitionStmt> getDefs(Local var) {
List<DefinitionStmt> toReturn = new ArrayList<DefinitionStmt>();
HashMap<Object, List> dU = useDefs.getDUHashMap();
Iterator<Object> it = dU.keySet().iterator();
while (it.hasNext()) {
DefinitionStmt s = (DefinitionStmt) it.next();
Value left = s.getLeftOp();
if (left instanceof Local) {
if (((Local) left).getName().compareTo(var.getName()) == 0) {
toReturn.add(s);
}
}
}
return toReturn;
}
public boolean removeStmt(Stmt stmt) {
Object tempParent = parentOf.getParentOf(stmt);
if (tempParent == null) {
// System.out.println("NO PARENT FOUND CANT DO ANYTHING");
return false;
}
// parents are always ASTNodes, hence safe to cast
ASTNode parent = (ASTNode) tempParent;
// REMOVING STMT
if (!(parent instanceof ASTStatementSequenceNode)) {
// parent of a statement should always be a ASTStatementSequenceNode
return false;
}
ASTStatementSequenceNode parentNode = (ASTStatementSequenceNode) parent;
ArrayList<AugmentedStmt> newSequence = new ArrayList<AugmentedStmt>();
int size = parentNode.getStatements().size();
for (AugmentedStmt as : parentNode.getStatements()) {
Stmt s = as.get_Stmt();
if (s.toString().compareTo(stmt.toString()) != 0) {
// this is not the stmt to be removed
newSequence.add(as);
}
}
// System.out.println("STMT REMOVED---------------->"+stmt);
parentNode.setStatements(newSequence);
if (newSequence.size() < size) {
return true; // size of new node is smaller than orignal size
}
return false;// didnt actually delete anything for some weird reason...shouldnt happen
}
}
| 8,067
| 32.338843
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/LoopStrengthener.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 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.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:
*/
public class LoopStrengthener extends DepthFirstAdapter {
public LoopStrengthener() {
}
public LoopStrengthener(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 ASTWhileNode || temp instanceof ASTUnconditionalLoopNode || temp instanceof ASTDoWhileNode) {
ASTNode oneNode = getOnlySubNode(temp);
if (oneNode != null) {
List<ASTNode> newNode = null;
if (oneNode instanceof ASTIfNode) {
newNode = StrengthenByIf.getNewNode(temp, (ASTIfNode) oneNode);
} else if (oneNode instanceof ASTIfElseNode) {
newNode = StrengthenByIfElse.getNewNode(temp, (ASTIfElseNode) oneNode);
}
if (newNode != null) {
// some pattern was matched
// replace the temp node with the newNode
replaceNode(node, subBodyNumber, nodeNumber, temp, newNode);
UselessLabelFinder.v().findAndKill(node);
}
}
}
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 ASTWhileNode || temp instanceof ASTUnconditionalLoopNode || temp instanceof ASTDoWhileNode) {
ASTNode oneNode = getOnlySubNode(temp);
if (oneNode != null) {
List<ASTNode> newNode = null;
if (oneNode instanceof ASTIfNode) {
newNode = StrengthenByIf.getNewNode(temp, (ASTIfNode) oneNode);
} else if (oneNode instanceof ASTIfElseNode) {
newNode = StrengthenByIfElse.getNewNode(temp, (ASTIfElseNode) oneNode);
}
if (newNode != null) {
// some pattern was matched
// replace the temp node with the newNode
List<Object> newBody = createNewSubBody(tryBody, nodeNumber, temp, newNode);
if (newBody != null) {
// something did not go wrong
node.replaceTryBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("strengthened loop within trybody");
}
UselessLabelFinder.v().findAndKill(node);
}
}
} // it was a loop node
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 ASTWhileNode || temp instanceof ASTUnconditionalLoopNode || temp instanceof ASTDoWhileNode) {
ASTNode oneNode = getOnlySubNode(temp);
if (oneNode != null) {
List<ASTNode> newNode = null;
if (oneNode instanceof ASTIfNode) {
newNode = StrengthenByIf.getNewNode(temp, (ASTIfNode) oneNode);
} else if (oneNode instanceof ASTIfElseNode) {
newNode = StrengthenByIfElse.getNewNode(temp, (ASTIfElseNode) oneNode);
}
if (newNode != null) {
// some pattern was matched
// replace the temp node with the newNode
List<Object> newBody = createNewSubBody(body, nodeNumber, temp, newNode);
if (newBody != null) {
// something did not go wrong
catchBody.replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("strengthened loop within catchbody");
}
UselessLabelFinder.v().findAndKill(node);
}
}
} // it was a loop node
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 ASTWhileNode || temp instanceof ASTUnconditionalLoopNode || temp instanceof ASTDoWhileNode) {
ASTNode oneNode = getOnlySubNode(temp);
if (oneNode != null) {
List<ASTNode> newNode = null;
if (oneNode instanceof ASTIfNode) {
newNode = StrengthenByIf.getNewNode(temp, (ASTIfNode) oneNode);
} else if (oneNode instanceof ASTIfElseNode) {
newNode = StrengthenByIfElse.getNewNode(temp, (ASTIfElseNode) oneNode);
}
if (newNode != null) {
// some pattern was matched
// replace the temp node with the newNode
List<Object> newBody = createNewSubBody(body, nodeNumber, temp, newNode);
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("strengthened loop within switch body");
}
UselessLabelFinder.v().findAndKill(node);
}
}
} // it was a loop node
temp.apply(this);
nodeNumber++;
}
}
}
}
/*
* Given an ASTNode as input this method checks the following: 1, The node is either ASTWhile, ASTDoWhile or
* ASTUnconditionalLoop 2, The node has one subBody 3, The onlySubBody has one node
*
* it returns the only node in the only SubBody
*/
private ASTNode getOnlySubNode(ASTNode node) {
if (!(node instanceof ASTWhileNode || node instanceof ASTDoWhileNode || node instanceof ASTUnconditionalLoopNode)) {
// not one of these loops
return null;
}
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 1) {
// we are coming from loop nodes so subBodies should always be one
return null;
}
List subBody = (List) subBodies.get(0);
if (subBody.size() != 1) {
// only want the case which the subBody has a single node
return null;
}
return (ASTNode) subBody.get(0);
}
/*
* - Go through the node bodies till you find subBodyNumber - Go through this subBody until you find nodeNumber - This is
* the temp node Replace it with the newNodes
*
* Node is the node which contains the loop node subBodyNumber is the subBody which of the node which contains the loopNode
* nodeNumber is the location of the loopNode in the subBody newNode is the loopNode which will replace the old loopNode
*/
private void replaceNode(ASTNode node, int subBodyNumber, int nodeNumber, ASTNode loopNode, List<ASTNode> newNode) {
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 loopNode to be replaced at location given by the nodeNumber variable
*/
List<Object> newBody = createNewSubBody(onlySubBody, nodeNumber, loopNode, newNode);
if (newBody == null) {
// something went wrong
return;
}
if (node instanceof ASTMethodNode) {
((ASTMethodNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("Stenghtened Loop");
} else if (node instanceof ASTSynchronizedBlockNode) {
((ASTSynchronizedBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("Stenghtened Loop in synchblock");
} else if (node instanceof ASTLabeledBlockNode) {
((ASTLabeledBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("Stenghtened Loop in labeledblock node");
} else if (node instanceof ASTUnconditionalLoopNode) {
((ASTUnconditionalLoopNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("Stenghtened Loop in unconditionalloopNode");
} else if (node instanceof ASTIfNode) {
((ASTIfNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("Stenghtened Loop in ifnode");
} else if (node instanceof ASTWhileNode) {
((ASTWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("Stenghtened Loop in whilenode");
} else if (node instanceof ASTDoWhileNode) {
((ASTDoWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("Stenghtened Loop in dowhile node");
} 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 labeledBlockNode to be removed at location given by the nodeNumber variable
*/
List<Object> newBody = createNewSubBody(toModifySubBody, nodeNumber, loopNode, newNode);
if (newBody == null) {
// something went wrong
return;
}
if (subBodyNumber == 0) {
// the if body was modified
// System.out.println("Stenghtened Loop");
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("Stenghtened Loop");
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> createNewSubBody(List<Object> oldSubBody, int nodeNumber, ASTNode oldNode,
List<ASTNode> newNode) {
// 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 ASTNode to be removed
// just to make sure check this
ASTNode toRemove = (ASTNode) it.next();
if (toRemove.toString().compareTo(oldNode.toString()) != 0) {
System.out.println("The replace nodes dont match please report benchmark to developer");
return null;
} else {
// not adding the oldNode into the newSubBody but adding its replacement
newSubBody.addAll(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;
}
}
| 16,858
| 36.381375
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/NewStringBufferSimplification.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.Value;
import soot.ValueBox;
import soot.dava.internal.javaRep.DNewInvokeExpr;
import soot.dava.internal.javaRep.DVirtualInvokeExpr;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.grimp.internal.GAddExpr;
/*
* Matches the output pattern
* (new StringBuffer()).append ............ .toString();
* Convert it to
* append1 + append2 .....;
*/
public class NewStringBufferSimplification extends DepthFirstAdapter {
public static boolean DEBUG = false;
public NewStringBufferSimplification() {
}
public NewStringBufferSimplification(boolean verbose) {
super(verbose);
}
public void inExprOrRefValueBox(ValueBox argBox) {
if (DEBUG) {
System.out.println("ValBox is: " + argBox.toString());
}
Value tempArgValue = argBox.getValue();
if (DEBUG) {
System.out.println("arg value is: " + tempArgValue);
}
if (!(tempArgValue instanceof DVirtualInvokeExpr)) {
if (DEBUG) {
System.out.println("Not a DVirtualInvokeExpr" + tempArgValue.getClass());
}
return;
}
// check this is a toString for StringBuffer
if (DEBUG) {
System.out.println("arg value is a virtual invokeExpr");
}
DVirtualInvokeExpr vInvokeExpr = ((DVirtualInvokeExpr) tempArgValue);
// need this try catch since DavaStmtHandler expr will not have a "getMethod"
try {
if (!(vInvokeExpr.getMethod().toString().equals("<java.lang.StringBuffer: java.lang.String toString()>"))) {
return;
}
} catch (Exception e) {
return;
}
if (DEBUG) {
System.out.println("Ends in toString()");
}
Value base = vInvokeExpr.getBase();
List args = new ArrayList();
while (base instanceof DVirtualInvokeExpr) {
DVirtualInvokeExpr tempV = (DVirtualInvokeExpr) base;
if (DEBUG) {
System.out.println("base method is " + tempV.getMethod());
}
if (!tempV.getMethod().toString().startsWith("<java.lang.StringBuffer: java.lang.StringBuffer append")) {
if (DEBUG) {
System.out.println("Found a virtual invoke which is not a append" + tempV.getMethod());
}
return;
}
args.add(0, tempV.getArg(0));
// System.out.println("Append: "+((DVirtualInvokeExpr)base).getArg(0) );
// move to next base
base = ((DVirtualInvokeExpr) base).getBase();
}
if (!(base instanceof DNewInvokeExpr)) {
return;
}
if (DEBUG) {
System.out.println("New expr is " + ((DNewInvokeExpr) base).getMethod());
}
if (!((DNewInvokeExpr) base).getMethod().toString().equals("<java.lang.StringBuffer: void <init>()>")) {
return;
}
/*
* The arg is a new invoke expr of StringBuffer and all the appends are present in the args list
*/
if (DEBUG) {
System.out.println("Found a new StringBuffer.append list in it");
}
// argBox contains the new StringBuffer
Iterator it = args.iterator();
Value newVal = null;
while (it.hasNext()) {
Value temp = (Value) it.next();
if (newVal == null) {
newVal = temp;
} else {
// create newVal + temp
newVal = new GAddExpr(newVal, temp);
}
}
if (DEBUG) {
System.out.println("New expression for System.out.println is" + newVal);
}
argBox.setValue(newVal);
}
}
| 4,302
| 28.074324
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/OrAggregatorFour.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.ASTCondition;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTOrCondition;
import soot.dava.internal.AST.ASTStatementSequenceNode;
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.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
label_1:
while(cond){ label_1:
BodyA; while(cond){
label_2:{ BodyA;
if(cond1){ if(cond1 || ..... || !cond2){
break label_2; BodyB
} }
//same as above }//end of while
.
. remove label_1 if BodyA and BodyB
if(cond2){ dont have any reference to label_1 (highly likely)
continue label_1; ------> should be done as a separate analysis
}
}//end of label_2
BodyB
}//end while
This pattern is applicable to the four cycle nodes representing
while(true), while(cond) and dowhile(cond) for loops
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
*/
public class OrAggregatorFour extends DepthFirstAdapter {
public OrAggregatorFour() {
}
public OrAggregatorFour(boolean verbose) {
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
}
public void outASTForLoopNode(ASTForLoopNode node) {
String label = node.get_Label().toString();
if (label == null) {
return;
}
List<Object> subBodies = node.get_SubBodies();
List<Object> newBody = matchPattern(label, subBodies);
if (newBody != null) {
node.replaceBody(newBody);
// System.out.println("OR AGGREGATOR FOUR");
G.v().ASTTransformations_modified = true;
}
/*
* see if we can remove the label from this construct
*/
UselessLabelFinder.v().findAndKill(node);
}
public void outASTWhileNode(ASTWhileNode node) {
String label = node.get_Label().toString();
if (label == null) {
return;
}
List<Object> subBodies = node.get_SubBodies();
List<Object> newBody = matchPattern(label, subBodies);
if (newBody != null) {
node.replaceBody(newBody);
// System.out.println("OR AGGREGATOR FOUR");
G.v().ASTTransformations_modified = true;
}
/*
* see if we can remove the label from this construct
*/
UselessLabelFinder.v().findAndKill(node);
}
public void outASTDoWhileNode(ASTDoWhileNode node) {
String label = node.get_Label().toString();
if (label == null) {
return;
}
List<Object> subBodies = node.get_SubBodies();
List<Object> newBody = matchPattern(label, subBodies);
if (newBody != null) {
node.replaceBody(newBody);
// System.out.println("OR AGGREGATOR FOUR");
G.v().ASTTransformations_modified = true;
}
/*
* see if we can remove the label from this construct
*/
UselessLabelFinder.v().findAndKill(node);
}
public void outASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
String label = node.get_Label().toString();
if (label == null) {
return;
}
List<Object> subBodies = node.get_SubBodies();
List<Object> newBody = matchPattern(label, subBodies);
if (newBody != null) {
node.replaceBody(newBody);
// System.out.println("OR AGGREGATOR FOUR");
G.v().ASTTransformations_modified = true;
}
/*
* see if we can remove the label from this construct
*/
UselessLabelFinder.v().findAndKill(node);
}
public List<Object> matchPattern(String whileLabel, List<Object> subBodies) {
// since the subBodies are coming from a cycle node we know
// there is only one subBody
if (subBodies.size() != 1) {
// size should be one
return null;
}
List subBody = (List) subBodies.get(0);
Iterator it = subBody.iterator();
int nodeNumber = 0;
while (it.hasNext()) {
// going through the ASTNodes
// look for a labeledBlock
ASTNode temp = (ASTNode) it.next();
if (temp instanceof ASTLabeledBlockNode) {
// see if the inner pattern matches
ASTLabeledBlockNode labeledNode = (ASTLabeledBlockNode) temp;
String innerLabel = labeledNode.get_Label().toString();
if (innerLabel == null) {
// label better not be null
nodeNumber++;
continue;
}
// get labeledBlocksBodies
List<Object> labeledBlocksSubBodies = labeledNode.get_SubBodies();
if (labeledBlocksSubBodies.size() != 1) {
// should always be one
nodeNumber++;
continue;
}
// get the subBody
List labeledBlocksSubBody = (List) labeledBlocksSubBodies.get(0);
boolean allIfs = checkAllAreIfsWithProperBreaks(labeledBlocksSubBody.iterator(), whileLabel, innerLabel);
if (!allIfs) {
// pattern doesnt match
nodeNumber++;
continue;
}
// the pattern has been matched do the transformation
// nodeNumber is the location of the ASTLabeledBlockNode
List<Object> whileBody = createWhileBody(subBody, labeledBlocksSubBody, nodeNumber);
if (whileBody != null) {
return whileBody;
}
} // if its an ASTLabeledBlockNode
nodeNumber++;
} // end of going through ASTNodes
return null;
}
private List<Object> createWhileBody(List subBody, List labeledBlocksSubBody, int nodeNumber) {
// create BodyA, Nodes from 0 to nodeNumber
List<Object> bodyA = new ArrayList<Object>();
// this is an iterator of ASTNodes
Iterator it = subBody.iterator();
// copy to bodyA all nodes until you get to nodeNumber
int index = 0;
while (index != nodeNumber) {
if (!it.hasNext()) {
return null;
}
bodyA.add(it.next());
index++;
}
// create ASTIfNode
// Create a list of conditions to be Ored together
// remembering that the last ones condition is to be flipped
List<ASTCondition> conditions = getConditions(labeledBlocksSubBody.iterator());
// create an aggregated condition
Iterator<ASTCondition> condIt = conditions.iterator();
ASTCondition newCond = null;
;
while (condIt.hasNext()) {
ASTCondition next = condIt.next();
if (newCond == null) {
newCond = next;
} else {
newCond = new ASTOrCondition(newCond, next);
}
}
// create BodyB
it.next();// this skips the LabeledBlockNode
List<Object> bodyB = new ArrayList<Object>();
while (it.hasNext()) {
bodyB.add(it.next());
}
ASTIfNode newNode = new ASTIfNode(new SETNodeLabel(), newCond, bodyB);
// add this node to the bodyA
bodyA.add(newNode);
return bodyA;
}
/*
* The method will go through the iterator because of the sequence of methods called before in the outASTLabeledBlockNode
* it knows the following: All nodes are ASTIFNodes
*/
private List<ASTCondition> getConditions(Iterator it) {
List<ASTCondition> toReturn = new ArrayList<ASTCondition>();
while (it.hasNext()) {
// safe cast since we know these are all ASTIfNodes
ASTIfNode node = (ASTIfNode) it.next();
ASTCondition cond = node.get_Condition();
// check if this is the last in which case we need to flip
if (it.hasNext()) {
// no need to flip
toReturn.add(cond);
} else {
// need to flip condition
// System.out.println("old:"+cond);
cond.flip();
// System.out.println("new"+cond);
toReturn.add(cond);
}
} // end of while
return toReturn;
}
private boolean checkAllAreIfsWithProperBreaks(Iterator it, String outerLabel, String innerLabel) {
// the pattern says that ALL bodies in this list should be IF statements
while (it.hasNext()) {
ASTNode secondLabelsBody = (ASTNode) it.next();
// check that this is a ifNode with a single statement
Stmt stmt = isIfNodeWithOneStatement(secondLabelsBody);
if (stmt == null) {
// pattern is broken
return false;
}
// check if the single stmt follows the pattern
boolean abrupt = abruptLabel(stmt, outerLabel, innerLabel, it.hasNext());
if (!abrupt) {
// stmt does not follow the pattern
return false;
}
} // end of while going through all the bodies of the secondlabel
// if we get here that means everything was according to the pattern
return true;
}
/*
* If the stmt is a break stmt then see it breaks the inner label and thee boolean is true return true If the stmt is a
* continue then see it continues the outer label and the boolean is false return true else return false
*/
private boolean abruptLabel(Stmt stmt, String outerLabel, String innerLabel, boolean hasNext) {
if (!(stmt instanceof DAbruptStmt)) {
// this is not a break/continue stmt
return false;
}
DAbruptStmt abStmt = (DAbruptStmt) stmt;
SETNodeLabel label = abStmt.getLabel();
String abruptLabel = label.toString();
if (abruptLabel == null) {
return false;
}
if (abStmt.is_Break() && abruptLabel.compareTo(innerLabel) == 0 && hasNext) {
return true;
} else if (abStmt.is_Continue() && abruptLabel.compareTo(outerLabel) == 0 && !hasNext) {
return true;
} else {
return false;
}
}
private Stmt isIfNodeWithOneStatement(ASTNode secondLabelsBody) {
if (!(secondLabelsBody instanceof ASTIfNode)) {
// pattern broken as this should be a IfNode
return null;
}
// check that the body of ASTIfNode has a single ASTStatementSequence
ASTIfNode ifNode = (ASTIfNode) secondLabelsBody;
List<Object> ifSubBodies = ifNode.get_SubBodies();
if (ifSubBodies.size() != 1) {
// if body should always have oneSubBody
return null;
}
// if has one SubBody
List ifBody = (List) ifSubBodies.get(0);
// Looking for a statement sequence node with a single stmt
if (ifBody.size() != 1) {
// there should only be one body
return null;
}
// The only subBody has one ASTNode
ASTNode ifBodysBody = (ASTNode) ifBody.get(0);
if (!(ifBodysBody instanceof ASTStatementSequenceNode)) {
// had to be a STMTSEQ node
return null;
}
// the only ASTnode is a ASTStatementSequence
List<AugmentedStmt> statements = ((ASTStatementSequenceNode) ifBodysBody).getStatements();
if (statements.size() != 1) {
// there is more than one statement
return null;
}
// there is only one statement return the statement
AugmentedStmt as = statements.get(0);
Stmt s = as.get_Stmt();
return s;
}
}
| 12,550
| 30.936387
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/OrAggregatorOne.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.ASTCondition;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTOrCondition;
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.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
label_1:{ label_1:{
label_0:{ if(cond1 || cond2){
if(cond1){ Body1
break label_0; }
} }
if(!cond2){ Body2
break label_1; ------>
} Cant remove label_1 as Body 1
}//end of label_0 might have reference to it
Body1 can however set some flag if we are
}//end of label_1 sure that label_1 is not broken
Body2 and later removed
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
*/
public class OrAggregatorOne extends DepthFirstAdapter {
public OrAggregatorOne() {
}
public OrAggregatorOne(boolean verbose) {
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
}
public void outASTLabeledBlockNode(ASTLabeledBlockNode node) {
String outerLabel = node.get_Label().toString();
if (outerLabel == null) {
return;
}
String innerLabel = null;
ASTLabeledBlockNode secondLabeledBlockNode = isLabelWithinLabel(node);
if (secondLabeledBlockNode == null) {
// node doesnt have an immediate label following it
return;
}
// store the labelname
innerLabel = secondLabeledBlockNode.get_Label().toString();
if (innerLabel == null) {
// empty or marked for deletion
return;
}
List secondLabelsBodies = getSecondLabeledBlockBodies(secondLabeledBlockNode);
boolean allIfs = checkAllAreIfsWithProperBreaks(secondLabelsBodies.iterator(), outerLabel, innerLabel);
if (!allIfs) {
// pattern doesnt match
return;
}
// the pattern has been matched do the transformation
// Create a list of conditions to be Ored together
// remembering that the last ones condition is to be flipped
List<ASTCondition> conditions = getConditions(secondLabelsBodies.iterator());
// create an aggregated condition
Iterator<ASTCondition> condIt = conditions.iterator();
ASTCondition newCond = null;
;
while (condIt.hasNext()) {
ASTCondition next = condIt.next();
if (newCond == null) {
newCond = next;
} else {
newCond = new ASTOrCondition(newCond, next);
}
}
// will contain the Body of the ASTIfNode
List<Object> newIfBody = new ArrayList<Object>();
// get_SubBodies of upper labeled block
List<Object> subBodies = node.get_SubBodies();
// we know that there is only one SubBody for this node retrieve that
List labeledBlockBody = (List) subBodies.get(0);
// from the isLabelWithinLabel method we know that the first is the labeled block
// discard that keep the rest
Iterator subBodiesIt = labeledBlockBody.iterator();
subBodiesIt.next();// discarding first
while (subBodiesIt.hasNext()) {
ASTNode temp = (ASTNode) subBodiesIt.next();
newIfBody.add(temp);
}
ASTIfNode newNode = new ASTIfNode(new SETNodeLabel(), newCond, newIfBody);
List<Object> newLabeledBlockBody = new ArrayList<Object>();
newLabeledBlockBody.add(newNode);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATING ONE!!!");
node.replaceBody(newLabeledBlockBody);
/*
* See if the outer label can be marked as useless
*/
UselessLabelFinder.v().findAndKill(node);
}
private ASTLabeledBlockNode isLabelWithinLabel(ASTLabeledBlockNode node) {
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() == 0) { // shouldnt happen
// labeledBlockNodes size is zero this is a useless label
// marked for removal by setting an empty SETNodeLabel
node.set_Label(new SETNodeLabel());
return null;
}
// LabeledBlockNode had SubBody we know there is always only one
List bodies = (List) subBodies.get(0);
// these bodies should be a labelled block followed by something
if (bodies.size() == 0) {
// there is nothing inside this labeledBlock
// an empty Body is useless
node.set_Label(new SETNodeLabel());
return null;
}
// there is some ASTNode there
ASTNode firstBody = (ASTNode) bodies.get(0);
if (!(firstBody instanceof ASTLabeledBlockNode)) {
// first body is not a labeledBlock node thus the pattern
// does not have the shape
// label_1:
// label_0
return null;
}
// Pattern is fine return the ASTLabeledBlockNode found
return (ASTLabeledBlockNode) firstBody;
}
private List getSecondLabeledBlockBodies(ASTLabeledBlockNode secondLabeledBlockNode) {
// retrieve the SubBodies of this second labeledblock
List<Object> secondLabelsSubBodies = secondLabeledBlockNode.get_SubBodies();
if (secondLabelsSubBodies.size() == 0) {
// there is nothing in the labeledblock
// highlly unlikely but if yes then set labeledBlockNode for not printing/deletion
secondLabeledBlockNode.set_Label(new SETNodeLabel());
return null;
}
/*
* there is atleast one body in there and infact it should be only one since this is a labeledBlockNode
*/
List secondLabelsBodies = (List) secondLabelsSubBodies.get(0);
// return the list
return secondLabelsBodies;
}
private boolean checkAllAreIfsWithProperBreaks(Iterator it, String outerLabel, String innerLabel) {
// the pattern says that ALL bodies in this list should be IF statements
while (it.hasNext()) {
ASTNode secondLabelsBody = (ASTNode) it.next();
// check that this is a ifNode with a single statement
Stmt stmt = isIfNodeWithOneStatement(secondLabelsBody);
if (stmt == null) {
// pattern is broken
return false;
}
// check if the single stmt is a break stmt
String labelBroken = breaksLabel(stmt);
if (labelBroken == null) {
// stmt does not break a label
return false;
}
// check if this is the inner label broken and is not the last in the iterator
if (labelBroken.compareTo(innerLabel) == 0 && it.hasNext()) {
continue;
}
// check if this is the outer label broken and is the last in the iterator
if (labelBroken.compareTo(outerLabel) == 0 && !it.hasNext()) {
continue;
}
// if we get here that means this is not a break breaking the label we want
return false;
} // end of while going through all the bodies of the secondlabel
// if we get here that means everything was according to the pattern
return true;
}
/*
* If the stmt is a break stmt then this method returns the labels name else returns null
*/
private String breaksLabel(Stmt stmt) {
if (!(stmt instanceof DAbruptStmt)) {
// this is not a break stmt
return null;
}
DAbruptStmt abStmt = (DAbruptStmt) stmt;
if (!abStmt.is_Break()) {
// not a break stmt
return null;
}
SETNodeLabel label = abStmt.getLabel();
return label.toString();
}
private Stmt isIfNodeWithOneStatement(ASTNode secondLabelsBody) {
if (!(secondLabelsBody instanceof ASTIfNode)) {
// pattern broken as this should be a IfNode
return null;
}
// check that the body of ASTIfNode has a single ASTStatementSequence
ASTIfNode ifNode = (ASTIfNode) secondLabelsBody;
List<Object> ifSubBodies = ifNode.get_SubBodies();
if (ifSubBodies.size() != 1) {
// if body should always have oneSubBody
return null;
}
// if has one SubBody
List ifBody = (List) ifSubBodies.get(0);
// Looking for a statement sequence node with a single stmt
if (ifBody.size() != 1) {
// there should only be one body
return null;
}
// The only subBody has one ASTNode
ASTNode ifBodysBody = (ASTNode) ifBody.get(0);
if (!(ifBodysBody instanceof ASTStatementSequenceNode)) {
// had to be a STMTSEQ node
return null;
}
// the only ASTnode is a ASTStatementSequence
List<AugmentedStmt> statements = ((ASTStatementSequenceNode) ifBodysBody).getStatements();
if (statements.size() != 1) {
// there is more than one statement
return null;
}
// there is only one statement return the statement
AugmentedStmt as = statements.get(0);
Stmt s = as.get_Stmt();
return s;
}
/*
* The method will go through the iterator because of the sequence of methods called before in the outASTLabeledBlockNode
* it knows the following: 1, All nodes are ASTIFNodes
*/
private List<ASTCondition> getConditions(Iterator it) {
List<ASTCondition> toReturn = new ArrayList<ASTCondition>();
while (it.hasNext()) {
// safe cast since we know these are all ASTIfNodes
ASTIfNode node = (ASTIfNode) it.next();
ASTCondition cond = node.get_Condition();
// check if this is the last in which case we need to flip
if (it.hasNext()) {
// no need to flip
toReturn.add(cond);
} else {
// need to flip condition
cond.flip();
toReturn.add(cond);
}
} // end of while
return toReturn;
}
}
| 10,978
| 32.472561
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/OrAggregatorThree.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.ASTCondition;
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.ASTOrCondition;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
import soot.dava.internal.AST.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DAbruptStmt;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
/*
Nomair A. Naeem 21-FEB-2005
The class is responsible to do the following transformation on the AST
if(cond1){ if(cond1 || cond2)
A A
} }
if(cond2){
A
}
Notice that this kind of conversion is only possible if A is an
abrupt edge like:
a, break label_0;
b, continue label_0;
c, return;
i.e. we need to make sure that the A bodies are single statements
and that too an abrupt control flow
Also note that in the new aggregated or condition it is very important
that cond2 be checked AFTER cond1 has been checked and failed.
The reason for this being side effects that these conditions can cause.
*/
public class OrAggregatorThree {
public static void checkAndTransform(ASTNode node, ASTIfNode ifOne, ASTIfNode ifTwo, int nodeNumber, int subBodyNumber) {
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 Two consective if nodes at location given by nodeNumber and nodeNumber+1
*/
// match the pattern and get the newBody
List<Object> newBody = createNewNodeBody(onlySubBody, nodeNumber, ifOne, ifTwo);
if (newBody == null) {
// something went wrong, pattern didnt match or some other problem
return;
}
if (node instanceof ASTMethodNode) {
((ASTMethodNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATOR THREE");
} else if (node instanceof ASTSynchronizedBlockNode) {
((ASTSynchronizedBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATOR THREE");
} else if (node instanceof ASTLabeledBlockNode) {
((ASTLabeledBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATOR THREE");
} else if (node instanceof ASTUnconditionalLoopNode) {
((ASTUnconditionalLoopNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATOR THREE");
} else if (node instanceof ASTIfNode) {
((ASTIfNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATOR THREE");
} else if (node instanceof ASTWhileNode) {
((ASTWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATOR THREE");
} else if (node instanceof ASTDoWhileNode) {
((ASTDoWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("OR AGGREGATOR THREE");
} 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 two consective if nodes in question at location given by the nodeNumber and
* nodeNumer+1
*/
List<Object> newBody = createNewNodeBody(toModifySubBody, nodeNumber, ifOne, ifTwo);
if (newBody == null) {
// something went wrong, the pattern didnt match or something else
return;
}
if (subBodyNumber == 0) {
// the if body was modified
// System.out.println("OR AGGREGATOR THREE");
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("OR AGGREGATOR THREE");
G.v().ASTTransformations_modified = true;
((ASTIfElseNode) node).replaceBody((List<Object>) subBodies.get(0), newBody);
}
} // end of ASTIfElseNode
}
/*
* This method does the following: 1, check that the OrAggregatorThree pattern matches for node ifOne and ifTwo 2, if
* pattern does not match return null 3, if pattern matches create and return a newSubBody which has: a, ifOne with its
* condition ORED with that of ifTwo b, ifTwo has been removed from the subBody
*/
public static List<Object> createNewNodeBody(List<Object> oldSubBody, int nodeNumber, ASTIfNode ifOne, ASTIfNode ifTwo) {
if (!matchPattern(ifOne, ifTwo)) {
// pattern did not match
return null;
}
// 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 ASTIFNode
// just to make sure check this
ASTNode isItIfOne = (ASTNode) it.next();
if (!(isItIfOne instanceof ASTIfNode)) {
// something is wrong
return null;
}
// get the next node that should also be an ASTIfNode
ASTNode isItIfTwo = (ASTNode) it.next();
if (!(isItIfTwo instanceof ASTIfNode)) {
// something is wrong
return null;
}
// double check by invoking matchPattern on these
// if speed is an issue this check can be removed
if (!matchPattern((ASTIfNode) isItIfOne, (ASTIfNode) isItIfTwo)) {
// pattern did not match
return null;
}
// we are sure that we have the two nodes
// create new node
ASTIfNode firstOne = (ASTIfNode) isItIfOne;
ASTIfNode secondOne = (ASTIfNode) isItIfTwo;
// create new condition
ASTCondition firstCond = firstOne.get_Condition();
ASTCondition secondCond = secondOne.get_Condition();
ASTCondition newCond = new ASTOrCondition(firstCond, secondCond);
ASTIfNode newNode = new ASTIfNode(firstOne.get_Label(), newCond, firstOne.getIfBody());
// add the new node
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;
}
/*
* Given two IfNodes as input the pattern checks the following: a, each if node has a single ASTSTatementSequenceNode in
* the body b, Each StatementSequenceNode is a single statement c, The statement is the same in both nodes d, The statement
* is an abrupt control flow statement
*/
private static boolean matchPattern(ASTIfNode one, ASTIfNode two) {
List<Object> subBodiesOne = one.get_SubBodies();
List<Object> subBodiesTwo = two.get_SubBodies();
if (subBodiesOne.size() != 1 || subBodiesTwo.size() != 1) {
// these are both if nodes they should always have one subBody
return false;
}
List onlySubBodyOne = (List) subBodiesOne.get(0);
List onlySubBodyTwo = (List) subBodiesTwo.get(0);
if (onlySubBodyOne.size() != 1 || onlySubBodyTwo.size() != 1) {
// these subBodies are expected to have a single StatementSequenceNode
return false;
}
ASTNode onlyASTNodeOne = (ASTNode) onlySubBodyOne.get(0);
ASTNode onlyASTNodeTwo = (ASTNode) onlySubBodyTwo.get(0);
if (!(onlyASTNodeOne instanceof ASTStatementSequenceNode) || !(onlyASTNodeTwo instanceof ASTStatementSequenceNode)) {
// need both of these nodes to be StatementSequnceNodes
return false;
}
ASTStatementSequenceNode stmtSeqOne = (ASTStatementSequenceNode) onlyASTNodeOne;
ASTStatementSequenceNode stmtSeqTwo = (ASTStatementSequenceNode) onlyASTNodeTwo;
List<AugmentedStmt> stmtsOne = stmtSeqOne.getStatements();
List<AugmentedStmt> stmtsTwo = stmtSeqTwo.getStatements();
if (stmtsOne.size() != 1 || stmtsTwo.size() != 1) {
// there should only be one statement
return false;
}
AugmentedStmt asOne = stmtsOne.get(0);
AugmentedStmt asTwo = stmtsTwo.get(0);
Stmt s1 = asOne.get_Stmt();
Stmt s2 = asTwo.get_Stmt();
if (s1.toString().compareTo(s2.toString()) != 0) {
// the two stmts are not the same
return false;
}
// check if they are abrupt statements
if (s1 instanceof DAbruptStmt && s2 instanceof DAbruptStmt) {
// takes care of break <label> and continue <label>
return true;
} else if (s1 instanceof ReturnStmt && s2 instanceof ReturnStmt) {
// takes care of return <var>
return true;
} else if (s1 instanceof ReturnVoidStmt && s2 instanceof ReturnVoidStmt) {
// takes care of return;
return true;
} else {
return false;
}
}
}
| 11,315
| 35.385852
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/OrAggregatorTwo.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.List;
import soot.G;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTIfNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTOrCondition;
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.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.Stmt;
/*
Nomair A. Naeem 21-FEB-2005
The class is responsible to one of the following two transformation on the AST
PRIORITY 1:
if(cond1){ if(cond1 || cond2) if(cond1 || cond2){
A A A
} } }
else{ ---> else{ --->
if(cond2){ empty else body
A }
}
}
The removal of the empty else body is done by a different Transformation since
we need a reference to the parent node of this if
PRIORITY 2:
If the above pattern fails to match the following pattern is checked:
if(cond1){ if(!cond1){
break label_1; Body1
} ----> }
else{ else{
Body1 break label_1
} }
The idea behind this is that this type of flipping of conditions
will help in moving a condition into a cycle node
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
*/
public class OrAggregatorTwo extends DepthFirstAdapter {
public OrAggregatorTwo() {
DEBUG = false;
}
public OrAggregatorTwo(boolean verbose) {
super(verbose);
DEBUG = false;
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
}
public void outASTIfElseNode(ASTIfElseNode node) {
// check whether the else body has another if and nothing else
List<Object> ifBody = node.getIfBody();
List<Object> elseBody = node.getElseBody();
List<Object> innerIfBody = checkElseHasOnlyIf(elseBody);
if (innerIfBody == null) {
// pattern 1 did not match
// check for pattern 2
matchPatternTwo(node);
return;
}
// pattern 1 is fine till now
// compare the ifBody with the innerIfBody
// They need to match exactly
if (ifBody.toString().compareTo(innerIfBody.toString()) != 0) {
matchPatternTwo(node);
return;
}
ASTCondition leftCond = node.get_Condition();
ASTCondition rightCond = getRightCond(elseBody);
ASTCondition newCond = new ASTOrCondition(leftCond, rightCond);
/*
* The outer if and inner if could both have labels. Note that if the inner if had a label which was broken from inside
* its body the two bodies would not have been the same since the outerifbody could not have the same label.
*
* We therefore keep the outerIfElse label
*/
// System.out.println("OR AGGREGATOR TWO");
node.set_Condition(newCond);
/*
* Always have to follow with a parse to remove unwanted empty ElseBodies
*/
node.replaceElseBody(new ArrayList<Object>());
G.v().ASTTransformations_modified = true;
}
public ASTCondition getRightCond(List<Object> elseBody) {
// We know from checkElseHasOnlyIf that there is only one node
// in this body and it is an ASTIfNode
ASTIfNode innerIfNode = (ASTIfNode) elseBody.get(0);
return innerIfNode.get_Condition();
}
public List<Object> checkElseHasOnlyIf(List<Object> elseBody) {
if (elseBody.size() != 1) {
// there should only be on IfNode here
return null;
}
// there is only one node check that its a ASTIFNode
ASTNode temp = (ASTNode) elseBody.get(0);
if (!(temp instanceof ASTIfNode)) {
// should have been an If node to match the pattern
return null;
}
ASTIfNode innerIfNode = (ASTIfNode) temp;
List<Object> innerIfBody = innerIfNode.getIfBody();
return innerIfBody;
}
public void matchPatternTwo(ASTIfElseNode node) {
debug("OrAggregatorTwo", "matchPatternTwo", "Did not match patternOne...trying patternTwo");
List<Object> ifBody = node.getIfBody();
if (ifBody.size() != 1) {
// we are only interested if size is one
return;
}
ASTNode onlyNode = (ASTNode) ifBody.get(0);
if (!(onlyNode instanceof ASTStatementSequenceNode)) {
// only interested in StmtSeq nodes
return;
}
ASTStatementSequenceNode stmtNode = (ASTStatementSequenceNode) onlyNode;
List<AugmentedStmt> statements = stmtNode.getStatements();
if (statements.size() != 1) {
// there is more than one statement
return;
}
// there is only one statement
AugmentedStmt as = statements.get(0);
Stmt stmt = as.get_Stmt();
if (!(stmt instanceof DAbruptStmt)) {
// this is not a break/continue stmt
return;
}
DAbruptStmt abStmt = (DAbruptStmt) stmt;
if (!(abStmt.is_Break() || abStmt.is_Continue())) {
// not a break/continue
return;
}
// pattern matched
// flip condition and switch bodies
ASTCondition cond = node.get_Condition();
cond.flip();
List<Object> elseBody = node.getElseBody();
SETNodeLabel label = node.get_Label();
node.replace(label, cond, elseBody, ifBody);
debug("", "", "REVERSED CONDITIONS AND BODIES");
debug("", "", "elseBody is" + elseBody);
debug("", "", "ifBody is" + ifBody);
G.v().ASTIfElseFlipped = true;
}
}
| 6,577
| 30.625
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/PushLabeledBlockIn.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.ASTLabeledBlockNode;
import soot.dava.internal.AST.ASTLabeledNode;
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
label_1:{
___________________ ____________________
| | | |
| no break label_1 | | no break label_1 |
|___________________| |____________________|
| | | |
|ASTLabeledNode | | label_1: |
|while(cond){ | ----> | while(cond){ |
| use of label_1 | | use of label_1 |
| | | } |
|} | |____________________|
|___________________|
| |
| Nothing here |
|___________________|
}//end of label_1
The important thing to note in this case is that the node which uses breaks
extends ASTLabeledNode so that we can move the label down. Obviously there shouldnt be
an already existing label on this node. Once the node containing the break is detected
there should be no node following this in the body of the labeled block. This is so because
if the break is moved down that code will get executed and thats a wrong transformation.
label_1:{
___________________ _____________________
| | | |
|label_2 | | label_2: |
|while(cond){ | ----> | while(cond){ |
| use of label_1 | | label_1 replaced|
| | | by label_2 |
|} | |___}_________________|
|___________________|
| |
| Nothing here |
|___________________|
}//end of label_1
If the previous pattern did not match because the node on which we wanted to push the label
inwards already had a label we can try to use the label on the inner node. This is only possible
if there is only a single node in the labeledBlocks subBody, to make sure that we break and jump
to exactly the same point as we were jumping before.
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
*/
public class PushLabeledBlockIn extends DepthFirstAdapter {
public PushLabeledBlockIn() {
}
public PushLabeledBlockIn(boolean verbose) {
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
}
public void outASTLabeledBlockNode(ASTLabeledBlockNode node) {
String label = node.get_Label().toString();
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 1) {
return;
}
List subBody = (List) subBodies.get(0);
int nodeNumber = checkForBreak(subBody, label);
if (nodeNumber > -1) {
// found some break for this label
// retrieve element at this nodeNumber
if (subBody.size() < nodeNumber) {
// something is wrong
throw new RuntimeException("Please submit this benchmark as a bug");
}
// check that this is the last node in the list
// since otherwise we cant change anything
if (nodeNumber + 1 != subBody.size()) {
// it is not the last
return;
}
// safe to access the list
ASTNode temp = (ASTNode) subBody.get(nodeNumber);
if (!(temp instanceof ASTLabeledNode)) {
// does not extend labeledNode hence cannot give it a label
return;
}
ASTLabeledNode tempNode = (ASTLabeledNode) temp;
// shouldnt already have a label
String innerLabel = tempNode.get_Label().toString();
if (innerLabel != null) {
// already has a label
// we could still do something if this is the ONLY node in the
// body
if (subBody.size() == 1) {
// there is only one node
/*
* The situation is that there is a labeled block whic has only one node that also has a label on it.
*
* There is some statement deep down which breaks the outer label
*
* No reason why it cant break the inner label since there is nothing after that!!!
*
* label has the outer label whose break we found innerLabel has the label of the inner node which contains the
* break
*
* replace all occurances of break of outer label with that of break of inner label
*/
// we know that the breaks occur within the subtree rooted
// at temp
boolean done = replaceBreakLabels(temp, label, innerLabel);
if (done) {
// System.out.println("REMOVED LABELED BLOCK-replaced label names");
node.set_Label(new SETNodeLabel());
G.v().ASTTransformations_modified = true;
}
}
return;
} else {
// doesnt have a label
// System.out.println("PUSHED LABEL DOWN");
SETNodeLabel newLabel = new SETNodeLabel();
newLabel.set_Name(label);
tempNode.set_Label(newLabel);
node.set_Label(new SETNodeLabel());
G.v().ASTTransformations_modified = true;
}
}
}
private boolean replaceBreakLabels(ASTNode node, String toReplace, String replaceWith) {
boolean toReturn = false;
List<Object> subBodies = node.get_SubBodies();
Iterator<Object> subIt = subBodies.iterator();
while (subIt.hasNext()) {
List subBody = null;
if (node instanceof ASTTryNode) {
ASTTryNode.container subBodyContainer = (ASTTryNode.container) subIt.next();
subBody = (List) subBodyContainer.o;
} else {
subBody = (List) subIt.next();
}
Iterator it = subBody.iterator();
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
// check if this is ASTStatementSequenceNode
if (temp instanceof ASTStatementSequenceNode) {
ASTStatementSequenceNode stmtSeq = (ASTStatementSequenceNode) temp;
for (AugmentedStmt as : stmtSeq.getStatements()) {
Stmt s = as.get_Stmt();
String labelBroken = isAbrupt(s);
if (labelBroken != null) {
// stmt breaks some label
if (labelBroken.compareTo(toReplace) == 0) {
// we have found a break breaking this label
// replace the label with "replaceWith"
replaceLabel(s, replaceWith);
toReturn = true;
}
}
}
} // if it was a StmtSeq node
else {
// otherwise recursion
boolean returnVal = replaceBreakLabels(temp, toReplace, replaceWith);
if (returnVal) {
toReturn = true;
}
}
} // end of while
}
return toReturn;
}
private int checkForBreak(List ASTNodeBody, String outerLabel) {
Iterator it = ASTNodeBody.iterator();
int nodeNumber = 0;
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
// check if this is ASTStatementSequenceNode
if (temp instanceof ASTStatementSequenceNode) {
ASTStatementSequenceNode stmtSeq = (ASTStatementSequenceNode) temp;
for (AugmentedStmt as : stmtSeq.getStatements()) {
Stmt s = as.get_Stmt();
String labelBroken = breaksLabel(s);
if (labelBroken != null && outerLabel != null) {
// stmt
// breaks
// some
// label
if (labelBroken.compareTo(outerLabel) == 0) {
// we have found a break breaking this label
return nodeNumber;
}
}
}
} // if it was a StmtSeq node
else {
// otherwise recursion
// getSubBodies
List<Object> subBodies = temp.get_SubBodies();
Iterator<Object> subIt = subBodies.iterator();
while (subIt.hasNext()) {
if (temp instanceof ASTTryNode) {
ASTTryNode.container subBody = (ASTTryNode.container) subIt.next();
if (checkForBreak((List) subBody.o, outerLabel) > (-1)) {
// if this is true there was a break found
return nodeNumber;
}
} else {
if (checkForBreak((List) subIt.next(), outerLabel) > (-1)) {
// if this is true there was a break found
return nodeNumber;
}
}
}
}
nodeNumber++;
} // end of while
return -1;
}
/*
* If the stmt is a break stmt then this method returns the labels name else returns null
*/
private String breaksLabel(Stmt stmt) {
if (!(stmt instanceof DAbruptStmt)) {
// this is not a break stmt
return null;
}
DAbruptStmt abStmt = (DAbruptStmt) stmt;
if (!abStmt.is_Break()) {
// not a break stmt
return null;
}
SETNodeLabel label = abStmt.getLabel();
return label.toString();
}
/*
* If the stmt is a abruptstmt either break or continue returns the labels name else returns null
*/
private String isAbrupt(Stmt stmt) {
if (!(stmt instanceof DAbruptStmt)) {
// this is not a break stmt
return null;
}
DAbruptStmt abStmt = (DAbruptStmt) stmt;
if (abStmt.is_Break() || abStmt.is_Continue()) {
SETNodeLabel label = abStmt.getLabel();
return label.toString();
} else {
return null;
}
}
private void replaceLabel(Stmt s, String replaceWith) {
// we know its an AbruptStmt
DAbruptStmt abStmt = (DAbruptStmt) s;
SETNodeLabel label = abStmt.getLabel();
label.set_Name(replaceWith);
}
}
| 11,190
| 34.081505
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/RemoveEmptyBodyDefaultConstructor.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.ArrayList;
import java.util.Iterator;
import java.util.List;
import soot.Body;
import soot.SootClass;
import soot.SootMethod;
import soot.dava.DavaBody;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.util.Chain;
/*
* It has been seen that Dava's output contains the default constructor with just the invocation
* to super()
*
* According to the java specs the default constructor is not needed unless the constructor has been
* overloaded.
*
* The analysis checks whether there is only one constructor in the class being decompiled.
* If this is true and the constructor IS THE DEFAULT CONSTRUCTOR i.e. no arguments
* and has an empty body (there will always be a call to super
* but that is invoked automatically....) we can remove the constructor from the code
* also check tht the call to super has no arguments i.e. default super
*/
public class RemoveEmptyBodyDefaultConstructor {
public static boolean DEBUG = false;
public static void checkAndRemoveDefault(SootClass s) {
debug("\n\nRemoveEmptyBodyDefaultConstructor----" + s.getName());
List methods = s.getMethods();
Iterator it = methods.iterator();
List<SootMethod> constructors = new ArrayList<SootMethod>();
while (it.hasNext()) {
SootMethod method = (SootMethod) it.next();
debug("method name is" + method.getName());
if (method.getName().indexOf("<init>") > -1) {
// constructor add to constructor list
constructors.add(method);
}
}
if (constructors.size() != 1) {
// cant do anything since there are more than one constructors
debug("class has more than one constructors cant do anything");
return;
}
// only one constructor check its default (no arguments)
SootMethod constructor = constructors.get(0);
if (constructor.getParameterCount() != 0) {
// can only deal with default constructors
debug("constructor is not the default constructor");
return;
}
debug("Check that the body is empty....and call to super contains no arguments and delete");
if (!constructor.hasActiveBody()) {
debug("No active body found for the default constructor");
return;
}
if (!constructor.isPublic()) {
debug("Default constructor is not public.");
return;
}
Body body = constructor.getActiveBody();
Chain units = ((DavaBody) body).getUnits();
if (units.size() != 1) {
debug(" DavaBody AST does not have single root");
return;
}
ASTNode AST = (ASTNode) units.getFirst();
if (!(AST instanceof ASTMethodNode)) {
throw new RuntimeException("Starting node of DavaBody AST is not an ASTMethodNode");
}
ASTMethodNode methodNode = (ASTMethodNode) AST;
debug("got methodnode check body is empty and super has nothing in it");
List<Object> subBodies = methodNode.get_SubBodies();
if (subBodies.size() != 1) {
debug("Method node does not have one subBody!!!");
return;
}
List methodBody = (List) subBodies.get(0);
if (methodBody.size() != 0) {
debug("Method body size is greater than 1 so cant do nothing");
return;
}
debug("Method body is empty...check super call is empty");
if (((DavaBody) body).get_ConstructorExpr().getArgCount() != 0) {
debug("call to super not empty");
return;
}
debug("REMOVE METHOD");
s.removeMethod(constructor);
}
public static void debug(String debug) {
if (DEBUG) {
System.out.println("DEBUG: " + debug);
}
}
}
| 4,478
| 30.992857
| 100
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/ShortcutArrayInit.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.ArrayList;
import java.util.Iterator;
import java.util.List;
import soot.G;
import soot.Local;
import soot.Type;
import soot.Value;
import soot.ValueBox;
import soot.dava.DecompilationException;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DArrayInitExpr;
import soot.dava.internal.javaRep.DArrayInitValueBox;
import soot.dava.internal.javaRep.DAssignStmt;
import soot.dava.internal.javaRep.DShortcutAssignStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.dava.toolkits.base.AST.traversals.InitializationDeclarationShortcut;
import soot.jimple.ArrayRef;
import soot.jimple.DefinitionStmt;
import soot.jimple.IntConstant;
import soot.jimple.NewArrayExpr;
import soot.jimple.Stmt;
public class ShortcutArrayInit extends DepthFirstAdapter {
public static boolean DEBUG = false;
ASTMethodNode methodNode;
public ShortcutArrayInit() {
}
public ShortcutArrayInit(boolean verbose) {
super(verbose);
}
public void inASTMethodNode(ASTMethodNode node) {
methodNode = node;
}
public void debug(String msg) {
if (DEBUG) {
System.out.println("[SHortcutArrayInit] DEBUG" + msg);
}
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
debug("inASTStatementSequenceNode");
boolean success = false;
ArrayList<AugmentedStmt> toRemove = new ArrayList<AugmentedStmt>();
for (AugmentedStmt as : node.getStatements()) {
success = false;
Stmt s = as.get_Stmt();
if (!(s instanceof DefinitionStmt)) {
continue;
}
DefinitionStmt ds = (DefinitionStmt) s;
ValueBox right = ds.getRightOpBox();
Value rightValue = right.getValue();
if (!(rightValue instanceof NewArrayExpr)) {
continue;
}
debug("Found a new ArrayExpr" + rightValue);
debug("Type of array is:" + rightValue.getType());
// get type out
Type arrayType = rightValue.getType();
// get size....need to know this statically for sure!!!
Value size = ((NewArrayExpr) rightValue).getSize();
if (!(size instanceof IntConstant)) {
continue;
}
if (((IntConstant) size).value == 0) {
debug("Size of array is 0 dont do anything");
continue;
}
if (DEBUG) {
System.out.println("Size of array is: " + ((IntConstant) size).value);
}
Iterator<AugmentedStmt> tempIt = node.getStatements().iterator();
// get to the array creation stmt
while (tempIt.hasNext()) {
AugmentedStmt tempAs = tempIt.next();
Stmt tempS = tempAs.get_Stmt();
if (tempS.equals(s)) {
break;
}
}
// have the size have the type, tempIt is poised at the current def
// stmt
ValueBox[] array = new ValueBox[((IntConstant) size).value];
success = true;
for (int i = 0; i < ((IntConstant) size).value; i++) {
// check these many next stmts they better all be array
// initializations
if (!tempIt.hasNext()) {
// since its end of the stmt seq node just return
if (DEBUG) {
System.out.println("returning");
}
return;
}
AugmentedStmt aug = tempIt.next();
Stmt augS = aug.get_Stmt();
if (!isInSequenceAssignment(augS, ds.getLeftOp(), i)) {
// cant create shortcut since we dont have all necessary
// initializations
if (DEBUG) {
System.out.println("Out of order assignment aborting attempt");
}
success = false;
break;
} else {
if (DEBUG) {
System.out.println("Assignment stmt in order adding to array");
}
// the augS is the next assignment in the sequence add to
// ValueBox array
array[i] = ((DefinitionStmt) augS).getRightOpBox();
toRemove.add(aug);
}
} // end checking for 1D pattern
if (success) {
DArrayInitExpr tempExpr = new DArrayInitExpr(array, arrayType);
DArrayInitValueBox tempValueBox = new DArrayInitValueBox(tempExpr);
DAssignStmt newStmt = new DAssignStmt(ds.getLeftOpBox(), tempValueBox);
// cant do array initialization without declaration being part
// of the stmt!!!!!
// have to prove that this array is never utilized before i.e.
// from start of method to this point there is no use
// or def of this array then only can we create this decl/init
// stmt
if (DEBUG) {
System.out.println("Created new DAssignStmt and replacing it");
}
InitializationDeclarationShortcut shortcutChecker = new InitializationDeclarationShortcut(as);
methodNode.apply(shortcutChecker);
boolean possible = shortcutChecker.isShortcutPossible();
if (possible) {
if (DEBUG) {
System.out.println("Shortcut is possible");
}
// create shortcut stmt
DShortcutAssignStmt newShortcutStmt = new DShortcutAssignStmt(newStmt, arrayType);
as.set_Stmt(newShortcutStmt);
// make sure to mark the local in the DVariableDeclarations
// so that its not printed
markLocal(ds.getLeftOp());
}
break;
}
} // end going through stmt seq node
if (success) {
// means we did a transformation remove the stmts
List<AugmentedStmt> newStmtList = new ArrayList<AugmentedStmt>();
for (AugmentedStmt as : node.getStatements()) {
if (toRemove.contains(as)) {
toRemove.remove(as);
} else {
newStmtList.add(as);
}
}
node.setStatements(newStmtList);
// make sure any other possible simplifications are done
inASTStatementSequenceNode(node);
G.v().ASTTransformations_modified = true;
}
// try the second pattern also
secondPattern(node);
}
/*
* Check that s is a definition stmt which assigns to array leftOp and index location index
*/
public boolean isInSequenceAssignment(Stmt s, Value leftOp, int index) {
// DEBUG=false;
if (!(s instanceof DefinitionStmt)) {
return false;
}
DefinitionStmt ds = (DefinitionStmt) s;
Value leftValue = ds.getLeftOp();
if (!(leftValue instanceof ArrayRef)) {
return false;
}
if (DEBUG) {
System.out.println("Stmt number " + index + " is an array ref assignment" + leftValue);
System.out.println("Array is" + leftOp);
}
ArrayRef leftRef = (ArrayRef) leftValue;
if (!(leftOp.equals(leftRef.getBase()))) {
if (DEBUG) {
System.out.println("Not assigning to same array");
}
return false;
}
if (!(leftRef.getIndex() instanceof IntConstant)) {
if (DEBUG) {
System.out.println("Cant determine index of assignment");
}
return false;
}
IntConstant leftIndex = (IntConstant) leftRef.getIndex();
if (leftIndex.value != index) {
if (DEBUG) {
System.out.println("Out of order assignment");
}
return false;
}
return true;
}
/*
* Maybe its a multi-D array then we need to look for a DAssignStmt followed by a definition Stmt
*/
public void secondPattern(ASTStatementSequenceNode node) {
boolean success = false;
ArrayList<AugmentedStmt> toRemove = new ArrayList<AugmentedStmt>();
for (AugmentedStmt as : node.getStatements()) {
success = false;
Stmt s = as.get_Stmt();
if (!(s instanceof DefinitionStmt)) {
continue;
}
DefinitionStmt ds = (DefinitionStmt) s;
ValueBox right = ds.getRightOpBox();
Value rightValue = right.getValue();
if (!(rightValue instanceof NewArrayExpr)) {
continue;
}
if (DEBUG) {
System.out.println("Found a new ArrayExpr" + rightValue);
System.out.println("Type of array is:" + rightValue.getType());
}
// get type out
Type arrayType = rightValue.getType();
// get size....need to know this statically for sure!!!
Value size = ((NewArrayExpr) rightValue).getSize();
if (!(size instanceof IntConstant)) {
continue;
}
if (((IntConstant) size).value == 0) {
debug("Found value to be 0 doing nothing");
continue;
}
if (DEBUG) {
System.out.println("Size of array is: " + ((IntConstant) size).value);
}
Iterator<AugmentedStmt> tempIt = node.getStatements().iterator();
// get to the array creation stmt
while (tempIt.hasNext()) {
AugmentedStmt tempAs = (AugmentedStmt) tempIt.next();
Stmt tempS = tempAs.get_Stmt();
if (tempS.equals(s)) {
break;
}
}
// have the size have the type, tempIt is poised at the current def
// stmt
ValueBox[] array = new ValueBox[((IntConstant) size).value];
success = true;
for (int i = 0; i < ((IntConstant) size).value; i++) {
// check for each iteration there is one DAssignStmt followed by
// a DefinitionStmt
if (!tempIt.hasNext()) {
// since its end of the stmt seq node just return
if (DEBUG) {
System.out.println("returning");
}
return;
}
AugmentedStmt augOne = tempIt.next();
Stmt augSOne = augOne.get_Stmt();
if (!tempIt.hasNext()) {
// since its end of the stmt seq node just return
if (DEBUG) {
System.out.println("returning");
}
return;
}
AugmentedStmt augTwo = tempIt.next();
Stmt augSTwo = augTwo.get_Stmt();
if (!isInSequenceAssignmentPatternTwo(augSOne, augSTwo, ds.getLeftOp(), i)) {
// cant create shortcut since we dont have all necessary
// initializations
if (DEBUG) {
System.out.println("Out of order assignment aborting attempt");
}
success = false;
break;
} else {
if (DEBUG) {
System.out.println("Assignment stmt in order adding to array");
}
// the RHS of augSOne is the next assignment in the sequence
// add to ValueBox array
array[i] = ((DShortcutAssignStmt) augSOne).getRightOpBox();
toRemove.add(augOne);
toRemove.add(augTwo);
}
} // end checking for 1D pattern
if (success) {
DArrayInitExpr tempExpr = new DArrayInitExpr(array, arrayType);
DArrayInitValueBox tempValueBox = new DArrayInitValueBox(tempExpr);
DAssignStmt newStmt = new DAssignStmt(ds.getLeftOpBox(), tempValueBox);
// cant do array initialization without declaration being part
// of the stmt!!!!!
// have to prove that this array is never utilized before i.e.
// from start of method to this point there is no use
// or def of this array then only can we create this decl/init
// stmt
if (DEBUG) {
System.out.println("Created new DAssignStmt and replacing it");
}
InitializationDeclarationShortcut shortcutChecker = new InitializationDeclarationShortcut(as);
methodNode.apply(shortcutChecker);
boolean possible = shortcutChecker.isShortcutPossible();
if (possible) {
if (DEBUG) {
System.out.println("Shortcut is possible");
}
// create shortcut stmt
DShortcutAssignStmt newShortcutStmt = new DShortcutAssignStmt(newStmt, arrayType);
as.set_Stmt(newShortcutStmt);
// make sure to mark the local in the DVariableDeclarations
// so that its not printed
markLocal(ds.getLeftOp());
}
break;
}
} // end going through stmt seq node
if (success) {
// means we did a transformation remove the stmts
List<AugmentedStmt> newStmtList = new ArrayList<AugmentedStmt>();
for (AugmentedStmt as : node.getStatements()) {
if (toRemove.contains(as)) {
toRemove.remove(as);
} else {
newStmtList.add(as);
}
}
node.setStatements(newStmtList);
// make sure any other possible simplifications are done
inASTStatementSequenceNode(node);
G.v().ASTTransformations_modified = true;
}
}
/*
* Check that one is a definition stmt which declares an array Check that two is a definition of leftOp at index location
*/
public boolean isInSequenceAssignmentPatternTwo(Stmt one, Stmt two, Value leftOp, int index) {
if (!(two instanceof DefinitionStmt)) {
return false;
}
DefinitionStmt ds = (DefinitionStmt) two;
Value leftValue = ds.getLeftOp();
if (!(leftValue instanceof ArrayRef)) {
return false;
}
ArrayRef leftRef = (ArrayRef) leftValue;
if (!(leftOp.equals(leftRef.getBase()))) {
if (DEBUG) {
System.out.println("Not assigning to same array");
}
return false;
}
if (!(leftRef.getIndex() instanceof IntConstant)) {
if (DEBUG) {
System.out.println("Cant determine index of assignment");
}
return false;
}
IntConstant leftIndex = (IntConstant) leftRef.getIndex();
if (leftIndex.value != index) {
if (DEBUG) {
System.out.println("Out of order assignment");
}
return false;
}
Value rightOp = ds.getRightOp();
if (!(one instanceof DShortcutAssignStmt)) {
return false;
}
DShortcutAssignStmt shortcut = (DShortcutAssignStmt) one;
Value shortcutVar = shortcut.getLeftOp();
if (!shortcutVar.equals(rightOp)) {
return false;
}
return true;
}
// This local is declared using a shortcut declaration hence needs to be
// somehow removed from the declared locals list
// actually all that is needed is that this localnot be printed there! it
// might be a good
// idea to keep the local stored there since other analyses use that as the
// list of all
// declared locals in the method
public void markLocal(Value shortcutLocal) {
if (!(shortcutLocal instanceof Local)) {
throw new DecompilationException("Found non local. report to developer.");
}
methodNode.addToDontPrintLocalsList((Local) shortcutLocal);
}
}
| 15,343
| 30.768116
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/ShortcutIfGenerator.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 soot.BooleanType;
import soot.IntType;
import soot.Type;
import soot.Value;
import soot.ValueBox;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DShortcutIf;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.CastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.IntConstant;
import soot.jimple.Stmt;
import soot.jimple.internal.ImmediateBox;
public class ShortcutIfGenerator extends DepthFirstAdapter {
public ShortcutIfGenerator() {
}
public ShortcutIfGenerator(boolean verbose) {
super(verbose);
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
if (!(s instanceof DefinitionStmt)) {
continue;
}
DefinitionStmt ds = (DefinitionStmt) s;
ValueBox rightBox = ds.getRightOpBox();
Value right = rightBox.getValue();
/*
* Going to match int i = (int) z where z is a boolean or int i= z i.e. without the cast
*/
// right type should contain the expected type on the left
// in the case of the cast this is the cast type else just get the left type
Type rightType = null;
ValueBox OpBox = null;
if (right instanceof CastExpr) {
rightType = ((CastExpr) right).getCastType();
OpBox = ((CastExpr) right).getOpBox();
} else {
rightType = ds.getLeftOp().getType();
OpBox = rightBox;
}
if (!(rightType instanceof IntType)) {
continue;
}
Value Op = OpBox.getValue();
if (!(Op.getType() instanceof BooleanType)) {
continue;
}
// ready for the switch
ImmediateBox trueBox = new ImmediateBox(IntConstant.v(1));
ImmediateBox falseBox = new ImmediateBox(IntConstant.v(0));
DShortcutIf shortcut = new DShortcutIf(OpBox, trueBox, falseBox);
if (DEBUG) {
System.out.println("created: " + shortcut);
}
rightBox.setValue(shortcut);
}
}
}
| 2,993
| 28.643564
| 94
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/SimplifyConditions.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 soot.BooleanType;
import soot.Value;
import soot.dava.internal.AST.ASTAggregatedCondition;
import soot.dava.internal.AST.ASTAndCondition;
import soot.dava.internal.AST.ASTBinaryCondition;
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.ASTOrCondition;
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.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
/*
* 5 == 5 true DONE
* 5 != 5 false DONE (all other relational operators done)
*
* !true --> false DONE
* !false --> true DONE
*
* DONE WHEN one or both are constants (did all combinations)
* true || b ----> true
* true && b -----> b
* false || b -----> b
* false && b -------> false
*
* if ( (z0 && z1) || ( ! ( ! (z2) || ! (z3)) ) )
* ---> if ( (z0 && z1) || (z2 && z3) ) DONE
*
*
*
* TODO currently only doing primtype comparison of same types not handled are following types
* long <= int
* int <=long
* bla bla
*
*
* TODO IDEA if(io==0 && io==0) --> if(io==0)
*/
public class SimplifyConditions extends DepthFirstAdapter {
public static boolean DEBUG = false;
public boolean changed = false;
public SimplifyConditions() {
super();
}
public SimplifyConditions(boolean verbose) {
super(verbose);
}
public void fixedPoint(ASTControlFlowNode node) {
ASTCondition returned;
do {
if (DEBUG) {
System.out.println("Invoking simplify");
}
changed = false;
ASTCondition cond = node.get_Condition();
returned = simplifyTheCondition(cond);
if (returned != null) {
node.set_Condition(returned);
}
} while (changed);
}
public void outASTIfNode(ASTIfNode node) {
fixedPoint(node);
}
public void outASTIfElseNode(ASTIfElseNode node) {
fixedPoint(node);
}
public void outASTWhileNode(ASTWhileNode node) {
fixedPoint(node);
}
public void outASTDoWhileNode(ASTDoWhileNode node) {
fixedPoint(node);
}
public void outASTForLoopNode(ASTForLoopNode node) {
fixedPoint(node);
}
/*
* !z0 && !z1 ----> !(z0 || z1) !z0 || !z1 ----> !(z0 && z1)
*
* Send null if no change else send new condition CONDITION
*/
public ASTCondition applyDeMorgans(ASTAggregatedCondition aggCond) {
ASTCondition left = aggCond.getLeftOp();
ASTCondition right = aggCond.getRightOp();
if (aggCond.isNotted() && left instanceof ASTBinaryCondition && right instanceof ASTBinaryCondition) {
// we can remove the not sign by simply flipping the two conditions
// ! ( x==y && a<b )
left.flip();
right.flip();
if (aggCond instanceof ASTAndCondition) {
aggCond = new ASTOrCondition(left, right);
} else {
aggCond = new ASTAndCondition(left, right);
}
return aggCond;
}
if ((left.isNotted() && right.isNotted()
&& (!(left instanceof ASTBinaryCondition) && !(right instanceof ASTBinaryCondition)))
|| (left.isNotted() && aggCond.isNotted() && !(left instanceof ASTBinaryCondition))
|| (right.isNotted() && aggCond.isNotted() && !(right instanceof ASTBinaryCondition))) {
// both are notted and atleast one is not a binaryCondition
left.flip();
right.flip();
ASTAggregatedCondition newCond;
if (aggCond instanceof ASTAndCondition) {
newCond = new ASTOrCondition(left, right);
} else {
newCond = new ASTAndCondition(left, right);
}
if (aggCond.isNotted()) {
return newCond;
} else {
newCond.flip();
return newCond;
}
}
return null;
}
/*
* When this method is invoked we are sure that there are no occurences of !true or !false since this is AFTER doing depth
* first of the children so the unaryCondition must have simplified the above
*
* Return Null if no change else return changed condition
*/
public ASTCondition simplifyIfAtleastOneConstant(ASTAggregatedCondition aggCond) {
ASTCondition left = aggCond.getLeftOp();
ASTCondition right = aggCond.getRightOp();
Boolean leftBool = null;
Boolean rightBool = null;
if (left instanceof ASTUnaryCondition) {
leftBool = isBooleanConstant(((ASTUnaryCondition) left).getValue());
}
if (right instanceof ASTUnaryCondition) {
rightBool = isBooleanConstant(((ASTUnaryCondition) right).getValue());
}
/*
* a && b NOCHANGE DONE b && a NOCHANGE DONE
*
* a || b NOCHANGE DONE b || a NOCHANGE DONE
*
*/
if (leftBool == null && rightBool == null) {
// meaning both are not constants
return null;
}
if (aggCond instanceof ASTAndCondition) {
/*
* true && true ---> true DONE true && false --> false DONE false && false ---> false DONE false && true --> false DONE
*
* true && b -----> b DONE false && b -------> false DONE
*
* b && true ---> b DONE b && false ---> b && false (since b could have side effects and the overall condition has to
* be false) DONE
*
*/
if (leftBool != null && rightBool != null) {
// meaning both are constants
if (leftBool.booleanValue() && rightBool.booleanValue()) {
// both are true
return new ASTUnaryCondition(DIntConstant.v(1, BooleanType.v()));
} else {
// atleast one of the two is false
return new ASTUnaryCondition(DIntConstant.v(0, BooleanType.v()));
}
}
if (leftBool != null) {
// implicityly means that rigthBool is null since the above
// condition passed
if (leftBool.booleanValue()) {
// left bool is a true meaning we have to evaluate right
// condition.......just return the right condition
return right;
} else {
// left bool is false meaning no need to continue since we
// will never execute the right condition
// return a unary false
return new ASTUnaryCondition(DIntConstant.v(0, BooleanType.v()));
}
}
if (rightBool != null) {
// implicityly means that the leftBool is null
if (rightBool.booleanValue()) {
// rightBool is true so it all depends on left
return left;
} else {
// although we know the condition overall is false we cant
// remove the leftBool since there might be side effects
return aggCond;
}
}
} else if (aggCond instanceof ASTOrCondition) {
/*
*
* true || false ---> true DONE true || true --> true DONE false || true --> true DONE false || false ---> false DONE
*
*
* true || b ----> true DONE false || b -----> b DONE
*
* b || true ---> b || true .... although we know the condition is true we have to evaluate b because of possible side
* effects DONE b || false ---> b DONE
*
*/
if (leftBool != null && rightBool != null) {
// meaning both are constants
if (!leftBool.booleanValue() && !rightBool.booleanValue()) {
// both are false
return new ASTUnaryCondition(DIntConstant.v(0, BooleanType.v()));
} else {
// atleast one of the two is true
return new ASTUnaryCondition(DIntConstant.v(1, BooleanType.v()));
}
}
if (leftBool != null) {
// implicityly means that rigthBool is null since the above
// condition passed
if (leftBool.booleanValue()) {
// left bool is true that means we will stop evaluation of condition, just return true
return new ASTUnaryCondition(DIntConstant.v(1, BooleanType.v()));
} else {
// left bool is false so we have to continue evaluating right
return right;
}
}
if (rightBool != null) {
// implicityly means that the leftBool is null
if (rightBool.booleanValue()) {
// rightBool is true but leftBool must be evaluated beforehand
return aggCond;
} else {
// rightBool is false so everything depends on left
return left;
}
}
} else {
throw new RuntimeException("Found unknown aggregated condition");
}
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");
}
}
/*
* In a loop keep simplifying the condition as much as possible
*
*/
public ASTCondition simplifyTheCondition(ASTCondition cond) {
if (cond instanceof ASTAggregatedCondition) {
ASTAggregatedCondition aggCond = (ASTAggregatedCondition) cond;
ASTCondition leftCond = simplifyTheCondition(aggCond.getLeftOp());
ASTCondition rightCond = simplifyTheCondition(aggCond.getRightOp());
// if returned values are non null then set leftop /rightop to new condition
if (leftCond != null) {
aggCond.setLeftOp(leftCond);
}
if (rightCond != null) {
aggCond.setRightOp(rightCond);
}
ASTCondition returned = simplifyIfAtleastOneConstant(aggCond);
if (returned != null) {
changed = true;
return returned;
}
returned = applyDeMorgans(aggCond);
if (returned != null) {
changed = true;
return returned;
}
return aggCond;
} else if (cond instanceof ASTUnaryCondition) {
// dont do anything with unary conditions
ASTUnaryCondition unary = (ASTUnaryCondition) cond;
/*
* if unary is a noted constant simplify it !true to be converted to false !false to be converted to true
*/
Value unaryVal = unary.getValue();
if (unaryVal instanceof DNotExpr) {
if (DEBUG) {
System.out.println("Found NotExpr in unary COndition" + unaryVal);
}
DNotExpr notted = (DNotExpr) unaryVal;
Value internal = notted.getOp();
Boolean isIt = isBooleanConstant(internal);
if (isIt != null) {
// is a boolean constant truth value will give whether its true or false
// convert !true to false
if (isIt.booleanValue()) {
// true
if (DEBUG) {
System.out.println("CONVERTED !true to false");
}
changed = true;
return new ASTUnaryCondition(DIntConstant.v(0, BooleanType.v()));
} else if (!isIt.booleanValue()) {
// false
if (DEBUG) {
System.out.println("CONVERTED !false to true");
}
changed = true;
return new ASTUnaryCondition(DIntConstant.v(1, BooleanType.v()));
} else {
throw new RuntimeException("BooleanType found with value different than 0 or 1");
}
} else {
if (DEBUG) {
System.out.println("Not boolean type");
}
}
}
return unary;
} else if (cond instanceof ASTBinaryCondition) {
ASTBinaryCondition binary = (ASTBinaryCondition) cond;
ConditionExpr expr = binary.getConditionExpr();
// returns null if no change
ASTUnaryCondition temp = evaluateBinaryCondition(expr);
if (DEBUG) {
System.out.println("changed binary condition " + cond + " to" + temp);
}
if (temp != null) {
changed = true;
}
return temp;
} else {
throw new RuntimeException("Method getUseList in ASTUsesAndDefs encountered unknown condition type");
}
}
// return condition if was able to simplify (convert to a boolean true or false) else null
public ASTUnaryCondition evaluateBinaryCondition(ConditionExpr expr) {
String symbol = expr.getSymbol();
int op = -1;
if (symbol.indexOf("==") > -1) {
if (DEBUG) {
System.out.println("==");
}
op = 1;
} else if (symbol.indexOf(">=") > -1) {
if (DEBUG) {
System.out.println(">=");
}
op = 2;
} else if (symbol.indexOf('>') > -1) {
if (DEBUG) {
System.out.println(">");
}
op = 3;
} else if (symbol.indexOf("<=") > -1) {
if (DEBUG) {
System.out.println("<=");
}
op = 4;
} else if (symbol.indexOf('<') > -1) {
if (DEBUG) {
System.out.println("<");
}
op = 5;
} else if (symbol.indexOf("!=") > -1) {
if (DEBUG) {
System.out.println("!=");
}
op = 6;
}
Value leftOp = expr.getOp1();
Value rightOp = expr.getOp2();
Boolean result = null;
if (leftOp instanceof LongConstant && rightOp instanceof LongConstant) {
if (DEBUG) {
System.out.println("long constants!!");
}
long left = ((LongConstant) leftOp).value;
long right = ((LongConstant) rightOp).value;
result = longSwitch(op, left, right);
} else if (leftOp instanceof DoubleConstant && rightOp instanceof DoubleConstant) {
double left = ((DoubleConstant) leftOp).value;
double right = ((DoubleConstant) rightOp).value;
result = doubleSwitch(op, left, right);
} else if (leftOp instanceof FloatConstant && rightOp instanceof FloatConstant) {
float left = ((FloatConstant) leftOp).value;
float right = ((FloatConstant) rightOp).value;
result = floatSwitch(op, left, right);
} else if (leftOp instanceof IntConstant && rightOp instanceof IntConstant) {
int left = ((IntConstant) leftOp).value;
int right = ((IntConstant) rightOp).value;
result = intSwitch(op, left, right);
}
if (result != null) {
if (result.booleanValue()) {
return new ASTUnaryCondition(DIntConstant.v(1, BooleanType.v()));
} else {
return new ASTUnaryCondition(DIntConstant.v(0, BooleanType.v()));
}
}
return null;
}
public Boolean longSwitch(int op, long l, long r) {
switch (op) {
case 1:
// ==
if (l == r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 2:
// >=
if (l >= r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 3:
// >
if (l > r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 4:
// <=
if (l <= r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 5:
// <
if (l < r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 6:
// !=
if (l != r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
default:
if (DEBUG) {
System.out.println("got here");
}
return null;
}
}
public Boolean doubleSwitch(int op, double l, double r) {
switch (op) {
case 1:
// ==
if (l == r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 2:
// >=
if (l >= r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 3:
// >
if (l > r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 4:
// <=
if (l <= r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 5:
// <
if (l < r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 6:
// !=
if (l != r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
default:
return null;
}
}
public Boolean floatSwitch(int op, float l, float r) {
switch (op) {
case 1:
// ==
if (l == r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 2:
// >=
if (l >= r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 3:
// >
if (l > r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 4:
// <=
if (l <= r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 5:
// <
if (l < r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 6:
// !=
if (l != r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
default:
return null;
}
}
public Boolean intSwitch(int op, int l, int r) {
switch (op) {
case 1:
// ==
if (l == r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 2:
// >=
if (l >= r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 3:
// >
if (l > r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 4:
// <=
if (l <= r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 5:
// <
if (l < r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
case 6:
// !=
if (l != r) {
return new Boolean(true);
} else {
return new Boolean(false);
}
default:
return null;
}
}
}
| 20,155
| 26.573187
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/SimplifyExpressions.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 soot.Value;
import soot.ValueBox;
import soot.dava.internal.javaRep.DCmpExpr;
import soot.dava.internal.javaRep.DCmpgExpr;
import soot.dava.internal.javaRep.DCmplExpr;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.AddExpr;
import soot.jimple.BinopExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.MulExpr;
import soot.jimple.NumericConstant;
import soot.jimple.SubExpr;
/*
* x = 2+3 should be simplified to x =5
* 4l -3l should be 1l DONE
* Unary Condition:DONT NEED TO HANDLE IT since what would simplify
* in a boolean flag which is what unary conditions are
*
* Binary Codition: has a ConditionExpr stored in it not a valuebox???
* all other expression to be handled by caseExprOrRefValueBox
*/
public class SimplifyExpressions extends DepthFirstAdapter {
public static boolean DEBUG = false;
public SimplifyExpressions() {
super();
}
public SimplifyExpressions(boolean verbose) {
super(verbose);
}
/*
* public void inASTBinaryCondition(ASTBinaryCondition cond){ ConditionExpr condExpr = cond.getConditionExpr();
*
* ValueBox op1Box = condExpr.getOp1Box();
*
* ValueBox op2Box = condExpr.getOp2Box(); }
*/
public void outExprOrRefValueBox(ValueBox vb) {
// System.out.println("here"+vb);
Value v = vb.getValue();
if (!(v instanceof BinopExpr)) {
return;
}
BinopExpr binop = (BinopExpr) v;
if (DEBUG) {
System.out.println("calling getResult");
}
NumericConstant constant = getResult(binop);
if (constant == null) {
return;
}
if (DEBUG) {
System.out.println("Changin" + vb + " to...." + constant);
}
vb.setValue(constant);
}
public NumericConstant getResult(BinopExpr binop) {
if (DEBUG) {
System.out.println("Binop expr" + binop);
}
Value leftOp = binop.getOp1();
Value rightOp = binop.getOp2();
int op = 0;
if (binop instanceof AddExpr) {
op = 1;
} else if (binop instanceof SubExpr || binop instanceof DCmpExpr || binop instanceof DCmpgExpr
|| binop instanceof DCmplExpr) {
op = 2;
} else if (binop instanceof MulExpr) {
op = 3;
}
if (op == 0) {
if (DEBUG) {
System.out.println("not add sub or mult");
System.out.println(binop.getClass().getName());
}
return null;
}
NumericConstant constant = null;
if (leftOp instanceof LongConstant && rightOp instanceof LongConstant) {
if (DEBUG) {
System.out.println("long constants!!");
}
if (op == 1) {
constant = ((LongConstant) leftOp).add((LongConstant) rightOp);
} else if (op == 2) {
constant = ((LongConstant) leftOp).subtract((LongConstant) rightOp);
} else if (op == 3) {
constant = ((LongConstant) leftOp).multiply((LongConstant) rightOp);
}
} else if (leftOp instanceof DoubleConstant && rightOp instanceof DoubleConstant) {
if (DEBUG) {
System.out.println("double constants!!");
}
if (op == 1) {
constant = ((DoubleConstant) leftOp).add((DoubleConstant) rightOp);
} else if (op == 2) {
constant = ((DoubleConstant) leftOp).subtract((DoubleConstant) rightOp);
} else if (op == 3) {
constant = ((DoubleConstant) leftOp).multiply((DoubleConstant) rightOp);
}
} else if (leftOp instanceof FloatConstant && rightOp instanceof FloatConstant) {
if (DEBUG) {
System.out.println("Float constants!!");
}
if (op == 1) {
constant = ((FloatConstant) leftOp).add((FloatConstant) rightOp);
} else if (op == 2) {
constant = ((FloatConstant) leftOp).subtract((FloatConstant) rightOp);
} else if (op == 3) {
constant = ((FloatConstant) leftOp).multiply((FloatConstant) rightOp);
}
} else if (leftOp instanceof IntConstant && rightOp instanceof IntConstant) {
if (DEBUG) {
System.out.println("Integer constants!!");
}
if (op == 1) {
constant = ((IntConstant) leftOp).add((IntConstant) rightOp);
} else if (op == 2) {
constant = ((IntConstant) leftOp).subtract((IntConstant) rightOp);
} else if (op == 3) {
constant = ((IntConstant) leftOp).multiply((IntConstant) rightOp);
}
}
return constant;
}
}
| 5,314
| 30.449704
| 113
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/StrengthenByIf.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.ASTAndCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTDoWhileNode;
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.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.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
public class StrengthenByIf {
/*
* We know this method is called when there is a while node which has a body consisting entirely of one ASTIfNode
*/
public static List<ASTNode> getNewNode(ASTNode loopNode, ASTIfNode ifNode) {
List<Object> ifBody = ifNode.getIfBody();
String label = isItOnlyBreak(ifBody);
if (label != null) {
// only one break statement and it is breaking some label
// make sure its breaking the label on the loop
if (((ASTLabeledNode) loopNode).get_Label().toString() != null) {
if (((ASTLabeledNode) loopNode).get_Label().toString().compareTo(label) == 0) {
// the if has a single break breaking the loop
// pattern 1 matched
if (loopNode instanceof ASTWhileNode) {
ASTCondition outerCond = ((ASTWhileNode) loopNode).get_Condition();
// flip the inner condition
ASTCondition innerCond = ifNode.get_Condition();
innerCond.flip();
// aggregate the two conditions
ASTCondition newCond = new ASTAndCondition(outerCond, innerCond);
// make empty body
List<Object> newWhileBody = new ArrayList<Object>();
// SETNodeLabel newLabel =
// ((ASTWhileNode)loopNode).get_Label();
// dont need any label name since the body of the while
// is empty
SETNodeLabel newLabel = new SETNodeLabel();
// make new ASTWhileNode
List<ASTNode> toReturn = new ArrayList<ASTNode>();
toReturn.add(new ASTWhileNode(newLabel, newCond, newWhileBody));
return toReturn;
} else if (loopNode instanceof ASTDoWhileNode) {
/*
* What to do when the ASTDoWhileNode only has one body which is a break of the whileNode???
*/
return null;
} else if (loopNode instanceof ASTUnconditionalLoopNode) {
/*
* An UnconditionalLoopNode has a single If Condition which breaks the loop In this case Create an ASTWhileLoop
* Node with the flipped Condition of the If statement
*/
// flip the inner condition
ASTCondition innerCond = ifNode.get_Condition();
innerCond.flip();
// make empty body
List<Object> newWhileBody = new ArrayList<Object>();
// SETNodeLabel newLabel =
// ((ASTUnconditionalLoopNode)loopNode).get_Label();
// dont need any label name since the body of the while
// is empty
SETNodeLabel newLabel = new SETNodeLabel();
// make new ASTWhileNode
List<ASTNode> toReturn = new ArrayList<ASTNode>();
toReturn.add(new ASTWhileNode(newLabel, innerCond, newWhileBody));
return toReturn;
}
} // if the labels match
}
} // the first Pattern was a match
else if (loopNode instanceof ASTUnconditionalLoopNode && ifBody.size() == 1) {
// try the UnconditionalLoopNode pattern
// we need one stmtSeq Node
ASTNode tempNode = (ASTNode) ifBody.get(0);
if (tempNode instanceof ASTStatementSequenceNode) {
// a stmtSeq
List<AugmentedStmt> statements = ((ASTStatementSequenceNode) tempNode).getStatements();
Iterator<AugmentedStmt> stIt = statements.iterator();
while (stIt.hasNext()) {
AugmentedStmt as = stIt.next();
Stmt stmt = as.get_Stmt();
if (stmt instanceof DAbruptStmt && !(stIt.hasNext())) {
// this is an abrupt stmt and the last stmt
DAbruptStmt abStmt = (DAbruptStmt) stmt;
if (abStmt.is_Break()) {
// last statement and that too a break
String loopLabel = ((ASTLabeledNode) loopNode).get_Label().toString();
String breakLabel = abStmt.getLabel().toString();
if (loopLabel != null && breakLabel != null) {
if (loopLabel.compareTo(breakLabel) == 0) {
// pattern matched
// flip the inner condition
ASTCondition innerCond = ifNode.get_Condition();
innerCond.flip();
// make empty body
List<Object> newWhileBody = new ArrayList<Object>();
SETNodeLabel newLabel = ((ASTUnconditionalLoopNode) loopNode).get_Label();
// make new ASTWhileNode
List<ASTNode> toReturn = new ArrayList<ASTNode>();
toReturn.add(new ASTWhileNode(newLabel, innerCond, newWhileBody));
// Add the statementSequenceNode AFTER the
// whileNode except for the laststmt
Iterator<AugmentedStmt> tempIt = statements.iterator();
List<AugmentedStmt> newStmts = new ArrayList<AugmentedStmt>();
while (tempIt.hasNext()) {
AugmentedStmt tempStmt = tempIt.next();
if (tempIt.hasNext()) {
newStmts.add(tempStmt);
}
}
toReturn.add(new ASTStatementSequenceNode(newStmts));
return toReturn;
} // labels are the same
} // labels are non null
} // is a break stmt
} else if (stmt instanceof ReturnStmt || stmt instanceof ReturnVoidStmt) {
if (!(stIt.hasNext())) {
// return obj/return;
// flip cond
ASTCondition innerCond = ifNode.get_Condition();
innerCond.flip();
// make empty body
List<Object> newWhileBody = new ArrayList<Object>();
// SETNodeLabel newLabel =
// ((ASTUnconditionalLoopNode)loopNode).get_Label();
// dont need any label name since the body of the
// while is empty
SETNodeLabel newLabel = new SETNodeLabel();
// make new ASTWhileNode
List<ASTNode> toReturn = new ArrayList<ASTNode>();
toReturn.add(new ASTWhileNode(newLabel, innerCond, newWhileBody));
// Add the statementSequenceNode AFTER the whileNode
// except for the laststmt
Iterator<AugmentedStmt> tempIt = statements.iterator();
List<AugmentedStmt> newStmts = new ArrayList<AugmentedStmt>();
while (tempIt.hasNext()) {
newStmts.add(tempIt.next());
}
toReturn.add(new ASTStatementSequenceNode(newStmts));
return toReturn;
}
}
} // end of going through statements
} // end of stmtSEq node
} // end of else if
return null;
} // end of method
/*
* Given a body of a node the method checks for the following: 1, the body has only one node 2, the node is a
* statementSequenceNode 3, There is only one statement in the stmt seq node 4, the stmt is a break stmt
*
* If the conditions are true the label of the break stmt is returned otherwise null is returned
*/
private static String isItOnlyBreak(List<Object> body) {
if (body.size() != 1) {
// this is more than one we need one stmtSeq Node
return null;
}
ASTNode tempNode = (ASTNode) body.get(0);
if (!(tempNode instanceof ASTStatementSequenceNode)) {
// not a stmtSeq
return null;
}
List<AugmentedStmt> statements = ((ASTStatementSequenceNode) tempNode).getStatements();
if (statements.size() != 1) {
// we need one break
return null;
}
AugmentedStmt as = statements.get(0);
Stmt stmt = as.get_Stmt();
if (!(stmt instanceof DAbruptStmt)) {
// this is not a break stmt
return null;
}
DAbruptStmt abStmt = (DAbruptStmt) stmt;
if (!(abStmt.is_Break())) {
// we need a break
return null;
}
return abStmt.getLabel().toString();
}
}
| 9,569
| 39.210084
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/StrengthenByIfElse.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.ASTAndCondition;
import soot.dava.internal.AST.ASTCondition;
import soot.dava.internal.AST.ASTIfElseNode;
import soot.dava.internal.AST.ASTLabeledNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
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.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
/*
Nomair A. Naeem 18-FEB-2005
PATTERN ONE:
label_1:
while(cond1){ label_1:
if(cond2){ while(cond1 && cond2){
Body 1 Body1
} }
else{
break label_1
}
}
The important thing is that Body2 should contain an abrupt
edge out of the while loop. If Body2 is just a break and nothing
else the body2 in the transformed version is empty
PATTERN TWO:
label_1:
while(true){ label_1:
if(cond2){ while(cond2){
Body 1 Body1
} }
else{ Body2
Body 2
}
}
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
*/
public class StrengthenByIfElse {
/*
* We know this method is called when there is a loop node which has a body consisting entirely of one ASTIfElseNode
*/
public static List<ASTNode> getNewNode(ASTNode loopNode, ASTIfElseNode ifElseNode) {
// make sure that elsebody has only a stmtseq node
List<Object> elseBody = (ifElseNode).getElseBody();
if (elseBody.size() != 1) {
// this is more than one we need one stmtSeq Node
return null;
}
ASTNode tempNode = (ASTNode) elseBody.get(0);
if (!(tempNode instanceof ASTStatementSequenceNode)) {
// not a stmtSeq
return null;
}
List<AugmentedStmt> statements = ((ASTStatementSequenceNode) tempNode).getStatements();
Iterator<AugmentedStmt> stmtIt = statements.iterator();
while (stmtIt.hasNext()) {
AugmentedStmt as = stmtIt.next();
Stmt stmt = as.get_Stmt();
if (stmt instanceof DAbruptStmt) {
// this is a abrupt stmt
DAbruptStmt abStmt = (DAbruptStmt) stmt;
if (!(abStmt.is_Break())) {
// we need a break
return null;
} else {
if (stmtIt.hasNext()) {
// a break should be the last stmt
return null;
}
SETNodeLabel label = abStmt.getLabel();
String labelBroken = label.toString();
String loopLabel = ((ASTLabeledNode) loopNode).get_Label().toString();
if (labelBroken != null && loopLabel != null) {
// stmt
// breaks
// some
// label
if (labelBroken.compareTo(loopLabel) == 0) {
// we have found a break breaking this label
// make sure that if the orignal was an ASTWhileNode
// then there was
// ONLY a break statement
if (loopNode instanceof ASTWhileNode) {
if (statements.size() != 1) {
// more than 1 statement
return null;
}
}
// pattern matched
ASTWhileNode newWhileNode = makeWhileNode(ifElseNode, loopNode);
if (newWhileNode == null) {
return null;
}
List<ASTNode> toReturn = new ArrayList<ASTNode>();
toReturn.add(newWhileNode);
// Add the statementSequenceNode AFTER the whileNode
// except for the laststmt
if (statements.size() != 1) {
// size 1 means that the only stmt is a break
// stmt
Iterator<AugmentedStmt> tempIt = statements.iterator();
List<AugmentedStmt> newStmts = new ArrayList<AugmentedStmt>();
while (tempIt.hasNext()) {
AugmentedStmt tempStmt = tempIt.next();
if (tempIt.hasNext()) {
newStmts.add(tempStmt);
}
}
toReturn.add(new ASTStatementSequenceNode(newStmts));
}
return toReturn;
} // labels matched
} // non null labels
} // end of break stmt
} // stmt is an abrupt stmt
else if (stmt instanceof ReturnStmt || stmt instanceof ReturnVoidStmt) {
if (!(loopNode instanceof ASTUnconditionalLoopNode)) {
// this pattern is only possible for while(true)
return null;
}
if (stmtIt.hasNext()) {
// returns should come in the end
return null;
}
// pattern matched
ASTWhileNode newWhileNode = makeWhileNode(ifElseNode, loopNode);
if (newWhileNode == null) {
return null;
}
List<ASTNode> toReturn = new ArrayList<ASTNode>();
toReturn.add(newWhileNode);
// Add the statementSequenceNode AFTER the whileNode
List<AugmentedStmt> newStmts = new ArrayList<AugmentedStmt>(statements);
toReturn.add(new ASTStatementSequenceNode(newStmts));
return toReturn;
} // if stmt was a return stmt
} // going through the stmts
return null;
} // end of method
private static ASTWhileNode makeWhileNode(ASTIfElseNode ifElseNode, ASTNode loopNode) {
ASTCondition outerCond = null;
ASTCondition innerCond = ifElseNode.get_Condition();
ASTCondition newCond = null;
if (loopNode instanceof ASTWhileNode) {
outerCond = ((ASTWhileNode) loopNode).get_Condition();
newCond = new ASTAndCondition(outerCond, innerCond);
} else if (loopNode instanceof ASTUnconditionalLoopNode) {
newCond = innerCond;
} else {
// not dealing with the case of ASTDoWhileNode
return null;
}
List<Object> loopBody = ifElseNode.getIfBody();
SETNodeLabel newLabel = ((ASTLabeledNode) loopNode).get_Label();
// make new ASTWhileNode
return new ASTWhileNode(newLabel, newCond, loopBody);
}
} // end class
| 7,454
| 34
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/SuperFirstStmtHandler.java
|
package soot.dava.toolkits.base.AST.transformations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 - 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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.G;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.ShortType;
import soot.SootClass;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.VoidType;
import soot.dava.CorruptASTException;
import soot.dava.Dava;
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.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DIntConstant;
import soot.dava.internal.javaRep.DNewInvokeExpr;
import soot.dava.internal.javaRep.DSpecialInvokeExpr;
import soot.dava.internal.javaRep.DStaticInvokeExpr;
import soot.dava.internal.javaRep.DVariableDeclarationStmt;
import soot.dava.internal.javaRep.DVirtualInvokeExpr;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.dava.toolkits.base.AST.traversals.ASTParentNodeFinder;
import soot.dava.toolkits.base.AST.traversals.ASTUsesAndDefs;
import soot.dava.toolkits.base.AST.traversals.AllDefinitionsFinder;
import soot.grimp.internal.GAssignStmt;
import soot.grimp.internal.GCastExpr;
import soot.grimp.internal.GInvokeStmt;
import soot.grimp.internal.GReturnStmt;
import soot.jimple.DefinitionStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.internal.JimpleLocal;
public class SuperFirstStmtHandler extends DepthFirstAdapter {
public final boolean DEBUG = false;
ASTMethodNode originalASTMethod; // contains the entire method which was
// being decompiled
DavaBody originalDavaBody; // originalASTMethod.getDavaBody
Unit originalConstructorUnit; // contains this.init<>
InstanceInvokeExpr originalConstructorExpr; // contains the expr within the
// ConstructorUni
SootMethod originalSootMethod; // originalDavaBody.getMethod();
SootClass originalSootClass; // originalSootMethod.getDeclaringClass();
Map originalPMap;
List argsOneTypes = null; // initialized to the ParameterTypes of the
// original method
List argsOneValues = null; // initialized to the values of these parameters
// of the original method
List argsTwoValues = null; // initialized to the Parameter values of the
// call to super
List argsTwoTypes = null; // initialized to the ParameterTypes of the call
// to super
// PreInit fields
SootMethod newSootPreInitMethod = null;// only initialized by createMethod
DavaBody newPreInitDavaBody = null; // only initialized by createMethod
ASTMethodNode newASTPreInitMethod = null; // only initialized by
// createNewASTPreInitMethod
// Constructor fields
SootMethod newConstructor = null; // initialized by createNewConstructor
DavaBody newConstructorDavaBody = null; // initialized by
// createNewConstructor
ASTMethodNode newASTConstructorMethod = null; // only initialized by
// createNewASTConstructor
List<Local> mustInitialize;
int mustInitializeIndex = 0;
public SuperFirstStmtHandler(ASTMethodNode AST) {
this.originalASTMethod = AST;
initialize();
}
public SuperFirstStmtHandler(boolean verbose, ASTMethodNode AST) {
super(verbose);
this.originalASTMethod = AST;
initialize();
}
public void initialize() {
originalDavaBody = originalASTMethod.getDavaBody();
originalConstructorUnit = originalDavaBody.get_ConstructorUnit();
originalConstructorExpr = originalDavaBody.get_ConstructorExpr();
if (originalConstructorExpr != null) {
// should get the values and the types of these into lists for later
// use
argsTwoValues = originalConstructorExpr.getArgs();
argsTwoTypes = new ArrayList();
// get also the types of these args
Iterator valIt = argsTwoValues.iterator();
while (valIt.hasNext()) {
Value val = (Value) valIt.next();
Type type = val.getType();
argsTwoTypes.add(type);
}
}
originalSootMethod = originalDavaBody.getMethod();
originalSootClass = originalSootMethod.getDeclaringClass();
originalPMap = originalDavaBody.get_ParamMap();
argsOneTypes = originalSootMethod.getParameterTypes();
// initialize argsOneValues
argsOneValues = new ArrayList();
Iterator typeIt = argsOneTypes.iterator();
int count = 0;
while (typeIt.hasNext()) {
Type t = (Type) typeIt.next();
argsOneValues.add(originalPMap.get(new Integer(count)));
count++;
}
}
/*
* looking for an init stmt
*/
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
for (AugmentedStmt as : node.getStatements()) {
Unit u = as.get_Stmt();
if (u == originalConstructorUnit) {
// System.out.println("Found the constructorUnit"+u);
// ONE: make sure the parent of the super() call is an
// ASTMethodNode
ASTParentNodeFinder parentFinder = new ASTParentNodeFinder();
originalASTMethod.apply(parentFinder);
Object tempParent = parentFinder.getParentOf(node);
if (tempParent != originalASTMethod) {
// System.out.println("ASTMethod node is not the parent of
// constructorUnit");
// notice since we cant remove one call of super there is no
// point
// in trying to remove any other calls to super
removeInit();
return;
}
// only gets here if the call to super is not nested within some
// other construct
/**********************************************************/
/****************** CREATING PREINIT METHOD ***************/
/**********************************************************/
// CREATE UNIQUE METHOD
createSootPreInitMethod(); // new method is initalized in
// newSootPreInitMethod
// Create ASTMethodNode for this SootMethod
createNewASTPreInitMethod(node); // the field
// newASTPreInitMethod is
// initialized
// newASTPreInitMethod should be non null if we can go ahead
if (newASTPreInitMethod == null) {
// could not create ASTMethodNode for some reason or the
// other
// just silently return
// System.out.println(">>>>>>>>>>>>>>>>Couldnt not create
// ASTMethodNode for the new PreInitMethod");
removeInit();
return;
}
if (!finalizePreInitMethod()) {
// shouldnt be creating PreInit
// System.out.println(">>>>>>>>>>>>>>SHOULDNT BE CREATING
// PREINIT");
removeInit();
return;
}
/**********************************************************/
/************** CREATING NEW CONSTRUCTOR ******************/
/**********************************************************/
// create SootMethod for the constructor
createNewConstructor();
createNewASTConstructor(node);
if (!createCallToSuper()) {
// could not create call to super
// still safe to simply exit
// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>Could not
// create call to super...SuperFirstStmtHandler");
removeInit();
return;
}
finalizeConstructor();
/**********************************************************/
/************** CHANGE ORIGINAL CONSTRUCTOR ***************/
/**********************************************************/
if (changeOriginalAST()) {
// System.out.println("Done Done Done");
debug("SuperFirstStmtHandler....inASTStatementSeuqneNode", "Added PreInit");
G.v().SootMethodAddedByDava = true;
G.v().SootMethodsAdded.add(newSootPreInitMethod);
G.v().SootMethodsAdded.add(newConstructor);
/**********************************************************/
/****************** CREATING INNER CLASS ******************/
/**********************************************************/
// notice that inner class is created by DavaPrinter in the
// printTo method
// all we do is set a Global to true and later on when the
// SootClass is being
// output the inner class will be output also
G.v().SootClassNeedsDavaSuperHandlerClass.add(originalSootClass);
// System.out.println("\n\nSet SootMethodAddedByDava to
// true\n\n");
}
}
}
}
/*
* When we havent created the indirection to take care of super bug be it cos we dont need to or that we CANT cos of some
* limitation....should atleast remove the jimple this.init call from the statements
*/
public void removeInit() {
// remove constructorUnit from originalASTMethod
List<Object> newBody = new ArrayList<Object>();
List<Object> subBody = originalASTMethod.get_SubBodies();
if (subBody.size() != 1) {
return;
}
List oldBody = (List) subBody.get(0);
Iterator oldIt = oldBody.iterator();
while (oldIt.hasNext()) {
// going through each node in the old body
ASTNode node = (ASTNode) oldIt.next();
// copy the node as is unless its an ASTStatementSequence
if (!(node instanceof ASTStatementSequenceNode)) {
newBody.add(node);
continue;
}
// if the node is an ASTStatementSequenceNode
// copy all stmts unless it is a constructorUnit
ASTStatementSequenceNode seqNode = (ASTStatementSequenceNode) node;
List<AugmentedStmt> newStmtList = new ArrayList<AugmentedStmt>();
for (AugmentedStmt augStmt : seqNode.getStatements()) {
Stmt stmtTemp = augStmt.get_Stmt();
if (stmtTemp == originalConstructorUnit) {
// do nothing
} else {
newStmtList.add(augStmt);
}
}
if (newStmtList.size() != 0) {
newBody.add(new ASTStatementSequenceNode(newStmtList));
}
}
originalASTMethod.replaceBody(newBody);
}
/*
* Remove the entire body and replace with the statement this(args1, B.preInit(args1));
*/
public boolean changeOriginalAST() {
// originalDavaBody has to be changed
// fix up the call within the constructorUnit....the args should be
// argsOne followed by a method call to preInit
if (originalConstructorExpr == null) {
// hmm that means there was no call to super in the original code
// System.out.println("originalConstructorExpr is null");
return false;
}
List thisArgList = new ArrayList();
thisArgList.addAll(argsOneValues);
DStaticInvokeExpr newInvokeExpr = new DStaticInvokeExpr(newSootPreInitMethod.makeRef(), argsOneValues);
thisArgList.add(newInvokeExpr);
// the methodRef of themethod to be called is the new constructor we
// created
InstanceInvokeExpr tempExpr
= new DSpecialInvokeExpr(originalConstructorExpr.getBase(), newConstructor.makeRef(), thisArgList);
originalDavaBody.set_ConstructorExpr(tempExpr);
// create Invoke Stmt with tempExpr as the expression
GInvokeStmt s = new GInvokeStmt(tempExpr);
originalDavaBody.set_ConstructorUnit(s);
// originalASTMethod has to be made empty
originalASTMethod.setDeclarations(new ASTStatementSequenceNode(new ArrayList<AugmentedStmt>()));
originalASTMethod.replaceBody(new ArrayList<Object>());
return true;
}
private SootMethodRef makeMethodRef(String methodName, ArrayList args) {
// make MethodRef for methodName
SootMethod method = Scene.v().makeSootMethod(methodName, args, RefType.v("java.lang.Object"));
// set the declaring class of new method to be the DavaSuperHandler
// class
method.setDeclaringClass(new SootClass("DavaSuperHandler"));
return method.makeRef();
}
/*
* super( (CAST-TYPE)handler.get(0), ((CAST-TYPE)handler.get(1)).CONVERSION(), .......);
*
* returns false if we cant create the call to super
*/
private boolean createCallToSuper() {
// check that whether this call is even to be made or not
if (originalConstructorExpr == null) {
// hmm that means there was no call to super in the original code
// System.out.println("originalConstructorExpr is null");
return false;
}
// System.out.println("ConstructorExpr is non null...call to super has
// to be made");
// find the parent class of the current method being decompiled
SootClass parentClass = originalSootClass.getSuperclass();
// retrieve the constructor of the super class that we want to call
// remember argsTwoTypes contains the ParameterType to the call to the
// super method
if (!(parentClass.declaresMethod("<init>", argsTwoTypes))) {
// System.out.println("parentClass does not have a constructor with
// this name and ParamTypes");
return false;
}
SootMethod superConstructor = parentClass.getMethod("<init>", argsTwoTypes);
// create InstanceInvokeExpr
// need Value base: this??
// need SootMethod Ref...make sootmethoref of the super constructor
// found
// need list of thisLocals.........try empty arrayList since it doesnt
// seem to be used anywhere??
List argsForConstructor = new ArrayList();
int count = 0;
// have to make arg as "handler.get(0)"
// create new ReftType for DavaSuperHandler
RefType type = (new SootClass("DavaSuperHandler")).getType();
// make JimpleLocal to be used in each arg
Local jimpleLocal = new JimpleLocal("handler", type);// takes care of
// handler
// make reference to a method of name get takes one int arg belongs to
// DavaSuperHandler
ArrayList tempList = new ArrayList();
tempList.add(IntType.v());
SootMethodRef getMethodRef = makeMethodRef("get", tempList);
List tempArgList = null;
Iterator typeIt = argsTwoTypes.iterator();
while (typeIt.hasNext()) {
Type tempType = (Type) typeIt.next();
DIntConstant arg = DIntConstant.v(count, IntType.v());// takes care
// of the
// index
count++;
tempArgList = new ArrayList();
tempArgList.add(arg);
DVirtualInvokeExpr tempInvokeExpr
= new DVirtualInvokeExpr(jimpleLocal, getMethodRef, tempArgList, new HashSet<Object>());
// NECESASARY CASTING OR RETRIEVAL OF PRIM TYPES TO BE DONE HERE
Value toAddExpr = getProperCasting(tempType, tempInvokeExpr);
if (toAddExpr == null) {
throw new DecompilationException("UNABLE TO CREATE TOADDEXPR:" + tempType);
}
// the above virtualInvokeExpr is one of the args for the
// constructor
argsForConstructor.add(toAddExpr);
}
mustInitializeIndex = count;
// we are done with creating all necessary args to the virtualinvoke
// expr constructor
DVirtualInvokeExpr virtualInvoke = new DVirtualInvokeExpr(originalConstructorExpr.getBase(), superConstructor.makeRef(),
argsForConstructor, new HashSet<Object>());
// set the constructors constructorExpr
newConstructorDavaBody.set_ConstructorExpr(virtualInvoke);
// create Invoke Stmt with virtualInvoke as the expression
GInvokeStmt s = new GInvokeStmt(virtualInvoke);
newConstructorDavaBody.set_ConstructorUnit(s);
// return true if super call created
return true;
}
public Value getProperCasting(Type tempType, DVirtualInvokeExpr tempInvokeExpr) {
if (tempType instanceof RefType) {
// System.out.println("This is a reftype:"+tempType);
return new GCastExpr(tempInvokeExpr, tempType);
} else if (tempType instanceof PrimType) {
PrimType t = (PrimType) tempType;
// BooleanType, ByteType, CharType, DoubleType, FloatType, IntType,
// LongType, ShortType
if (t == BooleanType.v()) {
Value tempExpr = new GCastExpr(tempInvokeExpr, RefType.v("java.lang.Boolean"));
// booleanValue
SootMethod tempMethod = Scene.v().makeSootMethod("booleanValue", new ArrayList(), BooleanType.v());
tempMethod.setDeclaringClass(new SootClass("java.lang.Boolean"));
SootMethodRef tempMethodRef = tempMethod.makeRef();
return new DVirtualInvokeExpr(tempExpr, tempMethodRef, new ArrayList(), new HashSet<Object>());
} else if (t == ByteType.v()) {
Value tempExpr = new GCastExpr(tempInvokeExpr, RefType.v("java.lang.Byte"));
// byteValue
SootMethod tempMethod = Scene.v().makeSootMethod("byteValue", new ArrayList(), ByteType.v());
tempMethod.setDeclaringClass(new SootClass("java.lang.Byte"));
SootMethodRef tempMethodRef = tempMethod.makeRef();
return new DVirtualInvokeExpr(tempExpr, tempMethodRef, new ArrayList(), new HashSet<Object>());
} else if (t == CharType.v()) {
Value tempExpr = new GCastExpr(tempInvokeExpr, RefType.v("java.lang.Character"));
// charValue
SootMethod tempMethod = Scene.v().makeSootMethod("charValue", new ArrayList(), CharType.v());
tempMethod.setDeclaringClass(new SootClass("java.lang.Character"));
SootMethodRef tempMethodRef = tempMethod.makeRef();
return new DVirtualInvokeExpr(tempExpr, tempMethodRef, new ArrayList(), new HashSet<Object>());
} else if (t == DoubleType.v()) {
Value tempExpr = new GCastExpr(tempInvokeExpr, RefType.v("java.lang.Double"));
// doubleValue
SootMethod tempMethod = Scene.v().makeSootMethod("doubleValue", new ArrayList(), DoubleType.v());
tempMethod.setDeclaringClass(new SootClass("java.lang.Double"));
SootMethodRef tempMethodRef = tempMethod.makeRef();
return new DVirtualInvokeExpr(tempExpr, tempMethodRef, new ArrayList(), new HashSet<Object>());
} else if (t == FloatType.v()) {
Value tempExpr = new GCastExpr(tempInvokeExpr, RefType.v("java.lang.Float"));
// floatValue
SootMethod tempMethod = Scene.v().makeSootMethod("floatValue", new ArrayList(), FloatType.v());
tempMethod.setDeclaringClass(new SootClass("java.lang.Float"));
SootMethodRef tempMethodRef = tempMethod.makeRef();
return new DVirtualInvokeExpr(tempExpr, tempMethodRef, new ArrayList(), new HashSet<Object>());
} else if (t == IntType.v()) {
Value tempExpr = new GCastExpr(tempInvokeExpr, RefType.v("java.lang.Integer"));
// intValue
SootMethod tempMethod = Scene.v().makeSootMethod("intValue", new ArrayList(), IntType.v());
tempMethod.setDeclaringClass(new SootClass("java.lang.Integer"));
SootMethodRef tempMethodRef = tempMethod.makeRef();
return new DVirtualInvokeExpr(tempExpr, tempMethodRef, new ArrayList(), new HashSet<Object>());
} else if (t == LongType.v()) {
Value tempExpr = new GCastExpr(tempInvokeExpr, RefType.v("java.lang.Long"));
// longValue
SootMethod tempMethod = Scene.v().makeSootMethod("longValue", new ArrayList(), LongType.v());
tempMethod.setDeclaringClass(new SootClass("java.lang.Long"));
SootMethodRef tempMethodRef = tempMethod.makeRef();
return new DVirtualInvokeExpr(tempExpr, tempMethodRef, new ArrayList(), new HashSet<Object>());
} else if (t == ShortType.v()) {
Value tempExpr = new GCastExpr(tempInvokeExpr, RefType.v("java.lang.Short"));
// shortValue
SootMethod tempMethod = Scene.v().makeSootMethod("shortValue", new ArrayList(), ShortType.v());
tempMethod.setDeclaringClass(new SootClass("java.lang.Short"));
SootMethodRef tempMethodRef = tempMethod.makeRef();
return new DVirtualInvokeExpr(tempExpr, tempMethodRef, new ArrayList(), new HashSet<Object>());
} else {
throw new DecompilationException("Unhandle primType:" + tempType);
}
} else {
throw new DecompilationException("The type:" + tempType + " was not a reftye or primtype. PLEASE REPORT.");
}
}
private void finalizeConstructor() {
// set davaBody...totally redundant but have to do as this is checked by
// toString of ASTMethodNode
newASTConstructorMethod.setDavaBody(newConstructorDavaBody);
newConstructorDavaBody.getUnits().clear();
newConstructorDavaBody.getUnits().addLast(newASTConstructorMethod);
System.out.println("Setting declaring class of method" + newConstructor.getSubSignature());
newConstructor.setDeclaringClass(originalSootClass);
}
// method should return false if the PreInit body(ASTBody that is) is empty
// meaning there is no need to create it all
private boolean finalizePreInitMethod() {
// set davaBody...totally redundant but have to do as this is checked by
// toString of ASTMethodNode
newASTPreInitMethod.setDavaBody(newPreInitDavaBody);
// newPreInitDavaBody is the active body
newPreInitDavaBody.getUnits().clear();
newPreInitDavaBody.getUnits().addLast(newASTPreInitMethod);
// check whether there is something in side the ASTBody
// if its empty (maybe there were only declarations and that got removed
// then no point in creating the preInit method
List<Object> subBodies = newASTPreInitMethod.get_SubBodies();
if (subBodies.size() != 1) {
return false;
}
List body = (List) subBodies.get(0);
// body is NOT allowed to contain one declaration node with whatever in
// it
// after that it is NOT allowed all ASTStatement nodes with empty bodies
Iterator it = body.iterator();
boolean empty = true; // indicating that method is empty
while (it.hasNext()) {
ASTNode tempNode = (ASTNode) it.next();
if (!(tempNode instanceof ASTStatementSequenceNode)) {
// found some node other than stmtseq...body not empty return
// true
empty = false;
break;
}
List<AugmentedStmt> stmts = ((ASTStatementSequenceNode) tempNode).getStatements();
// all declaration stmts are allowed
for (AugmentedStmt as : stmts) {
Stmt s = as.get_Stmt();
if (!(s instanceof DVariableDeclarationStmt)) {
empty = false;
break;
}
}
if (!empty) {
break;
}
}
if (empty) {
// System.out.println("Method is empty not creating it");
return false;// should not be creating the method
}
// about to return true enter all DavaSuperHandler stmts to make it part
// of the preinit method
createDavaStoreStmts();
return true;
}
public void createNewASTConstructor(ASTStatementSequenceNode initNode) {
List<Object> newConstructorBody = new ArrayList<Object>();
List<AugmentedStmt> newStmts = new ArrayList<AugmentedStmt>();
/*
* add any definitions to live variables that might be in body X
*/
// we have gotten argsTwoType size() out of the handler so thats the
// index count
// mustInitialize has the live variables that need to be initialized
// create new ReftType for DavaSuperHandler
RefType type = (new SootClass("DavaSuperHandler")).getType();
// make JimpleLocal to be used in each arg
Local jimpleLocal = new JimpleLocal("handler", type);// takes care of
// handler
// make reference to a method of name get takes one int arg belongs to
// DavaSuperHandler
ArrayList tempList = new ArrayList();
tempList.add(IntType.v());
SootMethodRef getMethodRef = makeMethodRef("get", tempList);
// Iterator typeIt = argsTwoTypes.iterator();
if (mustInitialize != null) {
Iterator<Local> initIt = mustInitialize.iterator();
while (initIt.hasNext()) {
Local initLocal = initIt.next();
Type tempType = initLocal.getType();
DIntConstant arg = DIntConstant.v(mustInitializeIndex, IntType.v());// takes
// care
// of
// the
// index
mustInitializeIndex++;
ArrayList tempArgList = new ArrayList();
tempArgList.add(arg);
DVirtualInvokeExpr tempInvokeExpr
= new DVirtualInvokeExpr(jimpleLocal, getMethodRef, tempArgList, new HashSet<Object>());
// NECESASARY CASTING OR RETRIEVAL OF PRIM TYPES TO BE DONE HERE
Value toAddExpr = getProperCasting(tempType, tempInvokeExpr);
if (toAddExpr == null) {
throw new DecompilationException("UNABLE TO CREATE TOADDEXPR:" + tempType);
}
// need to create a def stmt with the local on the left and
// toAddExpr on the right
GAssignStmt assign = new GAssignStmt(initLocal, toAddExpr);
newStmts.add(new AugmentedStmt(assign));
}
}
// add any statements following the this.<init> statement
Iterator<AugmentedStmt> it = initNode.getStatements().iterator();
while (it.hasNext()) {
AugmentedStmt augStmt = (AugmentedStmt) it.next();
Stmt stmtTemp = augStmt.get_Stmt();
if (stmtTemp == originalConstructorUnit) {
break;
}
}
while (it.hasNext()) {
/*
* notice we dont need to clone these because these will be removed from the other method from which we are copying
* these
*/
newStmts.add(it.next());
}
if (newStmts.size() > 0) {
newConstructorBody.add(new ASTStatementSequenceNode(newStmts));
}
// adding body Y now
List<Object> originalASTMethodSubBodies = originalASTMethod.get_SubBodies();
if (originalASTMethodSubBodies.size() != 1) {
throw new CorruptASTException("size of ASTMethodNode subBody not 1");
}
List<Object> oldASTBody = (List<Object>) originalASTMethodSubBodies.get(0);
Iterator<Object> itOld = oldASTBody.iterator();
boolean sanity = false;
while (itOld.hasNext()) {
// going through originalASTMethodNode's ASTNodes
ASTNode tempNode = (ASTNode) itOld.next();
// enter only if its not the initNode
if (tempNode instanceof ASTStatementSequenceNode) {
if ((((ASTStatementSequenceNode) tempNode).getStatements()).equals(initNode.getStatements())) {
sanity = true;
break;
}
}
}
if (!sanity) {
// means we never found the initNode which shouldnt happen
throw new DecompilationException("never found the init node");
}
// so we have found the init node
// Y are all the nodes following the initNode
while (itOld.hasNext()) {
newConstructorBody.add(itOld.next());
}
// setDeclarations in newNode
// The LocalVariableCleaner which is called in the end of DavaBody will
// clear up any declarations that are not required
List<AugmentedStmt> newConstructorDeclarations = new ArrayList<AugmentedStmt>();
for (AugmentedStmt as : originalASTMethod.getDeclarations().getStatements()) {
DVariableDeclarationStmt varDecStmt = (DVariableDeclarationStmt) as.get_Stmt();
newConstructorDeclarations.add(new AugmentedStmt((DVariableDeclarationStmt) varDecStmt.clone()));
}
ASTStatementSequenceNode newDecs = new ASTStatementSequenceNode(new ArrayList<AugmentedStmt>());
if (newConstructorDeclarations.size() > 0) {
newDecs = new ASTStatementSequenceNode(newConstructorDeclarations);
// DONT FORGET TO SET THE DECLARATIONS IN THE METHOD ONCE IT IS
// CREATED
// newASTConstructorMethod.setDeclarations(newDecs);
// declarations are always the first element
newConstructorBody.add(0, newDecs);
}
// so we have any declarations followed by body Y
// have to put the newConstructorBody into an list of subBodies which
// goes into the newASTConstructorMethod
newASTConstructorMethod = new ASTMethodNode(newConstructorBody);
// dont forget to set the declarations
newASTConstructorMethod.setDeclarations(newDecs);
}
private void createNewConstructor() {
// the constructor name has to be <init>
String uniqueName = "<init>";
// NOTICE args of this constructor are argsOne followed by the
// DavaSuperHandler
List args = new ArrayList();
args.addAll(argsOneTypes);
// create new ReftType for DavaSuperHandler
RefType type = (new SootClass("DavaSuperHandler")).getType();
args.add(type);
// create SOOTMETHOD
newConstructor = Scene.v().makeSootMethod(uniqueName, args, IntType.v());
// set the declaring class of new method to be the originalSootClass
newConstructor.setDeclaringClass(originalSootClass);
// set method to public
newConstructor.setModifiers(soot.Modifier.PUBLIC);
// initalize a new DavaBody, notice this causes all DavaBody vars to be
// null
newConstructorDavaBody = Dava.v().newBody(newConstructor);
// setting params is really important if you want the args to have
// proper names in the new method
// make a copy of the originalHashMap
Map tempMap = new HashMap();
Iterator typeIt = argsOneTypes.iterator();
int count = 0;
while (typeIt.hasNext()) {
Type t = (Type) typeIt.next();
tempMap.put(new Integer(count), originalPMap.get(new Integer(count)));
count++;
}
// add the DavaSuperHandler var name in the Parameters
tempMap.put(new Integer(argsOneTypes.size()), "handler");
// add the ParamMap to the constructor's DavaBody
newConstructorDavaBody.set_ParamMap(tempMap);
// set as activeBody
newConstructor.setActiveBody(newConstructorDavaBody);
}
/*
* January 23rd New Algorithm Leave originalASTMethod unchanged Clone everything and copy only those which are needed in
* the newASTPreInitMethod
*/
private void createNewASTPreInitMethod(ASTStatementSequenceNode initNode) {
List<Object> newPreinitBody = new ArrayList<Object>();
// start adding ASTNodes into newPreinitBody from the
// originalASTMethod's body until we reach initNode
List<Object> originalASTMethodSubBodies = originalASTMethod.get_SubBodies();
if (originalASTMethodSubBodies.size() != 1) {
throw new CorruptASTException("size of ASTMethodNode subBody not 1");
}
List<Object> oldASTBody = (List<Object>) originalASTMethodSubBodies.get(0);
Iterator<Object> it = oldASTBody.iterator();
boolean sanity = false;
while (it.hasNext()) {
// going through originalASTMethodNode's ASTNodes
ASTNode tempNode = (ASTNode) it.next();
// enter only if its not the initNode
if (tempNode instanceof ASTStatementSequenceNode) {
if ((((ASTStatementSequenceNode) tempNode).getStatements()).equals(initNode.getStatements())) {
sanity = true;
break;
} else {
// this was not the initNode so we add
newPreinitBody.add(tempNode);
}
} else {
// not a stmtseq so simply add it
newPreinitBody.add(tempNode);
}
}
if (!sanity) {
// means we never found the initNode which shouldnt happen
throw new DecompilationException("never found the init node");
}
// at this moment newPreinitBody contains all of X except for any stmts
// above the this.init call in the stmtseq node
// copy those
List<AugmentedStmt> newStmts = new ArrayList<AugmentedStmt>();
for (AugmentedStmt augStmt : initNode.getStatements()) {
Stmt stmtTemp = augStmt.get_Stmt();
if (stmtTemp == originalConstructorUnit) {
break;
}
// adding any stmt until constructorUnit into topList for
// newMethodNode
/*
* notice we dont need to clone these because these will be removed from the other method from which we are copying
* these
*/
newStmts.add(augStmt);
}
if (newStmts.size() > 0) {
newPreinitBody.add(new ASTStatementSequenceNode(newStmts));
}
// setDeclarations in newNode
// The LocalVariableCleaner which is called in the end of DavaBody will
// clear up any declarations that are not required
List<AugmentedStmt> newPreinitDeclarations = new ArrayList<AugmentedStmt>();
for (AugmentedStmt as : originalASTMethod.getDeclarations().getStatements()) {
DVariableDeclarationStmt varDecStmt = (DVariableDeclarationStmt) as.get_Stmt();
newPreinitDeclarations.add(new AugmentedStmt((DVariableDeclarationStmt) varDecStmt.clone()));
}
ASTStatementSequenceNode newDecs = new ASTStatementSequenceNode(new ArrayList<AugmentedStmt>());
if (newPreinitDeclarations.size() > 0) {
newDecs = new ASTStatementSequenceNode(newPreinitDeclarations);
// DONT FORGET TO SET THE DECLARATIONS IN THE METHOD ONCE IT IS
// CREATED
// newASTPreInitMethod.setDeclarations(newDecs);
// when we copied the body X the first Node copied was the
// Declarations from the originalASTMethod
// replace that with this new one
newPreinitBody.remove(0);
newPreinitBody.add(0, newDecs);
}
// At this moment we have the newPreInitBody containing declarations
// followed by code X
// we need to check whether this actually contains anything cos
// otherwise super is infact the first stmt
if (newPreinitBody.size() < 1) {
// System.out.println("Method node empty doing nothing returning");
newASTPreInitMethod = null;// meaning ASTMethodNode for this method
// not created
return;
}
// so we have any declarations followed by body X
// NEXT THING SHOULD BE CODE TO CREATE A DAVAHANDLER AND STORE THE ARGS
// TO SUPER IN IT
// HOWEVER WE WILL DELAY THIS TILL UNTIL WE ARE READY TO FINALIZE the
// PREINIT
// reason for delaying is that even though we know that the body is not
// empty the body
// could be made empty by the transformations which act in the finalize
// method
// have to put the newPreinitBody into an list of subBodies which goes
// into the newASTPreInitMethod
newASTPreInitMethod = new ASTMethodNode(newPreinitBody);
// dont forget to set the declarations
newASTPreInitMethod.setDeclarations(newDecs);
}
/*
* Create a unique private static method name starts with preInit
*/
private void createSootPreInitMethod() {
// get a unique name for the method
String uniqueName = getUniqueName();
// NOTICE WE ARE DEFINING ARGS AS SAME AS THE ORIGINAL METHOD
newSootPreInitMethod = Scene.v().makeSootMethod(uniqueName, argsOneTypes, (new SootClass("DavaSuperHandler")).getType());
// set the declaring class of new method to be the originalSootClass
newSootPreInitMethod.setDeclaringClass(originalSootClass);
// set method to private and static
newSootPreInitMethod.setModifiers(soot.Modifier.PRIVATE | soot.Modifier.STATIC);
// initalize a new DavaBody, notice this causes all DavaBody vars to be
// null
newPreInitDavaBody = Dava.v().newBody(newSootPreInitMethod);
// setting params is really important if you want the args to have
// proper names in the new method
newPreInitDavaBody.set_ParamMap(originalPMap);
// set as activeBody
newSootPreInitMethod.setActiveBody(newPreInitDavaBody);
}
/*
* Check the sootClass that it doesnt have a name we have suggested ALSO VERY IMPORTANT TO CHECK THE NAMES IN THE
* SOOTMETHODSADDED Variable since these will be added to this sootclass by the PackManager
*/
private String getUniqueName() {
String toReturn = "preInit";
int counter = 0;
List methodList = originalSootClass.getMethods();
boolean done = false; // havent found the name
while (!done) {
// as long as name not found
done = true; // assume name found
Iterator it = methodList.iterator();
while (it.hasNext()) {
Object temp = it.next();
if (temp instanceof SootMethod) {
SootMethod method = (SootMethod) temp;
String name = method.getName();
if (toReturn.compareTo(name) == 0) {
// method exists with this name so change the name
counter++;
toReturn = "preInit" + counter;
done = false; // name was not found
break;// breaks the inner while since the name has been
// changed
}
} else {
throw new DecompilationException("SootClass returned a non SootMethod method");
}
}
// if we get here this means that the orignal names are different
// check the to be added names also
it = G.v().SootMethodsAdded.iterator();
while (it.hasNext()) {
// are sure its a sootMethod
SootMethod method = (SootMethod) it.next();
String name = method.getName();
if (toReturn.compareTo(name) == 0) {
// method exists with this name so change the name
counter++;
toReturn = "preInit" + counter;
done = false; // name was not found
break;// breaks the inner while since the name has been
// changed
}
}
} // end outer while
return toReturn;
}
/*
* Create the following code:
*
* DavaSuperHandler handler; handler = new DavaSuperHandler(); //code to evaluate all args in args2
*
* //evaluate 1st arg in args2 --------- handler.store(firstArg);
*
* //evaluate 2nd arg in args2 --------- handler.store(secondArg);
*
* //AND SO ON TILL ALL ARGS ARE FINISHED
*
* return handler;
*/
private void createDavaStoreStmts() {
List<AugmentedStmt> davaHandlerStmts = new ArrayList<AugmentedStmt>();
// create object of DavaSuperHandler handler
SootClass sootClass = new SootClass("DavaSuperHandler");
Type localType = sootClass.getType();
Local newLocal = new JimpleLocal("handler", localType);
/*
* Create * DavaSuperHandler handler; *
*/
DVariableDeclarationStmt varStmt = null;
varStmt = new DVariableDeclarationStmt(localType, newPreInitDavaBody);
varStmt.addLocal(newLocal);
AugmentedStmt as = new AugmentedStmt(varStmt);
davaHandlerStmts.add(as);
/*
* create * handler = new DavaSuperHandler(); *
*/
// create RHS
DNewInvokeExpr invokeExpr
= new DNewInvokeExpr(RefType.v(sootClass), makeMethodRef("DavaSuperHandler", new ArrayList()), new ArrayList());
// create LHS
GAssignStmt initialization = new GAssignStmt(newLocal, invokeExpr);
// add to stmts
davaHandlerStmts.add(new AugmentedStmt(initialization));
/*
* create * handler.store(firstArg); *
*/
// best done in a loop for all args
Iterator typeIt = argsTwoTypes.iterator();
Iterator valIt = argsTwoValues.iterator();
// make reference to a method of name store takes one Object arg belongs
// to DavaSuperHandler
ArrayList tempList = new ArrayList();
tempList.add(RefType.v("java.lang.Object"));// SHOULD BE OBJECT
SootMethod method = Scene.v().makeSootMethod("store", tempList, VoidType.v());
// set the declaring class of new method to be the DavaSuperHandler
// class
method.setDeclaringClass(sootClass);
SootMethodRef getMethodRef = method.makeRef();
// everything is ready all we need is the object argument before we can
// create the invokeStmt with the invokeexpr
// once that is done wrap it in augmented stmt and add to
// davaHandlerStmt
while (typeIt.hasNext() && valIt.hasNext()) {
Type tempType = (Type) typeIt.next();
Value tempVal = (Value) valIt.next();
AugmentedStmt toAdd = createStmtAccordingToType(tempType, tempVal, newLocal, getMethodRef);
davaHandlerStmts.add(toAdd);
} // end of going through all the types and vals
// sanity check
if (typeIt.hasNext() || valIt.hasNext()) {
throw new DecompilationException("Error creating DavaHandler stmts");
}
/*
* code to add defs
*/
List<Local> uniqueLocals = addDefsToLiveVariables();
Iterator<Local> localIt = uniqueLocals.iterator();
while (localIt.hasNext()) {
Local local = localIt.next();
AugmentedStmt toAdd = createStmtAccordingToType(local.getType(), local, newLocal, getMethodRef);
davaHandlerStmts.add(toAdd);
}
// set the mustInitialize field to uniqueLocals so that before Y we can
// assign these locals
mustInitialize = uniqueLocals;
/*
* create * return handler; *
*/
GReturnStmt returnStmt = new GReturnStmt(newLocal);
davaHandlerStmts.add(new AugmentedStmt(returnStmt));
// the appropriate dava handler stmts are all in place within
// davaHandlerStmts
// store them in an ASTSTatementSequenceNode
ASTStatementSequenceNode addedNode = new ASTStatementSequenceNode(davaHandlerStmts);
// add to method body
List<Object> subBodies = newASTPreInitMethod.get_SubBodies();
if (subBodies.size() != 1) {
throw new CorruptASTException("ASTMethodNode does not have one subBody");
}
List<Object> body = (List<Object>) subBodies.get(0);
body.add(addedNode);
newASTPreInitMethod.replaceBody(body);
}
public AugmentedStmt createStmtAccordingToType(Type tempType, Value tempVal, Local newLocal, SootMethodRef getMethodRef) {
if (tempType instanceof RefType) {
// simply add this to the handler using handler.store(tempVal);
// System.out.println("This is a reftype:"+tempType);
return createAugmentedStmtToAdd(newLocal, getMethodRef, tempVal);
} else if (tempType instanceof PrimType) {
// The value is a primitive type
// create wrapper object new Integer(tempVal)
PrimType t = (PrimType) tempType;
// create ArgList to be sent to DNewInvokeExpr constructor
ArrayList argList = new ArrayList();
argList.add(tempVal);
// BooleanType, ByteType, CharType, DoubleType, FloatType, IntType,
// LongType, ShortType
if (t == BooleanType.v()) {
// create TypeList to be sent to makeMethodRef
ArrayList typeList = new ArrayList();
typeList.add(IntType.v());
DNewInvokeExpr argForStore
= new DNewInvokeExpr(RefType.v("java.lang.Boolean"), makeMethodRef("Boolean", typeList), argList);
return createAugmentedStmtToAdd(newLocal, getMethodRef, argForStore);
} else if (t == ByteType.v()) {
// create TypeList to be sent to makeMethodRef
ArrayList typeList = new ArrayList();
typeList.add(ByteType.v());
DNewInvokeExpr argForStore
= new DNewInvokeExpr(RefType.v("java.lang.Byte"), makeMethodRef("Byte", typeList), argList);
return createAugmentedStmtToAdd(newLocal, getMethodRef, argForStore);
} else if (t == CharType.v()) {
// create TypeList to be sent to makeMethodRef
ArrayList typeList = new ArrayList();
typeList.add(CharType.v());
DNewInvokeExpr argForStore
= new DNewInvokeExpr(RefType.v("java.lang.Character"), makeMethodRef("Character", typeList), argList);
return createAugmentedStmtToAdd(newLocal, getMethodRef, argForStore);
} else if (t == DoubleType.v()) {
// create TypeList to be sent to makeMethodRef
ArrayList typeList = new ArrayList();
typeList.add(DoubleType.v());
DNewInvokeExpr argForStore
= new DNewInvokeExpr(RefType.v("java.lang.Double"), makeMethodRef("Double", typeList), argList);
return createAugmentedStmtToAdd(newLocal, getMethodRef, argForStore);
} else if (t == FloatType.v()) {
// create TypeList to be sent to makeMethodRef
ArrayList typeList = new ArrayList();
typeList.add(FloatType.v());
DNewInvokeExpr argForStore
= new DNewInvokeExpr(RefType.v("java.lang.Float"), makeMethodRef("Float", typeList), argList);
return createAugmentedStmtToAdd(newLocal, getMethodRef, argForStore);
} else if (t == IntType.v()) {
// create TypeList to be sent to makeMethodRef
ArrayList typeList = new ArrayList();
typeList.add(IntType.v());
DNewInvokeExpr argForStore
= new DNewInvokeExpr(RefType.v("java.lang.Integer"), makeMethodRef("Integer", typeList), argList);
return createAugmentedStmtToAdd(newLocal, getMethodRef, argForStore);
} else if (t == LongType.v()) {
// create TypeList to be sent to makeMethodRef
ArrayList typeList = new ArrayList();
typeList.add(LongType.v());
DNewInvokeExpr argForStore
= new DNewInvokeExpr(RefType.v("java.lang.Long"), makeMethodRef("Long", typeList), argList);
return createAugmentedStmtToAdd(newLocal, getMethodRef, argForStore);
} else if (t == ShortType.v()) {
// create TypeList to be sent to makeMethodRef
ArrayList typeList = new ArrayList();
typeList.add(ShortType.v());
DNewInvokeExpr argForStore
= new DNewInvokeExpr(RefType.v("java.lang.Short"), makeMethodRef("Short", typeList), argList);
return createAugmentedStmtToAdd(newLocal, getMethodRef, argForStore);
} else {
throw new DecompilationException("UNHANDLED PRIMTYPE:" + tempType);
}
} // end of primitivetypes
else {
throw new DecompilationException("The type:" + tempType + " is neither a reftype or a primtype");
}
}
/*
* newASTPreInitMethod at time of invocation just contains body X find all defs for this body
*/
private List<Local> addDefsToLiveVariables() {
// get all defs within x
AllDefinitionsFinder finder = new AllDefinitionsFinder();
newASTPreInitMethod.apply(finder);
List<DefinitionStmt> allDefs = finder.getAllDefs();
List<Local> uniqueLocals = new ArrayList<Local>();
List<DefinitionStmt> uniqueLocalDefs = new ArrayList<DefinitionStmt>();
// remove any defs for fields, and any which are done multiple times
Iterator<DefinitionStmt> it = allDefs.iterator();
while (it.hasNext()) {
DefinitionStmt s = it.next();
Value left = s.getLeftOp();
if (left instanceof Local) {
if (uniqueLocals.contains(left)) {
// a def for this local already encountered
int index = uniqueLocals.indexOf(left);
uniqueLocals.remove(index);
uniqueLocalDefs.remove(index);
} else {
// no def for this local yet
uniqueLocals.add((Local) left);
uniqueLocalDefs.add(s);
}
}
}
// at this point unique locals contains all locals defined and
// uniqueLocaldef list has a list of the corresponding definitions
// Now remove those unique locals and localdefs whose stmtseq node does
// not have the ASTMEthodNode as a parent
// This is a conservative step!!
ASTParentNodeFinder parentFinder = new ASTParentNodeFinder();
newASTPreInitMethod.apply(parentFinder);
List<DefinitionStmt> toRemoveDefs = new ArrayList<DefinitionStmt>();
it = uniqueLocalDefs.iterator();
while (it.hasNext()) {
DefinitionStmt s = it.next();
Object parent = parentFinder.getParentOf(s);
if (parent == null || (!(parent instanceof ASTStatementSequenceNode))) {
// shouldnt happen but if it does add this s to toRemove list
toRemoveDefs.add(s);
}
// parent is an ASTStatementsequence node. check that its parent is
// the ASTMethodNode
Object grandParent = parentFinder.getParentOf(parent);
if (grandParent == null || (!(grandParent instanceof ASTMethodNode))) {
// can happen if obfuscators are really smart. add s to toRemove
// list
toRemoveDefs.add(s);
}
}
// remove any defs and corresponding locals if present in the
// toRemoveDefs list
it = toRemoveDefs.iterator();
while (it.hasNext()) {
DefinitionStmt s = it.next();
int index = uniqueLocalDefs.indexOf(s);
uniqueLocals.remove(index);
uniqueLocalDefs.remove(index);
}
// the uniqueLocalDefs contains all those definitions to unique locals
// which are not deeply nested in the X body
// find all the uses of these definitions in the original method body
toRemoveDefs = new ArrayList<DefinitionStmt>();
ASTUsesAndDefs uDdU = new ASTUsesAndDefs(originalASTMethod);
originalASTMethod.apply(uDdU);
it = uniqueLocalDefs.iterator();
while (it.hasNext()) {
DefinitionStmt s = it.next();
Object temp = uDdU.getDUChain(s);
if (temp == null) {
// couldnt find uses
toRemoveDefs.add(s);
continue;
}
ArrayList uses = (ArrayList) temp;
// the uses list contains all stmts / nodes which use the
// definedLocal
// check if uses is non-empty
if (uses.size() == 0) {
toRemoveDefs.add(s);
}
// check for all the non zero uses
Iterator useIt = uses.iterator();
boolean onlyInConstructorUnit = true;
while (useIt.hasNext()) {
// a use is either a statement or a node(condition, synch,
// switch , for etc)
Object tempUse = useIt.next();
if (tempUse != originalConstructorUnit) {
onlyInConstructorUnit = false;
}
}
if (onlyInConstructorUnit) {
// mark it to be removed
toRemoveDefs.add(s);
}
}
// remove any defs and corresponding locals if present in the
// toRemoveDefs list
it = toRemoveDefs.iterator();
while (it.hasNext()) {
DefinitionStmt s = it.next();
int index = uniqueLocalDefs.indexOf(s);
uniqueLocals.remove(index);
uniqueLocalDefs.remove(index);
}
// the remaining uniquelocals are the ones which are needed for body Y
return uniqueLocals;
}
private AugmentedStmt createAugmentedStmtToAdd(Local newLocal, SootMethodRef getMethodRef, Value tempVal) {
ArrayList tempArgList = new ArrayList();
tempArgList.add(tempVal);
DVirtualInvokeExpr tempInvokeExpr = new DVirtualInvokeExpr(newLocal, getMethodRef, tempArgList, new HashSet<Object>());
// create Invoke Stmt with virtualInvoke as the expression
GInvokeStmt s = new GInvokeStmt(tempInvokeExpr);
return new AugmentedStmt(s);
}
public void debug(String methodName, String debug) {
if (DEBUG) {
System.out.println(methodName + " DEBUG: " + debug);
}
}
}
| 51,399
| 35.505682
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/TypeCastingError.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 soot.ByteType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.PrimType;
import soot.ShortType;
import soot.Type;
import soot.Value;
import soot.ValueBox;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.grimp.internal.GCastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
public class TypeCastingError extends DepthFirstAdapter {
public boolean myDebug = false;
public TypeCastingError() {
}
public TypeCastingError(boolean verbose) {
super(verbose);
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
if (!(s instanceof DefinitionStmt)) {
continue;
}
DefinitionStmt ds = (DefinitionStmt) s;
if (myDebug) {
System.out.println("Definition stmt" + ds);
}
ValueBox rightBox = ds.getRightOpBox();
ValueBox leftBox = ds.getLeftOpBox();
Value right = rightBox.getValue();
Value left = leftBox.getValue();
if (!(left.getType() instanceof PrimType && right.getType() instanceof PrimType)) {
// only interested in prim type casting errors
if (myDebug) {
System.out.println("\tDefinition stmt does not contain prims no need to modify");
}
continue;
}
Type leftType = left.getType();
Type rightType = right.getType();
if (myDebug) {
System.out.println("Left type is: " + leftType);
}
if (myDebug) {
System.out.println("Right type is: " + rightType);
}
if (leftType.equals(rightType)) {
if (myDebug) {
System.out.println("\tTypes are the same");
}
if (myDebug) {
System.out.println("Right value is of instance" + right.getClass());
}
}
if (!leftType.equals(rightType)) {
if (myDebug) {
System.out.println("\tDefinition stmt has to be modified");
}
// ByteType, DoubleType, FloatType, IntType, LongType, ShortType
/*
* byte Byte-length integer 8-bit two's complement short Short integer 16-bit two's complement int Integer 32-bit
* two's complement long Long integer 64-bit two's complement float Single-precision floating point 32-bit IEEE 754
* double Double-precision floating point 64-bit IEEE 754
*/
if (leftType instanceof ByteType && (rightType instanceof DoubleType || rightType instanceof FloatType
|| rightType instanceof IntType || rightType instanceof LongType || rightType instanceof ShortType)) {
// loss of precision do explicit casting
if (DEBUG) {
System.out.println("Explicit casting to BYTE required");
}
rightBox.setValue(new GCastExpr(right, ByteType.v()));
if (DEBUG) {
System.out.println("New right expr is " + rightBox.getValue().toString());
}
continue;
}
if (leftType instanceof ShortType && (rightType instanceof DoubleType || rightType instanceof FloatType
|| rightType instanceof IntType || rightType instanceof LongType)) {
// loss of precision do explicit casting
if (DEBUG) {
System.out.println("Explicit casting to SHORT required");
}
rightBox.setValue(new GCastExpr(right, ShortType.v()));
if (DEBUG) {
System.out.println("New right expr is " + rightBox.getValue().toString());
}
continue;
}
if (leftType instanceof IntType
&& (rightType instanceof DoubleType || rightType instanceof FloatType || rightType instanceof LongType)) {
// loss of precision do explicit casting
if (myDebug) {
System.out.println("Explicit casting to INT required");
}
rightBox.setValue(new GCastExpr(right, IntType.v()));
if (myDebug) {
System.out.println("New right expr is " + rightBox.getValue().toString());
}
continue;
}
if (leftType instanceof LongType && (rightType instanceof DoubleType || rightType instanceof FloatType)) {
// loss of precision do explicit casting
if (DEBUG) {
System.out.println("Explicit casting to LONG required");
}
rightBox.setValue(new GCastExpr(right, LongType.v()));
if (DEBUG) {
System.out.println("New right expr is " + rightBox.getValue().toString());
}
continue;
}
if (leftType instanceof FloatType && rightType instanceof DoubleType) {
// loss of precision do explicit casting
if (DEBUG) {
System.out.println("Explicit casting to FLOAT required");
}
rightBox.setValue(new GCastExpr(right, FloatType.v()));
if (DEBUG) {
System.out.println("New right expr is " + rightBox.getValue().toString());
}
continue;
}
}
}
}
}
| 6,096
| 33.061453
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/UnreachableCodeEliminator.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.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.Local;
import soot.SootClass;
import soot.Type;
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.asg.AugmentedStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.dava.toolkits.base.AST.structuredAnalysis.UnreachableCodeFinder;
import soot.jimple.Stmt;
public class UnreachableCodeEliminator extends DepthFirstAdapter {
public boolean DUBUG = true;
ASTNode AST;
UnreachableCodeFinder codeFinder;
public UnreachableCodeEliminator(ASTNode AST) {
super();
this.AST = AST;
setup();
}
public UnreachableCodeEliminator(boolean verbose, ASTNode AST) {
super(verbose);
this.AST = AST;
setup();
}
private void setup() {
codeFinder = new UnreachableCodeFinder(AST);
// parentOf = new ASTParentNodeFinder();
// AST.apply(parentOf);
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
List<AugmentedStmt> toRemove = new ArrayList<AugmentedStmt>();
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
// System.out.println("HERE!!!"+s.toString());
if (!codeFinder.isConstructReachable(s)) {
toRemove.add(as);
// if(DEBUG) System.out.println("Statement "+s.toString()+ " is NOT REACHABLE REMOVE IT");
}
}
for (AugmentedStmt as : toRemove) {
node.getStatements().remove(as);
}
}
public void normalRetrieving(ASTNode node) {
if (node instanceof ASTSwitchNode) {
dealWithSwitchNode((ASTSwitchNode) node);
return;
}
// from the Node get the subBodes
List<ASTNode> toReturn = new ArrayList<ASTNode>();
Iterator<Object> sbit = node.get_SubBodies().iterator();
while (sbit.hasNext()) {
Object subBody = sbit.next();
Iterator<ASTNode> it = ((List<ASTNode>) subBody).iterator();
// go over the ASTNodes in this subBody and apply
while (it.hasNext()) {
ASTNode temp = it.next();
if (!codeFinder.isConstructReachable(temp)) {
// System.out.println("-------------------------A child of node of type "+node.getClass()+" whose type is
// "+temp.getClass()+" is
// unreachable");
toReturn.add(temp);
} else {
// only apply on reachable nodes
temp.apply(this);
}
}
it = toReturn.iterator();
while (it.hasNext()) {
// System.out.println("Removed");
((List) subBody).remove(it.next());
}
} // end of going over subBodies
}
// TODO
public void caseASTTryNode(ASTTryNode node) {
// get try body
List<Object> tryBody = node.get_TryBody();
Iterator<Object> it = tryBody.iterator();
// go over the ASTNodes in this tryBody and apply
List<Object> toReturn = new ArrayList<Object>();
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
if (!codeFinder.isConstructReachable(temp)) {
toReturn.add(temp);
} else {
// only apply on reachable nodes
temp.apply(this);
}
}
it = toReturn.iterator();
while (it.hasNext()) {
tryBody.remove(it.next());
}
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);
/*
* March 18th, 2006, Since these are always locals we dont have access to ValueBox
*/
decideCaseExprOrRef(local);
// apply on catchBody
List<Object> body = (List<Object>) catchBody.o;
toReturn = new ArrayList<Object>();
itBody = body.iterator();
while (itBody.hasNext()) {
ASTNode temp = (ASTNode) itBody.next();
if (!codeFinder.isConstructReachable(temp)) {
toReturn.add(temp);
} else {
// only apply on reachable nodes
temp.apply(this);
}
}
itBody = toReturn.iterator();
while (itBody.hasNext()) {
body.remove(itBody.next());
}
}
}
private void dealWithSwitchNode(ASTSwitchNode node) {
// System.out.println("dealing with SwitchNode");
// 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 body = index2BodyList.get(currentIndex);
if (body == null) {
continue;
}
// this body is a list of ASTNodes
List<ASTNode> toReturn = new ArrayList<ASTNode>();
Iterator itBody = body.iterator();
// go over the ASTNodes and apply
while (itBody.hasNext()) {
ASTNode temp = (ASTNode) itBody.next();
// System.out.println("Checking whether child of type "+temp.getClass()+" is reachable");
if (!codeFinder.isConstructReachable(temp)) {
// System.out.println(">>>>>>>>>>>>>>>>>-------------------------A child of node of type "+node.getClass()+" whose
// type is
// "+temp.getClass()+" is unreachable");
toReturn.add(temp);
} else {
// System.out.println("child of type "+temp.getClass()+" is reachable");
// only apply on reachable nodes
temp.apply(this);
}
}
Iterator<ASTNode> newit = toReturn.iterator();
while (newit.hasNext()) {
// System.out.println("Removed");
body.remove(newit.next());
}
}
}
}
| 7,270
| 30.613043
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/UselessAbruptStmtRemover.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 soot.G;
import soot.dava.DecompilationException;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
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.ASTUnconditionalLoopNode;
import soot.dava.internal.AST.ASTWhileNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DAbruptStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.dava.toolkits.base.AST.traversals.ASTParentNodeFinder;
import soot.dava.toolkits.base.AST.traversals.LabelToNodeMapper;
import soot.jimple.Stmt;
/*
* It has been seen that a lot of times there are break statements targeting
* a label absolutely unnecessarily (with continues this is rare but to be complete
* we will handle them too)
* An example:
* label1:
* if(cond1){
* BodyA
* break label1
* }
*
* As in the above code the break stmt is absolutely unnessary as the code
* will itself flow to the required position.
*
* However, remember that breaks and continues are also used to
* exit or repeat a loop in which case we should keep the break and continue!!!
*
* TODO Also if we do decide to remove an abrupt stmt make sure that the
* stmt seq node has not become empty. If it has remove the node and see
* if the construct carrying this node has become empty and so on.....
*/
public class UselessAbruptStmtRemover extends DepthFirstAdapter {
public static boolean DEBUG = false;
ASTParentNodeFinder finder;
ASTMethodNode methodNode;
LabelToNodeMapper mapper;
public UselessAbruptStmtRemover() {
finder = null;
}
public UselessAbruptStmtRemover(boolean verbose) {
super(verbose);
finder = null;
}
public void inASTMethodNode(ASTMethodNode node) {
methodNode = node;
mapper = new LabelToNodeMapper();
methodNode.apply(mapper);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node) {
Iterator<AugmentedStmt> it = node.getStatements().iterator();
AugmentedStmt remove = null;
ASTLabeledNode target = null;
while (it.hasNext()) {
AugmentedStmt as = it.next();
Stmt s = as.get_Stmt();
// we only care about break and continue stmts
if (!(s instanceof DAbruptStmt)) {
continue;
}
DAbruptStmt abrupt = (DAbruptStmt) s;
String label = abrupt.getLabel().toString();
if (label == null) {
// could at some time implement a version of the same
// analysis with implicit abrupt flow but not needed currently
continue;
}
if (it.hasNext()) {
// there is an abrupt stmt and this stmt seq node has something
// afterwards...that is for sure dead code
throw new DecompilationException("Dead code detected. Report to developer");
}
// get the target node
Object temp = mapper.getTarget(label);
if (temp == null) {
continue;
// throw new DecompilationException("Could not find target for abrupt stmt"+abrupt.toString());
}
target = (ASTLabeledNode) temp;
// will need to find parents of ancestors see if we need to initialize the finder
if (finder == null) {
finder = new ASTParentNodeFinder();
methodNode.apply(finder);
}
if (DEBUG) {
System.out.println("Starting useless check for abrupt stmt: " + abrupt);
}
// start condition is that ancestor is the stmt seq node
ASTNode ancestor = node;
while (ancestor != target) {
Object tempParent = finder.getParentOf(ancestor);
if (tempParent == null) {
throw new DecompilationException("Parent found was null!!. Report to Developer");
}
ASTNode ancestorsParent = (ASTNode) tempParent;
if (DEBUG) {
System.out.println("\tCurrent ancestorsParent has type" + ancestorsParent.getClass());
}
// ancestor should be last child of ancestorsParent
if (!checkChildLastInParent(ancestor, ancestorsParent)) {
if (DEBUG) {
System.out.println("\t\tCurrent ancestorParent has more children after this ancestor");
}
// return from the method since this is the last stmt and we cant do anything
return;
}
// ancestorsParent should not be a loop of any kind OR A SWITCH
if (ancestorsParent instanceof ASTWhileNode || ancestorsParent instanceof ASTDoWhileNode
|| ancestorsParent instanceof ASTUnconditionalLoopNode || ancestorsParent instanceof ASTForLoopNode
|| ancestorsParent instanceof ASTSwitchNode) {
if (DEBUG) {
System.out.println("\t\tAncestorsParent is a loop shouldnt remove abrupt stmt");
}
return;
}
ancestor = ancestorsParent;
}
if (DEBUG) {
System.out.println("\tGot to target without returning means we can remove stmt");
}
remove = as;
} // end of while going through the statement sequence
if (remove != null) {
List<AugmentedStmt> stmts = node.getStatements();
stmts.remove(remove);
if (DEBUG) {
System.out.println("\tRemoved abrupt stmt");
}
if (target != null) {
if (DEBUG) {
System.out.println("Invoking findAndKill on the target");
}
UselessLabelFinder.v().findAndKill(target);
}
// TODO what if we just emptied a stmt seq block??
// not doing this for the moment
// set modified flag make finder null
G.v().ASTTransformations_modified = true;
finder = null;
}
}
public boolean checkChildLastInParent(ASTNode child, ASTNode parent) {
List<Object> subBodies = parent.get_SubBodies();
Iterator<Object> it = subBodies.iterator();
while (it.hasNext()) {
List subBody = null;
if (parent instanceof ASTTryNode) {
subBody = (List) ((ASTTryNode.container) it.next()).o;
} else {
subBody = (List) it.next();
}
if (subBody.contains(child)) {
if (subBody.indexOf(child) != subBody.size() - 1) {
return false;
} else {
return true;
}
}
}
return false;
}
}
| 7,411
| 31.942222
| 111
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/UselessLabelFinder.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.Singletons;
import soot.dava.internal.AST.ASTLabeledNode;
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.jimple.Stmt;
public class UselessLabelFinder {
public static boolean DEBUG = false;
public UselessLabelFinder(Singletons.Global g) {
}
public static UselessLabelFinder v() {
return G.v().soot_dava_toolkits_base_AST_transformations_UselessLabelFinder();
}
// check whether label on a node is useless
public boolean findAndKill(ASTNode node) {
if (!(node instanceof ASTLabeledNode)) {
if (DEBUG) {
System.out.println("Returning from findAndKill for node of type " + node.getClass());
}
return false;
} else {
if (DEBUG) {
System.out.println("FindAndKill continuing for node fo type" + node.getClass());
}
}
String label = ((ASTLabeledNode) node).get_Label().toString();
if (label == null) {
return false;
}
if (DEBUG) {
System.out.println("dealing with labeled node" + label);
}
List<Object> subBodies = node.get_SubBodies();
Iterator<Object> it = subBodies.iterator();
while (it.hasNext()) {
List subBodyTemp = null;
if (node instanceof ASTTryNode) {
// an astTryNode
ASTTryNode.container subBody = (ASTTryNode.container) it.next();
subBodyTemp = (List) subBody.o;
// System.out.println("\ntryNode body");
} else {
// not an astTryNode
// System.out.println("not try node in findAndkill");
subBodyTemp = (List) it.next();
}
if (checkForBreak(subBodyTemp, label)) {
// found a break
return false;
}
}
// only if all bodies dont contain a break can we remove the label
// means break was not found so we can remove
((ASTLabeledNode) node).set_Label(new SETNodeLabel());
if (DEBUG) {
System.out.println("USELESS LABEL DETECTED");
}
return true;
}
/*
* Returns True if finds a break for this label
*/
private boolean checkForBreak(List ASTNodeBody, String outerLabel) {
// if(DEBUG)
// System.out.println("method checkForBreak..... label is "+outerLabel);
Iterator it = ASTNodeBody.iterator();
while (it.hasNext()) {
ASTNode temp = (ASTNode) it.next();
// check if this is ASTStatementSequenceNode
if (temp instanceof ASTStatementSequenceNode) {
// if(DEBUG) System.out.println("Stmt seq Node");
ASTStatementSequenceNode stmtSeq = (ASTStatementSequenceNode) temp;
for (AugmentedStmt as : stmtSeq.getStatements()) {
Stmt s = as.get_Stmt();
String labelBroken = breaksLabel(s);
if (labelBroken != null && outerLabel != null) {
// stmt breaks some label
if (labelBroken.compareTo(outerLabel) == 0) {
// we have found a break breaking this label
return true;
}
}
}
} // if it was a StmtSeq node
else {
// otherwise recursion
// getSubBodies
// if(DEBUG) System.out.println("Not Stmt seq Node");
List<Object> subBodies = temp.get_SubBodies();
Iterator<Object> subIt = subBodies.iterator();
while (subIt.hasNext()) {
List subBodyTemp = null;
if (temp instanceof ASTTryNode) {
ASTTryNode.container subBody = (ASTTryNode.container) subIt.next();
subBodyTemp = (List) subBody.o;
// System.out.println("Try body node");
} else {
subBodyTemp = (List) subIt.next();
}
if (checkForBreak(subBodyTemp, outerLabel)) {
// if this is true there was a break found
return true;
}
}
}
}
return false;
}
/*
* If the stmt is a break/continue stmt then this method returns the labels name else returns null
*/
private String breaksLabel(Stmt stmt) {
if (!(stmt instanceof DAbruptStmt)) {
// this is not a break stmt
return null;
}
DAbruptStmt abStmt = (DAbruptStmt) stmt;
if (abStmt.is_Break() || abStmt.is_Continue()) {
SETNodeLabel label = abStmt.getLabel();
return label.toString();
} else {
return null;
}
}
}
| 5,399
| 30.764706
| 100
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/UselessLabeledBlockRemover.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.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.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.internal.SET.SETNodeLabel;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
/*
* CHANGE LOG:
* Nomair A Naeem
* 17th April 2006
* The class was implemented all wrong since the case methods were being overriddern and hence
* the analysis was nto going into all children.
*
* changed this by overridding out methods instead of case
*
*
* Class serves two purposes.
* If you know there is a useless labeled block then its static methods can be invoked
* as done by the ASTCleaner
*
* It can also be used to apply the UselessLabelFinder to all nodes of the AST
* if that is done then make sure to set the ASTAnalysisModified
*/
public class UselessLabeledBlockRemover extends DepthFirstAdapter {
boolean changed = false;
public UselessLabeledBlockRemover() {
}
public UselessLabeledBlockRemover(boolean verbose) {
super(verbose);
}
public void outASTMethodNode(ASTMethodNode node) {
if (changed) {
G.v().ASTTransformations_modified = true;
}
}
public void inASTMethodNode(ASTMethodNode node) {
changed = UselessLabelFinder.v().findAndKill(node);
}
/*
* public void caseASTSynchronizedBlockNode(ASTSynchronizedBlockNode node){
* changed=UselessLabelFinder.v().findAndKill(node); } public void caseASTLabeledBlockNode (ASTLabeledBlockNode node){
* changed=UselessLabelFinder.v().findAndKill(node); } public void caseASTUnconditionalLoopNode (ASTUnconditionalLoopNode
* node){ changed=UselessLabelFinder.v().findAndKill(node); } public void caseASTSwitchNode(ASTSwitchNode node){
* changed=UselessLabelFinder.v().findAndKill(node); } public void caseASTIfNode(ASTIfNode node){
* changed=UselessLabelFinder.v().findAndKill(node); } public void caseASTIfElseNode(ASTIfElseNode node){
* changed=UselessLabelFinder.v().findAndKill(node); } public void caseASTWhileNode(ASTWhileNode node){
* changed=UselessLabelFinder.v().findAndKill(node); } public void caseASTForLoopNode(ASTForLoopNode node){
* changed=UselessLabelFinder.v().findAndKill(node); } public void caseASTDoWhileNode(ASTDoWhileNode node){
* changed=UselessLabelFinder.v().findAndKill(node); } public void caseASTTryNode(ASTTryNode node){
* changed=UselessLabelFinder.v().findAndKill(node); }
*/
public void outASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public void outASTLabeledBlockNode(ASTLabeledBlockNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public void outASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public void outASTSwitchNode(ASTSwitchNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public void outASTIfNode(ASTIfNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public void outASTIfElseNode(ASTIfElseNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public void outASTWhileNode(ASTWhileNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public void outASTForLoopNode(ASTForLoopNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public void outASTDoWhileNode(ASTDoWhileNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public void outASTTryNode(ASTTryNode node) {
boolean modified = UselessLabelFinder.v().findAndKill(node);
if (modified) {
changed = true;
}
}
public static void removeLabeledBlock(ASTNode node, ASTLabeledBlockNode labelBlock, 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 labeledBlockNode to be removed at location given by the nodeNumber variable
*/
List<Object> newBody = createNewSubBody(onlySubBody, nodeNumber, labelBlock);
if (newBody == null) {
// something went wrong
return;
}
if (node instanceof ASTMethodNode) {
((ASTMethodNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL");
} else if (node instanceof ASTSynchronizedBlockNode) {
((ASTSynchronizedBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL");
} else if (node instanceof ASTLabeledBlockNode) {
((ASTLabeledBlockNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL");
} else if (node instanceof ASTUnconditionalLoopNode) {
((ASTUnconditionalLoopNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL");
} else if (node instanceof ASTIfNode) {
((ASTIfNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL");
} else if (node instanceof ASTWhileNode) {
((ASTWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL");
} else if (node instanceof ASTDoWhileNode) {
((ASTDoWhileNode) node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
// System.out.println("REMOVED LABEL");
} 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 labeledBlockNode to be removed at location given by the nodeNumber variable
*/
List<Object> newBody = createNewSubBody(toModifySubBody, nodeNumber, labelBlock);
if (newBody == null) {
// something went wrong
return;
}
if (subBodyNumber == 0) {
// the if body was modified
// System.out.println("REMOVED LABEL");
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 LABEL");
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> createNewSubBody(List<Object> oldSubBody, int nodeNumber, ASTLabeledBlockNode labelBlock) {
// 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 ASTLabeledBlock to be removed
// just to make sure check this
ASTNode toRemove = (ASTNode) it.next();
if (!(toRemove instanceof ASTLabeledBlockNode)) {
// something is wrong
return null;
} else {
ASTLabeledBlockNode toRemoveNode = (ASTLabeledBlockNode) toRemove;
// just double checking that this is a null label
SETNodeLabel label = toRemoveNode.get_Label();
if (label.toString() != null) {
// something is wrong we cant remove a non null label
return null;
}
// so this is the label to remove
// removing a label means bringing all its bodies one step up the hierarchy
List<Object> blocksSubBodies = toRemoveNode.get_SubBodies();
// we know this is a labeledBlock so it has only one subBody
List onlySubBodyOfLabeledBlock = (List) blocksSubBodies.get(0);
// all these subBodies should be added to the newSubbody
newSubBody.addAll(onlySubBodyOfLabeledBlock);
}
// 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;
}
}
| 11,351
| 35.501608
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/transformations/VoidReturnRemover.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.SootClass;
import soot.SootMethod;
import soot.VoidType;
import soot.dava.DavaBody;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
import soot.util.Chain;
public class VoidReturnRemover {
public static void cleanClass(SootClass s) {
List methods = s.getMethods();
Iterator it = methods.iterator();
while (it.hasNext()) {
removeReturn((SootMethod) it.next());
}
}
private static void removeReturn(SootMethod method) {
// check if this is a void method
if (!(method.getReturnType() instanceof VoidType)) {
return;
}
// get the methodnode
if (!method.hasActiveBody()) {
return;
}
Chain units = ((DavaBody) method.getActiveBody()).getUnits();
if (units.size() != 1) {
return;
}
ASTNode AST = (ASTNode) units.getFirst();
if (!(AST instanceof ASTMethodNode)) {
throw new RuntimeException("Starting node of DavaBody AST is not an ASTMethodNode");
}
ASTMethodNode node = (ASTMethodNode) AST;
// check there is only 1 subBody
List<Object> subBodies = node.get_SubBodies();
if (subBodies.size() != 1) {
return;
}
List subBody = (List) subBodies.get(0);
// see if the last of this is a stmtseq node
if (subBody.size() == 0) {
// nothing inside subBody
return;
}
// check last node is a ASTStatementSequenceNode
ASTNode last = (ASTNode) subBody.get(subBody.size() - 1);
if (!(last instanceof ASTStatementSequenceNode)) {
return;
}
// get last statement
List<AugmentedStmt> stmts = ((ASTStatementSequenceNode) last).getStatements();
if (stmts.size() == 0) {
// no stmts inside statement sequence node
subBody.remove(subBody.size() - 1);
return;
}
AugmentedStmt lastas = (AugmentedStmt) stmts.get(stmts.size() - 1);
Stmt lastStmt = lastas.get_Stmt();
if (!(lastStmt instanceof ReturnVoidStmt)) {
return;
}
// we can remove the lastStmt
stmts.remove(stmts.size() - 1);
/*
* we need to check if we have made the size 0 in which case the stmtSeq Node should also be removed
*/
if (stmts.size() == 0) {
subBody.remove(subBody.size() - 1);
}
}
// end method
}
| 3,341
| 27.564103
| 104
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/traversals/ASTParentNodeFinder.java
|
package soot.dava.toolkits.base.AST.traversals;
/*-
* #%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.HashMap;
import java.util.Stack;
import soot.Unit;
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.internal.javaRep.DVariableDeclarationStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.DefinitionStmt;
import soot.jimple.InvokeStmt;
import soot.jimple.ReturnStmt;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
/*
* This traversal class is responsible to gather information
* regarding the different nodes and statements in the AST.
* The class produces a HashMap between the node/statement given as
* key and the parent of this construct (value)
*
* November 23rd, 2005. (Nomair) It is used for instance in the CopyPropagation algorithm
* to be able to remove a particular copy
* stmt for instance from its parent.
*/
public class ASTParentNodeFinder extends DepthFirstAdapter {
HashMap<Unit, ASTNode> parentOf;
Stack<ASTNode> parentStack;
public ASTParentNodeFinder() {
parentOf = new HashMap<Unit, ASTNode>();
parentStack = new Stack<ASTNode>();
}
public ASTParentNodeFinder(boolean verbose) {
super(verbose);
parentOf = new HashMap<Unit, ASTNode>();
parentStack = new Stack<ASTNode>();
}
public void inASTMethodNode(ASTMethodNode node) {
parentOf.put(node, null);
parentStack.push(node);
}
public void outASTMethodNode(ASTMethodNode node) {
parentStack.pop();
}
public void inASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
parentStack.pop();
}
public void inASTLabeledBlockNode(ASTLabeledBlockNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTLabeledBlockNode(ASTLabeledBlockNode node) {
parentStack.pop();
}
public void inASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
parentStack.pop();
}
public void inASTSwitchNode(ASTSwitchNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTSwitchNode(ASTSwitchNode node) {
parentStack.pop();
}
public void inASTIfNode(ASTIfNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTIfNode(ASTIfNode node) {
parentStack.pop();
}
public void inASTIfElseNode(ASTIfElseNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTIfElseNode(ASTIfElseNode node) {
parentStack.pop();
}
public void inASTWhileNode(ASTWhileNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTWhileNode(ASTWhileNode node) {
parentStack.pop();
}
public void inASTForLoopNode(ASTForLoopNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTForLoopNode(ASTForLoopNode node) {
parentStack.pop();
}
public void inASTDoWhileNode(ASTDoWhileNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTDoWhileNode(ASTDoWhileNode node) {
parentStack.pop();
}
public void inASTTryNode(ASTTryNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTTryNode(ASTTryNode node) {
parentStack.pop();
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
parentOf.put(node, parentStack.peek());
parentStack.push(node);
}
public void outASTStatementSequenceNode(ASTStatementSequenceNode node) {
parentStack.pop();
}
public void inDefinitionStmt(DefinitionStmt s) {
parentOf.put(s, parentStack.peek());
}
public void inReturnStmt(ReturnStmt s) {
parentOf.put(s, parentStack.peek());
}
public void inInvokeStmt(InvokeStmt s) {
parentOf.put(s, parentStack.peek());
}
public void inThrowStmt(ThrowStmt s) {
parentOf.put(s, parentStack.peek());
}
public void inDVariableDeclarationStmt(DVariableDeclarationStmt s) {
parentOf.put(s, parentStack.peek());
}
public void inStmt(Stmt s) {
parentOf.put(s, parentStack.peek());
}
/*
* This is the method which should be invoked by classes needing parent information. When the method is invoked with a
* statement or node as input it returns the parent of that object. The parent can safely be casted to ASTNode as long as
* the parent returned is non null
*/
public Object getParentOf(Object statementOrNode) {
return parentOf.get(statementOrNode);
}
}
| 6,222
| 27.545872
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/traversals/ASTUsesAndDefs.java
|
package soot.dava.toolkits.base.AST.traversals;
/*-
* #%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 soot.Local;
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.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.ReachingDefs;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
/*
THE ALGORITHM USES THE RESULTS OF REACHINGDEFS STRUCTURAL FLOW ANALYSIS
DEFINITION uD Chain:
For a use of variable x, the uD Chain gives ALL POSSIBLE definitions of x that can reach the use x
DEFINITION dU Chain:
For a definition d, the dU Chain gives all places where this definition is used
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, while , do while, for condition
b, in the for init or update
c, in a switch choice
d, in a syncrhnoized block
d, in a statement
*/
public class ASTUsesAndDefs extends DepthFirstAdapter {
public static boolean DEBUG = false;
HashMap<Object, List<DefinitionStmt>> uD; // mapping a use to all possible
// definitions
HashMap<Object, List> dU; // mapping a def to all possible uses
ReachingDefs reaching; // using structural analysis information
public ASTUsesAndDefs(ASTNode AST) {
uD = new HashMap<Object, List<DefinitionStmt>>();
dU = new HashMap<Object, List>();
reaching = new ReachingDefs(AST);
}
public ASTUsesAndDefs(boolean verbose, ASTNode AST) {
super(verbose);
uD = new HashMap<Object, List<DefinitionStmt>>();
dU = new HashMap<Object, List>();
reaching = new ReachingDefs(AST);
}
/*
* Method is used to strip away boxes from the actual values only those are returned which are locals
*/
private List<Value> getUsesFromBoxes(List useBoxes) {
ArrayList<Value> toReturn = new ArrayList<Value>();
Iterator it = useBoxes.iterator();
while (it.hasNext()) {
Value val = ((ValueBox) it.next()).getValue();
if (val instanceof Local) {
toReturn.add(val);
}
}
// System.out.println("VALUES:"+toReturn);
return toReturn;
}
public void checkStatementUses(Stmt s, Object useNodeOrStatement) {
List useBoxes = s.getUseBoxes();
// System.out.println("Uses in this statement:"+useBoxes);
List<Value> uses = getUsesFromBoxes(useBoxes);
// System.out.println("Local Uses in this statement:"+uses);
Iterator<Value> it = uses.iterator();
while (it.hasNext()) {
Local local = (Local) it.next();
createUDDUChain(local, useNodeOrStatement);
} // end of going through all locals uses in statement
/*
* see if this is a def stmt in which case add an empty entry into the dU chain
*
* The wisdowm behind this is that later on when this definition is used we will use this arraylist to store the uses of
* this definition
*/
if (s instanceof DefinitionStmt) {
// check if dU doesnt already have something for this
if (dU.get(s) == null) {
dU.put(s, new ArrayList());
}
}
}
/*
* The method gets the reaching defs of local used Then all the possible defs are added into the uD chain of the node The
* use is added to all the defs reaching this node
*/
public void createUDDUChain(Local local, Object useNodeOrStatement) {
// System.out.println("Local is:"+local);
// System.out.println("useNodeOrStatement is"+useNodeOrStatement);
List<DefinitionStmt> reachingDefs = reaching.getReachingDefs(local, useNodeOrStatement);
if (DEBUG) {
System.out.println("Reaching def for:" + local + " are:" + reachingDefs);
}
// add the reaching defs into the use def chain
Object tempObj = uD.get(useNodeOrStatement);
if (tempObj != null) {
List<DefinitionStmt> tempList = (List<DefinitionStmt>) tempObj;
tempList.addAll(reachingDefs);
uD.put(useNodeOrStatement, tempList);
} else {
uD.put(useNodeOrStatement, reachingDefs);
}
// add the use into the def use chain
Iterator<DefinitionStmt> defIt = reachingDefs.iterator();
while (defIt.hasNext()) {
// for each reaching def
Object defStmt = defIt.next();
// get the dU Chain
Object useObj = dU.get(defStmt);
List<Object> uses = null;
if (useObj == null) {
uses = new ArrayList<Object>();
} else {
uses = (List<Object>) useObj;
}
// add the new local use to this list (we add the node since thats
// where the local is used
uses.add(useNodeOrStatement);
// System.out.println("Adding definition:"+defStmt+"with uses:"+uses);
dU.put(defStmt, uses);
}
}
/*
* Given a unary/binary or aggregated condition this method is used to find the locals used in the condition
*/
public List<Value> getUseList(ASTCondition cond) {
ArrayList<Value> useList = new ArrayList<Value>();
if (cond instanceof ASTAggregatedCondition) {
useList.addAll(getUseList(((ASTAggregatedCondition) cond).getLeftOp()));
useList.addAll(getUseList(((ASTAggregatedCondition) cond).getRightOp()));
return useList;
} else if (cond instanceof ASTUnaryCondition) {
// get uses from unary condition
List<Value> uses = new ArrayList<Value>();
Value val = ((ASTUnaryCondition) cond).getValue();
if (val instanceof Local) {
if (DEBUG) {
System.out.println("adding local from unary condition as a use" + val);
}
uses.add(val);
} else {
List useBoxes = val.getUseBoxes();
uses = getUsesFromBoxes(useBoxes);
}
return uses;
} else if (cond instanceof ASTBinaryCondition) {
// get uses from binaryCondition
Value val = ((ASTBinaryCondition) cond).getConditionExpr();
List useBoxes = val.getUseBoxes();
return getUsesFromBoxes(useBoxes);
} else {
throw new RuntimeException("Method getUseList in ASTUsesAndDefs encountered unknown condition type");
}
}
/*
* This method gets a list of all uses of locals in the condition Then it invokes the createUDDUChain for each local
*/
public void checkConditionalUses(ASTCondition cond, ASTNode node) {
List<Value> useList = getUseList(cond);
// System.out.println("FOR NODE with condition:"+cond+"USE list is:"+useList);
// FOR EACH USE
Iterator<Value> it = useList.iterator();
while (it.hasNext()) {
Local local = (Local) it.next();
// System.out.println("creating uddu for "+local);
createUDDUChain(local, node);
} // end of going through all locals uses in condition
}
/*
* The key in a switch stmt can be a local or a value which can contain Locals
*
* Hence the some what indirect approach
*/
public void inASTSwitchNode(ASTSwitchNode node) {
Value val = node.get_Key();
List<Value> uses = new ArrayList<Value>();
if (val instanceof Local) {
uses.add(val);
} else {
List useBoxes = val.getUseBoxes();
uses = getUsesFromBoxes(useBoxes);
}
Iterator<Value> it = uses.iterator();
// System.out.println("SWITCH uses start:");
while (it.hasNext()) {
Local local = (Local) it.next();
// System.out.println(local);
createUDDUChain(local, node);
} // end of going through all locals uses in switch key
// System.out.println("SWITCH uses end:");
}
public void inASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
Local local = node.getLocal();
createUDDUChain(local, node);
}
/*
* The condition of an if node can use a local
*/
public void inASTIfNode(ASTIfNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The condition of an ifElse node can use a local
*/
public void inASTIfElseNode(ASTIfElseNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The condition of a while node can use a local
*/
public void inASTWhileNode(ASTWhileNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The condition of a doWhile node can use a local
*/
public void inASTDoWhileNode(ASTDoWhileNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The init of a for loop can use a local The condition of a for node can use a local The update in a for loop can use a
* local
*/
public void inASTForLoopNode(ASTForLoopNode node) {
// checking uses in init
for (AugmentedStmt as : node.getInit()) {
Stmt s = as.get_Stmt();
checkStatementUses(s, node);
}
// 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();
checkStatementUses(s, node);
}
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
// in the case of stmtts in a stmtt sequence each stmt is considered
// an entity
// compared to the case where these stmts occur within other
// constructs
// where the node is the entity
checkStatementUses(s, s);
}
}
/*
* Input is a construct (ASTNode or statement) that has some locals used and output are all defs reached for all the uses
* in that construct...
*
* dont know whether it actually makes sense for the nodes but it definetly makes sense for the statements
*/
public List getUDChain(Object node) {
return uD.get(node);
}
/*
* Give it a def stmt and it will return all places where it is used a use is either a statement or a node(condition,
* synch, switch , for etc)
*/
public List getDUChain(Object node) {
return dU.get(node);
}
public HashMap<Object, List> getDUHashMap() {
return dU;
}
public void outASTMethodNode(ASTMethodNode node) {
// print();
}
public void print() {
System.out.println("\n\n\nPRINTING uD dU CHAINS ______________________________");
Iterator<Object> it = dU.keySet().iterator();
while (it.hasNext()) {
DefinitionStmt s = (DefinitionStmt) it.next();
System.out.println("*****The def " + s + " has following uses:");
Object obj = dU.get(s);
if (obj != null) {
ArrayList list = (ArrayList) obj;
Iterator tempIt = list.iterator();
while (tempIt.hasNext()) {
Object tempUse = tempIt.next();
System.out.println("-----------Use " + tempUse);
System.out.println("----------------Defs of this use: " + uD.get(tempUse));
}
}
}
System.out.println("END --------PRINTING uD dU CHAINS ______________________________");
}
}
| 12,458
| 32.224
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/traversals/AllDefinitionsFinder.java
|
package soot.dava.toolkits.base.AST.traversals;
/*-
* #%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.List;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.DefinitionStmt;
/*
* DefinitionStmts can occur in either ASTStatementSequenceNode or the for init and for update
* These are needed for the newinitialFlow method of reachingDefs which needs a universal set of definitions
*/
public class AllDefinitionsFinder extends DepthFirstAdapter {
ArrayList<DefinitionStmt> allDefs = new ArrayList<DefinitionStmt>();
public AllDefinitionsFinder() {
}
public AllDefinitionsFinder(boolean verbose) {
super(verbose);
}
public void inDefinitionStmt(DefinitionStmt s) {
allDefs.add(s);
}
public List<DefinitionStmt> getAllDefs() {
return allDefs;
}
}
| 1,608
| 27.732143
| 108
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/traversals/AllVariableUses.java
|
package soot.dava.toolkits.base.AST.traversals;
/*-
* #%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.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.ASTNode;
import soot.dava.internal.AST.ASTStatementSequenceNode;
import soot.dava.internal.AST.ASTSwitchNode;
import soot.dava.internal.AST.ASTSynchronizedBlockNode;
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.jimple.FieldRef;
import soot.jimple.Stmt;
/*
* Creates a mapping of locals and all places where they might be used
* creates a mapping of fields and all places where they might be used
* Notice that the mapping is for SootField to uses not for FieldRef to uses
*/
public class AllVariableUses extends DepthFirstAdapter {
ASTMethodNode methodNode;
HashMap<Local, List> localsToUses;
HashMap<SootField, List> fieldsToUses;
public AllVariableUses(ASTMethodNode node) {
super();
this.methodNode = node;
init();
}
public AllVariableUses(boolean verbose, ASTMethodNode node) {
super(verbose);
this.methodNode = node;
init();
}
public void init() {
localsToUses = new HashMap<Local, List>();
fieldsToUses = new HashMap<SootField, List>();
}
/*
* Notice as things stand synchblocks cant have the use of a SootField
*/
public void inASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
Local local = node.getLocal();
addLocalUse(local, node);
}
/*
* The key in a switch stmt can be a local or a SootField or a value which can contain Locals or SootFields
*
* Hence the some what indirect approach
*/
public void inASTSwitchNode(ASTSwitchNode node) {
Value val = node.get_Key();
List<Value> localUses = new ArrayList<Value>();
List<Value> fieldUses = new ArrayList<Value>();
if (val instanceof Local) {
localUses.add(val);
System.out.println("Added " + val + " to local uses for switch");
} else if (val instanceof FieldRef) {
fieldUses.add(val);
System.out.println("Added " + val + " to field uses for switch");
} else {
List useBoxes = val.getUseBoxes();
List<Value> localsOrFieldRefs = getUsesFromBoxes(useBoxes);
Iterator<Value> it = localsOrFieldRefs.iterator();
while (it.hasNext()) {
Value temp = it.next();
if (temp instanceof Local) {
localUses.add(temp);
System.out.println("Added " + temp + " to local uses for switch");
} else if (temp instanceof FieldRef) {
fieldUses.add(temp);
System.out.println("Added " + temp + " to field uses for switch");
}
}
}
// localuses stores Locals used
Iterator<Value> it = localUses.iterator();
while (it.hasNext()) {
Local local = (Local) it.next();
addLocalUse(local, node);
} // end of going through all locals uses in switch key
// fieldUses stores FieldRef
it = fieldUses.iterator();
while (it.hasNext()) {
FieldRef field = (FieldRef) it.next();
SootField sootField = field.getField();
addFieldUse(sootField, node);
} // end of going through all FieldRef uses in switch key
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
// in the case of stmtts in a stmtt sequence each stmt is considered
// an entity
// compared to the case where these stmts occur within other
// constructs
// where the node is the entity
checkStatementUses(s, s);
}
}
/*
* The init of a for loop can use a local/Sootfield The condition of a for node can use a local/SootField The update in a
* for loop can use a local/SootField
*/
public void inASTForLoopNode(ASTForLoopNode node) {
// checking uses in init
for (AugmentedStmt as : node.getInit()) {
Stmt s = as.get_Stmt();
checkStatementUses(s, node);
}
// 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();
checkStatementUses(s, node);
}
}
public void checkStatementUses(Stmt s, Object useNodeOrStatement) {
List useBoxes = s.getUseBoxes();
// remeber getUsesFromBoxes returns both Locals and FieldRefs
List<Value> uses = getUsesFromBoxes(useBoxes);
Iterator<Value> it = uses.iterator();
while (it.hasNext()) {
Value temp = it.next();
if (temp instanceof Local) {
addLocalUse((Local) temp, useNodeOrStatement);
} else if (temp instanceof FieldRef) {
FieldRef field = (FieldRef) temp;
SootField sootField = field.getField();
addFieldUse(sootField, useNodeOrStatement);
}
}
}
/*
* This method gets a list of all uses of locals/Sootfield in the condition and stores a use by this node
*/
public void checkConditionalUses(ASTCondition cond, ASTNode node) {
List<Value> useList = getUseList(cond);
// System.out.println("FOR NODE with condition:"+cond+"USE list is:"+useList);
// FOR EACH USE
Iterator<Value> it = useList.iterator();
while (it.hasNext()) {
Value temp = it.next();
if (temp instanceof Local) {
addLocalUse((Local) temp, node);
} else if (temp instanceof FieldRef) {
FieldRef field = (FieldRef) temp;
SootField sootField = field.getField();
addFieldUse(sootField, node);
}
} // end of going through all locals uses in condition
}
/*
* The condition of an if node can use a local
*/
public void inASTIfNode(ASTIfNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The condition of an ifElse node can use a local
*/
public void inASTIfElseNode(ASTIfElseNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The condition of a while node can use a local
*/
public void inASTWhileNode(ASTWhileNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* The condition of a doWhile node can use a local
*/
public void inASTDoWhileNode(ASTDoWhileNode node) {
ASTCondition cond = node.get_Condition();
checkConditionalUses(cond, node);
}
/*
* Given a unary/binary or aggregated condition this method is used to find the locals/SootFields used in the condition
*
* @param The condition to be checked for Local or FieldRef uses
*
* @return a list containing all Locals and FieldRefs used in this condition
*/
public List<Value> getUseList(ASTCondition cond) {
ArrayList<Value> useList = new ArrayList<Value>();
if (cond instanceof ASTAggregatedCondition) {
useList.addAll(getUseList(((ASTAggregatedCondition) cond).getLeftOp()));
useList.addAll(getUseList(((ASTAggregatedCondition) cond).getRightOp()));
return useList;
} else if (cond instanceof ASTUnaryCondition) {
// get uses from unary condition
List<Value> uses = new ArrayList<Value>();
Value val = ((ASTUnaryCondition) cond).getValue();
if (val instanceof Local || val instanceof FieldRef) {
uses.add(val);
} else {
List useBoxes = val.getUseBoxes();
uses = getUsesFromBoxes(useBoxes);
}
return uses;
} else if (cond instanceof ASTBinaryCondition) {
// get uses from binaryCondition
Value val = ((ASTBinaryCondition) cond).getConditionExpr();
List useBoxes = val.getUseBoxes();
return getUsesFromBoxes(useBoxes);
} else {
throw new RuntimeException("Method getUseList in ASTUsesAndDefs encountered unknown condition type");
}
}
private void addLocalUse(Local local, Object obj) {
Object temp = localsToUses.get(local);
List<Object> uses;
if (temp == null) {
uses = new ArrayList<Object>();
} else {
uses = (ArrayList<Object>) temp;
}
// add local to useList
uses.add(obj);
// update mapping
localsToUses.put(local, uses);
}
private void addFieldUse(SootField field, Object obj) {
Object temp = fieldsToUses.get(field);
List<Object> uses;
if (temp == null) {
uses = new ArrayList<Object>();
} else {
uses = (ArrayList<Object>) temp;
}
// add field to useList
uses.add(obj);
// update mapping
fieldsToUses.put(field, uses);
}
/*
* Method is used to strip away boxes from the actual values only those are returned which are locals or FieldRefs
*/
private List<Value> getUsesFromBoxes(List useBoxes) {
ArrayList<Value> toReturn = new ArrayList<Value>();
Iterator it = useBoxes.iterator();
while (it.hasNext()) {
Value val = ((ValueBox) it.next()).getValue();
if (val instanceof Local || val instanceof FieldRef) {
toReturn.add(val);
}
}
// System.out.println("VALUES:"+toReturn);
return toReturn;
}
public List getUsesForField(SootField field) {
Object temp = fieldsToUses.get(field);
if (temp == null) {
return null;
} else {
return (List) temp;
}
}
public List getUsesForLocal(Local local) {
Object temp = localsToUses.get(local);
if (temp == null) {
return null;
} else {
return (List) temp;
}
}
}
| 10,870
| 29.883523
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/traversals/ClosestAbruptTargetFinder.java
|
package soot.dava.toolkits.base.AST.traversals;
/*-
* #%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 soot.G;
import soot.Singletons;
import soot.dava.internal.AST.ASTDoWhileNode;
import soot.dava.internal.AST.ASTForLoopNode;
import soot.dava.internal.AST.ASTLabeledNode;
import soot.dava.internal.AST.ASTNode;
import soot.dava.internal.AST.ASTSwitchNode;
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.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.Stmt;
/**
* This class has been created because we need the immediate target of a implicit break/continue statement i.e. a
* break/continue statement which does not break/continue a particular label explicitly.
*
* Notice that this is only allowed for while do while, unconditional loop for loop switch construct.
*
* Notice continue is not allowed for switch also
*
* Explicit breaks can on the other hand break any label (that on a construct) which we are not worried about in this
* analysis
*/
public class ClosestAbruptTargetFinder extends DepthFirstAdapter {
public ClosestAbruptTargetFinder(Singletons.Global g) {
}
public static ClosestAbruptTargetFinder v() {
return G.v().soot_dava_toolkits_base_AST_traversals_ClosestAbruptTargetFinder();
}
HashMap<DAbruptStmt, ASTNode> closestNode = new HashMap<DAbruptStmt, ASTNode>();// a mapping of each abrupt statement to
// the node they are targeting
ArrayList<ASTLabeledNode> nodeStack = new ArrayList<ASTLabeledNode>(); // the last element will always be the "currentNode"
// meaning the closest
// target to a abrupt stmt
/**
* To be invoked by other analyses. Given an abrupt stmt as input this method will locate the closest target and return it
*/
public ASTNode getTarget(DAbruptStmt ab) {
Object node = closestNode.get(ab);
if (node != null) {
return (ASTNode) node;
} else {
throw new RuntimeException("Unable to find target for AbruptStmt");
}
}
/**
* Following methods add a new node to the end of the nodeStack arrayList Since that node becomes the closest target of an
* implicit break or continue
*/
public void inASTWhileNode(ASTWhileNode node) {
nodeStack.add(node);
}
public void inASTDoWhileNode(ASTDoWhileNode node) {
nodeStack.add(node);
}
public void inASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
nodeStack.add(node);
}
public void inASTForLoopNode(ASTForLoopNode node) {
nodeStack.add(node);
}
public void inASTSwitchNode(ASTSwitchNode node) {
nodeStack.add(node);
}
/**
* Following methods remove the last node from the end of the nodeStack arrayList Since the previous node now becomes the
* closest target to an implicit break or continue
*/
public void outASTWhileNode(ASTWhileNode node) {
if (nodeStack.isEmpty()) {
throw new RuntimeException("trying to remove node from empty stack: ClosestBreakTargetFinder");
}
nodeStack.remove(nodeStack.size() - 1);
}
public void outASTDoWhileNode(ASTDoWhileNode node) {
if (nodeStack.isEmpty()) {
throw new RuntimeException("trying to remove node from empty stack: ClosestBreakTargetFinder");
}
nodeStack.remove(nodeStack.size() - 1);
}
public void outASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
if (nodeStack.isEmpty()) {
throw new RuntimeException("trying to remove node from empty stack: ClosestBreakTargetFinder");
}
nodeStack.remove(nodeStack.size() - 1);
}
public void outASTForLoopNode(ASTForLoopNode node) {
if (nodeStack.isEmpty()) {
throw new RuntimeException("trying to remove node from empty stack: ClosestBreakTargetFinder");
}
nodeStack.remove(nodeStack.size() - 1);
}
public void outASTSwitchNode(ASTSwitchNode node) {
if (nodeStack.isEmpty()) {
throw new RuntimeException("trying to remove node from empty stack: ClosestBreakTargetFinder");
}
nodeStack.remove(nodeStack.size() - 1);
}
public void inStmt(Stmt s) {
if (s instanceof DAbruptStmt) {
// breaks and continues are abrupt statements
DAbruptStmt ab = (DAbruptStmt) s;
SETNodeLabel label = ab.getLabel();
if (label != null) {
if (label.toString() != null) {
// not considering explicit breaks
return;
}
}
// the break is an implict break
if (ab.is_Break()) {
// get the top of the stack
int index = nodeStack.size() - 1;
if (index < 0) {
// error
throw new RuntimeException("nodeStack empty??" + nodeStack.toString());
}
ASTNode currentNode = nodeStack.get(nodeStack.size() - 1);
closestNode.put(ab, currentNode);
} else if (ab.is_Continue()) {
// need something different because continues dont target switch
int index = nodeStack.size() - 1;
if (index < 0) {
// error
throw new RuntimeException("nodeStack empty??" + nodeStack.toString());
}
ASTNode currentNode = nodeStack.get(index);
while (currentNode instanceof ASTSwitchNode) {
if (index > 0) {
// more elements present in nodeStack
index--;
currentNode = nodeStack.get(index);
} else {
// error
throw new RuntimeException("Unable to find closest break Target");
}
}
// know that the currentNode is not an ASTSwitchNode
closestNode.put(ab, currentNode);
}
}
}
/*
* public void outASTMethodNode(ASTMethodNode node){ Iterator it = closestNode.keySet().iterator(); while(it.hasNext()){
* DAbruptStmt ab = (DAbruptStmt)it.next();
* System.out.println("Closest to "+ab+" is "+((ASTNode)closestNode.get(ab)).toString()+"\n\n"); }
*
* }
*/
}
| 7,010
| 33.880597
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/traversals/CopyPropagation.java
|
package soot.dava.toolkits.base.AST.traversals;
/*-
* #%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.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.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.DavaFlowSet;
import soot.dava.toolkits.base.AST.structuredAnalysis.ReachingCopies;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
/*
* TODO: shouldnt this be a transformation and hence under the transformation package???
This analysis uses the results from
1 ReachingCopies
2 uD and dU chains
to eliminate extra copies
ALGORITHM:
When you encounter a copy stmt (a=b) find all uses of local a (using dU chain)
if For ALL uses the ReachingCopies set contains copy stmt (a=b)
Remove Copy Stmt
Replace use of a with use of b
Note:
copy stmts can be encountered in:
a, ASTStatementSequenceNode
b, for loop init -------> dont want to remove this
c, for loop update ---------> dont want to remove this
*/
public class CopyPropagation extends DepthFirstAdapter {
public static boolean DEBUG = false;
ASTNode AST;
ASTUsesAndDefs useDefs;
ReachingCopies reachingCopies;
ASTParentNodeFinder parentOf;
boolean someCopyStmtModified;
// need to keep track of whenever we modify the AST
// this flag is set to true whenever a stmt is removed or a local
// substituted for another
boolean ASTMODIFIED;
public CopyPropagation(ASTNode AST) {
super();
someCopyStmtModified = false;
this.AST = AST;
ASTMODIFIED = false;
setup();
}
public CopyPropagation(boolean verbose, ASTNode AST) {
super(verbose);
someCopyStmtModified = false;
this.AST = AST;
ASTMODIFIED = false;
setup();
}
private void setup() {
// create the uD and dU chains
if (DEBUG) {
System.out.println("computing usesAnd Defs");
}
useDefs = new ASTUsesAndDefs(AST);
AST.apply(useDefs);
if (DEBUG) {
System.out.println("computing usesAnd Defs....done");
}
// apply the reaching copies Structural flow Analysis
reachingCopies = new ReachingCopies(AST);
parentOf = new ASTParentNodeFinder();
AST.apply(parentOf);
}
/*
* If any copy stmt was removed or any substitution made we might be able to get better results by redoing the analysis
*/
public void outASTMethodNode(ASTMethodNode node) {
if (ASTMODIFIED) {
// need to rerun copy prop
// before running a structured flow analysis have to do this one
AST.apply(ClosestAbruptTargetFinder.v());
// System.out.println("\n\n\nCOPY PROP\n\n\n\n");
CopyPropagation prop1 = new CopyPropagation(AST);
AST.apply(prop1);
}
}
public void inASTStatementSequenceNode(ASTStatementSequenceNode node) {
for (AugmentedStmt as : node.getStatements()) {
Stmt s = as.get_Stmt();
if (isCopyStmt(s)) {
handleCopyStmt((DefinitionStmt) s);
}
}
}
/*
* Method returns true if s is a copy stmt i.e. a = b where a and b are both locals
*/
public boolean isCopyStmt(Stmt s) {
if (!(s instanceof DefinitionStmt)) {
// only definition stmts can be copy stmts
return false;
}
// 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 && rightOp instanceof Local) {
// this is a copy statement
return true;
}
return false;
}
/*
* Given a copy stmt (a=b) find all uses of local a (using dU chain)
*
* if For ALL uses the ReachingCopies set contains copy stmt (a=b) Remove Copy Stmt Replace use of a with use of b
*/
public void handleCopyStmt(DefinitionStmt copyStmt) {
// System.out.println("COPY STMT FOUND-----------------------------------"+copyStmt);
// get defined local...safe to cast since this is copyStmt
Local definedLocal = (Local) copyStmt.getLeftOp();
// get all uses of this local from the dU chain
Object temp = useDefs.getDUChain(copyStmt);
ArrayList uses = new ArrayList();
if (temp != null) {
uses = (ArrayList) temp;
}
// the uses list contains all stmts / nodes which use the definedLocal
// check if uses is non-empty
if (uses.size() != 0) {
if (DEBUG) {
System.out.println(">>>>The defined local:" + definedLocal + " is used in the following");
System.out.println("\n numof uses:" + uses.size() + uses + ">>>>>>>>>>>>>>>\n\n");
}
// continuing with copy propagation algorithm
// create localPair for copy stmt in question...same to cast as its
// a copyStmt
Local leftLocal = (Local) copyStmt.getLeftOp();
Local rightLocal = (Local) copyStmt.getRightOp();
ReachingCopies.LocalPair localPair = reachingCopies.new LocalPair(leftLocal, rightLocal);
// check for all the non zero uses
Iterator useIt = uses.iterator();
while (useIt.hasNext()) {
// check that the reaching copies of each use has the copy stmt
// a use is either a statement or a node(condition, synch,
// switch , for etc)
Object tempUse = useIt.next();
DavaFlowSet reaching = reachingCopies.getReachingCopies(tempUse);
if (!reaching.contains(localPair)) {
// this copy stmt does not reach this use
// no copy elimination can be done
return;
}
}
// if we get here that means that the copy stmt reached each use
// replace each use of a with b
useIt = uses.iterator();
while (useIt.hasNext()) {
Object tempUse = useIt.next();
if (DEBUG) {
System.out.println("copy stmt reached this use" + tempUse);
}
replace(leftLocal, rightLocal, tempUse);
}
// remove copy stmt a=b
removeStmt(copyStmt);
if (someCopyStmtModified) {
// get all the analyses re-set
setup();
someCopyStmtModified = false;
}
} else {
// the copy stmt is usesless since the definedLocal is not being
// used anywhere after definition
// System.out.println("The defined local:"+definedLocal+" is not used anywhere");
removeStmt(copyStmt);
}
}
public void removeStmt(Stmt stmt) {
Object tempParent = parentOf.getParentOf(stmt);
if (tempParent == null) {
// System.out.println("NO PARENT FOUND CANT DO ANYTHING");
return;
}
// parents are always ASTNodes, hence safe to cast
ASTNode parent = (ASTNode) tempParent;
// REMOVING STMT
if (!(parent instanceof ASTStatementSequenceNode)) {
// parent of a statement should always be a ASTStatementSequenceNode
throw new RuntimeException("Found a stmt whose parent is not an ASTStatementSequenceNode");
}
ASTStatementSequenceNode parentNode = (ASTStatementSequenceNode) parent;
ArrayList<AugmentedStmt> newSequence = new ArrayList<AugmentedStmt>();
for (AugmentedStmt as : parentNode.getStatements()) {
Stmt s = as.get_Stmt();
if (s.toString().compareTo(stmt.toString()) != 0) {
// this is not the stmt to be removed
newSequence.add(as);
}
}
// System.out.println("STMT REMOVED---------------->"+stmt);
parentNode.setStatements(newSequence);
ASTMODIFIED = true;
return;
}
/*
* Method goes depth first into the condition tree and finds any use of local "from" If it finds the use it replaces it
* with the use of local "to"
*/
public void modifyUses(Local from, Local to, ASTCondition cond) {
if (cond instanceof ASTAggregatedCondition) {
// ArrayList useList = new ArrayList();
modifyUses(from, to, ((ASTAggregatedCondition) cond).getLeftOp());
modifyUses(from, to, ((ASTAggregatedCondition) cond).getRightOp());
} else if (cond instanceof ASTUnaryCondition) {
// get uses from unary condition
Value val = ((ASTUnaryCondition) cond).getValue();
if (val instanceof Local) {
Local local = (Local) val;
if (local.getName().compareTo(from.getName()) == 0) {
// replace the name with the one in "to"
((ASTUnaryCondition) cond).setValue(to);
ASTMODIFIED = true;
}
} else {
Iterator it = val.getUseBoxes().iterator();
while (it.hasNext()) {
ValueBox valBox = (ValueBox) it.next();
Value tempVal = valBox.getValue();
if (tempVal instanceof Local) {
Local local = (Local) tempVal;
if (local.getName().compareTo(from.getName()) == 0) {
// replace the name with the one in "to"
valBox.setValue(to);
ASTMODIFIED = true;
}
}
}
}
} // end unary condition
else if (cond instanceof ASTBinaryCondition) {
// get uses from binaryCondition
Value val = ((ASTBinaryCondition) cond).getConditionExpr();
Iterator it = val.getUseBoxes().iterator();
while (it.hasNext()) {
ValueBox valBox = (ValueBox) it.next();
Value tempVal = valBox.getValue();
if (tempVal instanceof Local) {
Local local = (Local) tempVal;
if (local.getName().compareTo(from.getName()) == 0) {
// replace the name with the one in "to"
valBox.setValue(to);
ASTMODIFIED = true;
}
}
}
} else {
throw new RuntimeException("Method getUseList in CopyPropagation encountered unknown condition type");
}
}
public void modifyUseBoxes(Local from, Local to, List useBoxes) {
Iterator it = useBoxes.iterator();
while (it.hasNext()) {
ValueBox valBox = (ValueBox) it.next();
Value tempVal = valBox.getValue();
if (tempVal instanceof Local) {
Local local = (Local) tempVal;
if (local.getName().compareTo(from.getName()) == 0) {
// replace the name with the one in "to"
valBox.setValue(to);
ASTMODIFIED = true;
}
}
}
}
/*
* Invoked by handleCopyStmt to replace the use of local <from> to the use of local <to> in <use>
*
* Notice <use> can be a stmt or an ASTNode
*/
public void replace(Local from, Local to, Object use) {
if (use instanceof Stmt) {
Stmt s = (Stmt) use;
if (isCopyStmt(s)) {
someCopyStmtModified = true;
}
List useBoxes = s.getUseBoxes();
if (DEBUG) {
System.out.println("Printing uses for stmt" + useBoxes);
}
// TODO
modifyUseBoxes(from, to, useBoxes);
} else if (use instanceof ASTNode) {
if (use instanceof ASTSwitchNode) {
ASTSwitchNode temp = (ASTSwitchNode) use;
Value val = temp.get_Key();
if (val instanceof Local) {
if (((Local) val).getName().compareTo(from.getName()) == 0) {
// replace the name with the one in "to"
ASTMODIFIED = true;
temp.set_Key(to);
}
} else {
List useBoxes = val.getUseBoxes();
// TODO
modifyUseBoxes(from, to, useBoxes);
}
} else if (use instanceof ASTSynchronizedBlockNode) {
ASTSynchronizedBlockNode temp = (ASTSynchronizedBlockNode) use;
Local local = temp.getLocal();
if (local.getName().compareTo(from.getName()) == 0) {
// replace the name with the one in "to"
temp.setLocal(to);
ASTMODIFIED = true;
}
} else if (use instanceof ASTIfNode) {
if (DEBUG) {
System.out.println("Use is an instanceof if node");
}
ASTIfNode temp = (ASTIfNode) use;
ASTCondition cond = temp.get_Condition();
modifyUses(from, to, cond);
} else if (use instanceof ASTIfElseNode) {
ASTIfElseNode temp = (ASTIfElseNode) use;
ASTCondition cond = temp.get_Condition();
modifyUses(from, to, cond);
} else if (use instanceof ASTWhileNode) {
ASTWhileNode temp = (ASTWhileNode) use;
ASTCondition cond = temp.get_Condition();
modifyUses(from, to, cond);
} else if (use instanceof ASTDoWhileNode) {
ASTDoWhileNode temp = (ASTDoWhileNode) use;
ASTCondition cond = temp.get_Condition();
modifyUses(from, to, cond);
} else if (use instanceof ASTForLoopNode) {
ASTForLoopNode temp = (ASTForLoopNode) use;
// init
for (AugmentedStmt as : temp.getInit()) {
Stmt s = as.get_Stmt();
replace(from, to, s);
}
// update
for (AugmentedStmt as : temp.getUpdate()) {
Stmt s = as.get_Stmt();
replace(from, to, s);
}
// condition
ASTCondition cond = temp.get_Condition();
modifyUses(from, to, cond);
} else {
throw new RuntimeException("Encountered an unknown ASTNode in copyPropagation method replace");
}
} else {
throw new RuntimeException("Encountered an unknown use in copyPropagation method replace");
}
}
}
| 14,667
| 31.166667
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/traversals/InitializationDeclarationShortcut.java
|
package soot.dava.toolkits.base.AST.traversals;
/*-
* #%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.List;
import soot.Local;
import soot.Value;
import soot.dava.internal.AST.ASTMethodNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
/*
* Given a statement of interest this traversal checks whether
* a, the defined variable is a local
* b, there is any def of the defined local of interest before
* the given statement
*
* if no then possible is set to true
* else false
*/
public class InitializationDeclarationShortcut extends DepthFirstAdapter {
AugmentedStmt ofInterest;
boolean possible = false;
Local definedLocal = null;
int seenBefore = 0;// if there is a definition of local which is not by stmt of interest increment this
public InitializationDeclarationShortcut(AugmentedStmt ofInterest) {
this.ofInterest = ofInterest;
}
public InitializationDeclarationShortcut(boolean verbose, AugmentedStmt ofInterest) {
super(verbose);
this.ofInterest = ofInterest;
}
public boolean isShortcutPossible() {
return possible;
}
/*
* Check that the stmt of interest defines a local in the DVariableDeclarationNode of the method else set to false and stop
*/
public void inASTMethodNode(ASTMethodNode node) {
Stmt s = ofInterest.get_Stmt();
// check this is a definition
if (!(s instanceof DefinitionStmt)) {
possible = false;
return;
}
Value defined = ((DefinitionStmt) s).getLeftOp();
if (!(defined instanceof Local)) {
possible = false;
return;
}
// check that this is a local defined in this method
// its a sanity check
List declaredLocals = node.getDeclaredLocals();
if (!declaredLocals.contains(defined)) {
possible = false;
return;
}
definedLocal = (Local) defined;
}
public void inDefinitionStmt(DefinitionStmt s) {
if (definedLocal == null) {
return;
}
Value defined = (s).getLeftOp();
if (!(defined instanceof Local)) {
return;
}
if (defined.equals(definedLocal)) {
// the local of interest is being defined
// if this is the augmentedStmt of interest set possible to true if not already seen
if (s.equals(ofInterest.get_Stmt())) {
// it is the stmt of interest
if (seenBefore == 0) {
possible = true;
} else {
possible = false;
}
} else {
// its a definition of the local of interest but not by the stmt of interest
seenBefore++;
}
}
}
}
| 3,454
| 27.791667
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/AST/traversals/LabelToNodeMapper.java
|
package soot.dava.toolkits.base.AST.traversals;
/*-
* #%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 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.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;
/*
* For each labeled node make a mapping of the label (a string)
* to the node.
* Eg. if label1:
* while(cond){
* BodyA
* }
*
* Then the mapping is (label1,ASTWhileNode Reference)
*
*/
public class LabelToNodeMapper extends DepthFirstAdapter {
private final HashMap<String, ASTLabeledNode> labelsToNode;
public LabelToNodeMapper() {
labelsToNode = new HashMap<String, ASTLabeledNode>();
}
public LabelToNodeMapper(boolean verbose) {
super(verbose);
labelsToNode = new HashMap<String, ASTLabeledNode>();
}
/*
* If the returned object is non null it is safe to cast it to ASTLabeledNode
*/
public Object getTarget(String label) {
return labelsToNode.get(label);
}
private void addToMap(ASTLabeledNode node) {
String str = node.get_Label().toString();
if (str != null) {
labelsToNode.put(str, node);
}
}
public void inASTLabeledBlockNode(ASTLabeledBlockNode node) {
addToMap(node);
}
public void inASTTryNode(ASTTryNode node) {
addToMap(node);
}
public void inASTUnconditionalLoopNode(ASTUnconditionalLoopNode node) {
addToMap(node);
}
public void inASTDoWhileNode(ASTDoWhileNode node) {
addToMap(node);
}
public void inASTForLoopNode(ASTForLoopNode node) {
addToMap(node);
}
public void inASTIfElseNode(ASTIfElseNode node) {
addToMap(node);
}
public void inASTIfNode(ASTIfNode node) {
addToMap(node);
}
public void inASTWhileNode(ASTWhileNode node) {
addToMap(node);
}
public void inASTSwitchNode(ASTSwitchNode node) {
addToMap(node);
}
public void inASTSynchronizedBlockNode(ASTSynchronizedBlockNode node) {
addToMap(node);
}
}
| 3,198
| 26.34188
| 79
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/DavaMonitor/DavaMonitor.java
|
package soot.dava.toolkits.base.DavaMonitor;
/*-
* #%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;
public class DavaMonitor {
private static final DavaMonitor instance = new DavaMonitor();
private final HashMap<Object, Lock> ref, lockTable;
private DavaMonitor() {
ref = new HashMap<Object, Lock>(1, 0.7f);
lockTable = new HashMap<Object, Lock>(1, 0.7f);
}
public static DavaMonitor v() {
return instance;
}
public synchronized void enter(Object o) throws NullPointerException {
Thread currentThread = Thread.currentThread();
if (o == null) {
throw new NullPointerException();
}
Lock lock = ref.get(o);
if (lock == null) {
lock = new Lock();
ref.put(o, lock);
}
if (lock.level == 0) {
lock.level = 1;
lock.owner = currentThread;
return;
}
if (lock.owner == currentThread) {
lock.level++;
return;
}
lockTable.put(currentThread, lock);
lock.enQ(currentThread);
while ((lock.level > 0) || (lock.nextThread() != currentThread)) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
currentThread = Thread.currentThread();
lock = lockTable.get(currentThread);
}
lock.deQ(currentThread);
lock.level = 1;
lock.owner = currentThread;
}
public synchronized void exit(Object o) throws NullPointerException, IllegalMonitorStateException {
if (o == null) {
throw new NullPointerException();
}
Lock lock = ref.get(o);
if ((lock == null) || (lock.level == 0) || (lock.owner != Thread.currentThread())) {
throw new IllegalMonitorStateException();
}
lock.level--;
if (lock.level == 0) {
notifyAll();
}
}
}
| 2,562
| 23.644231
| 101
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/DavaMonitor/Lock.java
|
package soot.dava.toolkits.base.DavaMonitor;
/*-
* #%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.LinkedList;
class Lock {
public Thread owner;
public int level;
private final LinkedList<Thread> q;
Lock() {
level = 0;
owner = null;
q = new LinkedList<Thread>();
}
public Thread nextThread() {
return q.getFirst();
}
public Thread deQ(Thread t) throws IllegalMonitorStateException {
if (t != q.getFirst()) {
throw new IllegalMonitorStateException();
}
return q.removeFirst();
}
public void enQ(Thread t) {
q.add(t);
}
}
| 1,356
| 23.672727
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/AbruptEdgeFinder.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.G;
import soot.Singletons;
import soot.dava.Dava;
import soot.dava.DavaBody;
import soot.dava.RetriggerAnalysisException;
import soot.dava.internal.SET.SETCycleNode;
import soot.dava.internal.SET.SETNode;
import soot.dava.internal.SET.SETStatementSequenceNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.dava.internal.javaRep.DAbruptStmt;
import soot.util.IterableSet;
public class AbruptEdgeFinder implements FactFinder {
public AbruptEdgeFinder(Singletons.Global g) {
}
public static AbruptEdgeFinder v() {
return G.v().soot_dava_toolkits_base_finders_AbruptEdgeFinder();
}
public void find(DavaBody body, AugmentedStmtGraph asg, SETNode SET) throws RetriggerAnalysisException {
Dava.v().log("AbruptEdgeFinder::find()");
SET.find_AbruptEdges(this);
}
public void find_Continues(SETNode SETParent, IterableSet body, IterableSet children) {
if ((SETParent instanceof SETCycleNode) == false) {
return;
}
SETCycleNode scn = (SETCycleNode) SETParent;
IterableSet naturalPreds = ((SETNode) children.getLast()).get_NaturalExits();
Iterator pit = scn.get_CharacterizingStmt().bpreds.iterator();
while (pit.hasNext()) {
AugmentedStmt pas = (AugmentedStmt) pit.next();
if ((body.contains(pas)) && (naturalPreds.contains(pas) == false)) {
((SETStatementSequenceNode) pas.myNode).insert_AbruptStmt(new DAbruptStmt("continue", scn.get_Label()));
}
}
}
public void find_Breaks(SETNode prev, SETNode cur) {
IterableSet naturalPreds = prev.get_NaturalExits();
Iterator pit = cur.get_EntryStmt().bpreds.iterator();
while (pit.hasNext()) {
AugmentedStmt pas = (AugmentedStmt) pit.next();
if (prev.get_Body().contains(pas) == false) {
continue;
}
if (naturalPreds.contains(pas) == false) {
Object temp = pas.myNode;
/*
* Nomair debugging bug number 29
*/
// System.out.println();
// ((SETNode)temp).dump();
// System.out.println("Statement is"+pas);
((SETStatementSequenceNode) temp).insert_AbruptStmt(new DAbruptStmt("break", prev.get_Label()));
}
}
}
}
| 3,113
| 31.4375
| 112
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/CycleFinder.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* 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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.G;
import soot.Local;
import soot.Singletons;
import soot.dava.Dava;
import soot.dava.DavaBody;
import soot.dava.RetriggerAnalysisException;
import soot.dava.internal.SET.SETCycleNode;
import soot.dava.internal.SET.SETDoWhileNode;
import soot.dava.internal.SET.SETNode;
import soot.dava.internal.SET.SETUnconditionalWhileNode;
import soot.dava.internal.SET.SETWhileNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.dava.internal.javaRep.DIntConstant;
import soot.dava.toolkits.base.misc.ConditionFlipper;
import soot.grimp.internal.GAssignStmt;
import soot.grimp.internal.GTableSwitchStmt;
import soot.jimple.AssignStmt;
import soot.jimple.ConditionExpr;
import soot.jimple.GotoStmt;
import soot.jimple.IfStmt;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.Stmt;
import soot.jimple.TableSwitchStmt;
import soot.jimple.internal.JGotoStmt;
import soot.toolkits.graph.StronglyConnectedComponentsFast;
import soot.util.IterableSet;
import soot.util.StationaryArrayList;
public class CycleFinder implements FactFinder {
private static final Logger logger = LoggerFactory.getLogger(CycleFinder.class);
public CycleFinder(Singletons.Global g) {
}
public static CycleFinder v() {
return G.v().soot_dava_toolkits_base_finders_CycleFinder();
}
@Override
public void find(DavaBody body, AugmentedStmtGraph asg, SETNode SET) throws RetriggerAnalysisException {
Dava.v().log("CycleFinder::find()");
AugmentedStmtGraph wasg = (AugmentedStmtGraph) asg.clone();
List<List<AugmentedStmt>> component_list = build_component_list(wasg);
// loop through all nestings
while (!component_list.isEmpty()) {
IterableSet<AugmentedStmt> node_list = new IterableSet<AugmentedStmt>();
// loop through all the strongly connected components
for (List<AugmentedStmt> cal : component_list) {
node_list.clear();
node_list.addAll(cal);
// node_list contains all the nodes belonging to this SCC
IterableSet<AugmentedStmt> entry_points = get_EntryPoint(node_list);
// if more than one entry points found
if (entry_points.size() > 1) {
LinkedList<AugmentedStmt> asgEntryPoints = new LinkedList<AugmentedStmt>();
for (AugmentedStmt au : entry_points) {
asgEntryPoints.addLast(asg.get_AugStmt(au.get_Stmt()));
}
IterableSet<AugmentedStmt> asgScc = new IterableSet<AugmentedStmt>();
for (AugmentedStmt au : node_list) {
asgScc.addLast(asg.get_AugStmt(au.get_Stmt()));
}
fix_MultiEntryPoint(body, asg, asgEntryPoints, asgScc);
throw new RetriggerAnalysisException();
}
// gets to this code only if each SCC has one entry point?
AugmentedStmt succ_stmt = null;
AugmentedStmt entry_point = entry_points.getFirst();
AugmentedStmt characterizing_stmt = find_CharacterizingStmt(entry_point, node_list, wasg);
if (characterizing_stmt != null) {
for (AugmentedStmt au : characterizing_stmt.bsuccs) {
succ_stmt = au;
if (!node_list.contains(succ_stmt)) {
break;
}
}
}
wasg.calculate_Reachability(succ_stmt, new HashSet<AugmentedStmt>(), entry_point);
IterableSet<AugmentedStmt> cycle_body = get_CycleBody(entry_point, succ_stmt, asg, wasg);
if (characterizing_stmt != null) {
checkExceptionLoop: for (ExceptionNode en : body.get_ExceptionFacts()) {
IterableSet<AugmentedStmt> tryBody = en.get_TryBody();
if (tryBody.contains(asg.get_AugStmt(characterizing_stmt.get_Stmt()))) {
for (AugmentedStmt cbas : cycle_body) {
if (!tryBody.contains(cbas)) {
characterizing_stmt = null;
break checkExceptionLoop;
}
}
}
}
}
// unconditional loop
SETCycleNode newNode;
if (characterizing_stmt == null) {
wasg.remove_AugmentedStmt(entry_point);
newNode = new SETUnconditionalWhileNode(cycle_body);
} else {
body.consume_Condition(asg.get_AugStmt(characterizing_stmt.get_Stmt()));
wasg.remove_AugmentedStmt(characterizing_stmt);
IfStmt condition = (IfStmt) characterizing_stmt.get_Stmt();
if (!cycle_body.contains(asg.get_AugStmt(condition.getTarget()))) {
condition.setCondition(ConditionFlipper.flip((ConditionExpr) condition.getCondition()));
}
if (characterizing_stmt == entry_point) {
newNode = new SETWhileNode(asg.get_AugStmt(characterizing_stmt.get_Stmt()), cycle_body);
} else {
newNode = new SETDoWhileNode(asg.get_AugStmt(characterizing_stmt.get_Stmt()),
asg.get_AugStmt(entry_point.get_Stmt()), cycle_body);
}
}
SET.nest(newNode);
}
component_list = build_component_list(wasg);
}
}
/*
* Nomair A. Naeem Entry point to a SCC ARE those stmts whose predecessor does not belong to the SCC
*/
private IterableSet<AugmentedStmt> get_EntryPoint(IterableSet<AugmentedStmt> nodeList) {
IterableSet<AugmentedStmt> entryPoints = new IterableSet<AugmentedStmt>();
for (AugmentedStmt as : nodeList) {
for (AugmentedStmt po : as.cpreds) {
if (!nodeList.contains(po)) {
entryPoints.add(as);
break;
}
}
}
return entryPoints;
}
private List<List<AugmentedStmt>> build_component_list(AugmentedStmtGraph asg) {
List<List<AugmentedStmt>> c_list = new LinkedList<List<AugmentedStmt>>();
// makes sure that all scc's with only one statement in them are removed
/*
* 26th Jan 2006 Nomair A. Naeem This could be potentially bad since self loops will also get removed Adding code to
* check for self loop (a stmt is a self loop if its pred and succ contain the stmt itself
*/
for (List<AugmentedStmt> wcomp : (new StronglyConnectedComponentsFast<AugmentedStmt>(asg)).getComponents()) {
final int size = wcomp.size();
if (size > 1) {
c_list.add(wcomp);
} else if (size == 1) {
// this is a scc of one augmented stmt
// We should add those which are self loops
AugmentedStmt as = wcomp.get(0);
if (as.cpreds.contains(as) && as.csuccs.contains(as)) {
// "as" has a predecssor and successor which is as i.e. it is a self loop
List<AugmentedStmt> currentComponent = new StationaryArrayList<AugmentedStmt>();
currentComponent.add(as);
// System.out.println("Special add of"+as);
c_list.add(currentComponent);
}
}
}
return c_list;
}
private AugmentedStmt find_CharacterizingStmt(AugmentedStmt entry_point, IterableSet<AugmentedStmt> sc_component,
AugmentedStmtGraph asg) {
/*
* Check whether we are a while loop.
*/
if (entry_point.get_Stmt() instanceof IfStmt) {
// see if there's a successor who's not in the strict loop set
for (AugmentedStmt au : entry_point.bsuccs) {
if (!sc_component.contains(au)) {
return entry_point;
}
}
}
/*
* We're not a while loop. Get the candidates for condition on a do-while loop.
*/
IterableSet<AugmentedStmt> candidates = new IterableSet<AugmentedStmt>();
HashMap<AugmentedStmt, AugmentedStmt> candSuccMap = new HashMap<AugmentedStmt, AugmentedStmt>();
HashSet<AugmentedStmt> blockers = new HashSet<AugmentedStmt>();
// Get the set of all candidates.
for (AugmentedStmt pas : entry_point.bpreds) {
final Stmt pasStmt = pas.get_Stmt();
if ((pasStmt instanceof GotoStmt) && (pas.bpreds.size() == 1)) {
pas = pas.bpreds.get(0);
}
if ((sc_component.contains(pas)) && (pasStmt instanceof IfStmt)) {
for (AugmentedStmt spas : pas.bsuccs) {
if (!sc_component.contains(spas)) {
candidates.add(pas);
candSuccMap.put(pas, spas);
blockers.add(spas);
break;
}
}
}
}
/*
* If there was no candidate, we are an unconditional loop.
*/
if (candidates.isEmpty()) {
return null;
}
/*
* Get the best candidate for the do-while condition.
*/
if (candidates.size() == 1) {
return candidates.getFirst();
}
// Take the candidate(s) whose successor has maximal reachability from
// all candidates.
asg.calculate_Reachability(candidates, blockers, entry_point);
IterableSet<AugmentedStmt> max_Reach_Set = null;
int reachSize = 0;
for (AugmentedStmt as : candidates) {
int current_reach_size = candSuccMap.get(as).get_Reachers().intersection(candidates).size();
if (current_reach_size > reachSize) {
max_Reach_Set = new IterableSet<AugmentedStmt>();
reachSize = current_reach_size;
}
if (current_reach_size == reachSize) {
max_Reach_Set.add(as);
}
}
candidates = max_Reach_Set;
if (candidates == null) {
throw new RuntimeException("Did not find a suitable candidate");
}
if (candidates.size() == 1) {
return candidates.getFirst();
}
// Find a single source shortest path from the entry point to any of the
// remaining candidates.
HashSet<Object> touchSet = new HashSet<Object>();
LinkedList<AugmentedStmt> worklist = new LinkedList<AugmentedStmt>();
worklist.addLast(entry_point);
touchSet.add(entry_point);
while (!worklist.isEmpty()) {
for (AugmentedStmt so : worklist.removeFirst().csuccs) {
if (candidates.contains(so)) {
return so;
}
if (sc_component.contains(so) && !touchSet.contains(so)) {
worklist.addLast(so);
touchSet.add(so);
}
}
}
throw new RuntimeException("Somehow didn't find a condition for a do-while loop!");
}
private IterableSet<AugmentedStmt> get_CycleBody(AugmentedStmt entry_point, AugmentedStmt boundary_stmt,
AugmentedStmtGraph asg, AugmentedStmtGraph wasg) {
IterableSet<AugmentedStmt> cycle_body = new IterableSet<AugmentedStmt>();
LinkedList<AugmentedStmt> worklist = new LinkedList<AugmentedStmt>();
AugmentedStmt asg_ep = asg.get_AugStmt(entry_point.get_Stmt());
worklist.add(entry_point);
cycle_body.add(asg_ep);
while (!worklist.isEmpty()) {
AugmentedStmt as = worklist.removeFirst();
for (AugmentedStmt wsas : as.csuccs) {
AugmentedStmt sas = asg.get_AugStmt(wsas.get_Stmt());
if (cycle_body.contains(sas)) {
continue;
}
if (!cycle_body.contains(sas) && sas.get_Dominators().contains(asg_ep)) {
if ((boundary_stmt != null) && (wsas.get_Reachers().contains(boundary_stmt) || (wsas == boundary_stmt))) {
continue;
}
// logger.debug(sas);
worklist.add(wsas);
cycle_body.add(sas);
}
}
}
return cycle_body;
}
private void fix_MultiEntryPoint(DavaBody body, AugmentedStmtGraph asg, LinkedList<AugmentedStmt> entry_points,
IterableSet<AugmentedStmt> scc) {
final AugmentedStmt naturalEntryPoint = get_NaturalEntryPoint(entry_points, scc);
final Local controlLocal = body.get_ControlLocal();
/*
* Nomair A Naeem, Micheal Batchelder 5 th April 2005 shouldn't send empty targets list to constructor of GTableSwitch
* since then it just creates an empty array to hold the targets. We intend to fill these in later using the setTarget
* method. Hence the hack is to just send an array filled with 'null' values, fully aware that they are going to be
* changed to the target we want within the following while loop.
*/
TableSwitchStmt tss = new GTableSwitchStmt(controlLocal, 0, entry_points.size() - 2,
Collections.nCopies(entry_points.size(), null), naturalEntryPoint.get_Stmt());
AugmentedStmt dispatchStmt = new AugmentedStmt(tss);
IterableSet<AugmentedStmt> predecessorSet = new IterableSet<AugmentedStmt>();
IterableSet<AugmentedStmt> indirectionStmtSet = new IterableSet<AugmentedStmt>();
IterableSet<AugmentedStmt> directionStmtSet = new IterableSet<AugmentedStmt>();
int count = 0;
for (AugmentedStmt entryPoint : entry_points) {
GotoStmt gotoStmt = new JGotoStmt(entryPoint.get_Stmt());
AugmentedStmt indirectionStmt = new AugmentedStmt(gotoStmt);
indirectionStmtSet.add(indirectionStmt);
tss.setTarget(count++, gotoStmt);
dispatchStmt.add_BSucc(indirectionStmt);
indirectionStmt.add_BPred(dispatchStmt);
indirectionStmt.add_BSucc(entryPoint);
entryPoint.add_BPred(indirectionStmt);
asg.add_AugmentedStmt(indirectionStmt);
LinkedList<AugmentedStmt> toRemove = new LinkedList<AugmentedStmt>();
for (AugmentedStmt pas : entryPoint.cpreds) {
if ((pas == indirectionStmt) || ((entryPoint != naturalEntryPoint) && scc.contains(pas))) {
continue;
}
if (!scc.contains(pas)) {
predecessorSet.add(pas);
}
AssignStmt asnStmt = new GAssignStmt(controlLocal, DIntConstant.v(count, null));
AugmentedStmt directionStmt = new AugmentedStmt(asnStmt);
directionStmtSet.add(directionStmt);
patch_Stmt(pas.get_Stmt(), entryPoint.get_Stmt(), asnStmt);
// Mark the original predecessor to be removed.
toRemove.addLast(pas);
pas.csuccs.remove(entryPoint);
pas.csuccs.add(directionStmt);
if (pas.bsuccs.contains(entryPoint)) {
pas.bsuccs.remove(entryPoint);
pas.bsuccs.add(directionStmt);
}
directionStmt.cpreds.add(pas);
if (pas.bsuccs.contains(directionStmt)) {
directionStmt.bpreds.add(pas);
}
directionStmt.add_BSucc(dispatchStmt);
dispatchStmt.add_BPred(directionStmt);
asg.add_AugmentedStmt(directionStmt);
}
for (AugmentedStmt ras : toRemove) {
entryPoint.cpreds.remove(ras);
if (entryPoint.bpreds.contains(ras)) {
entryPoint.bpreds.remove(ras);
}
}
}
asg.add_AugmentedStmt(dispatchStmt);
exceptionFactLoop: for (ExceptionNode en : body.get_ExceptionFacts()) {
IterableSet<AugmentedStmt> tryBody = en.get_TryBody();
for (AugmentedStmt au : entry_points) {
if (!tryBody.contains(au)) {
continue exceptionFactLoop;
}
}
en.add_TryStmts(indirectionStmtSet);
en.add_TryStmt(dispatchStmt);
for (AugmentedStmt au : predecessorSet) {
if (!tryBody.contains(au)) {
continue exceptionFactLoop;
}
}
en.add_TryStmts(directionStmtSet);
}
}
private AugmentedStmt get_NaturalEntryPoint(LinkedList<AugmentedStmt> entry_points, IterableSet<AugmentedStmt> scc) {
AugmentedStmt best_candidate = null;
int minScore = 0;
for (AugmentedStmt entryPoint : entry_points) {
HashSet<AugmentedStmt> touchSet = new HashSet<AugmentedStmt>(), backTargets = new HashSet<AugmentedStmt>();
touchSet.add(entryPoint);
DFS(entryPoint, touchSet, backTargets, scc);
if ((best_candidate == null) || (backTargets.size() < minScore)) {
minScore = touchSet.size();
best_candidate = entryPoint;
}
}
return best_candidate;
}
private void DFS(AugmentedStmt as, HashSet<AugmentedStmt> touchSet, HashSet<AugmentedStmt> backTargets,
IterableSet<AugmentedStmt> scc) {
for (AugmentedStmt sas : as.csuccs) {
if (!scc.contains(sas)) {
continue;
}
if (touchSet.contains(sas)) {
if (!backTargets.contains(sas)) {
backTargets.add(sas);
}
} else {
touchSet.add(sas);
DFS(sas, touchSet, backTargets, scc);
touchSet.remove(sas);
}
}
}
private void patch_Stmt(Stmt src, Stmt oldDst, Stmt newDst) {
if (src instanceof GotoStmt) {
((GotoStmt) src).setTarget(newDst);
return;
}
if (src instanceof IfStmt) {
IfStmt ifs = (IfStmt) src;
if (ifs.getTarget() == oldDst) {
ifs.setTarget(newDst);
}
return;
}
if (src instanceof TableSwitchStmt) {
TableSwitchStmt tss = (TableSwitchStmt) src;
if (tss.getDefaultTarget() == oldDst) {
tss.setDefaultTarget(newDst);
return;
}
for (int i = tss.getLowIndex(), e = tss.getHighIndex(); i <= e; i++) {
if (tss.getTarget(i) == oldDst) {
tss.setTarget(i, newDst);
return;
}
}
}
if (src instanceof LookupSwitchStmt) {
LookupSwitchStmt lss = (LookupSwitchStmt) src;
if (lss.getDefaultTarget() == oldDst) {
lss.setDefaultTarget(newDst);
return;
}
for (int i = 0, e = lss.getTargetCount(); i < e; i++) {
if (lss.getTarget(i) == oldDst) {
lss.setTarget(i, newDst);
return;
}
}
}
}
}
| 18,280
| 32.298725
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/ExceptionFinder.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import soot.G;
import soot.Singletons;
import soot.Trap;
import soot.Unit;
import soot.dava.Dava;
import soot.dava.DavaBody;
import soot.dava.RetriggerAnalysisException;
import soot.dava.internal.SET.SETNode;
import soot.dava.internal.SET.SETTryNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.jimple.GotoStmt;
import soot.jimple.Stmt;
import soot.util.IterableSet;
public class ExceptionFinder implements FactFinder {
public ExceptionFinder(Singletons.Global g) {
}
public static ExceptionFinder v() {
return G.v().soot_dava_toolkits_base_finders_ExceptionFinder();
}
@Override
public void find(DavaBody body, AugmentedStmtGraph asg, SETNode SET) throws RetriggerAnalysisException {
Dava.v().log("ExceptionFinder::find()");
final IterableSet<ExceptionNode> synchronizedBlockFacts = body.get_SynchronizedBlockFacts();
for (ExceptionNode en : body.get_ExceptionFacts()) {
if (!synchronizedBlockFacts.contains(en)) {
IterableSet<AugmentedStmt> fullBody = new IterableSet<AugmentedStmt>();
for (IterableSet<AugmentedStmt> is : en.get_CatchList()) {
fullBody.addAll(is);
}
fullBody.addAll(en.get_TryBody());
if (!SET.nest(new SETTryNode(fullBody, en, asg, body))) {
throw new RetriggerAnalysisException();
}
}
}
}
public void preprocess(DavaBody body, AugmentedStmtGraph asg) {
Dava.v().log("ExceptionFinder::preprocess()");
IterableSet<ExceptionNode> enlist = new IterableSet<ExceptionNode>();
// Find the first approximation for all the try catch bodies.
for (Trap trap : body.getTraps()) {
// get the body of the try block as a raw read of the area of protection
IterableSet<AugmentedStmt> tryBody = new IterableSet<AugmentedStmt>();
Iterator<Unit> it = body.getUnits().iterator(trap.getBeginUnit());
for (Unit u = it.next(), e = trap.getEndUnit(); u != e; u = it.next()) {
tryBody.add(asg.get_AugStmt((Stmt) u));
}
enlist.add(new ExceptionNode(tryBody, trap.getException(), asg.get_AugStmt((Stmt) trap.getHandlerUnit())));
}
// Add in gotos that may escape the try body (created by the indirection
// introduced in DavaBody).
for (ExceptionNode en : enlist) {
IterableSet<AugmentedStmt> try_body = en.get_TryBody();
ArrayList<AugmentedStmt> toAdd = new ArrayList<>();
for (AugmentedStmt tras : try_body) {
for (AugmentedStmt pas : tras.cpreds) {
if (!try_body.contains(pas) && (pas.get_Stmt() instanceof GotoStmt)) {
boolean add_it = true;
for (AugmentedStmt pred : pas.cpreds) {
add_it = try_body.contains(pred);
if (!add_it) {
break;
}
}
if (add_it) {
// FIX: directly calling en.add_TryStmt here will always cause
// ConcurrentModificationException so instead, store to add later.
toAdd.add(pas);
}
}
}
}
en.add_TryStmts(toAdd);
}
// Split up the try blocks until they cause no nesting problems.
splitLoop: while (true) {
// refresh the catch bodies
for (ExceptionNode enode : enlist) {
enode.refresh_CatchBody(this);
}
// split for inter-exception nesting problems
{
final int size = enlist.size();
ExceptionNode[] ena = new ExceptionNode[size];
int i = 0;
for (ExceptionNode next : enlist) {
ena[i] = next;
i++;
}
for (i = 0; i < size - 1; i++) {
ExceptionNode eni = ena[i];
for (int j = i + 1; j < size; j++) {
ExceptionNode enj = ena[j];
IterableSet<AugmentedStmt> eniTryBody = eni.get_TryBody();
IterableSet<AugmentedStmt> enjTryBody = enj.get_TryBody();
if (!eniTryBody.equals(enjTryBody) && eniTryBody.intersects(enjTryBody)) {
if (eniTryBody.isSupersetOf(enj.get_Body()) || enjTryBody.isSupersetOf(eni.get_Body())) {
continue;
}
IterableSet<AugmentedStmt> newTryBody = eniTryBody.intersection(enjTryBody);
if (newTryBody.equals(enjTryBody)) {
eni.splitOff_ExceptionNode(newTryBody, asg, enlist);
} else {
enj.splitOff_ExceptionNode(newTryBody, asg, enlist);
}
continue splitLoop;
}
}
}
}
// split for intra-try-body issues
for (ExceptionNode en : enlist) {
// Get the try block entry points
IterableSet<AugmentedStmt> tryBody = en.get_TryBody();
LinkedList<AugmentedStmt> heads = new LinkedList<AugmentedStmt>();
for (AugmentedStmt as : tryBody) {
if (as.cpreds.isEmpty()) {
heads.add(as);
continue;
}
for (AugmentedStmt pred : as.cpreds) {
if (!tryBody.contains(pred)) {
heads.add(as);
break;
}
}
}
HashSet<AugmentedStmt> touchSet = new HashSet<AugmentedStmt>(heads);
// Break up the try block for all the so-far detectable parts.
IterableSet<AugmentedStmt> subTryBlock = new IterableSet<AugmentedStmt>();
LinkedList<AugmentedStmt> worklist = new LinkedList<AugmentedStmt>();
AugmentedStmt head = heads.removeFirst();
worklist.add(head);
while (!worklist.isEmpty()) {
AugmentedStmt as = worklist.removeFirst();
subTryBlock.add(as);
for (AugmentedStmt sas : as.csuccs) {
if (!tryBody.contains(sas) || touchSet.contains(sas)) {
continue;
}
touchSet.add(sas);
if (sas.get_Dominators().contains(head)) {
worklist.add(sas);
} else {
heads.addLast(sas);
}
}
}
if (!heads.isEmpty()) {
en.splitOff_ExceptionNode(subTryBlock, asg, enlist);
continue splitLoop;
}
}
break;
}
// Aggregate the try blocks.
{
LinkedList<ExceptionNode> reps = new LinkedList<ExceptionNode>();
HashMap<Serializable, LinkedList<IterableSet<AugmentedStmt>>> hCode2bucket =
new HashMap<Serializable, LinkedList<IterableSet<AugmentedStmt>>>();
HashMap<Serializable, ExceptionNode> tryBody2exceptionNode = new HashMap<Serializable, ExceptionNode>();
for (ExceptionNode en : enlist) {
int hashCode = 0;
IterableSet<AugmentedStmt> curTryBody = en.get_TryBody();
for (AugmentedStmt au : curTryBody) {
hashCode ^= au.hashCode();
}
Integer I = new Integer(hashCode);
LinkedList<IterableSet<AugmentedStmt>> bucket = hCode2bucket.get(I);
if (bucket == null) {
bucket = new LinkedList<IterableSet<AugmentedStmt>>();
hCode2bucket.put(I, bucket);
}
ExceptionNode repExceptionNode = null;
for (IterableSet<AugmentedStmt> bucketTryBody : bucket) {
if (curTryBody.equals(bucketTryBody)) {
repExceptionNode = tryBody2exceptionNode.get(bucketTryBody);
break;
}
}
if (repExceptionNode == null) {
tryBody2exceptionNode.put(curTryBody, en);
bucket.add(curTryBody);
reps.add(en);
} else {
repExceptionNode.add_CatchBody(en);
}
}
enlist.clear();
enlist.addAll(reps);
}
IterableSet<ExceptionNode> exceptionFacts = body.get_ExceptionFacts();
exceptionFacts.clear();
exceptionFacts.addAll(enlist);
}
public IterableSet<AugmentedStmt> get_CatchBody(AugmentedStmt handlerAugmentedStmt) {
IterableSet<AugmentedStmt> catchBody = new IterableSet<AugmentedStmt>();
catchBody.add(handlerAugmentedStmt);
LinkedList<AugmentedStmt> catchQueue = new LinkedList<AugmentedStmt>(handlerAugmentedStmt.csuccs);
while (!catchQueue.isEmpty()) {
AugmentedStmt as = catchQueue.removeFirst();
if (!catchBody.contains(as) && as.get_Dominators().contains(handlerAugmentedStmt)) {
catchBody.add(as);
catchQueue.addAll(as.csuccs);
}
}
return catchBody;
}
}
| 9,392
| 32.073944
| 113
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/ExceptionNode.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootClass;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.util.IterableSet;
public class ExceptionNode {
private static final Logger logger = LoggerFactory.getLogger(ExceptionNode.class);
private final IterableSet<AugmentedStmt> body;
private IterableSet<AugmentedStmt> tryBody, catchBody;
private boolean dirty;
private List<AugmentedStmt> exitList;
private LinkedList<IterableSet<AugmentedStmt>> catchList;
private SootClass exception;
private HashMap<IterableSet<AugmentedStmt>, SootClass> catch2except;
private AugmentedStmt handlerAugmentedStmt;
public ExceptionNode(IterableSet<AugmentedStmt> tryBody, SootClass exception, AugmentedStmt handlerAugmentedStmt) {
this.tryBody = tryBody;
this.catchBody = null;
this.exception = exception;
this.handlerAugmentedStmt = handlerAugmentedStmt;
body = new IterableSet<AugmentedStmt>(tryBody);
dirty = true;
exitList = null;
catchList = null;
catch2except = null;
}
public boolean add_TryStmts(Collection<AugmentedStmt> c) {
for (AugmentedStmt as : c) {
if (add_TryStmt(as) == false) {
return false;
}
}
return true;
}
public boolean add_TryStmt(AugmentedStmt as) {
if ((body.contains(as)) || (tryBody.contains(as))) {
return false;
}
body.add(as);
tryBody.add(as);
return true;
}
public void refresh_CatchBody(ExceptionFinder ef) {
if (catchBody != null) {
body.removeAll(catchBody);
}
catchBody = ef.get_CatchBody(handlerAugmentedStmt);
body.addAll(catchBody);
}
public IterableSet<AugmentedStmt> get_Body() {
return body;
}
public IterableSet<AugmentedStmt> get_TryBody() {
return tryBody;
}
public IterableSet<AugmentedStmt> get_CatchBody() {
return catchBody;
}
public boolean remove(AugmentedStmt as) {
if (body.contains(as) == false) {
return false;
}
if (tryBody.contains(as)) {
tryBody.remove(as);
} else if ((catchBody != null) && (catchBody.contains(as))) {
catchBody.remove(as);
dirty = true;
} else {
return false;
}
body.remove(as);
return true;
}
public List<AugmentedStmt> get_CatchExits() {
if (catchBody == null) {
return null;
}
if (dirty) {
exitList = new LinkedList<AugmentedStmt>();
dirty = false;
for (AugmentedStmt as : catchBody) {
for (AugmentedStmt succ : as.bsuccs) {
if (catchBody.contains(succ) == false) {
exitList.add(as);
break;
}
}
}
}
return exitList;
}
public void splitOff_ExceptionNode(IterableSet<AugmentedStmt> newTryBody, AugmentedStmtGraph asg,
IterableSet<ExceptionNode> enlist) {
IterableSet<AugmentedStmt> oldTryBody = new IterableSet<AugmentedStmt>();
oldTryBody.addAll(tryBody);
IterableSet<AugmentedStmt> oldBody = new IterableSet<AugmentedStmt>();
oldBody.addAll(body);
for (AugmentedStmt as : newTryBody) {
if (remove(as) == false) {
StringBuffer b = new StringBuffer();
for (AugmentedStmt auBody : newTryBody) {
b.append("\n" + auBody.toString());
}
b.append("\n-");
for (AugmentedStmt auBody : oldTryBody) {
b.append("\n" + auBody.toString());
}
b.append("\n-");
for (AugmentedStmt auBody : oldBody) {
b.append("\n" + auBody.toString());
}
b.append("\n-");
throw new RuntimeException(
"Tried to split off a new try body that isn't in the old one.\n" + as + "\n - " + b.toString());
}
}
asg.clone_Body(catchBody);
AugmentedStmt oldCatchTarget = handlerAugmentedStmt, newCatchTarget = asg.get_CloneOf(handlerAugmentedStmt);
for (AugmentedStmt as : newTryBody) {
as.remove_CSucc(oldCatchTarget);
oldCatchTarget.remove_CPred(as);
}
for (AugmentedStmt as : tryBody) {
as.remove_CSucc(newCatchTarget);
newCatchTarget.remove_CPred(as);
}
for (ExceptionNode en : enlist) {
if (this == en) {
continue;
}
if (catchBody.isSupersetOf(en.get_Body())) {
IterableSet<AugmentedStmt> clonedTryBody = new IterableSet<AugmentedStmt>();
for (AugmentedStmt au : en.get_TryBody()) {
clonedTryBody.add(asg.get_CloneOf(au));
}
enlist.addLast(new ExceptionNode(clonedTryBody, en.exception, asg.get_CloneOf(en.handlerAugmentedStmt)));
}
}
enlist.addLast(new ExceptionNode(newTryBody, exception, asg.get_CloneOf(handlerAugmentedStmt)));
for (ExceptionNode en : enlist) {
en.refresh_CatchBody(ExceptionFinder.v());
}
asg.find_Dominators();
}
public void add_CatchBody(ExceptionNode other) {
if (other.get_CatchList() == null) {
add_CatchBody(other.get_CatchBody(), other.get_Exception());
return;
}
for (IterableSet<AugmentedStmt> c : other.get_CatchList()) {
add_CatchBody(c, other.get_Exception(c));
}
}
public void add_CatchBody(IterableSet<AugmentedStmt> newCatchBody, SootClass except) {
if (catchList == null) {
catchList = new LinkedList<IterableSet<AugmentedStmt>>();
catchList.addLast(catchBody);
catch2except = new HashMap<IterableSet<AugmentedStmt>, SootClass>();
catch2except.put(catchBody, exception);
}
body.addAll(newCatchBody);
catchList.addLast(newCatchBody);
catch2except.put(newCatchBody, except);
}
public List<IterableSet<AugmentedStmt>> get_CatchList() {
List<IterableSet<AugmentedStmt>> l = catchList;
if (l == null) {
l = new LinkedList<IterableSet<AugmentedStmt>>();
l.add(catchBody);
}
return l;
}
public Map<IterableSet<AugmentedStmt>, SootClass> get_ExceptionMap() {
Map<IterableSet<AugmentedStmt>, SootClass> m = catch2except;
if (m == null) {
m = new HashMap<IterableSet<AugmentedStmt>, SootClass>();
m.put(catchBody, exception);
}
return m;
}
public SootClass get_Exception() {
return exception;
}
public SootClass get_Exception(IterableSet<AugmentedStmt> catchBody) {
if (catch2except == null) {
return exception;
}
return catch2except.get(catchBody);
}
public void dump() {
logger.debug("try {");
for (AugmentedStmt au : get_TryBody()) {
logger.debug("\t" + au);
}
logger.debug("}");
for (IterableSet<AugmentedStmt> catchBody : get_CatchList()) {
logger.debug("catch " + get_ExceptionMap().get(catchBody) + " {");
for (AugmentedStmt au : catchBody) {
logger.debug("\t" + au);
}
logger.debug("}");
}
}
}
| 7,801
| 25.26936
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/FactFinder.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.DavaBody;
import soot.dava.RetriggerAnalysisException;
import soot.dava.internal.SET.SETNode;
import soot.dava.internal.asg.AugmentedStmtGraph;
public interface FactFinder {
public abstract void find(DavaBody body, AugmentedStmtGraph asg, SETNode SET) throws RetriggerAnalysisException;
}
| 1,156
| 34.060606
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/IfFinder.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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 soot.G;
import soot.Singletons;
import soot.dava.Dava;
import soot.dava.DavaBody;
import soot.dava.RetriggerAnalysisException;
import soot.dava.internal.SET.SETIfElseNode;
import soot.dava.internal.SET.SETNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.jimple.IfStmt;
import soot.jimple.Stmt;
import soot.util.IterableSet;
public class IfFinder implements FactFinder {
public IfFinder(Singletons.Global g) {
}
public static IfFinder v() {
return G.v().soot_dava_toolkits_base_finders_IfFinder();
}
public void find(DavaBody body, AugmentedStmtGraph asg, SETNode SET) throws RetriggerAnalysisException {
Dava.v().log("IfFinder::find()");
Iterator asgit = asg.iterator();
while (asgit.hasNext()) {
AugmentedStmt as = (AugmentedStmt) asgit.next();
Stmt s = as.get_Stmt();
if (s instanceof IfStmt) {
IfStmt ifs = (IfStmt) s;
if (body.get_ConsumedConditions().contains(as)) {
continue;
}
body.consume_Condition(as);
AugmentedStmt succIf = asg.get_AugStmt(ifs.getTarget()), succElse = (AugmentedStmt) as.bsuccs.get(0);
if (succIf == succElse) {
succElse = (AugmentedStmt) as.bsuccs.get(1);
}
asg.calculate_Reachability(succIf, succElse, as);
asg.calculate_Reachability(succElse, succIf, as);
IterableSet fullBody = new IterableSet(), ifBody = find_Body(succIf, succElse),
elseBody = find_Body(succElse, succIf);
fullBody.add(as);
fullBody.addAll(ifBody);
fullBody.addAll(elseBody);
Iterator enlit = body.get_ExceptionFacts().iterator();
while (enlit.hasNext()) {
ExceptionNode en = (ExceptionNode) enlit.next();
IterableSet tryBody = en.get_TryBody();
if (tryBody.contains(as)) {
Iterator fbit = fullBody.snapshotIterator();
while (fbit.hasNext()) {
AugmentedStmt fbas = (AugmentedStmt) fbit.next();
if (tryBody.contains(fbas) == false) {
fullBody.remove(fbas);
if (ifBody.contains(fbas)) {
ifBody.remove(fbas);
}
if (elseBody.contains(fbas)) {
elseBody.remove(fbas);
}
}
}
}
}
SET.nest(new SETIfElseNode(as, fullBody, ifBody, elseBody));
}
}
}
private IterableSet find_Body(AugmentedStmt targetBranch, AugmentedStmt otherBranch) {
IterableSet body = new IterableSet();
if (targetBranch.get_Reachers().contains(otherBranch)) {
return body;
}
LinkedList<AugmentedStmt> worklist = new LinkedList<AugmentedStmt>();
worklist.addLast(targetBranch);
while (worklist.isEmpty() == false) {
AugmentedStmt as = worklist.removeFirst();
if (body.contains(as) == false) {
body.add(as);
Iterator sit = as.csuccs.iterator();
while (sit.hasNext()) {
AugmentedStmt sas = (AugmentedStmt) sit.next();
if ((sas.get_Reachers().contains(otherBranch) == false) && (sas.get_Dominators().contains(targetBranch) == true)) {
worklist.addLast(sas);
}
}
}
}
return body;
}
}
| 4,236
| 28.423611
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/IndexComparator.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.Comparator;
class IndexComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (o1 == o2) {
return 0;
}
if (o1 instanceof String) {
return 1;
}
if (o2 instanceof String) {
return -1;
}
return ((Integer) o1).intValue() - ((Integer) o2).intValue();
}
public boolean equals(Object o) {
return (o instanceof IndexComparator);
}
}
| 1,278
| 25.645833
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/IndexSetComparator.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.Comparator;
import java.util.TreeSet;
class IndexSetComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (o1 == o2) {
return 0;
}
o1 = ((TreeSet) o1).last();
o2 = ((TreeSet) o2).last();
if (o1 instanceof String) {
return 1;
}
if (o2 instanceof String) {
return -1;
}
return ((Integer) o1).intValue() - ((Integer) o2).intValue();
}
public boolean equals(Object o) {
return (o instanceof IndexSetComparator);
}
}
| 1,375
| 25.461538
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/LabeledBlockFinder.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
import soot.G;
import soot.Singletons;
import soot.dava.Dava;
import soot.dava.DavaBody;
import soot.dava.RetriggerAnalysisException;
import soot.dava.internal.SET.SETBasicBlock;
import soot.dava.internal.SET.SETLabeledBlockNode;
import soot.dava.internal.SET.SETNode;
import soot.dava.internal.SET.SETStatementSequenceNode;
import soot.dava.internal.SET.SETTryNode;
import soot.dava.internal.SET.SETUnconditionalWhileNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.util.IterableSet;
public class LabeledBlockFinder implements FactFinder {
public LabeledBlockFinder(Singletons.Global g) {
}
public static LabeledBlockFinder v() {
return G.v().soot_dava_toolkits_base_finders_LabeledBlockFinder();
}
private final HashMap<SETNode, Integer> orderNumber = new HashMap();
public void find(DavaBody body, AugmentedStmtGraph asg, SETNode SET) throws RetriggerAnalysisException {
Dava.v().log("LabeledBlockFinder::find()");
Iterator bit = SET.get_Body().iterator();
while (bit.hasNext()) {
SET.find_SmallestSETNode((AugmentedStmt) bit.next());
}
SET.find_LabeledBlocks(this);
}
public void perform_ChildOrder(SETNode SETParent) {
Dava.v().log("LabeledBlockFinder::perform_ChildOrder()");
if (SETParent instanceof SETStatementSequenceNode) {
return;
}
Iterator<IterableSet> sbit = SETParent.get_SubBodies().iterator();
while (sbit.hasNext()) {
IterableSet body = sbit.next();
IterableSet children = SETParent.get_Body2ChildChain().get(body);
HashSet<SETBasicBlock> touchSet = new HashSet<SETBasicBlock>();
IterableSet childOrdering = new IterableSet();
LinkedList worklist = new LinkedList();
List<SETBasicBlock> SETBasicBlocks = null;
if (SETParent instanceof SETUnconditionalWhileNode) {
SETNode startSETNode = ((SETUnconditionalWhileNode) SETParent).get_CharacterizingStmt().myNode;
while (children.contains(startSETNode) == false) {
startSETNode = startSETNode.get_Parent();
}
SETBasicBlocks = build_Connectivity(SETParent, body, startSETNode);
worklist.add(SETBasicBlock.get_SETBasicBlock(startSETNode));
}
else if (SETParent instanceof SETTryNode) {
SETNode startSETNode = null;
Iterator bit = body.iterator();
find_entry_loop: while (bit.hasNext()) {
AugmentedStmt as = (AugmentedStmt) bit.next();
Iterator pbit = as.cpreds.iterator();
while (pbit.hasNext()) {
if (body.contains(pbit.next()) == false) {
startSETNode = as.myNode;
break find_entry_loop;
}
}
}
if (startSETNode == null) {
startSETNode = ((SETTryNode) SETParent).get_EntryStmt().myNode;
}
while (children.contains(startSETNode) == false) {
startSETNode = startSETNode.get_Parent();
}
SETBasicBlocks = build_Connectivity(SETParent, body, startSETNode);
worklist.add(SETBasicBlock.get_SETBasicBlock(startSETNode));
}
else {
SETBasicBlocks = build_Connectivity(SETParent, body, null);
Iterator cit = children.iterator();
while (cit.hasNext()) {
SETNode child = (SETNode) cit.next();
if (child.get_Predecessors().isEmpty()) {
worklist.add(SETBasicBlock.get_SETBasicBlock(child));
}
}
}
while (worklist.isEmpty() == false) {
SETBasicBlock sbb = (SETBasicBlock) worklist.removeFirst();
// extract and append the basic block to child ordering
Iterator bit = sbb.get_Body().iterator();
while (bit.hasNext()) {
childOrdering.addLast(bit.next());
}
touchSet.add(sbb);
/*
* ************************************************ * Basic orderer.
*/
TreeSet sortedSuccessors = new TreeSet();
Iterator sit = sbb.get_Successors().iterator();
SETBasicBlock_successor_loop: while (sit.hasNext()) {
SETBasicBlock ssbb = (SETBasicBlock) sit.next();
if (touchSet.contains(ssbb)) {
continue;
}
Iterator psit = ssbb.get_Predecessors().iterator();
while (psit.hasNext()) {
if (touchSet.contains(psit.next()) == false) {
continue SETBasicBlock_successor_loop;
}
}
sortedSuccessors.add(ssbb);
}
sit = sortedSuccessors.iterator();
while (sit.hasNext()) {
worklist.addFirst(sit.next());
}
/*
* End of Basic orderer. ************************************************
*/
}
int count = 0;
Iterator it = childOrdering.iterator();
while (it.hasNext()) {
orderNumber.put((SETNode) it.next(), new Integer(count++));
}
children.clear();
children.addAll(childOrdering);
}
}
private List<SETBasicBlock> build_Connectivity(SETNode SETParent, IterableSet body, SETNode startSETNode) {
Dava.v().log("LabeledBlockFinder::build_Connectivity()");
IterableSet children = SETParent.get_Body2ChildChain().get(body);
/*
* First task: establish the connectivity between the children of the current node.
*/
// look through all the statements in the current SETNode
Iterator it = body.iterator();
while (it.hasNext()) {
AugmentedStmt as = (AugmentedStmt) it.next();
// for each statement, examine each of it's successors
Iterator sit = as.csuccs.iterator();
while (sit.hasNext()) {
AugmentedStmt sas = (AugmentedStmt) sit.next();
if (body.contains(sas)) {
// get the child nodes that contain the source and destination statements
SETNode srcNode = as.myNode;
SETNode dstNode = sas.myNode;
while (children.contains(srcNode) == false) {
srcNode = srcNode.get_Parent();
}
while (children.contains(dstNode) == false) {
dstNode = dstNode.get_Parent();
}
if (srcNode == dstNode) {
continue;
}
// hook up the src and dst nodes
if (srcNode.get_Successors().contains(dstNode) == false) {
srcNode.get_Successors().add(dstNode);
}
if (dstNode.get_Predecessors().contains(srcNode) == false) {
dstNode.get_Predecessors().add(srcNode);
}
}
}
}
Dava.v().log("LabeledBlockFinder::build_Connectivity() - built connectivity");
/*
* Second task: build the basic block graph between the node.
*/
// first create the basic blocks
LinkedList<SETBasicBlock> basicBlockList = new LinkedList<SETBasicBlock>();
Iterator cit = children.iterator();
while (cit.hasNext()) {
SETNode child = (SETNode) cit.next();
if (SETBasicBlock.get_SETBasicBlock(child) != null) {
continue;
}
// build a basic block for every node with != 1 predecessor
SETBasicBlock basicBlock = new SETBasicBlock();
while (child.get_Predecessors().size() == 1) {
if ((startSETNode != null) && (child == startSETNode)) {
break;
}
SETNode prev = (SETNode) child.get_Predecessors().getFirst();
if ((SETBasicBlock.get_SETBasicBlock(prev) != null) || (prev.get_Successors().size() != 1)) {
break;
}
child = prev;
}
basicBlock.add(child);
while (child.get_Successors().size() == 1) {
child = (SETNode) child.get_Successors().getFirst();
if ((SETBasicBlock.get_SETBasicBlock(child) != null) || (child.get_Predecessors().size() != 1)) {
break;
}
basicBlock.add(child);
}
basicBlockList.add(basicBlock);
}
Dava.v().log("LabeledBlockFinder::build_Connectivity() - created basic blocks");
// next build the connectivity between the nodes of the basic block graph
Iterator<SETBasicBlock> bblit = basicBlockList.iterator();
while (bblit.hasNext()) {
SETBasicBlock sbb = bblit.next();
SETNode entryNode = sbb.get_EntryNode();
Iterator pit = entryNode.get_Predecessors().iterator();
while (pit.hasNext()) {
SETNode psn = (SETNode) pit.next();
SETBasicBlock psbb = SETBasicBlock.get_SETBasicBlock(psn);
if (sbb.get_Predecessors().contains(psbb) == false) {
sbb.get_Predecessors().add(psbb);
}
if (psbb.get_Successors().contains(sbb) == false) {
psbb.get_Successors().add(sbb);
}
}
}
Dava.v().log("LabeledBlockFinder::build_Connectivity() - done");
return basicBlockList;
}
public void find_LabeledBlocks(SETNode SETParent) {
Dava.v().log("LabeledBlockFinder::find_LabeledBlocks()");
Iterator<IterableSet> sbit = SETParent.get_SubBodies().iterator();
while (sbit.hasNext()) {
IterableSet curBody = sbit.next();
IterableSet children = SETParent.get_Body2ChildChain().get(curBody);
Iterator it = children.snapshotIterator();
if (it.hasNext()) {
SETNode curNode = (SETNode) it.next(), prevNode = null;
// Look through all the children of the current SET node.
while (it.hasNext()) {
prevNode = curNode;
curNode = (SETNode) it.next();
AugmentedStmt entryStmt = curNode.get_EntryStmt();
SETNode minNode = null;
boolean build = false;
// For each SET node, check the edges that come into it.
Iterator pit = entryStmt.cpreds.iterator();
while (pit.hasNext()) {
AugmentedStmt pas = (AugmentedStmt) pit.next();
if (curBody.contains(pas) == false) {
continue;
}
SETNode srcNode = pas.myNode;
while (children.contains(srcNode) == false) {
srcNode = srcNode.get_Parent();
}
if (srcNode == curNode) {
continue;
}
if (srcNode != prevNode) {
build = true;
if ((minNode == null) || (orderNumber.get(srcNode).intValue() < orderNumber.get(minNode).intValue())) {
minNode = srcNode;
}
}
}
if (build) {
IterableSet labeledBlockBody = new IterableSet();
Iterator cit = children.iterator(minNode);
while (cit.hasNext()) {
SETNode child = (SETNode) cit.next();
if (child == curNode) {
break;
}
labeledBlockBody.addAll(child.get_Body());
}
SETLabeledBlockNode slbn = new SETLabeledBlockNode(labeledBlockBody);
orderNumber.put(slbn, orderNumber.get(minNode));
cit = children.snapshotIterator(minNode);
while (cit.hasNext()) {
SETNode child = (SETNode) cit.next();
if (child == curNode) {
break;
}
SETParent.remove_Child(child, children);
slbn.add_Child(child, slbn.get_Body2ChildChain().get(slbn.get_SubBodies().get(0)));
}
SETParent.insert_ChildBefore(slbn, curNode, children);
}
}
}
}
}
}
| 12,410
| 29.720297
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/SequenceFinder.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.G;
import soot.Singletons;
import soot.dava.Dava;
import soot.dava.DavaBody;
import soot.dava.RetriggerAnalysisException;
import soot.dava.internal.SET.SETNode;
import soot.dava.internal.SET.SETStatementSequenceNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.util.IterableSet;
public class SequenceFinder implements FactFinder {
public SequenceFinder(Singletons.Global g) {
}
public static SequenceFinder v() {
return G.v().soot_dava_toolkits_base_finders_SequenceFinder();
}
public void find(DavaBody body, AugmentedStmtGraph asg, SETNode SET) throws RetriggerAnalysisException {
Dava.v().log("SequenceFinder::find()");
SET.find_StatementSequences(this, body);
}
public void find_StatementSequences(SETNode SETParent, IterableSet body, HashSet<AugmentedStmt> childUnion,
DavaBody davaBody) {
Iterator bit = body.iterator();
while (bit.hasNext()) {
AugmentedStmt as = (AugmentedStmt) bit.next();
if (childUnion.contains(as)) {
continue;
}
IterableSet sequenceBody = new IterableSet();
while (as.bpreds.size() == 1) {
AugmentedStmt pas = (AugmentedStmt) as.bpreds.get(0);
if ((body.contains(pas) == false) || (childUnion.contains(pas) == true)) {
break;
}
as = pas;
}
while ((body.contains(as)) && (childUnion.contains(as) == false)) {
childUnion.add(as);
sequenceBody.addLast(as);
if (as.bsuccs.isEmpty() == false) {
as = (AugmentedStmt) as.bsuccs.get(0);
}
if (as.bpreds.size() != 1) {
break;
}
}
SETParent.add_Child(new SETStatementSequenceNode(sequenceBody, davaBody), SETParent.get_Body2ChildChain().get(body));
}
}
}
| 2,732
| 28.706522
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/SwitchFinder.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeSet;
import soot.G;
import soot.Singletons;
import soot.Value;
import soot.dava.Dava;
import soot.dava.DavaBody;
import soot.dava.RetriggerAnalysisException;
import soot.dava.internal.SET.SETNode;
import soot.dava.internal.SET.SETSwitchNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.Stmt;
import soot.jimple.TableSwitchStmt;
import soot.util.IterableSet;
public class SwitchFinder implements FactFinder {
public SwitchFinder(Singletons.Global g) {
}
public static SwitchFinder v() {
return G.v().soot_dava_toolkits_base_finders_SwitchFinder();
}
private IterableSet junkBody;
private HashSet targetSet;
private LinkedList targetList, snTargetList, tSuccList;
private HashMap index2target, tSucc2indexSet, tSucc2target, tSucc2Body;
public void find(DavaBody davaBody, AugmentedStmtGraph asg, SETNode SET) throws RetriggerAnalysisException {
Dava.v().log("SwitchFinder::find()");
final String defaultStr = "default";
Iterator asgit = asg.iterator();
while (asgit.hasNext()) {
AugmentedStmt as = (AugmentedStmt) asgit.next();
Stmt s = as.get_Stmt();
if (((s instanceof TableSwitchStmt) == false) && ((s instanceof LookupSwitchStmt) == false)) {
continue;
}
Value key = null;
junkBody = new IterableSet();
targetSet = new HashSet();
targetList = new LinkedList();
snTargetList = new LinkedList();
tSuccList = new LinkedList();
index2target = new HashMap();
tSucc2indexSet = new HashMap();
tSucc2target = new HashMap();
tSucc2Body = new HashMap();
if (s instanceof TableSwitchStmt) {
TableSwitchStmt tss = (TableSwitchStmt) s;
int target_count = tss.getHighIndex() - tss.getLowIndex() + 1;
for (int i = 0; i < target_count; i++) {
build_Bindings(as, new Integer(i + tss.getLowIndex()), asg.get_AugStmt((Stmt) tss.getTarget(i)));
}
build_Bindings(as, defaultStr, asg.get_AugStmt((Stmt) tss.getDefaultTarget()));
key = tss.getKey();
}
else if (s instanceof LookupSwitchStmt) {
LookupSwitchStmt lss = (LookupSwitchStmt) s;
int target_count = lss.getTargetCount();
for (int i = 0; i < target_count; i++) {
build_Bindings(as, new Integer(lss.getLookupValue(i)), asg.get_AugStmt((Stmt) lss.getTarget(i)));
}
build_Bindings(as, defaultStr, asg.get_AugStmt((Stmt) lss.getDefaultTarget()));
key = lss.getKey();
}
Iterator tsit = tSuccList.iterator();
while (tsit.hasNext()) {
AugmentedStmt tSucc = (AugmentedStmt) tsit.next();
AugmentedStmt target = (AugmentedStmt) tSucc2target.get(tSucc);
snTargetList.addLast(
new SwitchNode(target, (TreeSet<Object>) tSucc2indexSet.get(tSucc), (IterableSet) tSucc2Body.get(tSucc)));
}
TreeSet targetHeads = new TreeSet(), killBodies = new TreeSet();
// Get the set of head cases and clear those bodies that should not be included in the switch. Clear as mud, huh? :-)
{
asg.calculate_Reachability(targetList, targetSet, as);
SwitchNodeGraph sng = new SwitchNodeGraph(snTargetList);
killBodies.addAll(snTargetList);
snTargetList = new LinkedList();
LinkedList worklist = new LinkedList();
worklist.addAll(sng.getHeads());
while (worklist.isEmpty() == false) {
SwitchNode sn = (SwitchNode) worklist.removeFirst();
snTargetList.addLast(sn);
killBodies.remove(sn);
SwitchNode champ = null;
Iterator sit = sn.get_Succs().iterator();
while (sit.hasNext()) {
SwitchNode ssn = (SwitchNode) sit.next();
if ((champ == null) || (champ.get_Score() < ssn.get_Score())) {
champ = ssn;
}
}
if ((champ != null) && (champ.get_Score() > 0)) {
worklist.addLast(champ);
}
}
Iterator kit = killBodies.iterator();
while (kit.hasNext()) {
SwitchNode sn = (SwitchNode) kit.next();
IterableSet snBody = sn.get_Body();
snBody.clear();
snBody.add(sn.get_AugStmt());
}
sng = new SwitchNodeGraph(snTargetList);
targetHeads.addAll(sng.getHeads());
}
LinkedList<SwitchNode> switchNodeList = new LinkedList<SwitchNode>();
// Now, merge the targetHeads list and the killBodies list, keeping bundles of case fall throughs from the node graph.
{
while ((targetHeads.isEmpty() == false) || (killBodies.isEmpty() == false)) {
if ((targetHeads.isEmpty()) || ((targetHeads.isEmpty() == false) && (killBodies.isEmpty() == false)
&& (((SwitchNode) targetHeads.first()).compareTo(killBodies.first()) > 0))) {
SwitchNode nextNode = (SwitchNode) killBodies.first();
killBodies.remove(nextNode);
switchNodeList.addLast(nextNode);
} else {
SwitchNode nextNode = (SwitchNode) targetHeads.first();
targetHeads.remove(nextNode);
while (true) {
switchNodeList.addLast(nextNode);
if (nextNode.get_Succs().isEmpty()) {
break;
}
nextNode = (SwitchNode) nextNode.get_Succs().get(0);
}
}
}
}
IterableSet body = new IterableSet();
body.add(as);
for (SwitchNode sn : switchNodeList) {
body.addAll(sn.get_Body());
if (sn.get_IndexSet().contains(defaultStr)) {
sn.get_IndexSet().clear();
sn.get_IndexSet().add(defaultStr);
}
}
body.addAll(junkBody);
for (ExceptionNode en : davaBody.get_ExceptionFacts()) {
IterableSet tryBody = en.get_TryBody();
if (tryBody.contains(as)) {
Iterator fbit = body.snapshotIterator();
while (fbit.hasNext()) {
AugmentedStmt fbas = (AugmentedStmt) fbit.next();
if (tryBody.contains(fbas) == false) {
body.remove(fbas);
for (SwitchNode sn : switchNodeList) {
IterableSet switchBody = sn.get_Body();
if (switchBody.contains(fbas)) {
switchBody.remove(fbas);
break;
}
}
}
}
}
}
SET.nest(new SETSwitchNode(as, key, body, switchNodeList, junkBody));
}
}
private IterableSet find_SubBody(AugmentedStmt switchAS, AugmentedStmt branchS) {
IterableSet subBody = new IterableSet();
LinkedList<AugmentedStmt> worklist = new LinkedList<AugmentedStmt>();
subBody.add(branchS);
branchS = (AugmentedStmt) branchS.bsuccs.get(0);
if (branchS.get_Dominators().contains(switchAS)) {
worklist.addLast(branchS);
subBody.add(branchS);
}
while (worklist.isEmpty() == false) {
AugmentedStmt as = worklist.removeFirst();
Iterator sit = as.csuccs.iterator();
while (sit.hasNext()) {
AugmentedStmt sas = (AugmentedStmt) sit.next();
if ((subBody.contains(sas) == false) && (sas.get_Dominators().contains(branchS))) {
worklist.addLast(sas);
subBody.add(sas);
}
}
}
return subBody;
}
private void build_Bindings(AugmentedStmt swAs, Object index, AugmentedStmt target) {
AugmentedStmt tSucc = (AugmentedStmt) target.bsuccs.get(0);
if (targetSet.add(tSucc)) {
targetList.addLast(tSucc);
}
index2target.put(index, target);
TreeSet indices = null;
if ((indices = (TreeSet) tSucc2indexSet.get(tSucc)) == null) {
indices = new TreeSet(new IndexComparator());
tSucc2indexSet.put(tSucc, indices);
tSucc2target.put(tSucc, target);
tSucc2Body.put(tSucc, find_SubBody(swAs, target));
tSuccList.add(tSucc);
} else {
junkBody.add(target);
// break all edges between the junk body and any of it's successors
Iterator sit = target.bsuccs.iterator();
while (sit.hasNext()) {
((AugmentedStmt) sit.next()).bpreds.remove(target);
}
sit = target.csuccs.iterator();
while (sit.hasNext()) {
((AugmentedStmt) sit.next()).cpreds.remove(target);
}
target.bsuccs.clear();
target.csuccs.clear();
}
indices.add(index);
}
}
| 9,485
| 29.6
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/SwitchNode.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.TreeSet;
import soot.dava.internal.asg.AugmentedStmt;
import soot.util.IterableSet;
public class SwitchNode implements Comparable {
private final LinkedList preds, succs;
private AugmentedStmt as;
private int score;
private TreeSet<Object> indexSet;
private IterableSet body;
public SwitchNode(AugmentedStmt as, TreeSet<Object> indexSet, IterableSet body) {
this.as = as;
this.indexSet = indexSet;
this.body = body;
preds = new LinkedList();
succs = new LinkedList();
score = -1;
}
public int get_Score() {
if (score == -1) {
score = 0;
if (preds.size() < 2) {
Iterator sit = succs.iterator();
while (sit.hasNext()) {
SwitchNode ssn = (SwitchNode) sit.next();
int curScore = ssn.get_Score();
if (score < curScore) {
score = curScore;
}
}
score++;
}
}
return score;
}
public List get_Preds() {
return preds;
}
public List get_Succs() {
return succs;
}
public AugmentedStmt get_AugStmt() {
return as;
}
public TreeSet<Object> get_IndexSet() {
return new TreeSet<Object>(indexSet);
}
public IterableSet get_Body() {
return body;
}
public SwitchNode reset() {
preds.clear();
succs.clear();
return this;
}
public void setup_Graph(HashMap<AugmentedStmt, SwitchNode> binding) {
Iterator rit = ((AugmentedStmt) as.bsuccs.get(0)).get_Reachers().iterator();
while (rit.hasNext()) {
SwitchNode pred = binding.get(rit.next());
if (pred != null) {
if (preds.contains(pred) == false) {
preds.add(pred);
}
if (pred.succs.contains(this) == false) {
pred.succs.add(this);
}
}
}
}
/*
* Can compare to an Integer, a String, a set of Indices, and another SwitchNode.
*/
public int compareTo(Object o) {
if (o == this) {
return 0;
}
if (indexSet.last() instanceof String) {
return 1;
}
if (o instanceof String) {
return -1;
}
if (o instanceof Integer) {
return ((Integer) indexSet.last()).intValue() - ((Integer) o).intValue();
}
if (o instanceof TreeSet) {
TreeSet other = (TreeSet) o;
if (other.last() instanceof String) {
return -1;
}
return ((Integer) indexSet.last()).intValue() - ((Integer) other.last()).intValue();
}
SwitchNode other = (SwitchNode) o;
if (other.indexSet.last() instanceof String) {
return -1;
}
return ((Integer) indexSet.last()).intValue() - ((Integer) other.indexSet.last()).intValue();
}
}
| 3,626
| 21.811321
| 97
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/SwitchNodeGraph.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%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.toolkits.graph.DirectedGraph;
class SwitchNodeGraph implements DirectedGraph {
private LinkedList body;
private final LinkedList heads, tails;
private final HashMap binding;
public SwitchNodeGraph(List body) {
this.body = new LinkedList(body);
this.binding = new HashMap();
this.heads = new LinkedList();
this.tails = new LinkedList();
for (Object o : body) {
SwitchNode sn = (SwitchNode) o;
binding.put(sn.get_AugStmt().bsuccs.get(0), sn);
sn.reset();
}
for (Object o : body) {
((SwitchNode) o).setup_Graph(binding);
}
for (Object o : body) {
SwitchNode sn = (SwitchNode) o;
if (sn.get_Preds().isEmpty()) {
heads.add(sn);
}
if (sn.get_Succs().isEmpty()) {
tails.add(sn);
}
}
}
@Override
public int size() {
return body.size();
}
@Override
public List getHeads() {
return heads;
}
@Override
public List getTails() {
return tails;
}
@Override
public List getPredsOf(Object o) {
return ((SwitchNode) o).get_Preds();
}
@Override
public List getSuccsOf(Object o) {
return ((SwitchNode) o).get_Succs();
}
@Override
public Iterator iterator() {
return body.iterator();
}
public List getBody() {
return body;
}
}
| 2,273
| 21.74
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/finders/SynchronizedBlockFinder.java
|
package soot.dava.toolkits.base.finders;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* Copyright (C) 2004 - 20055 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.LinkedList;
import java.util.List;
import java.util.Map;
import soot.G;
import soot.Local;
import soot.RefType;
import soot.Singletons;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.dava.Dava;
import soot.dava.DavaBody;
import soot.dava.RetriggerAnalysisException;
import soot.dava.internal.SET.SETNode;
import soot.dava.internal.SET.SETSynchronizedBlockNode;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.asg.AugmentedStmtGraph;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.DefinitionStmt;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.GotoStmt;
import soot.jimple.MonitorStmt;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.toolkits.graph.StronglyConnectedComponentsFast;
import soot.util.IterableSet;
public class SynchronizedBlockFinder implements FactFinder {
public SynchronizedBlockFinder(Singletons.Global g) {
}
public static SynchronizedBlockFinder v() {
return G.v().soot_dava_toolkits_base_finders_SynchronizedBlockFinder();
}
private HashMap<AugmentedStmt, Map<Value, Integer>> as2ml;
private DavaBody davaBody;
/*
* Nomair A Naeem 08-FEB-2005 monitorLocalSet contains all the locals that are used in monitors monitorEnterSet contains
* all enterMonitorStmts Statements
*/
private IterableSet monitorLocalSet, monitorEnterSet;
private final Integer WHITE = new Integer(0);// never visited in DFS
private final Integer GRAY = new Integer(1);// visited but not finished
private final Integer BLACK = new Integer(2);// finished
private final int UNKNOWN = -100000; // Note there are at most 65536 monitor
// exits in a method.
private final Integer VARIABLE_INCR = new Integer(UNKNOWN);
private final String THROWABLE = "java.lang.Throwable";
public void find(DavaBody body, AugmentedStmtGraph asg, SETNode SET) throws RetriggerAnalysisException {
davaBody = body;
Dava.v().log("SynchronizedBlockFinder::find()");
as2ml = new HashMap();
IterableSet synchronizedBlockFacts = body.get_SynchronizedBlockFacts();
synchronizedBlockFacts.clear();
set_MonitorLevels(asg);
Map<AugmentedStmt, IterableSet> as2synchSet = build_SynchSets();
IterableSet usedMonitors = new IterableSet();
AugmentedStmt previousStmt = null;
Iterator asgit = asg.iterator();
while (asgit.hasNext()) {
// going through all augmentedStmts
AugmentedStmt as = (AugmentedStmt) asgit.next();
if (as.get_Stmt() instanceof EnterMonitorStmt) {
// for each monitor enter stmt found
IterableSet synchSet = as2synchSet.get(as);
if (synchSet != null) {
IterableSet synchBody = get_BodyApproximation(as, synchSet);
Value local = ((EnterMonitorStmt) as.get_Stmt()).getOp();
Value copiedLocal = null;
/*
* Synch bug due to copy stmts r2 = r1 enter monitor r1 synch body exit monitor r2 we need to realize that r1 and
* r2 are the same implemented as a hack, the correct approach is reaching copies
*/
if (previousStmt != null) {
Stmt previousS = previousStmt.get_Stmt();
if (previousS instanceof DefinitionStmt) {
DefinitionStmt previousDef = (DefinitionStmt) previousS;
Value rightPrevious = previousDef.getRightOp();
if (rightPrevious.toString().compareTo(local.toString()) == 0) {
copiedLocal = previousDef.getLeftOp();
}
}
}
Integer level = as2ml.get(as).get(local);
Iterator enit = body.get_ExceptionFacts().iterator();
// going through all exception nodes in the DavaBody
boolean done = false;
IterableSet origSynchBody = synchBody;
while (enit.hasNext()) {
ExceptionNode en = (ExceptionNode) enit.next();
synchBody = (IterableSet) origSynchBody.clone();
// see if the two bodies match exactly
if (verify_CatchBody(en, synchBody, local, copiedLocal)) {
if (SET.nest(new SETSynchronizedBlockNode(en, local))) {
done = true;
// System.out.println("synch block created");
Iterator ssit = synchSet.iterator();
while (ssit.hasNext()) {
AugmentedStmt ssas = (AugmentedStmt) ssit.next();
Stmt sss = ssas.get_Stmt();
/*
* Jeromes Implementation: changed because of copy stmt bug
*
* if ((sss instanceof MonitorStmt) && (((MonitorStmt) sss).getOp() == local) && (((Integer) ((HashMap)
* as2ml.get( ssas)).get( local)).equals( level)) && (usedMonitors.contains( ssas) == false)){
*/
if (sss instanceof MonitorStmt) {
if ((((MonitorStmt) sss).getOp() == local) && ((as2ml.get(ssas).get(local)).equals(level))
&& (usedMonitors.contains(ssas) == false)) {
usedMonitors.add(ssas);
} else {
if ((((MonitorStmt) sss).getOp() == copiedLocal) && (usedMonitors.contains(ssas) == false)) {
// note we dont check levels in
// this case
usedMonitors.add(ssas);
}
}
}
}
synchronizedBlockFacts.add(en);
}
break;
} else {
// throw new
// RuntimeException("Could not verify approximated Synchronized body");
}
}
if (!done) {
throw new RuntimeException("Could not verify approximated Synchronized body!\n" + "Method:\n" + body.getMethod()
+ "Body:\n" + "===============================================================\n" + body.getUnits()
+ "===============================================================\n");
}
} // non null synch set for this enter monitor stmt
} // if the augmented stmt was a enter monitor stmt
previousStmt = as;
} // going through all augmented stmts
IterableSet<AugmentedStmt> monitorFacts = body.get_MonitorFacts();
monitorFacts.clear();
for (AugmentedStmt as : asg) {
if ((as.get_Stmt() instanceof MonitorStmt) && (usedMonitors.contains(as) == false)) {
monitorFacts.add(as);
}
}
}
/*
* as2locals: contains all locals which have unknown level for this augmented stmt viAugStmts: contains all augmented stmts
* which have some unknown level local in them
*/
private void find_VariableIncreasing(AugmentedStmtGraph asg, HashMap local2level_template,
LinkedList<AugmentedStmt> viAugStmts, HashMap<AugmentedStmt, LinkedList<Value>> as2locals) {
StronglyConnectedComponentsFast scc = new StronglyConnectedComponentsFast(asg);
IterableSet viSeeds = new IterableSet();
HashMap as2color = new HashMap(), as2rml = new HashMap();
// as2rml contains each augmented stmt as key with a local2Level mapping
// as value
Iterator asgit = asg.iterator();
while (asgit.hasNext()) {
as2rml.put(asgit.next(), local2level_template.clone());
}
// loop through all the strongly connected components in the graph
Iterator<List> sccit = scc.getTrueComponents().iterator();
while (sccit.hasNext()) {
// componentList contains augmentedstmts belonging to a particular
// scc
List componentList = sccit.next();
// component contains augmentedstmts belonging to a particular scc
IterableSet component = new IterableSet();
component.addAll(componentList);
// add to as2color each augstmt belonging to the component as the
// key and the color white as the value
Iterator cit = component.iterator();
while (cit.hasNext()) {
as2color.put(cit.next(), WHITE);
}
// DFS and mark enough of the variable increasing points to get
// started.
AugmentedStmt seedStmt = (AugmentedStmt) component.getFirst();
// seedStmt contains the first stmt of the scc
DFS_Scc(seedStmt, component, as2rml, as2color, seedStmt, viSeeds);
// viSeeds contain augmentedStmts which have unknown level since
// their level was less
// than that of their predecessors
}
// viSeeds contains all the augmentedStmts with unknown level in the
// method (for all scc)
IterableSet worklist = new IterableSet();
worklist.addAll(viSeeds);
// Propegate the variable increasing property.
while (worklist.isEmpty() == false) {
AugmentedStmt as = (AugmentedStmt) worklist.getFirst();
worklist.removeFirst();
HashMap local2level = (HashMap) as2rml.get(as);
// get all sucessors of the viSeed
Iterator sit = as.csuccs.iterator();
while (sit.hasNext()) {
AugmentedStmt sas = (AugmentedStmt) sit.next();
HashMap<Value, Integer> slocal2level = (HashMap<Value, Integer>) as2rml.get(sas);
Iterator mlsit = monitorLocalSet.iterator();
while (mlsit.hasNext()) {
Value local = (Value) mlsit.next();
// if the level for a local is set to unknown and the level
// for the same local is not
// set to unknown in the successor set it and add it to the
// worklist
if ((local2level.get(local) == VARIABLE_INCR) && (slocal2level.get(local) != VARIABLE_INCR)) {
slocal2level.put(local, VARIABLE_INCR);
if (worklist.contains(sas) == false) {
worklist.addLast(sas);
}
}
}
}
}
/*
* At the end of this the worklist is empty the unknown level of locals of an augmentedstmt present in the viSeed has
* been propagated through out the stmts reachable from that stmt
*/
// Summarize the variable increasing information for the
// set_MonitorLevels() function.
asgit = asg.iterator();
while (asgit.hasNext()) {
AugmentedStmt as = (AugmentedStmt) asgit.next();
HashMap local2level = (HashMap) as2rml.get(as);
Iterator mlsit = monitorLocalSet.iterator();
while (mlsit.hasNext()) {
// for each local involved in monitor stmts
Value local = (Value) mlsit.next();
if (local2level.get(local) == VARIABLE_INCR) {
/*
* Nomair A. Naeem 08-FEB-2005 BUG IN CODE. The getLast method returns a NoSuchElementException if list is empty.
* Protect this by checking isEmpty
*/
if (!viAugStmts.isEmpty()) {
if (viAugStmts.getLast() != as) {
viAugStmts.addLast(as);
}
} else {
// System.out.println("List was empty added as");
viAugStmts.addLast(as);
}
LinkedList<Value> locals = null;
if ((locals = as2locals.get(as)) == null) {
locals = new LinkedList<Value>();
as2locals.put(as, locals);
}
locals.addLast(local);
}
}
}
}
/*
* Inputs: as: the seed stmt, i.e. the first statement of a strongly connected component component: the strongly connected
* stmt being processed as2rml: a hashmap which contains an augmentedstmt as key and a hashmap with local to level mapping
* as value as2color: maps each augmentedstmt of a scc to a color (white initially) viSeeds: variable increasing levels,
* initially empty
*
* Purpose: makes a traversal of the entire scc and increases the levels of locals when used in monitor enter decreases the
* levels of locals when leaving monitor if a successor has never been visited invoke same method on it with updated level
* information if a sucessor has been visited before and has a lower level than a seed the level of the sucessor is marked
* unknown and is added to the viSeeds list
*/
private void DFS_Scc(AugmentedStmt as, IterableSet component, HashMap as2rml, HashMap as2color, AugmentedStmt seedStmt,
IterableSet viSeeds) {
as2color.put(as, GRAY);
Stmt s = as.get_Stmt();
// get local to level mapping of the augmented stmt
HashMap<Value, Integer> local2level = (HashMap<Value, Integer>) as2rml.get(as);
if (s instanceof MonitorStmt) {
Value local = ((MonitorStmt) s).getOp();
if (s instanceof EnterMonitorStmt) {
// its an enter hence increase
// level for this local
local2level.put(local, new Integer(local2level.get(local).intValue() + 1));
} else {
// its an exit stmt hence reduce level
local2level.put(local, new Integer(local2level.get(local).intValue() - 1));
}
}
// get all successors of the augmented stmt
Iterator sit = as.csuccs.iterator();
// going through sucessors
while (sit.hasNext()) {
AugmentedStmt sas = (AugmentedStmt) sit.next();
if (component.contains(sas) == false) {
continue;
}
// get the local2Level hashmap for the successor
HashMap<Value, Integer> slocal2level = (HashMap<Value, Integer>) as2rml.get(sas);
// get the color for the sucessor
Integer scolor = (Integer) as2color.get(sas);
if (scolor.equals(WHITE)) {
// the augmented stmt hasnt been handled yet
Iterator mlsit = monitorLocalSet.iterator();
while (mlsit.hasNext()) {
// for all locals which are used in monitor stmts
Value local = (Value) mlsit.next();
/*
* update the sucessors hashtable with level values from the seed stmt The loca2Level is the hashmap of
* local-->level for the seed The sLocal2Level is the hashmap of local --> level for the successor of the seed
*/
slocal2level.put(local, local2level.get(local));
}
// do recursive call on the sucessor
DFS_Scc(sas, component, as2rml, as2color, seedStmt, viSeeds);
}
else {
// if the augmented stmt has been visited before
Iterator mlsit = monitorLocalSet.iterator();
while (mlsit.hasNext()) {
Value local = (Value) mlsit.next();
if (slocal2level.get(local).intValue() < local2level.get(local).intValue()) {
// if the sucessors value for the level of a local is
// less than that of the level of the seed
// make the level for this local to be unknown-->
// VARIABLE_INCR
slocal2level.put(local, VARIABLE_INCR);
// add this to the viSeeds list
if (viSeeds.contains(sas) == false) {
viSeeds.add(sas);
}
}
}
}
}
// mark augmented stmt as done
as2color.put(as, BLACK);
}
/*
* Created a synch set for each enter monitor stmt. The synch set contains all sucessors of the monitor enter stmt which is
* dominated by the enter stmt and the level is greater or equal to that of the enter stmt
*/
private Map<AugmentedStmt, IterableSet> build_SynchSets() {
HashMap<AugmentedStmt, IterableSet> as2synchSet = new HashMap<AugmentedStmt, IterableSet>();
Iterator mesit = monitorEnterSet.iterator();
monitorEnterLoop: while (mesit.hasNext()) {
// going through monitor enter stmts
AugmentedStmt headAs = (AugmentedStmt) mesit.next();
Value local = ((EnterMonitorStmt) headAs.get_Stmt()).getOp();
IterableSet synchSet = new IterableSet();
// get the monitor level for the local uses in the enter stmt
int monitorLevel = (as2ml.get(headAs).get(local)).intValue();
IterableSet worklist = new IterableSet();
worklist.add(headAs);
while (worklist.isEmpty() == false) {
AugmentedStmt as = (AugmentedStmt) worklist.getFirst();
worklist.removeFirst();
Stmt s = as.get_Stmt();
if ((s instanceof DefinitionStmt) && (((DefinitionStmt) s).getLeftOp() == local)) {
continue monitorEnterLoop;
}
synchSet.add(as);
Iterator sit = as.csuccs.iterator();
while (sit.hasNext()) {
AugmentedStmt sas = (AugmentedStmt) sit.next();
// get the sucessors monitor level
int sml = (as2ml.get(sas).get(local)).intValue();
/*
* if the sucessor is dominated by the head stmt and the level is greater or equal to that of the head and is not
* waiting to be analysed and is not in the synchSet.. then add it to worklist
*/
if (sas.get_Dominators().contains(headAs) && (sml >= monitorLevel) && (worklist.contains(sas) == false)
&& (synchSet.contains(sas) == false)) {
worklist.addLast(sas);
}
}
}
as2synchSet.put(headAs, synchSet);
}
return as2synchSet;
}
/*
* MonitorLocalSet: contains all locals used in monitor enter statements MonitorEnterSet: contains all monitor enter
* statements as2ml : key is each augmented stmt of the augmented graph, value is a hashmap which contains a local as key
* and the level as value
*/
private void set_MonitorLevels(AugmentedStmtGraph asg) {
monitorLocalSet = new IterableSet();
monitorEnterSet = new IterableSet();
// Identify the locals that are used in monitor statements, and all the
// monitor enters.
Iterator<AugmentedStmt> asgit = asg.iterator();
while (asgit.hasNext()) {
AugmentedStmt as = asgit.next();
Stmt s = as.get_Stmt();
if (s instanceof MonitorStmt) {
Value local = ((MonitorStmt) s).getOp();
// if the monitorLocalSet does not contain this local add it
if (monitorLocalSet.contains(local) == false) {
monitorLocalSet.add(local);
}
// add the monitor enter statement to the monitorEnter Set
if (s instanceof EnterMonitorStmt) {
monitorEnterSet.add(as);
}
}
}
// Set up a base monitor lock level of 0 for all monitor locals.
HashMap local2level_template = new HashMap();
Iterator mlsit = monitorLocalSet.iterator();
while (mlsit.hasNext()) {
// add the local as key and value 0 as value
local2level_template.put(mlsit.next(), new Integer(0));
}
// Give each statement the base monitor lock levels.
asgit = asg.iterator();
while (asgit.hasNext()) {
// the augmented stmt is key and the whole hashMap with all the
// local-->value mapping is the key
as2ml.put(asgit.next(), (Map<Value, Integer>) local2level_template.clone());
}
LinkedList<AugmentedStmt> viAugStmts = new LinkedList<AugmentedStmt>();
HashMap<AugmentedStmt, LinkedList<Value>> incrAs2locals = new HashMap<AugmentedStmt, LinkedList<Value>>();
// setup the variable increasing monitor levels
find_VariableIncreasing(asg, local2level_template, viAugStmts, incrAs2locals);
/*
* At this time the viAugStmts contains all augments Stmt which have some local that has unknown level the incrAs2locals
* contains a map of augmented stmt to a linkedlist which contains locals with unknown level
*/
// going through all augmented stmts with some local with unknown level
Iterator<AugmentedStmt> viasit = viAugStmts.iterator();
while (viasit.hasNext()) {
AugmentedStmt vias = viasit.next();
Map local2level = as2ml.get(vias);
// getting the list of locals with unknown level for this augmented
// stmt
Iterator lit = incrAs2locals.get(vias).iterator();
while (lit.hasNext()) {
// marking the level for this local as unknown
local2level.put(lit.next(), VARIABLE_INCR);
}
}
IterableSet worklist = new IterableSet();
worklist.addAll(monitorEnterSet);
// Flow monitor lock levels.
while (worklist.isEmpty() == false) {
// going through all monitor enter stmts
AugmentedStmt as = (AugmentedStmt) worklist.getFirst();
worklist.removeFirst();
Map<Value, Integer> cur_local2level = as2ml.get(as);
Iterator pit = as.cpreds.iterator();
while (pit.hasNext()) {
// going through preds of an enter monitor stmt
AugmentedStmt pas = (AugmentedStmt) pit.next();
Stmt s = as.get_Stmt();
Map pred_local2level = as2ml.get(pas);
mlsit = monitorLocalSet.iterator();
while (mlsit.hasNext()) {
Value local = (Value) mlsit.next();
int predLevel = ((Integer) pred_local2level.get(local)).intValue();
Stmt ps = pas.get_Stmt();
if (predLevel == UNKNOWN) {
// increasing.
continue;
}
if (ps instanceof ExitMonitorStmt) {
ExitMonitorStmt ems = (ExitMonitorStmt) ps;
/*
* if the predecessor stmt is a monitor exit and the local it exits is the same as this local and the predLevel
* is greater than 0 decrease the pred level
*/
if ((ems.getOp() == local) && (predLevel > 0)) {
predLevel--;
}
}
if (s instanceof EnterMonitorStmt) {
EnterMonitorStmt ems = (EnterMonitorStmt) s;
/*
* if the stmt is a monitor enter (which is true for the initial worklist) and the local it enters is the same as
* this local and the predLevel is greater or equal to 0 increase the pred level
*/
if ((ems.getOp() == local) && (predLevel >= 0)) {
predLevel++;
}
}
int curLevel = cur_local2level.get(local).intValue();
/*
* if the pred level is greater than the current level update current level add the sucessors of the stmt to the
* worklist
*/
if (predLevel > curLevel) {
cur_local2level.put(local, new Integer(predLevel));
Iterator sit = as.csuccs.iterator();
while (sit.hasNext()) {
Object so = sit.next();
if (worklist.contains(so) == false) {
worklist.add(so);
}
}
}
}
}
}
}
/*
* If a stmt is removed from the synchBody then all other stmts which are dominated by this stmt should also be removed
* from the synchBody
*/
private void removeOtherDominatedStmts(IterableSet synchBody, AugmentedStmt sas) {
ArrayList toRemove = new ArrayList();
Iterator it = synchBody.iterator();
while (it.hasNext()) {
AugmentedStmt as = (AugmentedStmt) it.next();
IterableSet doms = as.get_Dominators();
if (doms.contains(sas)) {
// System.out.println("\n\nstmt:"+as+" is dominated by removed stmt"+sas);
toRemove.add(as);
}
}
it = toRemove.iterator();
while (it.hasNext()) {
AugmentedStmt as = (AugmentedStmt) it.next();
// System.out.println("Removed dominated stmt: "+as);
synchBody.remove(as);
}
}
private boolean verify_CatchBody(ExceptionNode en, IterableSet synchBody, Value monitorVariable, Value copiedLocal) {
// System.out.println("starting verification");
{
/*
* synchBody is a likely superset of exception Node since the synchBody contains a goto stmt to the stmt right after
* the "to be created synch block" See if this is the case and remove the stmt
*/
IterableSet tryBodySet = en.get_TryBody();
Iterator tempIt = tryBodySet.iterator();
AugmentedStmt tempas = null;
// to compute last stmt in a tryBody one should find the stmt whose
// sucessor is not in the tryBody
outer: while (tempIt.hasNext()) {
tempas = (AugmentedStmt) tempIt.next();
// get natural sucessors
Iterator succIt = tempas.bsuccs.iterator();
while (succIt.hasNext()) {
AugmentedStmt succAS = (AugmentedStmt) succIt.next();
if (!tryBodySet.contains(succAS)) {
// tempas has a sucessor which is not part of the
// trybody hence this is the last stmt
break outer;
}
}
// System.out.println(tempas);
}
// tempas contains the last augmentedStmt
if (tempas != null) {
// retrieving successors
Iterator sit = tempas.bsuccs.iterator();
while (sit.hasNext()) {
AugmentedStmt sas = (AugmentedStmt) sit.next();
// System.out.println("Removing: successor of last stmt:"+sas.get_Stmt());
// this is the stmt which is the successor of the try block
// which shouldnt be in the synchronized block
// remove the stmt if present in synchBody
synchBody.remove(sas);
// System.out.println("Here, removed: "+sas);
// should remove all other stmts in the synchBody which are
// dominated by this stmt
removeOtherDominatedStmts(synchBody, sas);
}
}
}
/*
* In the abc created code when a synch body occurs within a try block There is an error because the synchBody created
* has addition statements regarding the catching of exception due to the outer try block
*
* Since these statements are not part of the synch body they should be removed
*/
{
Iterator tempIt = en.get_TryBody().iterator();
while (tempIt.hasNext()) {
AugmentedStmt as = (AugmentedStmt) tempIt.next();
if (as.get_Stmt() instanceof ExitMonitorStmt) {
// System.out.println("All possible sucessors of as (CSUCCS):"+as.csuccs);
List csuccs = as.csuccs;
// remove the natural sucessors
csuccs.remove(as.bsuccs);
// now csuccs have the exception sucessors
// System.out.println("Exception sucessors of Exit (CSUCCS:"+csuccs);
Iterator succIt = csuccs.iterator();
while (succIt.hasNext()) {
AugmentedStmt as1 = (AugmentedStmt) succIt.next();
if (as1.get_Stmt() instanceof GotoStmt) {
Unit target = ((soot.jimple.internal.JGotoStmt) as1.get_Stmt()).getTarget();
if (target instanceof DefinitionStmt) {
DefinitionStmt defStmt = (DefinitionStmt) target;
/*
* These are the caught exceptions (can be more than once if there are multiple areas of protection Keep the
* one which is of type Throwable
*/
Value asnFrom = defStmt.getRightOp();
// if not a caught exception of type throwable
// remove from synch
if (!(asnFrom instanceof CaughtExceptionRef)) {
// System.out.println("REMOVING:"+defStmt+" since this is not a caughtexception def");
synchBody.remove(as1);
// should remove all other stmts in the
// synchBody which are dominated by this
// stmt
removeOtherDominatedStmts(synchBody, as1);
} else {
Value leftOp = defStmt.getLeftOp();
// System.out.println("the left op is:"+leftOp);
/*
* Only keep this if it is of throwable type
*/
HashSet params = new HashSet();
params.addAll(davaBody.get_CaughtRefs());
Iterator localIt = davaBody.getLocals().iterator();
String typeName = "";
while (localIt.hasNext()) {
Local local = (Local) localIt.next();
if (local.toString().compareTo(leftOp.toString()) == 0) {
Type t = local.getType();
typeName = t.toString();
break;
}
}
if (!(typeName.compareTo(THROWABLE) == 0)) {
// System.out.println("REMOVING:"+defStmt+
// " since the caughtException not throwable type");
synchBody.remove(as1);
// should remove all other stmts in the
// synchBody which are dominated by this
// stmt
removeOtherDominatedStmts(synchBody, as1);
} else {
// System.out.println("KEEPING"+defStmt);
// System.out.println((RefType)((CaughtExceptionRef)
// asnFrom).getType());
}
}
} else {
// System.out.println("\n\nnot definition"+target);
// System.out.println("Removed"+as1);
synchBody.remove(as1);
// System.out.println(as1.bsuccs.get(0));
synchBody.remove(as1.bsuccs.get(0));
// should remove all other stmts in the
// synchBody which are dominated by this stmt
removeOtherDominatedStmts(synchBody, as1);
}
}
}
}
}
}
/*
* There might be some unwanted stmts in the synch body. These are likely to be stmts which have no predecessor in the
* synchbody. Remove these stmts. NOTE: the entry of the synchbody is a special case since its predecessor is also not
* going to be in the synchbody but we SHOULD not remove the entry point
*/
// find the entry point of synchbody
/*
* One way of doing this is going through the synch body and finiding a stmt whose predecessor is an enter monitor stmt
* NOT present in the synchBody
*/
AugmentedStmt synchEnter = null;
Iterator synchIt = synchBody.iterator();
outerLoop: while (synchIt.hasNext()) {
AugmentedStmt as = (AugmentedStmt) synchIt.next();
Iterator pit = as.cpreds.iterator();
while (pit.hasNext()) {
AugmentedStmt pas = (AugmentedStmt) pit.next();
if (synchBody.contains(pas) == false) {
// the as stmt has a predecessor which is not part of the
// synchBody
Stmt pasStmt = pas.get_Stmt();
if (pasStmt instanceof EnterMonitorStmt) {
// found the entry point to the synchBody
synchEnter = as;
break outerLoop;
}
}
}
}
if (synchEnter == null) {
throw new RuntimeException("Could not find enter stmt of the synchBody: " + davaBody.getMethod().getSignature());
}
// System.out.println("Enter stmt of synchBody is:"+synchEnter);
/*
* Now that we know the exception case we can go through the synchBody and remove all stmts whose predecessor does not
* belong to the synchBody
*/
boolean unChanged = false;
while (!unChanged) {
unChanged = true;
List<AugmentedStmt> toRemove = new ArrayList<AugmentedStmt>();
synchIt = synchBody.iterator();
while (synchIt.hasNext()) {
AugmentedStmt synchAs = (AugmentedStmt) synchIt.next();
if (synchAs == synchEnter) {
// entrypoint is an exception so just continue
continue;
}
Iterator pit = synchAs.cpreds.iterator();
boolean remove = true;
while (pit.hasNext()) {
AugmentedStmt pAs = (AugmentedStmt) pit.next();
if (synchBody.contains(pAs)) {
// one of the preds of this as is in the synchBody so
// dont remove
remove = false;
}
} // going through preds of the synchAs
if (remove) {
// all preds not present in synchBody
toRemove.add(synchAs);
}
} // going through the synchBody
if (toRemove.size() > 0) {
// none of the preds of synchAs are in the synchBody hence this
// stmt is unreachable
synchBody.removeAll(toRemove);
// System.out.println("Removing:"+toRemove+" since none of its preds are in the synchBody");
unChanged = false;
}
}
// see if the two bodies match
if ((en.get_Body().equals(synchBody) == false)) {
// System.out.println("returning unverified since synchBody does not match");
// System.out.println("\n\nEN BODY:\n"+en.get_Body());
// System.out.println("\n\nSYNCH BODY:\n"+synchBody);
return false;
}
/*
* The two bodies match check if the exception thrown is of type "throwable" and that there is only one catchlist The
* reason for doing this is that synchronized blocks get converted to a try catch block with the catch , catching the
* throwable exception and this is the ONLY catch
*/
if ((en.get_Exception().getName().equals(THROWABLE) == false) || (en.get_CatchList().size() > 1)) {
// System.out.println("returning unverified here");
return false;
}
// at this point we know that the two bodies match and that the en
// exception is a throwable exception
/*
* find the entry point of the catch boody The entry point of the catch body is the first stmt in the catchbody This can
* be found by finiding the stmt whose predecessor is not part of the catch body
*/
IterableSet catchBody = en.get_CatchBody();
AugmentedStmt entryPoint = null;
Iterator it = catchBody.iterator();
catchBodyLoop: while (it.hasNext()) {
AugmentedStmt as = (AugmentedStmt) it.next();
Iterator pit = as.cpreds.iterator();
while (pit.hasNext()) {
AugmentedStmt pas = (AugmentedStmt) pit.next();
if (catchBody.contains(pas) == false) {
entryPoint = as;
break catchBodyLoop;
}
}
}
// Horror upon horrors, what follows is a hard coded state machine.
/*
* To verify the catchbody one has to go through the catchbody ONE stmt at a time. This is NOT a good approach as it is
* using PATTERN MATCHING
*
* FIRST STEP Need to verify that the entrypoint stmt and any goto stmts following it all point to the entrypoint
*/
Unit entryPointTarget = null;
if (entryPoint.get_Stmt() instanceof GotoStmt) {
// System.out.println("Entry point is a goto stmt getting the target");
entryPointTarget = ((soot.jimple.internal.JGotoStmt) entryPoint.get_Stmt()).getTarget();
}
AugmentedStmt as = entryPoint;
if (as.bsuccs.size() != 1) {
// System.out.println("here1");
return false;
}
while (as.get_Stmt() instanceof GotoStmt) {
as = (AugmentedStmt) as.bsuccs.get(0);
// if ((as.bsuccs.size() != 1) || ((as != entryPoint) &&
// (as.cpreds.size() != 1))) {
// return false;
// }
if (as.bsuccs.size() != 1) {
// System.out.println("here2a");
return false;
}
if (entryPointTarget != null) {
if ((as.get_Stmt() != entryPointTarget) && (as.cpreds.size() != 1)) {
if (as.cpreds.size() != 1) {
// System.out.println("here2b");
return false;
}
}
} else {
if ((as != entryPoint) && (as.cpreds.size() != 1)) {
// System.out.println("here2c");
return false;
}
}
}
// so now we are not at a goto stmt for sure
// according to the creation pattern of the try catch block we should be
// at the definition stmt
// e.g. <var> := @caughtexception
Stmt s = as.get_Stmt();
if (!(s instanceof DefinitionStmt)) {
// System.out.println("here3");
return false;
}
DefinitionStmt ds = (DefinitionStmt) s;
Value asnFrom = ds.getRightOp();
// if not a caught exception of type throwable we have a problem
if (!((asnFrom instanceof CaughtExceptionRef)
&& (((RefType) ((CaughtExceptionRef) asnFrom).getType()).getSootClass().getName().equals(THROWABLE)))) {
// System.out.println("here4");
return false;
}
Value throwlocal = ds.getLeftOp();
// System.out.println("Throw local is:"+throwlocal);
/*
* The escuccs contains all the EXCEPTION SUCESSORS of the caughtexception stmt
*/
IterableSet esuccs = new IterableSet();
esuccs.addAll(as.csuccs);
esuccs.removeAll(as.bsuccs);
// sucessor of definition stmt
as = (AugmentedStmt) as.bsuccs.get(0);
s = as.get_Stmt();
// this COULD be a copy stmt in which case update the throwlocal
while (s instanceof DefinitionStmt
&& (((DefinitionStmt) s).getRightOp().toString().compareTo(throwlocal.toString()) == 0)) {
// System.out.println("copy stmt using throwLocal found");
// System.out.println("Right op is :"+((DefinitionStmt)s).getRightOp());
// return false;
throwlocal = ((DefinitionStmt) s).getLeftOp();
// the sucessor of this stmt MIGHT be the exitmonitor stmt
as = (AugmentedStmt) as.bsuccs.get(0);
s = as.get_Stmt();
}
if (as.bsuccs.size() != 1) {
// should have one true sucessor
// System.out.println("here5a");
return false;
}
if (as.cpreds.size() != 1) {
// should have one true predecessor
// System.out.println("here5b");
return false;
}
// need to check whether this stmt is protected by the same exception
// block as the whole catchbody
checkProtectionArea(as, ds);
s = as.get_Stmt();
if (!(s instanceof ExitMonitorStmt)) {
// System.out.println("Not an exit monitor stmt"+s);
return false;
}
if ((((ExitMonitorStmt) s).getOp() != monitorVariable)) {
if ((((ExitMonitorStmt) s).getOp() != copiedLocal)) {
// System.out.println("exit monitor variable does not match enter monitor variable");
return false;
}
}
// next stmt should be a throw stmt
as = (AugmentedStmt) as.bsuccs.get(0);
if ((as.bsuccs.size() != 0) || (as.cpreds.size() != 1) || (verify_ESuccs(as, esuccs) == false)) {
// System.out.println("here7");
return false;
}
s = as.get_Stmt();
if (!((s instanceof ThrowStmt) && (((ThrowStmt) s).getOp() == throwlocal))) {
// System.out.println("here8"+s+" Throw local is:"+throwlocal);
return false;
}
return true;
}
/*
* DefinitionStmt s is the start of the area of protection The exception sucessors of as should directly or indirectly
* point to s
*/
private boolean checkProtectionArea(AugmentedStmt as, DefinitionStmt s) {
IterableSet esuccs = new IterableSet();
esuccs.addAll(as.csuccs);
esuccs.removeAll(as.bsuccs);
// esuccs contains the exception sucessors of as
// System.out.println("ESUCCS are:"+esuccs);
Iterator it = esuccs.iterator();
while (it.hasNext()) {
// going through each exception sucessor
AugmentedStmt tempas = (AugmentedStmt) it.next();
Stmt temps = tempas.get_Stmt();
if (temps instanceof GotoStmt) {
Unit target = ((GotoStmt) temps).getTarget();
if (target != s) {
// System.out.println("DID NOT Match indirectly");
return false;
} else {
// System.out.println("Matched indirectly");
}
} else {
if (temps != s) {
// System.out.println("DID NOT Match directly");
return false;
} else {
// System.out.println("Matched directly");
}
}
}
return true;
}
private boolean verify_ESuccs(AugmentedStmt as, IterableSet ref) {
IterableSet esuccs = new IterableSet();
esuccs.addAll(as.csuccs);
esuccs.removeAll(as.bsuccs);
// System.out.println("ESUCCS are:"+esuccs);
// System.out.println("ref are:"+ref);
return esuccs.equals(ref);
}
/*
* Input: head: this is the monitor enter stmt synchSet: this contains all sucessors of head which have level greater or
* equal to the head
*/
private IterableSet get_BodyApproximation(AugmentedStmt head, IterableSet synchSet) {
IterableSet body = (IterableSet) synchSet.clone();
Value local = ((EnterMonitorStmt) head.get_Stmt()).getOp();
Integer level = as2ml.get(head).get(local);
// System.out.println("BODY"+body);
body.remove(head);
Iterator bit = body.snapshotIterator();
while (bit.hasNext()) {
AugmentedStmt as = (AugmentedStmt) bit.next();
Stmt s = as.get_Stmt();
if ((s instanceof ExitMonitorStmt) && (((ExitMonitorStmt) s).getOp() == local)
&& ((as2ml.get(as).get(local)).equals(level))) {
Iterator sit = as.csuccs.iterator();
while (sit.hasNext()) {
AugmentedStmt sas = (AugmentedStmt) sit.next();
// if not dominated by head continue with next stmt in body
if (sas.get_Dominators().contains(head) == false) {
continue;
}
Stmt ss = sas.get_Stmt();
if (((ss instanceof GotoStmt) || (ss instanceof ThrowStmt)) && (body.contains(sas) == false)) {
// if (ss instanceof ThrowStmt && (body.contains( sas)
// == false)){
// System.out.println("adding"+sas);
body.add(sas);
}
}
}
}
return body;
}
}
| 42,231
| 35.75544
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/misc/ConditionFlipper.java
|
package soot.dava.toolkits.base.misc;
/*-
* #%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.grimp.internal.GEqExpr;
import soot.grimp.internal.GGeExpr;
import soot.grimp.internal.GGtExpr;
import soot.grimp.internal.GLeExpr;
import soot.grimp.internal.GLtExpr;
import soot.grimp.internal.GNeExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.EqExpr;
import soot.jimple.GeExpr;
import soot.jimple.GtExpr;
import soot.jimple.LeExpr;
import soot.jimple.LtExpr;
import soot.jimple.NeExpr;
public class ConditionFlipper {
public static ConditionExpr flip(ConditionExpr ce) {
if (ce instanceof EqExpr) {
return new GNeExpr(ce.getOp1(), ce.getOp2());
}
if (ce instanceof NeExpr) {
return new GEqExpr(ce.getOp1(), ce.getOp2());
}
if (ce instanceof GtExpr) {
return new GLeExpr(ce.getOp1(), ce.getOp2());
}
if (ce instanceof LtExpr) {
return new GGeExpr(ce.getOp1(), ce.getOp2());
}
if (ce instanceof GeExpr) {
return new GLtExpr(ce.getOp1(), ce.getOp2());
}
if (ce instanceof LeExpr) {
return new GGtExpr(ce.getOp1(), ce.getOp2());
}
return null;
}
}
| 1,913
| 27.147059
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/misc/MonitorConverter.java
|
package soot.dava.toolkits.base.misc;
/*-
* #%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.HashSet;
import java.util.LinkedList;
import soot.G;
import soot.Modifier;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.VoidType;
import soot.dava.DavaBody;
import soot.dava.internal.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DStaticInvokeExpr;
import soot.dava.internal.javaRep.DVirtualInvokeExpr;
import soot.grimp.internal.GInvokeStmt;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.MonitorStmt;
public class MonitorConverter {
public MonitorConverter(Singletons.Global g) {
SootClass davaMonitor = new SootClass("soot.dava.toolkits.base.DavaMonitor.DavaMonitor", Modifier.PUBLIC);
davaMonitor.setSuperclass(Scene.v().loadClassAndSupport("java.lang.Object"));
LinkedList objectSingleton = new LinkedList();
objectSingleton.add(RefType.v("java.lang.Object"));
v = Scene.v().makeSootMethod("v", new LinkedList(), RefType.v("soot.dava.toolkits.base.DavaMonitor.DavaMonitor"),
Modifier.PUBLIC | Modifier.STATIC);
enter = Scene.v().makeSootMethod("enter", objectSingleton, VoidType.v(), Modifier.PUBLIC | Modifier.SYNCHRONIZED);
exit = Scene.v().makeSootMethod("exit", objectSingleton, VoidType.v(), Modifier.PUBLIC | Modifier.SYNCHRONIZED);
davaMonitor.addMethod(v);
davaMonitor.addMethod(enter);
davaMonitor.addMethod(exit);
Scene.v().addClass(davaMonitor);
}
public static MonitorConverter v() {
return G.v().soot_dava_toolkits_base_misc_MonitorConverter();
}
private final SootMethod v, enter, exit;
public void convert(DavaBody body) {
for (AugmentedStmt mas : body.get_MonitorFacts()) {
MonitorStmt ms = (MonitorStmt) mas.get_Stmt();
body.addToImportList("soot.dava.toolkits.base.DavaMonitor.DavaMonitor");
ArrayList arg = new ArrayList();
arg.add(ms.getOp());
if (ms instanceof EnterMonitorStmt) {
mas.set_Stmt(new GInvokeStmt(new DVirtualInvokeExpr(new DStaticInvokeExpr(v.makeRef(), new ArrayList()),
enter.makeRef(), arg, new HashSet<Object>())));
} else {
mas.set_Stmt(new GInvokeStmt(new DVirtualInvokeExpr(new DStaticInvokeExpr(v.makeRef(), new ArrayList()),
exit.makeRef(), arg, new HashSet<Object>())));
}
}
}
}
| 3,181
| 35.159091
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/misc/PackageNamer.java
|
package soot.dava.toolkits.base.misc;
/*-
* #%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.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.jar.JarFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.G;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.dava.Dava;
import soot.util.IterableSet;
public class PackageNamer {
private static final Logger logger = LoggerFactory.getLogger(PackageNamer.class);
public PackageNamer(Singletons.Global g) {
}
public static PackageNamer v() {
return G.v().soot_dava_toolkits_base_misc_PackageNamer();
}
public boolean has_FixedNames() {
return fixed;
}
public boolean use_ShortName(String fixedPackageName, String fixedShortClassName) {
if (fixed == false) {
return false;
}
if (fixedPackageName.equals(Dava.v().get_CurrentPackage())) {
return true;
}
IterableSet packageContext = Dava.v().get_CurrentPackageContext();
if (packageContext == null) {
return true;
}
packageContext = patch_PackageContext(packageContext);
int count = 0;
StringTokenizer st = new StringTokenizer(classPath, pathSep);
while (st.hasMoreTokens()) {
String classpathDir = st.nextToken();
Iterator packIt = packageContext.iterator();
while (packIt.hasNext()) {
if (package_ContainsClass(classpathDir, (String) packIt.next(), fixedShortClassName)) {
if (++count > 1) {
return false;
}
}
}
}
return true;
}
public String get_FixedClassName(String originalFullClassName) {
if (fixed == false) {
return originalFullClassName;
}
Iterator<NameHolder> it = appRoots.iterator();
while (it.hasNext()) {
NameHolder h = it.next();
if (h.contains_OriginalName(new StringTokenizer(originalFullClassName, "."), true)) {
return h.get_FixedName(new StringTokenizer(originalFullClassName, "."), true);
}
}
return originalFullClassName.substring(originalFullClassName.lastIndexOf(".") + 1);
}
public String get_FixedPackageName(String originalPackageName) {
if (fixed == false) {
return originalPackageName;
}
if (originalPackageName.equals("")) {
return "";
}
Iterator<NameHolder> it = appRoots.iterator();
while (it.hasNext()) {
NameHolder h = it.next();
if (h.contains_OriginalName(new StringTokenizer(originalPackageName, "."), false)) {
return h.get_FixedName(new StringTokenizer(originalPackageName, "."), false);
}
}
return originalPackageName;
}
private class NameHolder {
private final String originalName;
private String packageName, className;
private final ArrayList<NameHolder> children;
private NameHolder parent;
private boolean isClass;
public NameHolder(String name, NameHolder parent, boolean isClass) {
originalName = name;
className = name;
packageName = name;
this.parent = parent;
this.isClass = isClass;
children = new ArrayList<NameHolder>();
}
public NameHolder get_Parent() {
return parent;
}
public void set_ClassAttr() {
isClass = true;
}
public boolean is_Class() {
if (children.isEmpty()) {
return true;
} else {
return isClass;
}
}
public boolean is_Package() {
return (children.isEmpty() == false);
}
public String get_PackageName() {
return packageName;
}
public String get_ClassName() {
return className;
}
public void set_PackageName(String packageName) {
this.packageName = packageName;
}
public void set_ClassName(String className) {
this.className = className;
}
public String get_OriginalName() {
return originalName;
}
public ArrayList<NameHolder> get_Children() {
return children;
}
public String get_FixedPackageName() {
if (parent == null) {
return "";
}
return parent.retrieve_FixedPackageName();
}
public String retrieve_FixedPackageName() {
if (parent == null) {
return packageName;
}
return parent.get_FixedPackageName() + "." + packageName;
}
public String get_FixedName(StringTokenizer st, boolean forClass) {
if (st.nextToken().equals(originalName) == false) {
throw new RuntimeException("Unable to resolve naming.");
}
return retrieve_FixedName(st, forClass);
}
private String retrieve_FixedName(StringTokenizer st, boolean forClass) {
if (st.hasMoreTokens() == false) {
if (forClass) {
return className;
} else {
return packageName;
}
}
String subName = st.nextToken();
Iterator<NameHolder> cit = children.iterator();
while (cit.hasNext()) {
NameHolder h = cit.next();
if (h.get_OriginalName().equals(subName)) {
if (forClass) {
return h.retrieve_FixedName(st, forClass);
} else {
return packageName + "." + h.retrieve_FixedName(st, forClass);
}
}
}
throw new RuntimeException("Unable to resolve naming.");
}
public String get_OriginalPackageName(StringTokenizer st) {
if (st.hasMoreTokens() == false) {
return get_OriginalName();
}
String subName = st.nextToken();
Iterator<NameHolder> cit = children.iterator();
while (cit.hasNext()) {
NameHolder h = cit.next();
if (h.get_PackageName().equals(subName)) {
String originalSubPackageName = h.get_OriginalPackageName(st);
if (originalSubPackageName == null) {
return null;
} else {
return get_OriginalName() + "." + originalSubPackageName;
}
}
}
return null;
}
public boolean contains_OriginalName(StringTokenizer st, boolean forClass) {
if (get_OriginalName().equals(st.nextToken()) == false) {
return false;
}
return finds_OriginalName(st, forClass);
}
private boolean finds_OriginalName(StringTokenizer st, boolean forClass) {
if (st.hasMoreTokens() == false) {
return (((forClass) && (is_Class())) || ((!forClass) && (is_Package())));
}
String subName = st.nextToken();
Iterator<NameHolder> cit = children.iterator();
while (cit.hasNext()) {
NameHolder h = cit.next();
if (h.get_OriginalName().equals(subName)) {
return h.finds_OriginalName(st, forClass);
}
}
return false;
}
public void fix_ClassNames(String curPackName) {
if ((is_Class()) && (keywords.contains(className))) {
String tClassName = className;
if (Character.isLowerCase(className.charAt(0))) {
tClassName = tClassName.substring(0, 1).toUpperCase() + tClassName.substring(1);
className = tClassName;
}
for (int i = 0; keywords.contains(className); i++) {
className = tClassName + "_c" + i;
}
}
Iterator<NameHolder> it = children.iterator();
while (it.hasNext()) {
it.next().fix_ClassNames(curPackName + "." + packageName);
}
}
public void fix_PackageNames() {
if ((is_Package()) && (verify_PackageName() == false)) {
String tPackageName = packageName;
if (Character.isUpperCase(packageName.charAt(0))) {
tPackageName = tPackageName.substring(0, 1).toLowerCase() + tPackageName.substring(1);
packageName = tPackageName;
}
for (int i = 0; verify_PackageName() == false; i++) {
packageName = tPackageName + "_p" + i;
}
}
Iterator<NameHolder> it = children.iterator();
while (it.hasNext()) {
it.next().fix_PackageNames();
}
}
public boolean verify_PackageName() {
return ((keywords.contains(packageName) == false) && (siblingClashes(packageName) == false)
&& ((is_Class() == false) || (className.equals(packageName) == false)));
}
public boolean siblingClashes(String name) {
Iterator<NameHolder> it = null;
if (parent == null) {
if (appRoots.contains(this)) {
it = appRoots.iterator();
} else {
throw new RuntimeException("Unable to find package siblings.");
}
} else {
it = parent.get_Children().iterator();
}
while (it.hasNext()) {
NameHolder sibling = it.next();
if (sibling == this) {
continue;
}
if (((sibling.is_Package()) && (sibling.get_PackageName().equals(name)))
|| ((sibling.is_Class()) && (sibling.get_ClassName().equals(name)))) {
return true;
}
}
return false;
}
public void dump(String indentation) {
logger.debug("" + indentation + "\"" + originalName + "\", \"" + packageName + "\", \"" + className + "\" (");
if (is_Class()) {
logger.debug("c");
}
if (is_Package()) {
logger.debug("p");
}
logger.debug("" + ")");
Iterator<NameHolder> it = children.iterator();
while (it.hasNext()) {
it.next().dump(indentation + " ");
}
}
}
private boolean fixed = false;
private final ArrayList<NameHolder> appRoots = new ArrayList<NameHolder>();
private final ArrayList<NameHolder> otherRoots = new ArrayList<NameHolder>();
private final HashSet<String> keywords = new HashSet<String>();
private char fileSep;
private String classPath, pathSep;
public void fixNames() {
if (fixed) {
return;
}
String[] keywordArray = { "abstract", "default", "if", "private", "this", "boolean", "do", "implements", "protected",
"throw", "break", "double", "import", "public", "throws", "byte", "else", "instanceof", "return", "transient",
"case", "extends", "int", "short", "try", "catch", "final", "interface", "static", "void", "char", "finally", "long",
"strictfp", "volatile", "class", "float", "native", "super", "while", "const", "for", "new", "switch", "continue",
"goto", "package", "synchronized", "true", "false", "null" };
for (String element : keywordArray) {
keywords.add(element);
}
Iterator classIt = Scene.v().getLibraryClasses().iterator();
while (classIt.hasNext()) {
add_ClassName(((SootClass) classIt.next()).getName(), otherRoots);
}
classIt = Scene.v().getApplicationClasses().iterator();
while (classIt.hasNext()) {
add_ClassName(((SootClass) classIt.next()).getName(), appRoots);
}
Iterator<NameHolder> arit = appRoots.iterator();
while (arit.hasNext()) {
arit.next().fix_ClassNames("");
}
arit = appRoots.iterator();
while (arit.hasNext()) {
arit.next().fix_PackageNames();
}
fileSep = System.getProperty("file.separator").charAt(0);
pathSep = System.getProperty("path.separator");
classPath = System.getProperty("java.class.path");
fixed = true;
}
private void add_ClassName(String className, ArrayList<NameHolder> roots) {
ArrayList<NameHolder> children = roots;
NameHolder curNode = null;
StringTokenizer st = new StringTokenizer(className, ".");
while (st.hasMoreTokens()) {
String curName = st.nextToken();
NameHolder child = null;
boolean found = false;
Iterator<NameHolder> lit = children.iterator();
while (lit.hasNext()) {
child = lit.next();
if (child.get_OriginalName().equals(curName)) {
if (st.hasMoreTokens() == false) {
child.set_ClassAttr();
}
found = true;
break;
}
}
if (!found) {
child = new NameHolder(curName, curNode, st.hasMoreTokens() == false);
children.add(child);
}
curNode = child;
children = child.get_Children();
}
}
public boolean package_ContainsClass(String classpathDir, String packageName, String className) {
File p = new File(classpathDir);
if (p.exists() == false) {
return false;
}
packageName = packageName.replace('.', fileSep);
if ((packageName.length() > 0) && (packageName.charAt(packageName.length() - 1) != fileSep)) {
packageName += fileSep;
}
String name = packageName + className + ".class";
if (p.isDirectory()) {
if ((classpathDir.length() > 0) && (classpathDir.charAt(classpathDir.length() - 1) != fileSep)) {
classpathDir += fileSep;
}
return (new File(classpathDir + name)).exists();
}
else {
JarFile jf = null;
try {
jf = new JarFile(p);
} catch (IOException ioe) {
return false;
}
return (jf.getJarEntry(name) != null);
}
}
IterableSet patch_PackageContext(IterableSet currentContext) {
IterableSet newContext = new IterableSet();
Iterator it = currentContext.iterator();
while (it.hasNext()) {
String currentPackage = (String) it.next(), newPackage = null;
StringTokenizer st = new StringTokenizer(currentPackage, ".");
if (st.hasMoreTokens() == false) {
newContext.add(currentPackage);
continue;
}
String firstToken = st.nextToken();
Iterator<NameHolder> arit = appRoots.iterator();
while (arit.hasNext()) {
NameHolder h = arit.next();
if (h.get_PackageName().equals(firstToken)) {
newPackage = h.get_OriginalPackageName(st);
break;
}
}
if (newPackage != null) {
newContext.add(newPackage);
} else {
newContext.add(currentPackage);
}
}
return newContext;
}
}
| 14,677
| 26.435514
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/misc/ThrowFinder.java
|
package soot.dava.toolkits.base.misc;
/*-
* #%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.HashSet;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.PatchingChain;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.Trap;
import soot.Type;
import soot.Unit;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.internal.JExitMonitorStmt;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.CallGraphBuilder;
import soot.jimple.toolkits.callgraph.Edge;
import soot.util.Chain;
import soot.util.IterableSet;
/*
* Nomair A. Naeem 7th April 2006
* This class detects and propagates whether the signature of a method should have some throws Exception constructs.
*
* The reason we need to do this is since the JVM does not force all compilers to store throws information
* as attributes (javac does it ) but other compilers are not forced to do it
*
* Hence if we are coming from javac we dont need to perform this analysis since we already have the information
* if we are not coming from javac then we need to perform this analysis to say
* what the checked exceptions are for this method.
*
* Alls good until u try to decompile code like this
* try{
* synchronized(bla){
* bla
* bla
* }
* }catch(InterruptedException e){
* bla
* }
*
* If you create bytecode for this you will notice that because exitmointer has to be invoked if an exception occurs
* this is done by catching a Throwable(all possible exceptions) exiting the monitor and rethrowing the exception.
*
* Now that is alright the problem occurs because InterruptedExceptions will be caught but since we are throwing the
* general Throwable exception this algorithm says that the method should state in its signature that it throws
* java.lang,Throwable.
* CHANGE LOG: current fix is to hack into the algo find the place where we are about to add the java.lang.Throwable
* and if it is near an exit monitor we know dava is going to convert this to a synch and hence not add this exception!!
*
*
*/
public class ThrowFinder {
private static final Logger logger = LoggerFactory.getLogger(ThrowFinder.class);
public ThrowFinder(Singletons.Global g) {
}
public static ThrowFinder v() {
return G.v().soot_dava_toolkits_base_misc_ThrowFinder();
}
private HashSet<SootMethod> registeredMethods;
private HashMap<Stmt, HashSet<SootClass>> protectionSet;
public static boolean DEBUG = false;
public void find() {
logger.debug("" + "Verifying exception handling.. ");
registeredMethods = new HashSet<SootMethod>();
protectionSet = new HashMap<Stmt, HashSet<SootClass>>();
CallGraph cg;
if (Scene.v().hasCallGraph()) {
cg = Scene.v().getCallGraph();
} else {
new CallGraphBuilder().build();
cg = Scene.v().getCallGraph();
Scene.v().releaseCallGraph();
}
IterableSet worklist = new IterableSet();
logger.debug("\b. ");
// Get all the methods, and find protection for every statement.
Iterator<SootClass> classIt = Scene.v().getApplicationClasses().iterator();
while (classIt.hasNext()) {
Iterator<SootMethod> methodIt = classIt.next().methodIterator();
while (methodIt.hasNext()) {
SootMethod m = (SootMethod) methodIt.next();
register_AreasOfProtection(m);
worklist.add(m);
}
}
// Build the subClass and superClass mappings.
HashMap<SootClass, IterableSet> subClassSet = new HashMap<SootClass, IterableSet>(),
superClassSet = new HashMap<SootClass, IterableSet>();
HashSet<SootClass> applicationClasses = new HashSet<SootClass>();
applicationClasses.addAll(Scene.v().getApplicationClasses());
classIt = Scene.v().getApplicationClasses().iterator();
while (classIt.hasNext()) {
SootClass c = (SootClass) classIt.next();
IterableSet superClasses = superClassSet.get(c);
if (superClasses == null) {
superClasses = new IterableSet();
superClassSet.put(c, superClasses);
}
IterableSet subClasses = subClassSet.get(c);
if (subClasses == null) {
subClasses = new IterableSet();
subClassSet.put(c, subClasses);
}
if (c.hasSuperclass()) {
SootClass superClass = c.getSuperclass();
IterableSet superClassSubClasses = subClassSet.get(superClass);
if (superClassSubClasses == null) {
superClassSubClasses = new IterableSet();
subClassSet.put(superClass, superClassSubClasses);
}
superClassSubClasses.add(c);
superClasses.add(superClass);
}
Iterator interfaceIt = c.getInterfaces().iterator();
while (interfaceIt.hasNext()) {
SootClass interfaceClass = (SootClass) interfaceIt.next();
IterableSet interfaceClassSubClasses = subClassSet.get(interfaceClass);
if (interfaceClassSubClasses == null) {
interfaceClassSubClasses = new IterableSet();
subClassSet.put(interfaceClass, interfaceClassSubClasses);
}
interfaceClassSubClasses.add(c);
superClasses.add(interfaceClass);
}
}
// Build the subMethod and superMethod mappings.
HashMap<SootMethod, IterableSet> agreementMethodSet = new HashMap<SootMethod, IterableSet>();
// Get exceptions from throw statements and add them to the exceptions that the method throws.
Iterator worklistIt = worklist.iterator();
while (worklistIt.hasNext()) {
SootMethod m = (SootMethod) worklistIt.next();
if (!m.isAbstract() && !m.isNative()) {
List<SootClass> exceptionList = m.getExceptions();
IterableSet exceptionSet = new IterableSet(exceptionList);
boolean changed = false;
Iterator it = m.retrieveActiveBody().getUnits().iterator();
while (it.hasNext()) {
Unit u = (Unit) it.next();
HashSet handled = protectionSet.get(u);
if (u instanceof ThrowStmt) {
Type t = ((ThrowStmt) u).getOp().getType();
if (t instanceof RefType) {
SootClass c = ((RefType) t).getSootClass();
if ((handled_Exception(handled, c) == false) && (exceptionSet.contains(c) == false)) {
/*
* Nomair A Naeem 7th April HACK TRYING TO MATCH PATTERN label0: r3 = r0; entermonitor r0; label1: r1.up();
* r0.wait(); exitmonitor r3; label2: goto label6; label3: $r5 := @caughtexception; label4: r4 = $r5;
* exitmonitor r3; label5: throw r4; HERE IS THE THROW WE JUST DETECTED LOOK and see if the previous unit is
* an exitmonitor label6: goto label8; label7: $r6 := @caughtexception; r7 = $r6; label8: r1.down(); return;
* catch java.lang.Throwable from label1 to label2 with label3; catch java.lang.Throwable from label4 to
* label5 with label3; catch java.lang.InterruptedException from label0 to label6 with label7;
*
*/
PatchingChain list = m.retrieveActiveBody().getUnits();
Unit pred = (Unit) list.getPredOf(u);
if (!(pred instanceof JExitMonitorStmt)) {
exceptionSet.add(c);
changed = true;
if (DEBUG) {
System.out.println("Added exception which is explicitly thrown" + c.getName());
}
} else {
if (DEBUG) {
System.out.println("Found monitor exit" + pred + " hence not adding");
}
}
}
}
}
}
it = cg.edgesOutOf(m);
while (it.hasNext()) {
Edge e = (Edge) it.next();
Stmt callSite = e.srcStmt();
if (callSite == null) {
continue;
}
HashSet handled = protectionSet.get(callSite);
SootMethod target = e.tgt();
Iterator<SootClass> exceptionIt = target.getExceptions().iterator();
while (exceptionIt.hasNext()) {
SootClass exception = exceptionIt.next();
if ((handled_Exception(handled, exception) == false) && (exceptionSet.contains(exception) == false)) {
exceptionSet.add(exception);
changed = true;
}
}
}
if (changed) {
exceptionList.clear();
exceptionList.addAll(exceptionSet);
}
}
// While we're at it, put the superMethods and the subMethods in the agreementMethodSet.
find_OtherMethods(m, agreementMethodSet, subClassSet, applicationClasses);
find_OtherMethods(m, agreementMethodSet, superClassSet, applicationClasses);
}
// Perform worklist algorithm to propegate the throws information.
while (worklist.isEmpty() == false) {
SootMethod m = (SootMethod) worklist.getFirst();
worklist.removeFirst();
IterableSet agreementMethods = agreementMethodSet.get(m);
if (agreementMethods != null) {
Iterator amit = agreementMethods.iterator();
while (amit.hasNext()) {
SootMethod otherMethod = (SootMethod) amit.next();
List<SootClass> otherExceptionsList = otherMethod.getExceptions();
IterableSet otherExceptionSet = new IterableSet(otherExceptionsList);
boolean changed = false;
Iterator<SootClass> exceptionIt = m.getExceptions().iterator();
while (exceptionIt.hasNext()) {
SootClass exception = exceptionIt.next();
if (otherExceptionSet.contains(exception) == false) {
otherExceptionSet.add(exception);
changed = true;
}
}
if (changed) {
otherExceptionsList.clear();
otherExceptionsList.addAll(otherExceptionSet);
if (worklist.contains(otherMethod) == false) {
worklist.addLast(otherMethod);
}
}
}
}
Iterator it = cg.edgesOutOf(m);
while (it.hasNext()) {
Edge e = (Edge) it.next();
Stmt callingSite = e.srcStmt();
if (callingSite == null) {
continue;
}
SootMethod callingMethod = e.src();
List<SootClass> exceptionList = callingMethod.getExceptions();
IterableSet exceptionSet = new IterableSet(exceptionList);
HashSet handled = protectionSet.get(callingSite);
boolean changed = false;
Iterator<SootClass> exceptionIt = m.getExceptions().iterator();
while (exceptionIt.hasNext()) {
SootClass exception = exceptionIt.next();
if ((handled_Exception(handled, exception) == false) && (exceptionSet.contains(exception) == false)) {
exceptionSet.add(exception);
changed = true;
}
}
if (changed) {
exceptionList.clear();
exceptionList.addAll(exceptionSet);
if (worklist.contains(callingMethod) == false) {
worklist.addLast(callingMethod);
}
}
}
}
}
private void find_OtherMethods(SootMethod startingMethod, HashMap<SootMethod, IterableSet> methodMapping,
HashMap<SootClass, IterableSet> classMapping, HashSet<SootClass> applicationClasses) {
IterableSet worklist = (IterableSet) classMapping.get(startingMethod.getDeclaringClass()).clone();
HashSet<SootClass> touchSet = new HashSet<SootClass>();
touchSet.addAll(worklist);
String signature = startingMethod.getSubSignature();
while (worklist.isEmpty() == false) {
SootClass currentClass = (SootClass) worklist.getFirst();
worklist.removeFirst();
if (applicationClasses.contains(currentClass) == false) {
continue;
}
if (currentClass.declaresMethod(signature)) {
IterableSet otherMethods = methodMapping.get(startingMethod);
if (otherMethods == null) {
otherMethods = new IterableSet();
methodMapping.put(startingMethod, otherMethods);
}
otherMethods.add(currentClass.getMethod(signature));
}
else {
IterableSet otherClasses = classMapping.get(currentClass);
if (otherClasses != null) {
Iterator ocit = otherClasses.iterator();
while (ocit.hasNext()) {
SootClass otherClass = (SootClass) ocit.next();
if (touchSet.contains(otherClass) == false) {
worklist.addLast(otherClass);
touchSet.add(otherClass);
}
}
}
}
}
}
private void register_AreasOfProtection(SootMethod m) {
if (registeredMethods.contains(m)) {
return;
}
registeredMethods.add(m);
if (m.hasActiveBody() == false) {
return;
}
Body b = m.getActiveBody();
Chain stmts = b.getUnits();
Iterator trapIt = b.getTraps().iterator();
while (trapIt.hasNext()) {
Trap t = (Trap) trapIt.next();
SootClass exception = t.getException();
Iterator sit = stmts.iterator(t.getBeginUnit(), stmts.getPredOf(t.getEndUnit()));
while (sit.hasNext()) {
Stmt s = (Stmt) sit.next();
HashSet<SootClass> handled = null;
if ((handled = protectionSet.get(s)) == null) {
handled = new HashSet<SootClass>();
protectionSet.put(s, handled);
}
if (handled.contains(exception) == false) {
handled.add(exception);
}
}
}
}
private boolean handled_Exception(HashSet handledExceptions, SootClass c) {
SootClass thrownException = c;
if (is_HandledByRuntime(thrownException)) {
return true;
}
if (handledExceptions == null) {
return false;
}
while (true) {
if (handledExceptions.contains(thrownException)) {
return true;
}
if (thrownException.hasSuperclass() == false) {
return false;
}
thrownException = thrownException.getSuperclass();
}
}
private boolean is_HandledByRuntime(SootClass c) {
SootClass thrownException = c, runtimeException = Scene.v().getSootClass("java.lang.RuntimeException"),
error = Scene.v().getSootClass("java.lang.Error");
while (true) {
if ((thrownException == runtimeException) || (thrownException == error)) {
return true;
}
if (thrownException.hasSuperclass() == false) {
return false;
}
thrownException = thrownException.getSuperclass();
}
}
}
| 15,512
| 32.650759
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/misc/ThrowNullConverter.java
|
package soot.dava.toolkits.base.misc;
/*-
* #%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 soot.G;
import soot.NullType;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.dava.DavaBody;
import soot.dava.internal.javaRep.DNewInvokeExpr;
import soot.jimple.ThrowStmt;
public class ThrowNullConverter {
public ThrowNullConverter(Singletons.Global g) {
}
public static ThrowNullConverter v() {
return G.v().soot_dava_toolkits_base_misc_ThrowNullConverter();
}
private final RefType npeRef = RefType.v(Scene.v().loadClassAndSupport("java.lang.NullPointerException"));
public void convert(DavaBody body) {
Iterator it = body.getUnits().iterator();
while (it.hasNext()) {
Unit u = (Unit) it.next();
if (u instanceof ThrowStmt) {
ValueBox opBox = ((ThrowStmt) u).getOpBox();
Value op = opBox.getValue();
if (op.getType() instanceof NullType) {
opBox.setValue(new DNewInvokeExpr(npeRef, null, new ArrayList()));
}
}
}
}
}
| 1,910
| 27.954545
| 108
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/renamer/RemoveFullyQualifiedName.java
|
package soot.dava.toolkits.base.renamer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import soot.ArrayType;
import soot.Type;
import soot.util.IterableSet;
public class RemoveFullyQualifiedName {
public static boolean containsMultiple(Iterator it, String qualifiedName, Type t) {
/*
* The fully qualified name might contain [] in the end if the type is an ArrayType
*/
if (t != null) {
if (t instanceof ArrayType) {
if (qualifiedName.indexOf('[') >= 0) {
qualifiedName = qualifiedName.substring(0, qualifiedName.indexOf('['));
}
}
}
// get last name
String className = getClassName(qualifiedName);
int count = 0;
while (it.hasNext()) {
String tempName = getClassName((String) it.next());
if (tempName.equals(className)) {
count++;
}
}
if (count > 1) {
return true;
}
return false;
}
/*
* Method finds the last . and returns the className after that if no dot is found (shouldnt happen) then the name is
* simply returned back
*/
public static String getClassName(String qualifiedName) {
if (qualifiedName.lastIndexOf('.') > -1) {
return qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1);
}
return qualifiedName;
}
public static String getReducedName(IterableSet importList, String qualifiedName, Type t) {
// if two explicit imports dont import the same class we can remove explicit qualification
if (!containsMultiple(importList.iterator(), qualifiedName, t)) {
return getClassName(qualifiedName);
}
return qualifiedName;
}
}
| 2,434
| 29.061728
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/renamer/Renamer.java
|
package soot.dava.toolkits.base.renamer;
/*-
* #%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 java.util.List;
import soot.ArrayType;
import soot.Local;
import soot.RefLikeType;
import soot.SootClass;
import soot.SootField;
import soot.Type;
import soot.dava.internal.AST.ASTMethodNode;
import soot.util.Chain;
public class Renamer {
public final boolean DEBUG = false;
heuristicSet heuristics;
List locals; // a list of locals in scope
Chain fields; // a list of fields in scope
ASTMethodNode methodNode;
List<String> forLoopNames;
HashMap<Local, Boolean> changedOrNot;// keeps track of which local was changed previously
public Renamer(heuristicSet info, ASTMethodNode node) {
heuristics = info;
locals = null;
methodNode = node;
changedOrNot = new HashMap<Local, Boolean>();
Iterator<Local> localIt = info.getLocalsIterator();
while (localIt.hasNext()) {
changedOrNot.put(localIt.next(), new Boolean(false));
}
forLoopNames = new ArrayList<String>();
forLoopNames.add("i");
forLoopNames.add("j");
forLoopNames.add("k");
forLoopNames.add("l");
}
/*
* Add any naming heuristic as a separate method and invoke the method from this method.
*
* HOWEVER, NOTE that the order of naming really really matters
*/
public void rename() {
debug("rename", "Renaming started");
// String args
mainMethodArgument();
// for(i=0;i<bla;i++)
forLoopIndexing();
// exceptions are named using first letter of each capital char in the class name
exceptionNaming();
// arrays get <type>Array
arraysGetTypeArray();
// if a local is assigned a field that name can be used since fields are conserved
assignedFromAField();
// check if a local is assigned the result of a new invocation
newClassName();
// check if a local is assigned after casting
castedObject();
// if nothing else give a reference the name of the class
objectsGetClassName();
// atleast remove the ugly dollar signs
removeDollarSigns();
}
/*
* if there is an array int[] x. then if no other heuristic matches give it the name intArray
*/
private void arraysGetTypeArray() {
Iterator<Local> it = heuristics.getLocalsIterator();
while (it.hasNext()) {
Local tempLocal = it.next();
if (alreadyChanged(tempLocal)) {
continue;
}
debug("arraysGetTypeArray", "checking " + tempLocal);
Type type = tempLocal.getType();
if (type instanceof ArrayType) {
debug("arraysGetTypeArray", "Local:" + tempLocal + " is an Array Type: " + type.toString());
String tempClassName = type.toString();
// remember that a toString of an array gives you the square brackets
if (tempClassName.indexOf('[') >= 0) {
tempClassName = tempClassName.substring(0, tempClassName.indexOf('['));
}
// debug("arraysGetTypeArray","type of object is"+tempClassName);
if (tempClassName.indexOf('.') != -1) {
// contains a dot have to remove that
tempClassName = tempClassName.substring(tempClassName.lastIndexOf('.') + 1);
}
String newName = tempClassName.toLowerCase();
newName = newName + "Array";
int count = 0;
newName += count;
count++;
while (!isUniqueName(newName)) {
newName = newName.substring(0, newName.length() - 1) + count;
count++;
}
setName(tempLocal, newName);
}
}
}
/*
* The method assigns any local whose name hasnt been changed yet to the name of the class type it belongs to
*/
private void objectsGetClassName() {
Iterator<Local> it = heuristics.getLocalsIterator();
while (it.hasNext()) {
Local tempLocal = it.next();
if (alreadyChanged(tempLocal)) {
continue;
}
debug("objectsGetClassName", "checking " + tempLocal);
Type type = tempLocal.getType();
if (type instanceof ArrayType) {
// should have been handled by arraysGetTypeArray heuristic
continue;
}
if (type instanceof RefLikeType) {
debug("objectsGetClassName", "Local:" + tempLocal + " Type: " + type.toString());
// debug("objectsGetClassName","getting array type"+type.getArrayType());
String tempClassName = type.toString();
// debug("objectsGetClassName","type of object is"+tempClassName);
if (tempClassName.indexOf('.') != -1) {
// contains a dot have to remove that
tempClassName = tempClassName.substring(tempClassName.lastIndexOf('.') + 1);
}
String newName = tempClassName.toLowerCase();
int count = 0;
newName += count;
count++;
while (!isUniqueName(newName)) {
newName = newName.substring(0, newName.length() - 1) + count;
count++;
}
setName(tempLocal, newName);
}
}
}
/*
* If a local is assigned the resullt of a cast expression temp = (List) object; then u can use list as the name...however
* only if its always casted to the same object
*/
private void castedObject() {
debug("castedObject", "");
Iterator<Local> it = heuristics.getLocalsIterator();
while (it.hasNext()) {
Local tempLocal = it.next();
if (!alreadyChanged(tempLocal)) {
debug("castedObject", "checking " + tempLocal);
List<String> classes = heuristics.getCastStrings(tempLocal);
Iterator<String> itClass = classes.iterator();
String classNameToUse = null;
while (itClass.hasNext()) {
String tempClassName = itClass.next();
if (tempClassName.indexOf('.') != -1) {
// contains a dot have to remove that
tempClassName = tempClassName.substring(tempClassName.lastIndexOf('.') + 1);
}
if (classNameToUse == null) {
classNameToUse = tempClassName;
} else if (!classNameToUse.equals(tempClassName)) {
// different new assignment
// cant use these classNames
classNameToUse = null;
break;
}
} // going through class names stored
if (classNameToUse != null) {
debug("castedObject", "found a classNametoUse through cast expr");
/*
* We should use this classNAme to assign to the local name We are guaranteed that all cast expressions use this
* type
*/
String newName = classNameToUse.toLowerCase();
int count = 0;
newName += count;
count++;
while (!isUniqueName(newName)) {
newName = newName.substring(0, newName.length() - 1) + count;
count++;
}
setName(tempLocal, newName);
}
} // not already changed
} // going through locals
}
/*
* See if any local was initialized using the new operator That name might give us a hint to a name to use for the local
*/
private void newClassName() {
debug("newClassName", "");
// check if CLASSNAME is set
// that would mean there was new className invocation
Iterator<Local> it = heuristics.getLocalsIterator();
while (it.hasNext()) {
Local tempLocal = it.next();
if (!alreadyChanged(tempLocal)) {
debug("newClassName", "checking " + tempLocal);
List<String> classes = heuristics.getObjectClassName(tempLocal);
Iterator<String> itClass = classes.iterator();
String classNameToUse = null;
while (itClass.hasNext()) {
String tempClassName = itClass.next();
if (tempClassName.indexOf('.') != -1) {
// contains a dot have to remove that
tempClassName = tempClassName.substring(tempClassName.lastIndexOf('.') + 1);
}
if (classNameToUse == null) {
classNameToUse = tempClassName;
} else if (!classNameToUse.equals(tempClassName)) {
// different new assignment
// cant use these classNames
classNameToUse = null;
break;
}
} // going through class names stored
if (classNameToUse != null) {
debug("newClassName", "found a classNametoUse");
/*
* We should use this classNAme to assign to the local name We are guaranteed that all new invocations use this
* class name
*/
String newName = classNameToUse.toLowerCase();
int count = 0;
newName += count;
count++;
while (!isUniqueName(newName)) {
newName = newName.substring(0, newName.length() - 1) + count;
count++;
}
setName(tempLocal, newName);
}
} // not already changed
} // going through locals
}
/*
* If a local is assigned from a field (static or non staitc) we can use that name to assign a some what better name for
* the local
*
* If multiple fields are assigned then it might be a better idea to not do anything since that will only confuse the user
*
*/
private void assignedFromAField() {
Iterator<Local> it = heuristics.getLocalsIterator();
while (it.hasNext()) {
Local tempLocal = it.next();
if (!alreadyChanged(tempLocal)) {
debug("assignedFromField", "checking " + tempLocal);
List<String> fieldNames = heuristics.getFieldName(tempLocal);
if (fieldNames.size() > 1) {
// more than one fields were assigned to this var
continue;
} else if (fieldNames.size() == 1) {
// only one field was used
String fieldName = fieldNames.get(0);
// okkay to use the name of the field if its not in scope
// eg it was some other classes field
int count = 0;
while (!isUniqueName(fieldName)) {
if (count == 0) {
fieldName = fieldName + count;
} else {
fieldName = fieldName.substring(0, fieldName.length() - 1) + count;
}
count++;
}
setName(tempLocal, fieldName);
} // only one field assigned to this local
} // not changed
} // going through locals
}
/*
* If we cant come up with any better name atleast we should remove the $ signs
*/
private void removeDollarSigns() {
Iterator<Local> it = heuristics.getLocalsIterator();
while (it.hasNext()) {
Local tempLocal = it.next();
String currentName = tempLocal.getName();
int dollarIndex = currentName.indexOf('$');
if (dollarIndex == 0) {
// meaning there is a $ sign in the first location
String newName = currentName.substring(1, currentName.length());
if (isUniqueName(newName)) {
setName(tempLocal, newName);
// System.out.println("Changed "+currentName+" to "+newName);
// tempLocal.setName(newName);
}
}
}
}
/*
*
*/
private void exceptionNaming() {
Iterator<Local> it = heuristics.getLocalsIterator();
while (it.hasNext()) {
Local tempLocal = it.next();
Type localType = tempLocal.getType();
String typeString = localType.toString();
if (typeString.indexOf("Exception") >= 0) {
// the string xception occurs in this type
debug("exceptionNaming", "Type is an exception" + tempLocal);
// make a new name of all caps characters in typeString
String newName = "";
for (int i = 0; i < typeString.length(); i++) {
char character = typeString.charAt(i);
if (Character.isUpperCase(character)) {
newName += Character.toLowerCase(character);
}
}
int count = 0;
if (!isUniqueName(newName)) {
count++;
while (!isUniqueName(newName + count)) {
count++;
}
}
if (count != 0) {
newName = newName + count;
}
setName(tempLocal, newName);
}
}
}
/*
* Probably one of the most common programming idioms for loop indexes are often i j k l
*/
private void forLoopIndexing() {
Iterator<Local> it = heuristics.getLocalsIterator();
while (it.hasNext()) {
Local tempLocal = it.next();
debug("foeLoopIndexing", "Checking local" + tempLocal.getName());
if (heuristics.getHeuristic(tempLocal, infoGatheringAnalysis.FORLOOPUPDATE)) {
// this local variable is the main argument
// will like to set it to args if no one has an objection
int count = -1;
String newName;
do {
count++;
if (count >= forLoopNames.size()) {
newName = null;
break;
}
newName = (String) forLoopNames.get(count);
} while (!isUniqueName(newName));
if (newName != null) {
setName(tempLocal, newName);
}
}
}
}
/*
* A simple heuristic which sets the mainMethodArgument's name to args
*/
private void mainMethodArgument() {
Iterator<Local> it = heuristics.getLocalsIterator();
while (it.hasNext()) {
Local tempLocal = it.next();
if (heuristics.getHeuristic(tempLocal, infoGatheringAnalysis.MAINARG)) {
// this local variable is the main argument
// will like to set it to args if no one has an objection
String newName = "args";
int count = 0;
while (!isUniqueName(newName)) {
if (count == 0) {
newName = newName + count;
} else {
newName = newName.substring(0, newName.length() - 1) + count;
}
count++;
}
setName(tempLocal, newName);
// there cant be a same local with this heuristic set so just return
return;
}
}
}
/*
* In order to make sure that some previous heuristic which is usually a STRONGER heuristic has not already changed the
* name we use this method which checks for past name changes and only changes the name if the name hasnt been changed
* previously
*/
private void setName(Local var, String newName) {
Object truthValue = changedOrNot.get(var);
// if it wasnt in there add it
if (truthValue == null) {
changedOrNot.put(var, new Boolean(false));
} else {
if (((Boolean) truthValue).booleanValue()) {
// already changed just return
debug("setName", "Var: " + var + " had already been renamed");
return;
}
}
// will only get here if the var had not been changed
debug("setName", "Changed " + var.getName() + " to " + newName);
var.setName(newName);
changedOrNot.put(var, new Boolean(true));
}
/*
* Check if a local has already been changed
*
* @param local to check
*
* @return true if already changed otherwise false
*/
private boolean alreadyChanged(Local var) {
Object truthValue = changedOrNot.get(var);
// if it wasnt in there add it
if (truthValue == null) {
changedOrNot.put(var, new Boolean(false));
return false;
} else {
if (((Boolean) truthValue).booleanValue()) {
// already changed just return
debug("alreadyChanged", "Var: " + var + " had already been renamed");
return true;
} else {
return false;
}
}
}
/*
* Should return true if the name is unique
*/
private boolean isUniqueName(String name) {
Iterator it = getScopedLocals();
// check that none of the locals uses this name
while (it.hasNext()) {
Local tempLocal = (Local) it.next();
if (tempLocal.getName().equals(name)) {
debug("isUniqueName", "New Name " + name + " is not unique (matches some local)..changing");
return false;
} else {
debug("isUniqueName", "New Name " + name + " is different from local " + tempLocal.getName());
}
}
it = getScopedFields();
// check that none of the fields uses this name
while (it.hasNext()) {
SootField tempField = (SootField) it.next();
if (tempField.getName().equals(name)) {
debug("isUniqueName", "New Name " + name + " is not unique (matches field)..changing");
return false;
} else {
debug("isUniqueName", "New Name " + name + " is different from field " + tempField.getName());
}
}
return true;
}
/*
* Method is responsible to find all names with which there could be a potential clash The variables are: all the fields of
* this class and all the locals defined in this method
*/
private Iterator getScopedFields() {
// get the fields for this class and store them
SootClass sootClass = methodNode.getDavaBody().getMethod().getDeclaringClass();
fields = sootClass.getFields();
return fields.iterator();
}
/*
* Method is responsible to find all variable names with which there could be a potential clash The variables are: all the
* fields of this class and all the locals defined in this method
*/
private Iterator getScopedLocals() {
Iterator<Local> it = heuristics.getLocalsIterator();
locals = new ArrayList();
while (it.hasNext()) {
locals.add(it.next());
}
return locals.iterator();
}
public void debug(String methodName, String debug) {
if (DEBUG) {
System.out.println(methodName + " DEBUG: " + debug);
}
}
}
| 18,297
| 30.712305
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/renamer/heuristicSet.java
|
package soot.dava.toolkits.base.renamer;
/*-
* #%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.HashMap;
import java.util.Iterator;
import java.util.List;
import soot.Local;
public class heuristicSet {
HashMap<Local, heuristicTuple> set;
public heuristicSet() {
set = new HashMap<Local, heuristicTuple>();
}
private heuristicTuple getTuple(Local var) {
return set.get(var);
}
public void add(Local var, int bits) {
heuristicTuple temp = new heuristicTuple(bits);
set.put(var, temp);
}
public void addCastString(Local var, String castString) {
heuristicTuple retrieved = getTuple(var);
retrieved.addCastString(castString);
}
public List<String> getCastStrings(Local var) {
heuristicTuple retrieved = getTuple(var);
return retrieved.getCastStrings();
}
public void setFieldName(Local var, String fieldName) {
heuristicTuple retrieved = getTuple(var);
retrieved.setFieldName(fieldName);
}
public List<String> getFieldName(Local var) {
heuristicTuple retrieved = getTuple(var);
return retrieved.getFieldName();
}
public void setObjectClassName(Local var, String objectClassName) {
heuristicTuple retrieved = getTuple(var);
retrieved.setObjectClassName(objectClassName);
}
public List<String> getObjectClassName(Local var) {
heuristicTuple retrieved = getTuple(var);
return retrieved.getObjectClassName();
}
public void setMethodName(Local var, String methodName) {
heuristicTuple retrieved = getTuple(var);
retrieved.setMethodName(methodName);
}
public List<String> getMethodName(Local var) {
heuristicTuple retrieved = getTuple(var);
return retrieved.getMethodName();
}
public void setHeuristic(Local var, int bitIndex) {
heuristicTuple retrieved = getTuple(var);
retrieved.setHeuristic(bitIndex);
}
public boolean getHeuristic(Local var, int bitIndex) {
heuristicTuple retrieved = getTuple(var);
return retrieved.getHeuristic(bitIndex);
}
public boolean isAnyHeuristicSet(Local var) {
heuristicTuple retrieved = getTuple(var);
return retrieved.isAnyHeuristicSet();
}
public void print() {
Iterator<Local> it = set.keySet().iterator();
while (it.hasNext()) {
Object local = it.next();
heuristicTuple temp = set.get(local);
String tuple = temp.getPrint();
System.out.println(local + " " + tuple + " DefinedType: " + ((Local) local).getType());
}
}
public Iterator<Local> getLocalsIterator() {
return set.keySet().iterator();
}
public boolean contains(Local var) {
if (set.get(var) != null) {
return true;
} else {
return false;
}
}
}
| 3,450
| 27.056911
| 94
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/renamer/heuristicTuple.java
|
package soot.dava.toolkits.base.renamer;
/*-
* #%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.BitSet;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
public class heuristicTuple {
BitSet heuristics;
int bitSetSize;
Vector<String> methodName; // local is assigned the result of this method call
Vector<String> objectClassName; // local is initialized with a new invocation of this class
Vector<String> fieldName; // local is initialized with a field
Vector<String> castStrings; // local is casted to a type
public heuristicTuple(int bits) {
heuristics = new BitSet(bits);
this.methodName = new Vector<String>();
this.objectClassName = new Vector<String>();
this.fieldName = new Vector<String>();
this.castStrings = new Vector<String>();
bitSetSize = bits;
}
public void addCastString(String castString) {
this.castStrings.add(castString);
setHeuristic(infoGatheringAnalysis.CAST);
}
public List<String> getCastStrings() {
return castStrings;
}
public void setFieldName(String fieldName) {
this.fieldName.add(fieldName);
setHeuristic(infoGatheringAnalysis.FIELDASSIGN);
}
public List<String> getFieldName() {
return fieldName;
}
public void setObjectClassName(String objectClassName) {
this.objectClassName.add(objectClassName);
setHeuristic(infoGatheringAnalysis.CLASSNAME);
}
public List<String> getObjectClassName() {
return objectClassName;
}
public void setMethodName(String methodName) {
this.methodName.add(methodName);
setHeuristic(infoGatheringAnalysis.METHODNAME);
if (methodName.startsWith("get") || methodName.startsWith("set")) {
setHeuristic(infoGatheringAnalysis.GETSET);
}
}
public List<String> getMethodName() {
return methodName;
}
public void setHeuristic(int bitIndex) {
heuristics.set(bitIndex);
}
public boolean getHeuristic(int bitIndex) {
return heuristics.get(bitIndex);
}
public boolean isAnyHeuristicSet() {
return !heuristics.isEmpty();
}
public String getPrint() {
String temp = "BitSet: ";
for (int i = 0; i < bitSetSize; i++) {
if (getHeuristic(i)) {
temp = temp.concat("1");
} else {
temp = temp.concat("0");
}
}
temp = temp.concat(" Field: " + fieldName.toString());
temp = temp.concat(" Method: ");
Iterator<String> it = getMethodName().iterator();
while (it.hasNext()) {
temp = temp.concat(it.next() + " , ");
}
temp = temp.concat(" Class: " + objectClassName.toString());
// System.out.println("TUPLE:"+temp);
return temp;
}
}
| 3,420
| 27.040984
| 93
|
java
|
soot
|
soot-master/src/main/java/soot/dava/toolkits/base/renamer/infoGatheringAnalysis.java
|
package soot.dava.toolkits.base.renamer;
/*-
* #%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.HashSet;
import java.util.Iterator;
import java.util.List;
import soot.BooleanType;
import soot.Local;
import soot.RefType;
import soot.SootField;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Type;
import soot.Value;
import soot.dava.DavaBody;
import soot.dava.DecompilationException;
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.ASTMethodNode;
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.asg.AugmentedStmt;
import soot.dava.internal.javaRep.DIntConstant;
import soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter;
import soot.grimp.NewInvokeExpr;
import soot.grimp.internal.GAssignStmt;
import soot.jimple.ArrayRef;
import soot.jimple.CastExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.EqExpr;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.NeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.internal.AbstractInstanceFieldRef;
//import soot.util.*;
public class infoGatheringAnalysis extends DepthFirstAdapter {
public boolean DEBUG = false;
public final static int CLASSNAME = 0; // used by renamer
public final static int METHODNAME = 1;
public final static int GETSET = 2;
public final static int IF = 3;
public final static int WHILE = 4;
public final static int SWITCH = 5;
public final static int ARRAYINDEX = 6;
public final static int MAINARG = 7; // used by renamer
public final static int FIELDASSIGN = 8; // used by renamer
public final static int FORLOOPUPDATE = 9; // used by renamer
public final static int CAST = 10;
public final static int NUMBITS = 11;
// dataset to store all information gathered
heuristicSet info;
// if we are within a subtree rooted at a definitionStmt this boolean is true
boolean inDefinitionStmt = false;
// whenever there is a definition to a local definedLocal will contain a ref to the local
Local definedLocal = null;
// if we are within a subtree rooted at a ifNode or IfElseNode this boolean is true
boolean inIf = false;
// if we are within a subtree rooted at a WhileNode or DoWhileNode this boolean is true
boolean inWhile = false;
// if we are within a subtree rooted at a ForLoop this boolean is true
boolean inFor = false;
public infoGatheringAnalysis(DavaBody davaBody) {
info = new heuristicSet();
List localList = new ArrayList();
/*
* Get locals info out of davaBody Copied with modifications from DavaPrinter method printLocalsInBody
*/
HashSet params = new HashSet();
// params.addAll(davaBody.get_ParamMap().values());
// params.addAll(davaBody.get_CaughtRefs());
HashSet<Object> thisLocals = davaBody.get_ThisLocals();
// System.out.println("params"+params);
Iterator localIt = davaBody.getLocals().iterator();
while (localIt.hasNext()) {
Local local = (Local) localIt.next();
if (params.contains(local) || thisLocals.contains(local)) {
continue;
}
localList.add(local);
}
// localList is a list with all locals
// initialize the info Set with empty info for each local
Iterator it = localList.iterator();
while (it.hasNext()) {
Local local = (Local) it.next();
info.add(local, NUMBITS);
debug("infoGatheringAnalysis", "added " + local.getName() + " to the heuristicset");
}
/*
* Check if we are dealing with a main method In which case set the MAINARG heuristic of the param
*/
// System.out.println("METHOD:"+davaBody.getMethod());
SootMethod method = davaBody.getMethod();
// System.out.println(method.getSubSignature());
if (method.getSubSignature().compareTo("void main(java.lang.String[])") == 0) {
// means we are currently working on the main method
it = davaBody.get_ParamMap().values().iterator();
int num = 0;
Local param = null;
while (it.hasNext()) {
num++;
param = (Local) it.next();
}
if (num > 1) {
throw new DecompilationException("main method has greater than 1 args!!");
} else {
info.setHeuristic(param, infoGatheringAnalysis.MAINARG);
}
}
}
/*
* This can be either an assignment or an identity statement. We are however only concerned with stmts which assign values
* to locals
*
* The method sets the inDefinitionStmt flag to true and if this is a local assignment The ref to the local is stored in
* definedLocal
*/
public void inDefinitionStmt(DefinitionStmt s) {
inDefinitionStmt = true;
// System.out.println(s);
Value v = s.getLeftOp();
if (v instanceof Local) {
// System.out.println("This is a local:"+v);
/*
* We want definedLocal to be set only if we are interested in naming it Variables that are created by Dava itself e.g.
* handler (refer to SuperFirstStmtHandler) Need not be renamed. So we check whether definedLocal is present in the
* info set if it is we set this other wise we dont
*/
if (info.contains((Local) v)) {
definedLocal = (Local) v;
} else {
definedLocal = null;
}
} else {
// System.out.println("Not a local"+v);
}
}
public void outDefinitionStmt(DefinitionStmt s) {
// checking casting here because we want to see if the expr
// on the right of def stmt is a cast expr not whether it contains a cast expr
if (definedLocal != null && s.getRightOp() instanceof CastExpr) {
Type castType = ((CastExpr) s.getRightOp()).getCastType();
info.addCastString(definedLocal, castType.toString());
}
inDefinitionStmt = false;
definedLocal = null;
}
/*
* Deals with cases in which a local is assigned a value from a static field int local = field int local = class.field
*/
public void inStaticFieldRef(StaticFieldRef sfr) {
if (inDefinitionStmt && (definedLocal != null)) {
SootField field = sfr.getField();
info.setFieldName(definedLocal, field.getName());
}
}
/*
* Deals with cases in which a local is assigned a value from a field int local = field or int local = obj.field
*/
public void inInstanceFieldRef(InstanceFieldRef ifr) {
if (ifr instanceof AbstractInstanceFieldRef) {
if (inDefinitionStmt && (definedLocal != null)) {
SootField field = ((AbstractInstanceFieldRef) ifr).getField();
// System.out.println(definedLocal+" is being assigned field:"+field.getName());
info.setFieldName(definedLocal, field.getName());
}
}
}
/*
* (non-Javadoc)
*
* @see soot.dava.toolkits.base.AST.analysis.DepthFirstAdapter#outInvokeExpr(soot.jimple.InvokeExpr) If it is a newInvoke
* expr we know that the name of the class can come in handy while renaming because this could be a subtype
*/
public void outInvokeExpr(InvokeExpr ie) {
// If this is within a definitionStmt of a local
if (inDefinitionStmt && (definedLocal != null)) {
// if its a new object being created
if (ie instanceof NewInvokeExpr) {
// System.out.println("new object being created retrieve the name");
RefType ref = ((NewInvokeExpr) ie).getBaseType();
String className = ref.getClassName();
debug("outInvokeExpr", "defined local is" + definedLocal);
info.setObjectClassName(definedLocal, className);
} else {
SootMethodRef methodRef = ie.getMethodRef();
String name = methodRef.name();
// System.out.println(name);
info.setMethodName(definedLocal, name);
}
}
}
/*
* This is the object for a flag use in a conditional If the value is a local set the appropriate heuristic
*/
public void inASTUnaryCondition(ASTUnaryCondition uc) {
Value val = uc.getValue();
if (val instanceof Local) {
if (inIf) {
info.setHeuristic((Local) val, infoGatheringAnalysis.IF);
}
if (inWhile) {
info.setHeuristic((Local) val, infoGatheringAnalysis.WHILE);
}
}
}
public void inASTBinaryCondition(ASTBinaryCondition bc) {
ConditionExpr condition = bc.getConditionExpr();
Local local = checkBooleanUse(condition);
if (local != null) {
if (inIf) {
info.setHeuristic(local, infoGatheringAnalysis.IF);
}
if (inWhile) {
info.setHeuristic(local, infoGatheringAnalysis.WHILE);
}
}
}
/*
* Setting if to true in inASTIfNode so that later we know whether this is a flag use in an if
*/
public void inASTIfNode(ASTIfNode node) {
inIf = true;
}
/*
* Going out of if set flag to false
*/
public void outASTIfNode(ASTIfNode node) {
inIf = false;
}
/*
* Setting if to true in inASTIfElseNode so that later we know whether this is a flag use in an ifElse
*/
public void inASTIfElseNode(ASTIfElseNode node) {
inIf = true;
}
/*
* Going out of ifElse set flag to false
*/
public void outASTIfElseNode(ASTIfElseNode node) {
inIf = false;
}
/*
* Setting if to true in inASTWhileNode so that later we know whether this is a flag use in a WhileNode
*/
public void inASTWhileNode(ASTWhileNode node) {
inWhile = true;
}
/*
* setting flag to false
*/
public void outASTWhileNode(ASTWhileNode node) {
inWhile = false;
}
/*
* Setting if to true in inASTDoWhileNode so that later we know whether this is a flag use in a WhileNode
*/
public void inASTDoWhileNode(ASTDoWhileNode node) {
inWhile = true;
}
/*
* setting flag to false
*/
public void outASTDoWhileNode(ASTDoWhileNode node) {
inWhile = false;
}
/*
* Check the key of the switch statement to see if its a local
*/
public void inASTSwitchNode(ASTSwitchNode node) {
Value key = node.get_Key();
if (key instanceof Local) {
info.setHeuristic((Local) key, infoGatheringAnalysis.SWITCH);
}
}
public void inArrayRef(ArrayRef ar) {
Value index = ar.getIndex();
if (index instanceof Local) {
info.setHeuristic((Local) index, infoGatheringAnalysis.ARRAYINDEX);
}
}
public void inASTTryNode(ASTTryNode node) {
}
/*
* setting flag to true
*/
public void inASTForLoopNode(ASTForLoopNode node) {
inFor = true;
for (AugmentedStmt as : node.getUpdate()) {
Stmt s = as.get_Stmt();
if (s instanceof GAssignStmt) {
Value leftOp = ((GAssignStmt) s).getLeftOp();
if (leftOp instanceof Local) {
info.setHeuristic((Local) leftOp, infoGatheringAnalysis.FORLOOPUPDATE);
}
}
}
}
/*
* setting flag to false
*/
public void outASTForLoopNode(ASTForLoopNode node) {
inFor = false;
}
/*
* If there are any locals at this point who do not have any className set it might be a good idea to store that
* information
*/
public void outASTMethodNode(ASTMethodNode node) {
if (DEBUG) {
System.out.println("SET START");
info.print();
System.out.println("SET END");
}
}
/*
* The method checks whether a particular ConditionExpr is a comparison of a local with a boolean If so the local is
* returned
*/
private Local checkBooleanUse(ConditionExpr condition) {
boolean booleanUse = false;
// 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) {
booleanUse = true;
}
} else if (op2 instanceof DIntConstant) {
Type op2Type = ((DIntConstant) op2).type;
if (op2Type instanceof BooleanType) {
booleanUse = true;
}
}
if (booleanUse) {
// at this point we know that one of the values op1 or op2 was a boolean
// check whether the other is a local
if (op1 instanceof Local) {
return (Local) op1;
} else if (op2 instanceof Local) {
return (Local) op2;
}
} else {
return null;// meaning no local used as boolean found
}
}
return null; // meaning no local used as boolean found
}
public heuristicSet getHeuristicSet() {
return info;
}
public void debug(String methodName, String debug) {
if (DEBUG) {
System.out.println(methodName + " DEBUG: " + debug);
}
}
}
| 13,769
| 29.464602
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/AbstractNullTransformer.java
|
package soot.dexpler;
/*-
* #%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.RefLikeType;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.ConditionExpr;
import soot.jimple.EqExpr;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.NeExpr;
import soot.jimple.NullConstant;
/**
* Abstract base class for {@link DexNullTransformer} and {@link DexIfTransformer}.
*
* @author Steven Arzt
*/
public abstract class AbstractNullTransformer extends DexTransformer {
/**
* Examine expr if it is a comparison with 0.
*
* @param expr
* the ConditionExpr to examine
*/
protected boolean isZeroComparison(ConditionExpr expr) {
if (expr instanceof EqExpr || expr instanceof NeExpr) {
if (expr.getOp2() instanceof IntConstant && ((IntConstant) expr.getOp2()).value == 0) {
return true;
}
if (expr.getOp2() instanceof LongConstant && ((LongConstant) expr.getOp2()).value == 0) {
return true;
}
}
return false;
}
/**
* Replace 0 with null in the given unit.
*
* @param u
* the unit where 0 will be replaced with null.
*/
protected void replaceWithNull(Unit u) {
if (u instanceof IfStmt) {
ConditionExpr expr = (ConditionExpr) ((IfStmt) u).getCondition();
if (isZeroComparison(expr)) {
expr.setOp2(NullConstant.v());
}
} else if (u instanceof AssignStmt) {
AssignStmt s = (AssignStmt) u;
Value v = s.getRightOp();
if ((v instanceof IntConstant && ((IntConstant) v).value == 0)
|| (v instanceof LongConstant && ((LongConstant) v).value == 0)) {
// If this is a field assignment, double-check the type. We
// might have a.f = 2 with a being a null candidate, but a.f
// being an int.
if (!(s.getLeftOp() instanceof InstanceFieldRef)
|| ((InstanceFieldRef) s.getLeftOp()).getFieldRef().type() instanceof RefLikeType) {
s.setRightOp(NullConstant.v());
}
}
}
}
protected static boolean isObject(Type t) {
return t instanceof RefLikeType;
}
}
| 3,011
| 30.051546
| 96
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DalvikThrowAnalysis.java
|
//
// (c) 2012 University of Luxembourg - Interdisciplinary Centre for
// Security Reliability and Trust (SnT) - All rights reserved
//
// Author: Alexandre Bartel
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package soot.dexpler;
import soot.FastHierarchy;
/*-
* #%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.G;
import soot.NullType;
import soot.PrimType;
import soot.RefLikeType;
import soot.Scene;
import soot.Singletons;
import soot.SootMethod;
import soot.Type;
import soot.UnknownType;
import soot.baf.EnterMonitorInst;
import soot.baf.ReturnInst;
import soot.baf.ReturnVoidInst;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.ClassConstant;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.StringConstant;
import soot.toolkits.exceptions.ThrowableSet;
import soot.toolkits.exceptions.UnitThrowAnalysis;
/**
*
* @author alex
*
*
* According to
* https://android.googlesource.com/platform/dalvik/+/2988c4f272f62af2e96f1e6161d4e99bc1dc1b16/opcode-gen/bytecode.txt
* the following Dalvik bytecode instructions might throw an exception:
*
* op 1a const-string 21c y string-ref continue|throw op 1b const-string/jumbo 31c y string-ref continue|throw op 1c
* const-class 21c y type-ref continue|throw op 1d monitor-enter 11x n none continue|throw op 1e monitor-exit 11x n
* none continue|throw op 1f check-cast 21c y type-ref continue|throw op 20 instance-of 22c y type-ref continue|throw
* op 21 array-length 12x y none continue|throw op 22 new-instance 21c y type-ref continue|throw op 23 new-array 22c
* y type-ref continue|throw op 24 filled-new-array 35c n type-ref continue|throw op 25 filled-new-array/range 3rc n
* type-ref continue|throw
*
* op 27 throw 11x n none throw
*
* op 44 aget 23x y none continue|throw op 45 aget-wide 23x y none continue|throw op 46 aget-object 23x y none
* continue|throw op 47 aget-boolean 23x y none continue|throw op 48 aget-byte 23x y none continue|throw op 49
* aget-char 23x y none continue|throw op 4a aget-short 23x y none continue|throw op 4b aput 23x n none
* continue|throw op 4c aput-wide 23x n none continue|throw op 4d aput-object 23x n none continue|throw op 4e
* aput-boolean 23x n none continue|throw op 4f aput-byte 23x n none continue|throw op 50 aput-char 23x n none
* continue|throw op 51 aput-short 23x n none continue|throw op 52 iget 22c y field-ref continue|throw op 53
* iget-wide 22c y field-ref continue|throw op 54 iget-object 22c y field-ref continue|throw op 55 iget-boolean 22c y
* field-ref continue|throw op 56 iget-byte 22c y field-ref continue|throw op 57 iget-char 22c y field-ref
* continue|throw op 58 iget-short 22c y field-ref continue|throw op 59 iput 22c n field-ref continue|throw op 5a
* iput-wide 22c n field-ref continue|throw op 5b iput-object 22c n field-ref continue|throw op 5c iput-boolean 22c n
* field-ref continue|throw op 5d iput-byte 22c n field-ref continue|throw op 5e iput-char 22c n field-ref
* continue|throw op 5f iput-short 22c n field-ref continue|throw op 60 sget 21c y field-ref continue|throw op 61
* sget-wide 21c y field-ref continue|throw op 62 sget-object 21c y field-ref continue|throw op 63 sget-boolean 21c y
* field-ref continue|throw op 64 sget-byte 21c y field-ref continue|throw op 65 sget-char 21c y field-ref
* continue|throw op 66 sget-short 21c y field-ref continue|throw op 67 sput 21c n field-ref continue|throw op 68
* sput-wide 21c n field-ref continue|throw op 69 sput-object 21c n field-ref continue|throw op 6a sput-boolean 21c n
* field-ref continue|throw op 6b sput-byte 21c n field-ref continue|throw op 6c sput-char 21c n field-ref
* continue|throw op 6d sput-short 21c n field-ref continue|throw op 6e invoke-virtual 35c n method-ref
* continue|throw|invoke op 6f invoke-super 35c n method-ref continue|throw|invoke op 70 invoke-direct 35c n
* method-ref continue|throw|invoke op 71 invoke-static 35c n method-ref continue|throw|invoke op 72 invoke-interface
* 35c n method-ref continue|throw|invoke # unused: op 73 op 74 invoke-virtual/range 3rc n method-ref
* continue|throw|invoke op 75 invoke-super/range 3rc n method-ref continue|throw|invoke op 76 invoke-direct/range
* 3rc n method-ref continue|throw|invoke op 77 invoke-static/range 3rc n method-ref continue|throw|invoke op 78
* invoke-interface/range 3rc n method-ref continue|throw|invoke
*
* op 93 div-int 23x y none continue|throw op 94 rem-int 23x y none continue|throw
*
* op 9e div-long 23x y none continue|throw op 9f rem-long 23x y none continue|throw
*
* op b3 div-int/2addr 12x y none continue|throw op b4 rem-int/2addr 12x y none continue|throw
*
* op be div-long/2addr 12x y none continue|throw op bf rem-long/2addr 12x y none continue|throw
*
* op d3 div-int/lit16 22s y none continue|throw op d4 rem-int/lit16 22s y none continue|throw
*
* op db div-int/lit8 22b y none continue|throw op dc rem-int/lit8 22b y none continue|throw
*
* op e3 +iget-volatile 22c y field-ref optimized|continue|throw op e4 +iput-volatile 22c n field-ref
* optimized|continue|throw op e5 +sget-volatile 21c y field-ref optimized|continue|throw op e6 +sput-volatile 21c n
* field-ref optimized|continue|throw op e7 +iget-object-volatile 22c y field-ref optimized|continue|throw op e8
* +iget-wide-volatile 22c y field-ref optimized|continue|throw op e9 +iput-wide-volatile 22c n field-ref
* optimized|continue|throw op ea +sget-wide-volatile 21c y field-ref optimized|continue|throw op eb
* +sput-wide-volatile 21c n field-ref optimized|continue|throw
*
* op ed ^throw-verification-error 20bc n varies optimized|throw op ee +execute-inline 35mi n inline-method
* optimized|continue|throw op ef +execute-inline/range 3rmi n inline-method optimized|continue|throw
*
* op f0 +invoke-object-init/range 35c n method-ref optimized|continue|throw|invoke
*
* op f2 +iget-quick 22cs y field-offset optimized|continue|throw op f3 +iget-wide-quick 22cs y field-offset
* optimized|continue|throw op f4 +iget-object-quick 22cs y field-offset optimized|continue|throw op f5 +iput-quick
* 22cs n field-offset optimized|continue|throw op f6 +iput-wide-quick 22cs n field-offset optimized|continue|throw
* op f7 +iput-object-quick 22cs n field-offset optimized|continue|throw op f8 +invoke-virtual-quick 35ms n
* vtable-offset optimized|continue|throw|invoke op f9 +invoke-virtual-quick/range 3rms n vtable-offset
* optimized|continue|throw|invoke op fa +invoke-super-quick 35ms n vtable-offset optimized|continue|throw|invoke op
* fb +invoke-super-quick/range 3rms n vtable-offset optimized|continue|throw|invoke op fc +iput-object-volatile 22c
* n field-ref optimized|continue|throw op fd +sget-object-volatile 21c y field-ref optimized|continue|throw op fe
* +sput-object-volatile 21c n field-ref optimized|continue|throw
*
* In brief: - const [string|class] - monitor [enter|exit] already handled in UnitThrowAnalysis - check cast already
* handled in UnitThrowAnalysis - instanceof already handled in UnitThrowAnalysis - array length already handled in
* UnitThrowAnalysis - new [instance|array] already handled in UnitThrowAnalysis - filled new array - throw already
* handled in UnitThrowAnalysis - invoke* already handled in UnitThrowAnalysis - [ais][get|put] already handled in
* UnitThrowAnalysis - div/rem already handled in UnitThrowAnalysis
*
* For a reference manual, look at https://code.google.com/p/android-source-browsing
*
*
*/
public class DalvikThrowAnalysis extends UnitThrowAnalysis {
/**
* Constructs a <code>DalvikThrowAnalysis</code> for inclusion in Soot's global variable manager, {@link G}.
*
* @param g
* guarantees that the constructor may only be called from {@link Singletons}.
*/
public DalvikThrowAnalysis(Singletons.Global g) {
}
/**
* Returns the single instance of <code>DalvikThrowAnalysis</code>.
*
* @return Soot's <code>UnitThrowAnalysis</code>.
*/
public static DalvikThrowAnalysis v() {
return G.v().soot_dexpler_DalvikThrowAnalysis();
}
protected DalvikThrowAnalysis(boolean isInterproc) {
super(isInterproc);
}
public DalvikThrowAnalysis(Singletons.Global g, boolean isInterproc) {
super(isInterproc);
}
public static DalvikThrowAnalysis interproceduralAnalysis = null;
public static DalvikThrowAnalysis interproc() {
return G.v().interproceduralDalvikThrowAnalysis();
}
@Override
protected ThrowableSet defaultResult() {
return mgr.EMPTY;
}
@Override
protected UnitSwitch unitSwitch(SootMethod sm) {
return new UnitThrowAnalysis.UnitSwitch(sm) {
// Dalvik does not throw an exception for this instruction
@Override
public void caseReturnInst(ReturnInst i) {
}
// Dalvik does not throw an exception for this instruction
@Override
public void caseReturnVoidInst(ReturnVoidInst i) {
}
@Override
public void caseEnterMonitorInst(EnterMonitorInst i) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt s) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
result = result.add(mightThrow(s.getOp()));
}
@Override
public void caseAssignStmt(AssignStmt s) {
// Dalvik only throws ArrayIndexOutOfBounds and
// NullPointerException which are both handled through the
// ArrayRef expressions. There is no ArrayStoreException in
// Dalvik.
result = result.add(mightThrow(s.getLeftOp()));
result = result.add(mightThrow(s.getRightOp()));
}
};
}
@Override
protected ValueSwitch valueSwitch() {
return new UnitThrowAnalysis.ValueSwitch() {
// from ./vm/mterp/c/OP_CONST_STRING.c
//
// HANDLE_OPCODE(OP_CONST_STRING /*vAA, string@BBBB*/)
// {
// StringObject* strObj;
//
// vdst = INST_AA(inst);
// ref = FETCH(1);
// ILOGV("|const-string v%d string@0x%04x", vdst, ref);
// strObj = dvmDexGetResolvedString(methodClassDex, ref);
// if (strObj == NULL) {
// EXPORT_PC();
// strObj = dvmResolveString(curMethod->clazz, ref);
// if (strObj == NULL)
// GOTO_exceptionThrown(); <--- HERE
// }
// SET_REGISTER(vdst, (u4) strObj);
// }
// FINISH(2);
// OP_END
//
@Override
public void caseStringConstant(StringConstant c) {
//
// the string is already fetched when converting
// Dalvik bytecode to Jimple. A potential error
// would be detected there.
//
// result = result.add(mgr.RESOLVE_FIELD_ERRORS); // should we add another kind of exception for this?
}
//
// from ./vm/mterp/c/OP_CONST_CLASS.c
//
// HANDLE_OPCODE(OP_CONST_CLASS /*vAA, class@BBBB*/)
// {
// ClassObject* clazz;
//
// vdst = INST_AA(inst);
// ref = FETCH(1);
// ILOGV("|const-class v%d class@0x%04x", vdst, ref);
// clazz = dvmDexGetResolvedClass(methodClassDex, ref);
// if (clazz == NULL) {
// EXPORT_PC();
// clazz = dvmResolveClass(curMethod->clazz, ref, true);
// if (clazz == NULL)
// GOTO_exceptionThrown(); <--- HERE
// }
// SET_REGISTER(vdst, (u4) clazz);
// }
// FINISH(2);
// OP_END
//
@Override
public void caseClassConstant(ClassConstant c) {
//
// the string is already fetched and stored in a
// ClassConstant object when converting
// Dalvik bytecode to Jimple. A potential error
// would be detected there.
//
// result = result.add(mgr.RESOLVE_CLASS_ERRORS);
}
@Override
public void caseCastExpr(CastExpr expr) {
if (expr.getCastType() instanceof PrimType) {
// No exception are thrown for primitive casts
return;
}
Type fromType = expr.getOp().getType();
Type toType = expr.getCastType();
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
if (toType instanceof RefLikeType) {
// fromType might still be unknown when we are called,
// but toType will have a value.
FastHierarchy h = Scene.v().getOrMakeFastHierarchy();
if (fromType == null || fromType instanceof UnknownType
|| ((!(fromType instanceof NullType)) && (!h.canStoreType(fromType, toType)))) {
result = result.add(mgr.CLASS_CAST_EXCEPTION);
}
}
result = result.add(mightThrow(expr.getOp()));
}
};
}
}
| 14,670
| 43.865443
| 126
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexAnnotation.java
|
package soot.dexpler;
/*-
* #%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.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.jf.dexlib2.AnnotationVisibility;
import org.jf.dexlib2.iface.Annotation;
import org.jf.dexlib2.iface.AnnotationElement;
import org.jf.dexlib2.iface.ClassDef;
import org.jf.dexlib2.iface.Field;
import org.jf.dexlib2.iface.Method;
import org.jf.dexlib2.iface.MethodParameter;
import org.jf.dexlib2.iface.reference.FieldReference;
import org.jf.dexlib2.iface.reference.MethodReference;
import org.jf.dexlib2.iface.value.AnnotationEncodedValue;
import org.jf.dexlib2.iface.value.ArrayEncodedValue;
import org.jf.dexlib2.iface.value.BooleanEncodedValue;
import org.jf.dexlib2.iface.value.ByteEncodedValue;
import org.jf.dexlib2.iface.value.CharEncodedValue;
import org.jf.dexlib2.iface.value.DoubleEncodedValue;
import org.jf.dexlib2.iface.value.EncodedValue;
import org.jf.dexlib2.iface.value.EnumEncodedValue;
import org.jf.dexlib2.iface.value.FieldEncodedValue;
import org.jf.dexlib2.iface.value.FloatEncodedValue;
import org.jf.dexlib2.iface.value.IntEncodedValue;
import org.jf.dexlib2.iface.value.LongEncodedValue;
import org.jf.dexlib2.iface.value.MethodEncodedValue;
import org.jf.dexlib2.iface.value.ShortEncodedValue;
import org.jf.dexlib2.iface.value.StringEncodedValue;
import org.jf.dexlib2.iface.value.TypeEncodedValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.RefType;
import soot.SootClass;
import soot.SootMethod;
import soot.SootResolver;
import soot.Type;
import soot.javaToJimple.IInitialResolver.Dependencies;
import soot.tagkit.AnnotationAnnotationElem;
import soot.tagkit.AnnotationArrayElem;
import soot.tagkit.AnnotationBooleanElem;
import soot.tagkit.AnnotationClassElem;
import soot.tagkit.AnnotationConstants;
import soot.tagkit.AnnotationDefaultTag;
import soot.tagkit.AnnotationDoubleElem;
import soot.tagkit.AnnotationElem;
import soot.tagkit.AnnotationEnumElem;
import soot.tagkit.AnnotationFloatElem;
import soot.tagkit.AnnotationIntElem;
import soot.tagkit.AnnotationLongElem;
import soot.tagkit.AnnotationStringElem;
import soot.tagkit.AnnotationTag;
import soot.tagkit.DeprecatedTag;
import soot.tagkit.EnclosingMethodTag;
import soot.tagkit.Host;
import soot.tagkit.InnerClassAttribute;
import soot.tagkit.InnerClassTag;
import soot.tagkit.ParamNamesTag;
import soot.tagkit.SignatureTag;
import soot.tagkit.Tag;
import soot.tagkit.VisibilityAnnotationTag;
import soot.tagkit.VisibilityParameterAnnotationTag;
import soot.toDex.SootToDexUtils;
/**
* Converts annotations from Dexlib to Jimple.
*
* @author alex
*
*/
public class DexAnnotation {
private static final Logger logger = LoggerFactory.getLogger(DexAnnotation.class);
public static final String JAVA_DEPRECATED = "java.lang.Deprecated";
public static final String DALVIK_ANNOTATION_THROWS = "dalvik.annotation.Throws";
public static final String DALVIK_ANNOTATION_SIGNATURE = "dalvik.annotation.Signature";
public static final String DALVIK_ANNOTATION_MEMBERCLASSES = "dalvik.annotation.MemberClasses";
public static final String DALVIK_ANNOTATION_INNERCLASS = "dalvik.annotation.InnerClass";
public static final String DALVIK_ANNOTATION_ENCLOSINGMETHOD = "dalvik.annotation.EnclosingMethod";
public static final String DALVIK_ANNOTATION_ENCLOSINGCLASS = "dalvik.annotation.EnclosingClass";
public static final String DALVIK_ANNOTATION_DEFAULT = "dalvik.annotation.AnnotationDefault";
private final Type ARRAY_TYPE = RefType.v("Array");
private final SootClass clazz;
private final Dependencies deps;
public DexAnnotation(SootClass clazz, Dependencies deps) {
this.clazz = clazz;
this.deps = deps;
}
/**
* Converts Class annotations from Dexlib to Jimple.
*
* @param classDef
*/
// .annotation "Ldalvik/annotation/AnnotationDefault;"
// .annotation "Ldalvik/annotation/EnclosingClass;"
// .annotation "Ldalvik/annotation/EnclosingMethod;"
// .annotation "Ldalvik/annotation/InnerClass;"
// .annotation "Ldalvik/annotation/MemberClasses;"
// .annotation "Ldalvik/annotation/Signature;"
// .annotation "Ldalvik/annotation/Throws;"
public void handleClassAnnotation(ClassDef classDef) {
Set<? extends Annotation> aSet = classDef.getAnnotations();
if (aSet == null || aSet.isEmpty()) {
return;
}
List<Tag> tags = handleAnnotation(aSet, classDef.getType());
if (tags == null) {
return;
}
InnerClassAttribute ica = null;
for (Tag t : tags) {
if (t != null) {
if (t instanceof InnerClassTag) {
if (ica == null) {
// Do we already have an InnerClassAttribute?
ica = (InnerClassAttribute) clazz.getTag(InnerClassAttribute.NAME);
// If not, create one
if (ica == null) {
ica = new InnerClassAttribute();
clazz.addTag(ica);
}
}
ica.add((InnerClassTag) t);
} else if (t instanceof VisibilityAnnotationTag) {
// If a dalvik/annotation/AnnotationDefault tag is present
// in a class, its AnnotationElements must be propagated
// to methods through the creation of new
// AnnotationDefaultTag.
VisibilityAnnotationTag vt = (VisibilityAnnotationTag) t;
for (AnnotationTag a : vt.getAnnotations()) {
if (a.getType().equals("Ldalvik/annotation/AnnotationDefault;")) {
for (AnnotationElem ae : a.getElems()) {
if (ae instanceof AnnotationAnnotationElem) {
AnnotationAnnotationElem aae = (AnnotationAnnotationElem) ae;
AnnotationTag at = aae.getValue();
// extract default elements
Map<String, AnnotationElem> defaults = new HashMap<String, AnnotationElem>();
for (AnnotationElem aelem : at.getElems()) {
defaults.put(aelem.getName(), aelem);
}
// create default tags containing default
// elements
// and add tags on methods
for (SootMethod sm : clazz.getMethods()) {
String methodName = sm.getName();
if (defaults.containsKey(methodName)) {
AnnotationElem e = defaults.get(methodName);
// Okay, the name is the same, but
// is it actually the same type?
Type annotationType = getSootType(e);
boolean isCorrectType = false;
if (annotationType == null) {
// we do not know the type of
// the annotation, so we guess
// it's the correct type.
isCorrectType = true;
} else {
if (annotationType.equals(sm.getReturnType())) {
isCorrectType = true;
} else if (annotationType.equals(ARRAY_TYPE)) {
if (sm.getReturnType() instanceof ArrayType) {
isCorrectType = true;
}
}
}
if (isCorrectType && sm.getParameterCount() == 0) {
e.setName("default");
AnnotationDefaultTag d = new AnnotationDefaultTag(e);
sm.addTag(d);
// In case there is more than
// one matching method, we only
// use the first one
defaults.remove(sm.getName());
}
}
}
for (Entry<String, AnnotationElem> leftOverEntry : defaults.entrySet()) {
// We were not able to find a matching
// method for the tag, because the
// return signature
// does not match
SootMethod found = clazz.getMethodByNameUnsafe(leftOverEntry.getKey());
AnnotationElem element = leftOverEntry.getValue();
if (found != null) {
element.setName("default");
AnnotationDefaultTag d = new AnnotationDefaultTag(element);
found.addTag(d);
}
}
}
}
}
}
if (!(vt.getVisibility() == AnnotationConstants.RUNTIME_INVISIBLE)) {
clazz.addTag(vt);
}
} else {
clazz.addTag(t);
}
}
}
}
private Type getSootType(AnnotationElem e) {
Type annotationType;
switch (e.getKind()) {
case '[': // array
// Until now we only know it's some kind of array.
annotationType = ARRAY_TYPE;
AnnotationArrayElem array = (AnnotationArrayElem) e;
if (array.getNumValues() > 0) {
// Try to determine type of the array
AnnotationElem firstElement = array.getValueAt(0);
Type type = getSootType(firstElement);
if (type == null) {
return null;
}
if (type.equals(ARRAY_TYPE)) {
return ARRAY_TYPE;
}
return ArrayType.v(type, 1);
}
break;
case 's': // string
annotationType = RefType.v("java.lang.String");
break;
case 'c': // class
annotationType = RefType.v("java.lang.Class");
break;
case 'e': // enum
AnnotationEnumElem enumElem = (AnnotationEnumElem) e;
annotationType = Util.getType(enumElem.getTypeName());
;
break;
case 'L':
case 'J':
case 'S':
case 'D':
case 'I':
case 'F':
case 'B':
case 'C':
case 'V':
case 'Z':
annotationType = Util.getType(String.valueOf(e.getKind()));
break;
default:
annotationType = null;
break;
}
return annotationType;
}
/**
* Converts field annotations from Dexlib to Jimple
*
* @param h
* @param f
*/
public void handleFieldAnnotation(Host h, Field f) {
Set<? extends Annotation> aSet = f.getAnnotations();
if (aSet != null && !aSet.isEmpty()) {
List<Tag> tags = handleAnnotation(aSet, null);
if (tags != null) {
for (Tag t : tags) {
if (t != null) {
h.addTag(t);
}
}
}
}
}
/**
* Converts method and method parameters annotations from Dexlib to Jimple
*
* @param h
* @param method
*/
public void handleMethodAnnotation(Host h, Method method) {
Set<? extends Annotation> aSet = method.getAnnotations();
if (!(aSet == null || aSet.isEmpty())) {
List<Tag> tags = handleAnnotation(aSet, null);
if (tags != null) {
for (Tag t : tags) {
if (t != null) {
h.addTag(t);
}
}
}
}
String[] parameterNames = null;
int i = 0;
for (MethodParameter p : method.getParameters()) {
String name = p.getName();
if (name != null) {
parameterNames = new String[method.getParameters().size()];
parameterNames[i] = name;
}
i++;
}
if (parameterNames != null) {
h.addTag(new ParamNamesTag(parameterNames));
}
// Is there any parameter annotation?
boolean doParam = false;
List<? extends MethodParameter> parameters = method.getParameters();
for (MethodParameter p : parameters) {
if (p.getAnnotations().size() > 0) {
doParam = true;
break;
}
}
if (doParam) {
VisibilityParameterAnnotationTag tag
= new VisibilityParameterAnnotationTag(parameters.size(), AnnotationConstants.RUNTIME_VISIBLE);
for (MethodParameter p : parameters) {
List<Tag> tags = handleAnnotation(p.getAnnotations(), null);
// If we have no tag for this parameter, add a placeholder
// so that we keep the order intact.
if (tags == null) {
tag.addVisibilityAnnotation(null);
continue;
}
VisibilityAnnotationTag paramVat = new VisibilityAnnotationTag(AnnotationConstants.RUNTIME_VISIBLE);
tag.addVisibilityAnnotation(paramVat);
for (Tag t : tags) {
if (t == null) {
continue;
}
AnnotationTag vat = null;
if (!(t instanceof VisibilityAnnotationTag)) {
if (t instanceof DeprecatedTag) {
vat = new AnnotationTag("Ljava/lang/Deprecated;");
} else if (t instanceof SignatureTag) {
SignatureTag sig = (SignatureTag) t;
ArrayList<AnnotationElem> sigElements = new ArrayList<AnnotationElem>();
for (String s : SootToDexUtils.splitSignature(sig.getSignature())) {
sigElements.add(new AnnotationStringElem(s, 's', "value"));
}
AnnotationElem elem = new AnnotationArrayElem(sigElements, '[', "value");
vat = new AnnotationTag("Ldalvik/annotation/Signature;", Collections.singleton(elem));
} else {
throw new RuntimeException("error: unhandled tag for parameter annotation in method " + h + " (" + t + ").");
}
} else {
vat = ((VisibilityAnnotationTag) t).getAnnotations().get(0);
}
paramVat.addAnnotation(vat);
}
}
if (tag.getVisibilityAnnotations().size() > 0) {
h.addTag(tag);
}
}
}
class MyAnnotations {
List<AnnotationTag> annotationList = new ArrayList<AnnotationTag>();
List<Integer> visibilityList = new ArrayList<Integer>();
public void add(AnnotationTag a, int visibility) {
annotationList.add(a);
visibilityList.add(new Integer(visibility));
}
public List<AnnotationTag> getAnnotations() {
return annotationList;
}
public List<Integer> getVisibilityList() {
return visibilityList;
}
}
/**
*
* @param annotations
* @return
*/
private List<Tag> handleAnnotation(Set<? extends org.jf.dexlib2.iface.Annotation> annotations, String classType) {
if (annotations == null || annotations.size() == 0) {
return null;
}
List<Tag> tags = new ArrayList<Tag>();
VisibilityAnnotationTag[] vatg = new VisibilityAnnotationTag[3]; // RUNTIME_VISIBLE,
// RUNTIME_INVISIBLE,
// SOURCE_VISIBLE,
// see
// soot.tagkit.AnnotationConstants
for (Annotation a : annotations) {
addAnnotation(classType, tags, vatg, a);
}
for (VisibilityAnnotationTag vat : vatg) {
if (vat != null) {
tags.add(vat);
}
}
return tags;
}
protected void addAnnotation(String classType, List<Tag> tags, VisibilityAnnotationTag[] vatg, Annotation a) {
int v = getVisibility(a.getVisibility());
Tag t = null;
Type atype = DexType.toSoot(a.getType());
String atypes = atype.toString();
int eSize = a.getElements().size();
switch (atypes) {
case DALVIK_ANNOTATION_DEFAULT:
if (eSize != 1) {
throw new RuntimeException("error: expected 1 element for annotation Default. Got " + eSize + " instead.");
}
// get element
AnnotationElem anne = getElements(a.getElements()).get(0);
AnnotationTag adt = new AnnotationTag(a.getType());
adt.addElem(anne);
if (vatg[v] == null) {
vatg[v] = new VisibilityAnnotationTag(v);
}
vatg[v].addAnnotation(adt);
break;
case DALVIK_ANNOTATION_ENCLOSINGCLASS:
if (eSize != 1) {
throw new RuntimeException("error: expected 1 element for annotation EnclosingClass. Got " + eSize + " instead.");
}
for (AnnotationElement elem : a.getElements()) {
String outerClass = ((TypeEncodedValue) elem.getValue()).getValue();
outerClass = Util.dottedClassName(outerClass);
// If this APK specifies an invalid outer class, we try to
// repair it
if (outerClass.equals(clazz.getName())) {
if (outerClass.contains("$-")) {
/*
* This is a special case for generated lambda classes of jack and jill compiler. Generated lambda classes may
* contain '$' which do not indicate an inner/outer class separator if the '$' occurs after a inner class with
* a name starting with '-'. Thus we search for '$-' and anything after it including '-' is the inner classes
* name and anything before it is the outer classes name.
*/
outerClass = outerClass.substring(0, outerClass.indexOf("$-"));
} else if (outerClass.contains("$")) {
// remove everything after the last '$' including
// the last '$'
outerClass = outerClass.substring(0, outerClass.lastIndexOf("$"));
}
}
deps.typesToSignature.add(RefType.v(outerClass));
clazz.setOuterClass(SootResolver.v().makeClassRef(outerClass));
assert clazz.getOuterClass() != clazz;
}
// Do not add annotation tag
return;
case DALVIK_ANNOTATION_ENCLOSINGMETHOD:
// If we don't have any pointer to the enclosing method, we just
// ignore the annotation
if (eSize == 0) {
// Do not add annotation tag
return;
}
// If the pointer is ambiguous, we are in trouble
if (eSize != 1) {
throw new RuntimeException("error: expected 1 element for annotation EnclosingMethod. Got " + eSize + " instead.");
}
AnnotationStringElem e = (AnnotationStringElem) getElements(a.getElements()).get(0);
String[] split1 = e.getValue().split("\\ \\|");
if (split1.length < 4) {
logger.debug("Invalid or unsupported dalvik EnclosingMethod annotation value: \"{}\"", e.getValue());
break;
}
String classString = split1[0];
String methodString = split1[1];
String parameters = split1[2];
String returnType = split1[3];
String methodSigString = "(" + parameters + ")" + returnType;
t = new EnclosingMethodTag(classString, methodString, methodSigString);
String outerClass = classString.replace("/", ".");
deps.typesToSignature.add(RefType.v(outerClass));
clazz.setOuterClass(SootResolver.v().makeClassRef(outerClass));
assert clazz.getOuterClass() != clazz;
break;
case DALVIK_ANNOTATION_INNERCLASS:
int accessFlags = -1; // access flags of the inner class
String name = null; // name of the inner class
for (AnnotationElem ele : getElements(a.getElements())) {
if (ele instanceof AnnotationIntElem && ele.getName().equals("accessFlags")) {
accessFlags = ((AnnotationIntElem) ele).getValue();
} else if (ele instanceof AnnotationStringElem && ele.getName().equals("name")) {
name = ((AnnotationStringElem) ele).getValue();
} else {
throw new RuntimeException("Unexpected inner class annotation element");
}
}
if (clazz.hasOuterClass()) {
// If we have already set an outer class from some other
// annotation, we use that
// one.
outerClass = clazz.getOuterClass().getName();
} else if (classType.contains("$-")) {
/*
* This is a special case for generated lambda classes of jack and jill compiler. Generated lambda classes may
* contain '$' which do not indicate an inner/outer class separator if the '$' occurs after a inner class with a
* name starting with '-'. Thus we search for '$-' and anything after it including '-' is the inner classes name
* and anything before it is the outer classes name.
*/
outerClass = classType.substring(0, classType.indexOf("$-"));
if (Util.isByteCodeClassName(classType)) {
outerClass += ";";
}
} else if (classType.contains("$")) {
// remove everything after the last '$' including the last
// '$'
outerClass = classType.substring(0, classType.lastIndexOf("$")) + ";";
if (Util.isByteCodeClassName(classType)) {
outerClass += ";";
}
} else {
// Make sure that no funny business is going on if the
// annotation is broken and does not end in $nn.
outerClass = null;
}
Tag innerTag = new InnerClassTag(DexType.toSootICAT(classType),
outerClass == null ? null : DexType.toSootICAT(outerClass), name, accessFlags);
tags.add(innerTag);
if (outerClass != null && !clazz.hasOuterClass()) {
String sootOuterClass = Util.dottedClassName(outerClass);
deps.typesToSignature.add(RefType.v(sootOuterClass));
clazz.setOuterClass(SootResolver.v().makeClassRef(sootOuterClass));
assert clazz.getOuterClass() != clazz;
}
// Do not add annotation tag
return;
case DALVIK_ANNOTATION_MEMBERCLASSES:
AnnotationArrayElem arre = (AnnotationArrayElem) getElements(a.getElements()).get(0);
for (AnnotationElem ae : arre.getValues()) {
AnnotationClassElem c = (AnnotationClassElem) ae;
String innerClass = c.getDesc();
if (innerClass.contains("$-")) {
/*
* This is a special case for generated lambda classes of jack and jill compiler. Generated lambda classes may
* contain '$' which do not indicate an inner/outer class separator if the '$' occurs after a inner class with a
* name starting with '-'. Thus we search for '$-' and anything after it including '-' is the inner classes name
* and anything before it is the outer classes name.
*/
int i = innerClass.indexOf("$-");
outerClass = innerClass.substring(0, i);
name = innerClass.substring(i + 2).replaceAll(";$", "");
} else if (innerClass.contains("$")) {
// remove everything after the last '$' including the
// last '$'
int i = innerClass.lastIndexOf("$");
outerClass = innerClass.substring(0, i);
name = innerClass.substring(i + 1).replaceAll(";$", "");
} else {
// Make sure that no funny business is going on if the
// annotation is broken and does not end in $nn.
outerClass = null;
name = null;
}
if (name != null && name.matches("^\\d*$")) {
// local inner
// classes
name = null;
}
accessFlags = 0; // seems like this information is lost
// during the .class -- dx --> .dex
// process.
innerTag = new InnerClassTag(DexType.toSootICAT(innerClass),
outerClass == null ? null : DexType.toSootICAT(outerClass), name, accessFlags);
tags.add(innerTag);
}
// Do not add annotation tag
return;
case DALVIK_ANNOTATION_SIGNATURE:
if (eSize != 1) {
throw new RuntimeException(
"error: expected 1 element for annotation Signature. Got " + eSize + " instead. Class " + classType);
}
arre = (AnnotationArrayElem) getElements(a.getElements()).get(0);
String sig = "";
for (AnnotationElem ae : arre.getValues()) {
AnnotationStringElem s = (AnnotationStringElem) ae;
sig += s.getValue();
}
t = new SignatureTag(sig);
break;
case DALVIK_ANNOTATION_THROWS:
// Do not add annotation tag
return;
case JAVA_DEPRECATED:
if (eSize > 2) {
throw new RuntimeException(
"error: expected up to 2 attributes for annotation Deprecated. Got " + eSize + " instead. Class " + classType);
}
Boolean forRemoval = null;
String since = null;
for (AnnotationElem elem : getElements(a.getElements())) {
if ((elem instanceof AnnotationBooleanElem) && "forRemoval".equals(elem.getName())) {
forRemoval = ((AnnotationBooleanElem) elem).getValue();
} else if ((elem instanceof AnnotationStringElem) && "since".equals(elem.getName())) {
since = ((AnnotationStringElem) elem).getValue();
} else {
throw new RuntimeException(
"Unsupported attribute in Deprecated annotation found in class " + classType + " " + elem);
}
}
t = new DeprecatedTag(forRemoval, since);
AnnotationTag deprecated = new AnnotationTag("Ljava/lang/Deprecated;");
if (vatg[v] == null) {
vatg[v] = new VisibilityAnnotationTag(v);
}
vatg[v].addAnnotation(deprecated);
break;
default:
addNormalAnnotation(vatg, a, v);
break;
}
tags.add(t);
}
/**
* Processes a normal annotation and adds it to the proper visibility annotation tag in the given array
*
* @param vatg
* the visibility annotation tags for different visibility levels
* @param a
* the annotation
* @param v
* the visibility
*/
protected void addNormalAnnotation(VisibilityAnnotationTag[] vatg, Annotation a, int v) {
if (vatg[v] == null) {
vatg[v] = new VisibilityAnnotationTag(v);
}
AnnotationTag tag = new AnnotationTag(a.getType());
for (AnnotationElem e : getElements(a.getElements())) {
tag.addElem(e);
}
vatg[v].addAnnotation(tag);
}
private ArrayList<AnnotationElem> getElements(Set<? extends AnnotationElement> set) {
ArrayList<AnnotationElem> aelemList = new ArrayList<>();
for (AnnotationElement ae : set) {
logger.trace("element: {}={} type: {}", ae.getName(), ae.getValue(), ae.getClass());
// Debug.printDbg("value type: ", ae.getValue().getValueType() ,"
// class: ", ae.getValue().getClass());
List<AnnotationElem> eList = handleAnnotationElement(ae, Collections.singletonList(ae.getValue()));
if (eList != null) {
aelemList.addAll(eList);
}
}
return aelemList;
}
private ArrayList<AnnotationElem> handleAnnotationElement(AnnotationElement ae, List<? extends EncodedValue> evList) {
ArrayList<AnnotationElem> aelemList = new ArrayList<AnnotationElem>();
for (EncodedValue ev : evList) {
int type = ev.getValueType();
AnnotationElem elem = null;
switch (type) {
case 0x00: // BYTE
{
ByteEncodedValue v = (ByteEncodedValue) ev;
elem = new AnnotationIntElem(v.getValue(), 'B', ae.getName());
break;
}
case 0x02: // SHORT
{
ShortEncodedValue v = (ShortEncodedValue) ev;
elem = new AnnotationIntElem(v.getValue(), 'S', ae.getName());
break;
}
case 0x03: // CHAR
{
CharEncodedValue v = (CharEncodedValue) ev;
elem = new AnnotationIntElem(v.getValue(), 'C', ae.getName());
break;
}
case 0x04: // INT
{
IntEncodedValue v = (IntEncodedValue) ev;
elem = new AnnotationIntElem(v.getValue(), 'I', ae.getName());
break;
}
case 0x06: // LONG
{
LongEncodedValue v = (LongEncodedValue) ev;
elem = new AnnotationLongElem(v.getValue(), 'J', ae.getName());
break;
}
case 0x10: // FLOAT
{
FloatEncodedValue v = (FloatEncodedValue) ev;
elem = new AnnotationFloatElem(v.getValue(), 'F', ae.getName());
break;
}
case 0x11: // DOUBLE
{
DoubleEncodedValue v = (DoubleEncodedValue) ev;
elem = new AnnotationDoubleElem(v.getValue(), 'D', ae.getName());
break;
}
case 0x17: // STRING
{
StringEncodedValue v = (StringEncodedValue) ev;
elem = new AnnotationStringElem(v.getValue(), 's', ae.getName());
break;
}
case 0x18: // TYPE
{
TypeEncodedValue v = (TypeEncodedValue) ev;
elem = new AnnotationClassElem(v.getValue(), 'c', ae.getName());
break;
}
case 0x19: // FIELD (Dalvik specific?)
{
FieldEncodedValue v = (FieldEncodedValue) ev;
FieldReference fr = v.getValue();
String fieldSig = "";
fieldSig += DexType.toSootAT(fr.getDefiningClass()) + ": ";
fieldSig += DexType.toSootAT(fr.getType()) + " ";
fieldSig += fr.getName();
elem = new AnnotationStringElem(fieldSig, 'f', ae.getName());
break;
}
case 0x1a: // METHOD (Dalvik specific?)
{
MethodEncodedValue v = (MethodEncodedValue) ev;
MethodReference mr = v.getValue();
String className = DexType.toSootICAT(mr.getDefiningClass());
String returnType = DexType.toSootAT(mr.getReturnType());
String methodName = mr.getName();
String parameters = "";
for (CharSequence p : mr.getParameterTypes()) {
parameters += DexType.toSootAT(p.toString());
}
String mSig = className + " |" + methodName + " |" + parameters + " |" + returnType;
elem = new AnnotationStringElem(mSig, 'M', ae.getName());
break;
}
case 0x1b: // ENUM : Warning -> encoding Dalvik specific!
{
EnumEncodedValue v = (EnumEncodedValue) ev;
FieldReference fr = v.getValue();
elem = new AnnotationEnumElem(DexType.toSootAT(fr.getType()).toString(), fr.getName(), 'e', ae.getName());
break;
}
case 0x1c: // ARRAY
{
ArrayEncodedValue v = (ArrayEncodedValue) ev;
ArrayList<AnnotationElem> l = handleAnnotationElement(ae, v.getValue());
if (l != null) {
elem = new AnnotationArrayElem(l, '[', ae.getName());
}
break;
}
case 0x1d: // ANNOTATION
{
AnnotationEncodedValue v = (AnnotationEncodedValue) ev;
AnnotationTag t = new AnnotationTag(DexType.toSootAT(v.getType()).toString());
for (AnnotationElement newElem : v.getElements()) {
List<EncodedValue> l = new ArrayList<EncodedValue>();
l.add(newElem.getValue());
List<AnnotationElem> aList = handleAnnotationElement(newElem, l);
if (aList != null) {
for (AnnotationElem e : aList) {
t.addElem(e);
}
}
}
elem = new AnnotationAnnotationElem(t, '@', ae.getName());
break;
}
case 0x1e: // NULL (Dalvik specific?)
{
elem = new AnnotationStringElem(null, 'N', ae.getName());
break;
}
case 0x1f: // BOOLEAN
{
BooleanEncodedValue v = (BooleanEncodedValue) ev;
elem = new AnnotationBooleanElem(v.getValue(), 'Z', ae.getName());
break;
}
default: {
throw new RuntimeException("Unknown annotation element 0x" + Integer.toHexString(type));
}
} // switch (type)
if (elem != null) {
aelemList.add(elem);
}
} // for (EncodedValue)
return aelemList;
}
/**
* Converts Dexlib visibility to Jimple visibility.
*
* In Dalvik: VISIBILITY_BUILD 0x00 intended only to be visible at build time (e.g., during compilation of other code)
* VISIBILITY_RUNTIME 0x01 intended to visible at runtime VISIBILITY_SYSTEM 0x02 intended to visible at runtime, but only
* to the underlying system (and not to regular user code)
*
* @param visibility
* Dexlib visibility
* @return Jimple visibility
*/
protected static int getVisibility(int visibility) {
switch (AnnotationVisibility.getVisibility(visibility)) {
case "runtime":
return AnnotationConstants.RUNTIME_VISIBLE;
case "system":
return AnnotationConstants.RUNTIME_INVISIBLE;
case "build":
return AnnotationConstants.SOURCE_VISIBLE;
default:
throw new RuntimeException(String.format("error: unknown annotation visibility: '%d'", visibility));
}
}
}
| 33,509
| 36.609428
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexArrayInitReducer.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.Local;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.Constant;
import soot.jimple.Stmt;
import soot.options.Options;
import soot.toolkits.scalar.UnusedLocalEliminator;
/**
* Transformer that simplifies array initializations. It converts
*
* a = 0 b = 42 c[a] = b
*
* to
*
* c[0] 42
*
* This transformer performs copy propagation, dead assignment elimination, and unused local elimination at once for this
* special case. The idea is to reduce the code as much as possible for this special case before applying the more expensive
* other transformers.
*
* @author Steven Arzt
*
*/
public class DexArrayInitReducer extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(DexArrayInitReducer.class);
public static DexArrayInitReducer v() {
return new DexArrayInitReducer();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
// Make sure that we only have linear control flow
if (!b.getTraps().isEmpty()) {
return;
}
// Look for a chain of two constant assignments followed by an array put
Unit u1 = null, u2 = null;
for (Iterator<Unit> uIt = b.getUnits().snapshotIterator(); uIt.hasNext();) {
Unit u = uIt.next();
// If this is not an assignment, it does not matter.
if (!(u instanceof AssignStmt) || !((Stmt) u).getBoxesPointingToThis().isEmpty()) {
u1 = null;
u2 = null;
continue;
}
// If this is an assignment to an array, we must already have two
// preceding constant assignments
AssignStmt assignStmt = (AssignStmt) u;
if (assignStmt.getLeftOp() instanceof ArrayRef) {
if (u1 != null && u2 != null && u2.getBoxesPointingToThis().isEmpty()
&& assignStmt.getBoxesPointingToThis().isEmpty()) {
ArrayRef arrayRef = (ArrayRef) assignStmt.getLeftOp();
Value u1val = u1.getDefBoxes().get(0).getValue();
Value u2val = u2.getDefBoxes().get(0).getValue();
// index
if (arrayRef.getIndex() == u1val) {
arrayRef.setIndex(((AssignStmt) u1).getRightOp());
} else if (arrayRef.getIndex() == u2val) {
arrayRef.setIndex(((AssignStmt) u2).getRightOp());
}
// value
if (assignStmt.getRightOp() == u1val) {
assignStmt.setRightOp(((AssignStmt) u1).getRightOp());
} else if (assignStmt.getRightOp() == u2val) {
assignStmt.setRightOp(((AssignStmt) u2).getRightOp());
}
// Remove the unnecessary assignments
Iterator<Unit> checkIt = b.getUnits().iterator(u);
boolean foundU1 = false, foundU2 = false, doneU1 = false, doneU2 = false;
while (!(doneU1 && doneU2) && !(foundU1 && foundU2) && checkIt.hasNext()) {
Unit checkU = checkIt.next();
// Does the current statement use the value?
for (ValueBox vb : checkU.getUseBoxes()) {
if (!doneU1 && vb.getValue() == u1val) {
foundU1 = true;
}
if (!doneU2 && vb.getValue() == u2val) {
foundU2 = true;
}
}
// Does the current statement overwrite the value?
for (ValueBox vb : checkU.getDefBoxes()) {
if (vb.getValue() == u1val) {
doneU1 = true;
} else if (vb.getValue() == u2val) {
doneU2 = true;
}
}
// If this statement branches, we abort
if (checkU.branches()) {
foundU1 = true;
foundU2 = true;
break;
}
}
if (!foundU1) {
// only remove constant assignment if the left value is Local
if (u1val instanceof Local) {
b.getUnits().remove(u1);
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] remove 1 " + u1);
}
}
}
if (!foundU2) {
// only remove constant assignment if the left value is Local
if (u2val instanceof Local) {
b.getUnits().remove(u2);
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] remove 2 " + u2);
}
}
}
u1 = null;
u2 = null;
} else {
// No proper initialization before
u1 = null;
u2 = null;
continue;
}
}
// We have a normal assignment. This could be an array index or
// value.
if (!(assignStmt.getRightOp() instanceof Constant)) {
u1 = null;
u2 = null;
continue;
}
if (u1 == null) {
u1 = assignStmt;
} else if (u2 == null) {
u2 = assignStmt;
// If the last value is overwritten again, we start again at the beginning
if (u1 != null) {
Value op1 = ((AssignStmt) u1).getLeftOp();
if (op1 == ((AssignStmt) u2).getLeftOp()) {
u1 = u2;
u2 = null;
}
}
} else {
u1 = u2;
u2 = assignStmt;
}
}
// Remove all locals that are no longer necessary
UnusedLocalEliminator.v().transform(b);
}
}
| 6,472
| 30.730392
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexBody.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 static soot.dexpler.instructions.InstructionFactory.fromInstruction;
import com.google.common.collect.ArrayListMultimap;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jf.dexlib2.analysis.ClassPath;
import org.jf.dexlib2.analysis.ClassPathResolver;
import org.jf.dexlib2.analysis.ClassProvider;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import org.jf.dexlib2.iface.DexFile;
import org.jf.dexlib2.iface.ExceptionHandler;
import org.jf.dexlib2.iface.Method;
import org.jf.dexlib2.iface.MethodImplementation;
import org.jf.dexlib2.iface.MethodParameter;
import org.jf.dexlib2.iface.MultiDexContainer.DexEntry;
import org.jf.dexlib2.iface.TryBlock;
import org.jf.dexlib2.iface.debug.DebugItem;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.immutable.debug.ImmutableEndLocal;
import org.jf.dexlib2.immutable.debug.ImmutableLineNumber;
import org.jf.dexlib2.immutable.debug.ImmutableRestartLocal;
import org.jf.dexlib2.immutable.debug.ImmutableStartLocal;
import org.jf.dexlib2.util.MethodUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.DoubleType;
import soot.Local;
import soot.LongType;
import soot.Modifier;
import soot.NullType;
import soot.PackManager;
import soot.PhaseOptions;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Trap;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.Value;
import soot.ValueBox;
import soot.dexpler.instructions.DanglingInstruction;
import soot.dexpler.instructions.DeferableInstruction;
import soot.dexpler.instructions.DexlibAbstractInstruction;
import soot.dexpler.instructions.MoveExceptionInstruction;
import soot.dexpler.instructions.OdexInstruction;
import soot.dexpler.instructions.PseudoInstruction;
import soot.dexpler.instructions.RetypeableInstruction;
import soot.dexpler.typing.DalvikTyper;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ConditionExpr;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.EqExpr;
import soot.jimple.IfStmt;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.NeExpr;
import soot.jimple.NullConstant;
import soot.jimple.NumericConstant;
import soot.jimple.internal.JIdentityStmt;
import soot.jimple.toolkits.base.Aggregator;
import soot.jimple.toolkits.scalar.ConditionalBranchFolder;
import soot.jimple.toolkits.scalar.ConstantCastEliminator;
import soot.jimple.toolkits.scalar.CopyPropagator;
import soot.jimple.toolkits.scalar.DeadAssignmentEliminator;
import soot.jimple.toolkits.scalar.FieldStaticnessCorrector;
import soot.jimple.toolkits.scalar.IdentityCastEliminator;
import soot.jimple.toolkits.scalar.IdentityOperationEliminator;
import soot.jimple.toolkits.scalar.MethodStaticnessCorrector;
import soot.jimple.toolkits.scalar.NopEliminator;
import soot.jimple.toolkits.scalar.UnconditionalBranchFolder;
import soot.jimple.toolkits.scalar.UnreachableCodeEliminator;
import soot.jimple.toolkits.typing.TypeAssigner;
import soot.options.JBOptions;
import soot.options.Options;
import soot.tagkit.LineNumberTag;
import soot.tagkit.SourceLineNumberTag;
import soot.toolkits.exceptions.TrapTightener;
import soot.toolkits.scalar.LocalPacker;
import soot.toolkits.scalar.LocalSplitter;
import soot.toolkits.scalar.UnusedLocalEliminator;
/**
* A DexBody contains the code of a DexMethod and is used as a wrapper around JimpleBody in the jimplification process.
*
* @author Michael Markert
* @author Frank Hartmann
*/
public class DexBody {
private static final Logger logger = LoggerFactory.getLogger(DexBody.class);
protected List<DexlibAbstractInstruction> instructions;
// keeps track about the jimple locals that are associated with the dex
// registers
protected Local[] registerLocals;
protected Local storeResultLocal;
protected Map<Integer, DexlibAbstractInstruction> instructionAtAddress;
protected List<DeferableInstruction> deferredInstructions;
protected Set<RetypeableInstruction> instructionsToRetype;
protected DanglingInstruction dangling;
protected int numRegisters;
protected int numParameterRegisters;
protected final List<Type> parameterTypes;
protected final List<String> parameterNames;
protected boolean isStatic;
protected JimpleBody jBody;
protected List<? extends TryBlock<? extends ExceptionHandler>> tries;
protected RefType declaringClassType;
protected final DexEntry<? extends DexFile> dexEntry;
protected final Method method;
/**
* An entry of debug information for a register from the dex file.
*
* @author Zhenghao Hu
*/
protected class RegDbgEntry {
public int startAddress;
public int endAddress;
public int register;
public String name;
public Type type;
public String signature;
public RegDbgEntry(int sa, int ea, int reg, String nam, String ty, String sig) {
this.startAddress = sa;
this.endAddress = ea;
this.register = reg;
this.name = nam;
this.type = DexType.toSoot(ty);
this.signature = sig;
}
}
private final ArrayListMultimap<Integer, RegDbgEntry> localDebugs;
// detect array/instructions overlapping obfuscation
protected List<PseudoInstruction> pseudoInstructionData = new ArrayList<PseudoInstruction>();
PseudoInstruction isAddressInData(int a) {
for (PseudoInstruction pi : pseudoInstructionData) {
int fb = pi.getDataFirstByte();
int lb = pi.getDataLastByte();
if (fb <= a && a <= lb) {
return pi;
}
}
return null;
}
// the set of names used by Jimple locals
protected Set<String> takenLocalNames;
/**
* Allocate a fresh name for Jimple local
*
* @param hint
* A name that the fresh name will look like
* @author Zhixuan Yang (yangzhixuan@sbrella.com)
*/
protected String freshLocalName(String hint) {
if (hint == null || hint.equals("")) {
hint = "$local";
}
String fresh;
if (!takenLocalNames.contains(hint)) {
fresh = hint;
} else {
for (int i = 1;; i++) {
fresh = hint + Integer.toString(i);
if (!takenLocalNames.contains(fresh)) {
break;
}
}
}
takenLocalNames.add(fresh);
return fresh;
}
/**
* @param code
* the codeitem that is contained in this body
* @param method
* the method that is associated with this body
*/
protected DexBody(DexEntry<? extends DexFile> dexFile, Method method, RefType declaringClassType) {
MethodImplementation code = method.getImplementation();
if (code == null) {
throw new RuntimeException("error: no code for method " + method.getName());
}
this.declaringClassType = declaringClassType;
tries = code.getTryBlocks();
List<? extends MethodParameter> parameters = method.getParameters();
if (parameters != null) {
parameterNames = new ArrayList<String>();
parameterTypes = new ArrayList<Type>();
for (MethodParameter param : method.getParameters()) {
parameterNames.add(param.getName());
parameterTypes.add(DexType.toSoot(param.getType()));
}
} else {
parameterNames = Collections.emptyList();
parameterTypes = Collections.emptyList();
}
isStatic = Modifier.isStatic(method.getAccessFlags());
numRegisters = code.getRegisterCount();
numParameterRegisters = MethodUtil.getParameterRegisterCount(method);
if (!isStatic) {
numParameterRegisters--;
}
instructions = new ArrayList<DexlibAbstractInstruction>();
instructionAtAddress = new HashMap<Integer, DexlibAbstractInstruction>();
localDebugs = ArrayListMultimap.create();
takenLocalNames = new HashSet<String>();
registerLocals = new Local[numRegisters];
extractDexInstructions(code);
// Check taken from Android's dalvik/libdex/DexSwapVerify.cpp
if (numParameterRegisters > numRegisters) {
throw new RuntimeException(
"Malformed dex file: insSize (" + numParameterRegisters + ") > registersSize (" + numRegisters + ")");
}
for (DebugItem di : code.getDebugItems()) {
if (di instanceof ImmutableLineNumber) {
ImmutableLineNumber ln = (ImmutableLineNumber) di;
DexlibAbstractInstruction ins = instructionAtAddress(ln.getCodeAddress());
if (ins == null) {
// Debug.printDbg("Line number tag pointing to invalid
// offset: " + ln.getCodeAddress());
continue;
}
ins.setLineNumber(ln.getLineNumber());
} else if (di instanceof ImmutableStartLocal || di instanceof ImmutableRestartLocal) {
int reg, codeAddr;
String type, signature, name;
if (di instanceof ImmutableStartLocal) {
ImmutableStartLocal sl = (ImmutableStartLocal) di;
reg = sl.getRegister();
codeAddr = sl.getCodeAddress();
name = sl.getName();
type = sl.getType();
signature = sl.getSignature();
} else {
ImmutableRestartLocal sl = (ImmutableRestartLocal) di;
// ImmutableRestartLocal and ImmutableStartLocal share the same members but
// don't share a base. So we have to write some duplicated code.
reg = sl.getRegister();
codeAddr = sl.getCodeAddress();
name = sl.getName();
type = sl.getType();
signature = sl.getSignature();
}
if (name != null && type != null) {
localDebugs.put(reg, new RegDbgEntry(codeAddr, -1 /* endAddress */, reg, name, type, signature));
}
} else if (di instanceof ImmutableEndLocal) {
ImmutableEndLocal el = (ImmutableEndLocal) di;
List<RegDbgEntry> lds = localDebugs.get(el.getRegister());
if (lds == null || lds.isEmpty()) {
// Invalid debug info
continue;
} else {
lds.get(lds.size() - 1).endAddress = el.getCodeAddress();
}
}
}
this.dexEntry = dexFile;
this.method = method;
}
/**
* Extracts the list of dalvik instructions from dexlib and converts them into our own instruction data model
*
* @param code
* The dexlib method implementation
*/
protected void extractDexInstructions(MethodImplementation code) {
int address = 0;
for (Instruction instruction : code.getInstructions()) {
DexlibAbstractInstruction dexInstruction = fromInstruction(instruction, address);
instructions.add(dexInstruction);
instructionAtAddress.put(address, dexInstruction);
address += instruction.getCodeUnits();
}
}
/** Return the types that are used in this body. */
public Set<Type> usedTypes() {
Set<Type> types = new HashSet<Type>();
for (DexlibAbstractInstruction i : instructions) {
types.addAll(i.introducedTypes());
}
if (tries != null) {
for (TryBlock<? extends ExceptionHandler> tryItem : tries) {
List<? extends ExceptionHandler> hList = tryItem.getExceptionHandlers();
for (ExceptionHandler handler : hList) {
String exType = handler.getExceptionType();
if (exType == null) {
// Exceptions
continue;
}
types.add(DexType.toSoot(exType));
}
}
}
return types;
}
/**
* Add unit to this body.
*
* @param u
* Unit to add.
*/
public void add(Unit u) {
getBody().getUnits().add(u);
}
/**
* Add a deferred instruction to this body.
*
* @param i
* the deferred instruction.
*/
public void addDeferredJimplification(DeferableInstruction i) {
deferredInstructions.add(i);
}
/**
* Add a retypeable instruction to this body.
*
* @param i
* the retypeable instruction.
*/
public void addRetype(RetypeableInstruction i) {
instructionsToRetype.add(i);
}
/**
* Return the associated JimpleBody.
*
* @throws RuntimeException
* if no jimplification happened yet.
*/
public Body getBody() {
if (jBody == null) {
throw new RuntimeException("No jimplification happened yet, no body available.");
}
return jBody;
}
/** Return the Locals that are associated with the current register state. */
public Local[] getRegisterLocals() {
return registerLocals;
}
/**
* Return the Local that are associated with the number in the current register state.
*
* <p>
* Handles if the register number actually points to a method parameter.
*
* @param num
* the register number
* @throws InvalidDalvikBytecodeException
*/
public Local getRegisterLocal(int num) throws InvalidDalvikBytecodeException {
int totalRegisters = registerLocals.length;
if (num > totalRegisters) {
throw new InvalidDalvikBytecodeException(
"Trying to access register " + num + " but only " + totalRegisters + " is/are available.");
}
return registerLocals[num];
}
public Local getStoreResultLocal() {
return storeResultLocal;
}
/**
* Return the instruction that is present at the byte code address.
*
* @param address
* the byte code address.
* @throws RuntimeException
* if address is not part of this body.
*/
public DexlibAbstractInstruction instructionAtAddress(int address) {
DexlibAbstractInstruction i = null;
while (i == null && address >= 0) {
// catch addresses can be in the middlde of last instruction. Ex. in
// com.letang.ldzja.en.apk:
//
// 042c46: 7020 2a15 0100 |008f: invoke-direct {v1, v0},
// Ljavax/mi...
// 042c4c: 2701 |0092: throw v1
// catches : 4
// <any> -> 0x0065
// 0x0069 - 0x0093
//
// SA, 14.05.2014: We originally scanned only two code units back.
// This is not sufficient
// if we e.g., have a wide constant and the line number in the debug
// sections points to
// some address the middle.
i = instructionAtAddress.get(address);
address--;
}
return i;
}
/**
* Return the jimple equivalent of this body.
*
* @param m
* the SootMethod that contains this body
*/
public Body jimplify(Body b, SootMethod m) {
final Jimple jimple = Jimple.v();
final UnknownType unknownType = UnknownType.v();
final NullConstant nullConstant = NullConstant.v();
final Options options = Options.v();
/*
* Timer t_whole_jimplification = new Timer(); Timer t_num = new Timer(); Timer t_null = new Timer();
*
* t_whole_jimplification.start();
*/
JBOptions jbOptions = new JBOptions(PhaseOptions.v().getPhaseOptions("jb"));
jBody = (JimpleBody) b;
deferredInstructions = new ArrayList<DeferableInstruction>();
instructionsToRetype = new HashSet<RetypeableInstruction>();
if (jbOptions.use_original_names()) {
PhaseOptions.v().setPhaseOptionIfUnset("jb.lns", "only-stack-locals");
}
if (jbOptions.stabilize_local_names()) {
PhaseOptions.v().setPhaseOption("jb.lns", "sort-locals:true");
}
if (IDalvikTyper.ENABLE_DVKTYPER) {
DalvikTyper.v().clear();
}
// process method parameters and generate Jimple locals from Dalvik
// registers
List<Local> paramLocals = new LinkedList<Local>();
if (!isStatic) {
int thisRegister = numRegisters - numParameterRegisters - 1;
Local thisLocal = jimple.newLocal(freshLocalName("this"), unknownType); // generateLocal(UnknownType.v());
jBody.getLocals().add(thisLocal);
registerLocals[thisRegister] = thisLocal;
JIdentityStmt idStmt = (JIdentityStmt) jimple.newIdentityStmt(thisLocal, jimple.newThisRef(declaringClassType));
add(idStmt);
paramLocals.add(thisLocal);
if (IDalvikTyper.ENABLE_DVKTYPER) {
DalvikTyper.v().setType(idStmt.getLeftOpBox(), jBody.getMethod().getDeclaringClass().getType(), false);
}
}
{
int i = 0; // index of parameter type
int argIdx = 0;
int parameterRegister = numRegisters - numParameterRegisters; // index of parameter register
for (Type t : parameterTypes) {
String localName = null;
Type localType = null;
if (jbOptions.use_original_names()) {
// Attempt to read original parameter name.
try {
localName = parameterNames.get(argIdx);
localType = parameterTypes.get(argIdx);
} catch (Exception ex) {
logger.error("Exception while reading original parameter names.", ex);
}
}
if (localName == null && localDebugs.containsKey(parameterRegister)) {
localName = localDebugs.get(parameterRegister).get(0).name;
} else {
localName = "$u" + parameterRegister;
}
if (localType == null) {
// may only use UnknownType here because the local may be
// reused with a different type later (before splitting)
localType = unknownType;
}
Local gen = jimple.newLocal(freshLocalName(localName), localType);
jBody.getLocals().add(gen);
registerLocals[parameterRegister] = gen;
JIdentityStmt idStmt = (JIdentityStmt) jimple.newIdentityStmt(gen, jimple.newParameterRef(t, i++));
add(idStmt);
paramLocals.add(gen);
if (IDalvikTyper.ENABLE_DVKTYPER) {
DalvikTyper.v().setType(idStmt.getLeftOpBox(), t, false);
}
// some parameters may be encoded on two registers.
// in Jimple only the first Dalvik register name is used
// as the corresponding Jimple Local name. However, we also add
// the second register to the registerLocals array since it
// could be used later in the Dalvik bytecode
if (t instanceof LongType || t instanceof DoubleType) {
parameterRegister++;
// may only use UnknownType here because the local may be reused with a different
// type later (before splitting)
String name;
if (localDebugs.containsKey(parameterRegister)) {
name = localDebugs.get(parameterRegister).get(0).name;
} else {
name = "$u" + parameterRegister;
}
Local g = jimple.newLocal(freshLocalName(name), unknownType);
jBody.getLocals().add(g);
registerLocals[parameterRegister] = g;
}
parameterRegister++;
argIdx++;
}
}
for (int i = 0; i < (numRegisters - numParameterRegisters - (isStatic ? 0 : 1)); i++) {
String name;
if (localDebugs.containsKey(i)) {
name = localDebugs.get(i).get(0).name;
} else {
name = "$u" + i;
}
registerLocals[i] = jimple.newLocal(freshLocalName(name), unknownType);
jBody.getLocals().add(registerLocals[i]);
}
// add local to store intermediate results
storeResultLocal = jimple.newLocal(freshLocalName("$u-1"), unknownType);
jBody.getLocals().add(storeResultLocal);
// process bytecode instructions
final DexFile dexFile = dexEntry.getDexFile();
final boolean isOdex
= dexFile instanceof DexBackedDexFile ? ((DexBackedDexFile) dexFile).supportsOptimizedOpcodes() : false;
ClassPath cp = null;
if (isOdex) {
String[] sootClasspath = options.soot_classpath().split(File.pathSeparator);
List<String> classpathList = new ArrayList<String>();
for (String str : sootClasspath) {
classpathList.add(str);
}
try {
ClassPathResolver resolver = new ClassPathResolver(classpathList, classpathList, classpathList, dexEntry);
cp = new ClassPath(resolver.getResolvedClassProviders().toArray(new ClassProvider[0]));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
int prevLineNumber = -1;
for (DexlibAbstractInstruction instruction : instructions) {
if (isOdex && instruction instanceof OdexInstruction) {
((OdexInstruction) instruction).deOdex(dexFile, method, cp);
}
if (dangling != null) {
dangling.finalize(this, instruction);
dangling = null;
}
instruction.jimplify(this);
if (instruction.getLineNumber() > 0) {
prevLineNumber = instruction.getLineNumber();
} else {
instruction.setLineNumber(prevLineNumber);
}
}
if (dangling != null) {
dangling.finalize(this, null);
}
for (DeferableInstruction instruction : deferredInstructions) {
instruction.deferredJimplify(this);
}
if (tries != null) {
addTraps();
}
if (options.keep_line_number()) {
fixLineNumbers();
}
// At this point Jimple code is generated
// Cleaning...
instructions = null;
// registerLocals = null;
// storeResultLocal = null;
instructionAtAddress.clear();
// localGenerator = null;
deferredInstructions = null;
// instructionsToRetype = null;
dangling = null;
tries = null;
parameterNames.clear();
/*
* We eliminate dead code. Dead code has been shown to occur under the following circumstances.
*
* 0006ec: 0d00 |00a2: move-exception v0 ... 0006f2: 0d00 |00a5: move-exception v0 ... 0x0041 - 0x008a
* Ljava/lang/Throwable; -> 0x00a5 <any> -> 0x00a2
*
* Here there are two traps both over the same region. But the same always fires, hence rendering the code at a2
* unreachable. Dead code yields problems during local splitting because locals within dead code will not be split. Hence
* we remove all dead code here.
*/
// Fix traps that do not catch exceptions
DexTrapStackFixer.v().transform(jBody);
// Sort out jump chains
DexJumpChainShortener.v().transform(jBody);
// Make sure that we don't have any overlapping uses due to returns
DexReturnInliner.v().transform(jBody);
// Shortcut: Reduce array initializations
DexArrayInitReducer.v().transform(jBody);
// split first to find undefined uses
getLocalSplitter().transform(jBody);
// Remove dead code and the corresponding locals before assigning types
getUnreachableCodeEliminator().transform(jBody);
DeadAssignmentEliminator.v().transform(jBody);
UnusedLocalEliminator.v().transform(jBody);
for (RetypeableInstruction i : instructionsToRetype) {
i.retype(jBody);
}
// {
// // remove instructions from instructions list
// List<DexlibAbstractInstruction> iToRemove = new
// ArrayList<DexlibAbstractInstruction>();
// for (DexlibAbstractInstruction i: instructions)
// if (!jBody.getUnits().contains(i.getUnit()))
// iToRemove.add(i);
// for (DexlibAbstractInstruction i: iToRemove) {
// Debug.printDbg("removing dexinstruction containing unit '",
// i.getUnit() ,"'");
// instructions.remove(i);
// }
// }
if (IDalvikTyper.ENABLE_DVKTYPER) {
DexReturnValuePropagator.v().transform(jBody);
getCopyPopagator().transform(jBody);
DexNullThrowTransformer.v().transform(jBody);
DalvikTyper.v().typeUntypedConstrantInDiv(jBody);
DeadAssignmentEliminator.v().transform(jBody);
UnusedLocalEliminator.v().transform(jBody);
DalvikTyper.v().assignType(jBody);
// jBody.validate();
jBody.validateUses();
jBody.validateValueBoxes();
// jBody.checkInit();
// Validate.validateArrays(jBody);
// jBody.checkTypes();
// jBody.checkLocals();
} else {
// t_num.start();
DexNumTransformer.v().transform(jBody);
// t_num.end();
DexReturnValuePropagator.v().transform(jBody);
getCopyPopagator().transform(jBody);
DexNullThrowTransformer.v().transform(jBody);
// t_null.start();
DexNullTransformer.v().transform(jBody);
// t_null.end();
DexIfTransformer.v().transform(jBody);
DeadAssignmentEliminator.v().transform(jBody);
UnusedLocalEliminator.v().transform(jBody);
// DexRefsChecker.v().transform(jBody);
DexNullArrayRefTransformer.v().transform(jBody);
}
if (IDalvikTyper.ENABLE_DVKTYPER) {
for (Local l : jBody.getLocals()) {
l.setType(unknownType);
}
}
// Remove "instanceof" checks on the null constant
DexNullInstanceofTransformer.v().transform(jBody);
DexNullIfTransformer ni = DexNullIfTransformer.v();
ni.transform(jBody);
if (ni.hasModifiedBody()) {
// Now we might have unreachable code
ConditionalBranchFolder.v().transform(jBody);
UnreachableCodeEliminator.v().transform(jBody);
DeadAssignmentEliminator.v().transform(jBody);
UnconditionalBranchFolder.v().transform(jBody);
}
TypeAssigner.v().transform(jBody);
final RefType objectType = RefType.v("java.lang.Object");
if (IDalvikTyper.ENABLE_DVKTYPER) {
for (Unit u : jBody.getUnits()) {
if (u instanceof IfStmt) {
ConditionExpr expr = (ConditionExpr) ((IfStmt) u).getCondition();
if (((expr instanceof EqExpr) || (expr instanceof NeExpr))) {
Value op1 = expr.getOp1();
Value op2 = expr.getOp2();
if (op1 instanceof Constant && op2 instanceof Local) {
Local l = (Local) op2;
Type ltype = l.getType();
if (ltype instanceof PrimType) {
continue;
}
if (!(op1 instanceof IntConstant)) {
// null is
// IntConstant(0)
// in Dalvik
continue;
}
IntConstant icst = (IntConstant) op1;
int val = icst.value;
if (val != 0) {
continue;
}
expr.setOp1(nullConstant);
} else if (op1 instanceof Local && op2 instanceof Constant) {
Local l = (Local) op1;
Type ltype = l.getType();
if (ltype instanceof PrimType) {
continue;
}
if (!(op2 instanceof IntConstant)) {
// null is
// IntConstant(0)
// in Dalvik
continue;
}
IntConstant icst = (IntConstant) op2;
int val = icst.value;
if (val != 0) {
continue;
}
expr.setOp2(nullConstant);
} else if (op1 instanceof Local && op2 instanceof Local) {
// nothing to do
} else if (op1 instanceof Constant && op2 instanceof Constant) {
if (op1 instanceof NullConstant && op2 instanceof NumericConstant) {
IntConstant nc = (IntConstant) op2;
if (nc.value != 0) {
throw new RuntimeException("expected value 0 for int constant. Got " + expr);
}
expr.setOp2(NullConstant.v());
} else if (op2 instanceof NullConstant && op1 instanceof NumericConstant) {
IntConstant nc = (IntConstant) op1;
if (nc.value != 0) {
throw new RuntimeException("expected value 0 for int constant. Got " + expr);
}
expr.setOp1(nullConstant);
}
} else {
throw new RuntimeException("error: do not handle if: " + u);
}
}
}
}
// For null_type locals: replace their use by NullConstant()
List<ValueBox> uses = jBody.getUseBoxes();
// List<ValueBox> defs = jBody.getDefBoxes();
List<ValueBox> toNullConstantify = new ArrayList<ValueBox>();
List<Local> toRemove = new ArrayList<Local>();
for (Local l : jBody.getLocals()) {
if (l.getType() instanceof NullType) {
toRemove.add(l);
for (ValueBox vb : uses) {
Value v = vb.getValue();
if (v == l) {
toNullConstantify.add(vb);
}
}
}
}
for (ValueBox vb : toNullConstantify) {
System.out.println("replace valuebox '" + vb + " with null constant");
vb.setValue(nullConstant);
}
for (Local l : toRemove) {
System.out.println("removing null_type local " + l);
l.setType(objectType);
}
}
// We pack locals that are not used in overlapping regions. This may
// again lead to unused locals which we have to remove.
LocalPacker.v().transform(jBody);
UnusedLocalEliminator.v().transform(jBody);
PackManager.v().getTransform("jb.lns").apply(jBody);
// Some apps reference static fields as instance fields. We fix this
// on the fly.
if (Options.v().wrong_staticness() == Options.wrong_staticness_fix
|| Options.v().wrong_staticness() == Options.wrong_staticness_fixstrict) {
FieldStaticnessCorrector.v().transform(jBody);
MethodStaticnessCorrector.v().transform(jBody);
}
// Inline PackManager.v().getPack("jb").apply(jBody);
// Keep only transformations that have not been done
// at this point.
TrapTightener.v().transform(jBody);
TrapMinimizer.v().transform(jBody);
// LocalSplitter.v().transform(jBody);
Aggregator.v().transform(jBody);
// UnusedLocalEliminator.v().transform(jBody);
// TypeAssigner.v().transform(jBody);
// LocalPacker.v().transform(jBody);
// LocalNameStandardizer.v().transform(jBody);
// Remove if (null == null) goto x else <madness>. We can only do this
// after we have run the constant propagation as we might not be able
// to statically decide the conditions earlier.
ConditionalBranchFolder.v().transform(jBody);
// Remove unnecessary typecasts
ConstantCastEliminator.v().transform(jBody);
IdentityCastEliminator.v().transform(jBody);
// Remove unnecessary logic operations
IdentityOperationEliminator.v().transform(jBody);
// We need to run this transformer since the conditional branch folder
// might have rendered some code unreachable (well, it was unreachable
// before as well, but we didn't know).
UnreachableCodeEliminator.v().transform(jBody);
// Not sure whether we need this even though we do it earlier on as
// the earlier pass does not have type information
// CopyPropagator.v().transform(jBody);
// we might have gotten new dead assignments and unused locals through
// copy propagation and unreachable code elimination, so we have to do
// this again
DeadAssignmentEliminator.v().transform(jBody);
UnusedLocalEliminator.v().transform(jBody);
NopEliminator.v().transform(jBody);
// Remove unnecessary chains of return statements
DexReturnPacker.v().transform(jBody);
for (Unit u : jBody.getUnits()) {
if (u instanceof AssignStmt) {
AssignStmt ass = (AssignStmt) u;
if (ass.getRightOp() instanceof CastExpr) {
CastExpr c = (CastExpr) ass.getRightOp();
if (c.getType() instanceof NullType) {
ass.setRightOp(nullConstant);
}
}
}
if (u instanceof DefinitionStmt) {
DefinitionStmt def = (DefinitionStmt) u;
// If the body references a phantom class in a
// CaughtExceptionRef,
// we must manually fix the hierarchy
if (def.getLeftOp() instanceof Local && def.getRightOp() instanceof CaughtExceptionRef) {
Type t = def.getLeftOp().getType();
if (t instanceof RefType) {
RefType rt = (RefType) t;
if (rt.getSootClass().isPhantom() && !rt.getSootClass().hasSuperclass()
&& !rt.getSootClass().getName().equals("java.lang.Throwable")) {
rt.getSootClass().setSuperclass(Scene.v().getSootClass("java.lang.Throwable"));
}
}
}
}
}
// Replace local type null_type by java.lang.Object.
//
// The typing engine cannot find correct type for such code:
//
// null_type $n0;
// $n0 = null;
// $r4 = virtualinvoke $n0.<java.lang.ref.WeakReference:
// java.lang.Object get()>();
//
for (Local l : jBody.getLocals()) {
Type t = l.getType();
if (t instanceof NullType) {
l.setType(objectType);
}
}
// Must be last to ensure local ordering does not change
PackManager.v().getTransform("jb.lns").apply(jBody);
// t_whole_jimplification.end();
return jBody;
}
/**
* Fixes the line numbers. If there is a unit without a line number, it gets the line number of the last (transitive)
* predecessor that has a line number.
*/
protected void fixLineNumbers() {
int prevLn = -1;
for (DexlibAbstractInstruction instruction : instructions) {
Unit unit = instruction.getUnit();
int lineNumber = unit.getJavaSourceStartLineNumber();
if (lineNumber < 0) {
if (prevLn >= 0) {
unit.addTag(new LineNumberTag(prevLn));
unit.addTag(new SourceLineNumberTag(prevLn));
}
} else {
prevLn = lineNumber;
}
}
}
private LocalSplitter localSplitter = null;
protected LocalSplitter getLocalSplitter() {
if (this.localSplitter == null) {
this.localSplitter = new LocalSplitter(DalvikThrowAnalysis.v());
}
return this.localSplitter;
}
private UnreachableCodeEliminator unreachableCodeEliminator = null;
protected UnreachableCodeEliminator getUnreachableCodeEliminator() {
if (this.unreachableCodeEliminator == null) {
this.unreachableCodeEliminator = new UnreachableCodeEliminator(DalvikThrowAnalysis.v());
}
return this.unreachableCodeEliminator;
}
private CopyPropagator copyPropagator = null;
protected CopyPropagator getCopyPopagator() {
if (this.copyPropagator == null) {
this.copyPropagator = new CopyPropagator(DalvikThrowAnalysis.v(), false);
}
return this.copyPropagator;
}
/** Set a dangling instruction for this body. */
public void setDanglingInstruction(DanglingInstruction i) {
dangling = i;
}
/**
* Return the instructions that appear (lexically) after the given instruction.
*
* @param instruction
* the instruction which successors will be returned.
*/
public List<DexlibAbstractInstruction> instructionsAfter(DexlibAbstractInstruction instruction) {
int i = instructions.indexOf(instruction);
if (i == -1) {
throw new IllegalArgumentException("Instruction" + instruction + "not part of this body.");
}
return instructions.subList(i + 1, instructions.size());
}
/**
* Return the instructions that appear (lexically) before the given instruction.
*
* <p>
* The instruction immediately before the given is the first instruction and so on.
*
* @param instruction
* the instruction which successors will be returned.
*/
public List<DexlibAbstractInstruction> instructionsBefore(DexlibAbstractInstruction instruction) {
int i = instructions.indexOf(instruction);
if (i == -1) {
throw new IllegalArgumentException("Instruction " + instruction + " not part of this body.");
}
List<DexlibAbstractInstruction> l = new ArrayList<DexlibAbstractInstruction>();
l.addAll(instructions.subList(0, i));
Collections.reverse(l);
return l;
}
/**
* Add the traps of this body.
*
* <p>
* Should only be called at the end jimplify.
*/
private void addTraps() {
final Jimple jimple = Jimple.v();
for (TryBlock<? extends ExceptionHandler> tryItem : tries) {
int startAddress = tryItem.getStartCodeAddress();
int length = tryItem.getCodeUnitCount(); // .getTryLength();
int endAddress = startAddress + length; // - 1;
Unit beginStmt = instructionAtAddress(startAddress).getUnit();
// (startAddress + length) typically points to the first byte of the
// first instruction after the try block
// except if there is no instruction after the try block in which
// case it points to the last byte of the last
// instruction of the try block. Removing 1 from (startAddress +
// length) always points to "somewhere" in
// the last instruction of the try block since the smallest
// instruction is on two bytes (nop = 0x0000).
Unit endStmt = instructionAtAddress(endAddress).getUnit();
// if the try block ends on the last instruction of the body, add a
// nop instruction so Soot can include
// the last instruction in the try block.
if (jBody.getUnits().getLast() == endStmt && instructionAtAddress(endAddress - 1).getUnit() == endStmt) {
Unit nop = jimple.newNopStmt();
jBody.getUnits().insertAfter(nop, endStmt);
endStmt = nop;
}
List<? extends ExceptionHandler> hList = tryItem.getExceptionHandlers();
for (ExceptionHandler handler : hList) {
String exceptionType = handler.getExceptionType();
if (exceptionType == null) {
exceptionType = "Ljava/lang/Throwable;";
}
Type t = DexType.toSoot(exceptionType);
// exceptions can only be of RefType
if (t instanceof RefType) {
SootClass exception = ((RefType) t).getSootClass();
DexlibAbstractInstruction instruction = instructionAtAddress(handler.getHandlerCodeAddress());
if (!(instruction instanceof MoveExceptionInstruction)) {
logger.debug("" + String.format("First instruction of trap handler unit not MoveException but %s",
instruction.getClass().getName()));
} else {
((MoveExceptionInstruction) instruction).setRealType(this, exception.getType());
}
Trap trap = jimple.newTrap(exception, beginStmt, endStmt, instruction.getUnit());
jBody.getTraps().add(trap);
}
}
}
}
}
| 39,204
| 33.848889
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexClassLoader.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import org.jf.dexlib2.iface.ClassDef;
import org.jf.dexlib2.iface.DexFile;
import org.jf.dexlib2.iface.Field;
import org.jf.dexlib2.iface.Method;
import org.jf.dexlib2.iface.MultiDexContainer.DexEntry;
import soot.Modifier;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.SootResolver;
import soot.javaToJimple.IInitialResolver.Dependencies;
import soot.options.Options;
import soot.tagkit.InnerClassAttribute;
import soot.tagkit.InnerClassTag;
import soot.tagkit.SourceFileTag;
import soot.tagkit.Tag;
/**
* Class for loading methods from dex files
*/
public class DexClassLoader {
/**
* Loads a single method from a dex file
*
* @param method
* The method to load
* @param declaringClass
* The class that declares the method to load
* @param annotations
* The worker object for handling annotations
* @param dexMethodFactory
* The factory method for creating dex methods
*/
protected void loadMethod(Method method, SootClass declaringClass, DexAnnotation annotations, DexMethod dexMethodFactory) {
SootMethod sm = dexMethodFactory.makeSootMethod(method);
if (declaringClass.declaresMethod(sm.getName(), sm.getParameterTypes(), sm.getReturnType())) {
return;
}
declaringClass.addMethod(sm);
annotations.handleMethodAnnotation(sm, method);
}
public Dependencies makeSootClass(SootClass sc, ClassDef defItem, DexEntry<? extends DexFile> dexEntry) {
String superClass = defItem.getSuperclass();
Dependencies deps = new Dependencies();
// source file
String sourceFile = defItem.getSourceFile();
if (sourceFile != null) {
sc.addTag(new SourceFileTag(sourceFile));
}
// super class for hierarchy level
if (superClass != null) {
String superClassName = Util.dottedClassName(superClass);
SootClass sootSuperClass = SootResolver.v().makeClassRef(superClassName);
sc.setSuperclass(sootSuperClass);
deps.typesToHierarchy.add(sootSuperClass.getType());
}
// access flags
int accessFlags = defItem.getAccessFlags();
sc.setModifiers(accessFlags);
// Retrieve interface names
if (defItem.getInterfaces() != null) {
for (String interfaceName : defItem.getInterfaces()) {
String interfaceClassName = Util.dottedClassName(interfaceName);
if (sc.implementsInterface(interfaceClassName)) {
continue;
}
SootClass interfaceClass = SootResolver.v().makeClassRef(interfaceClassName);
interfaceClass.setModifiers(interfaceClass.getModifiers() | Modifier.INTERFACE);
sc.addInterface(interfaceClass);
deps.typesToHierarchy.add(interfaceClass.getType());
}
}
if (Options.v().oaat() && sc.resolvingLevel() <= SootClass.HIERARCHY) {
return deps;
}
DexAnnotation da = createDexAnnotation(sc, deps);
// get the fields of the class
for (Field sf : defItem.getStaticFields()) {
loadField(sc, da, sf);
}
for (Field f : defItem.getInstanceFields()) {
loadField(sc, da, f);
}
// get the methods of the class
DexMethod dexMethod = createDexMethodFactory(dexEntry, sc);
for (Method method : defItem.getDirectMethods()) {
loadMethod(method, sc, da, dexMethod);
}
for (Method method : defItem.getVirtualMethods()) {
loadMethod(method, sc, da, dexMethod);
}
da.handleClassAnnotation(defItem);
// In contrast to Java, Dalvik associates the InnerClassAttribute
// with the inner class, not the outer one. We need to copy the
// tags over to correspond to the Soot semantics.
InnerClassAttribute ica = (InnerClassAttribute) sc.getTag(InnerClassAttribute.NAME);
if (ica != null) {
Iterator<InnerClassTag> innerTagIt = ica.getSpecs().iterator();
while (innerTagIt.hasNext()) {
Tag t = innerTagIt.next();
if (t instanceof InnerClassTag) {
InnerClassTag ict = (InnerClassTag) t;
// Get the outer class name
String outer = DexInnerClassParser.getOuterClassNameFromTag(ict);
if (outer == null || outer.length() == 0) {
// If we don't have any clue what the outer class is, we
// just remove the reference entirely
innerTagIt.remove();
continue;
}
// If the tag is already associated with the outer class,
// we leave it as it is
if (outer.equals(sc.getName())) {
continue;
}
// Check the inner class to make sure that this tag actually
// refers to the current class as the inner class
String inner = ict.getInnerClass().replaceAll("/", ".");
if (!inner.equals(sc.getName())) {
innerTagIt.remove();
continue;
}
SootClass osc = SootResolver.v().makeClassRef(outer);
if (osc == sc) {
if (!sc.hasOuterClass()) {
continue;
}
osc = sc.getOuterClass();
} else {
deps.typesToHierarchy.add(osc.getType());
}
// Get the InnerClassAttribute of the outer class
InnerClassAttribute icat = (InnerClassAttribute) osc.getTag(InnerClassAttribute.NAME);
if (icat == null) {
icat = new InnerClassAttribute();
osc.addTag(icat);
}
// Transfer the tag from the inner class to the outer class
icat.add(new InnerClassTag(ict.getInnerClass(), ict.getOuterClass(), ict.getShortName(), ict.getAccessFlags()));
// Remove the tag from the inner class as inner classes do
// not have these tags in the Java / Soot semantics. The
// DexPrinter will copy it back if we do dex->dex.
innerTagIt.remove();
// Add the InnerClassTag to the inner class. This tag will
// be put in an InnerClassAttribute
// within the PackManager in method handleInnerClasses().
if (!sc.hasTag(InnerClassTag.NAME)) {
if (((InnerClassTag) t).getInnerClass().replaceAll("/", ".").equals(sc.toString())) {
sc.addTag(t);
}
}
}
}
// remove tag if empty
if (ica.getSpecs().isEmpty()) {
sc.getTags().remove(ica);
}
}
return deps;
}
/**
* Allow custom implementations to use different dex annotation implementations
*
* @param clazz
* @param deps
* @return
*/
protected DexAnnotation createDexAnnotation(SootClass clazz, Dependencies deps) {
return new DexAnnotation(clazz, deps);
}
/**
* Allow custom implementations to use different dex method factories
*
* @param dexFile
* @param sc
* @return
*/
protected DexMethod createDexMethodFactory(DexEntry<? extends DexFile> dexEntry, SootClass sc) {
return new DexMethod(dexEntry, sc);
}
/**
* Loads a single field from a dex file
*
* @param declaringClass
* The class that declares the method to load
* @param annotations
* The worker object for handling annotations
* @param field
* The field to load
*/
protected void loadField(SootClass declaringClass, DexAnnotation annotations, Field sf) {
if (declaringClass.declaresField(sf.getName(), DexType.toSoot(sf.getType()))) {
return;
}
SootField sootField = DexField.makeSootField(sf);
sootField = declaringClass.getOrAddField(sootField);
annotations.handleFieldAnnotation(sootField, sf);
}
}
| 8,451
| 32.407115
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexDefUseAnalysis.java
|
package soot.dexpler;
/*-
* #%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.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Local;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AssignStmt;
import soot.jimple.DefinitionStmt;
import soot.toolkits.scalar.LocalDefs;
/**
* Simplistic caching, flow-insensitive def/use analysis
*
* @author Steven Arzt
*
*/
public class DexDefUseAnalysis implements LocalDefs {
private final Body body;
private final Map<Local, Set<Unit>> localToUses = new HashMap<Local, Set<Unit>>();
private final Map<Local, Set<Unit>> localToDefs = new HashMap<Local, Set<Unit>>();
private final Map<Local, Set<Unit>> localToDefsWithAliases = new HashMap<Local, Set<Unit>>();
protected Map<Local, Integer> localToNumber = new HashMap<>();
protected BitSet[] localToDefsBits;
protected BitSet[] localToUsesBits;
protected List<Unit> unitList;
public DexDefUseAnalysis(Body body) {
this.body = body;
initialize();
}
protected void initialize() {
int lastLocalNumber = 0;
for (Local l : body.getLocals()) {
localToNumber.put(l, lastLocalNumber++);
}
localToDefsBits = new BitSet[body.getLocalCount()];
localToUsesBits = new BitSet[body.getLocalCount()];
unitList = new ArrayList<>(body.getUnits());
for (int i = 0; i < unitList.size(); i++) {
Unit u = unitList.get(i);
// Record the definitions
if (u instanceof DefinitionStmt) {
Value val = ((DefinitionStmt) u).getLeftOp();
if (val instanceof Local) {
final int localIdx = localToNumber.get((Local) val);
BitSet bs = localToDefsBits[localIdx];
if (bs == null) {
localToDefsBits[localIdx] = bs = new BitSet();
}
bs.set(i);
}
}
// Record the uses
for (ValueBox vb : u.getUseBoxes()) {
Value val = vb.getValue();
if (val instanceof Local) {
final int localIdx = localToNumber.get((Local) val);
BitSet bs = localToUsesBits[localIdx];
if (bs == null) {
localToUsesBits[localIdx] = bs = new BitSet();
}
bs.set(i);
}
}
}
}
public Set<Unit> getUsesOf(Local l) {
Set<Unit> uses = localToUses.get(l);
if (uses == null) {
uses = new HashSet<>();
BitSet bs = localToUsesBits[localToNumber.get(l)];
if (bs != null) {
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
uses.add(unitList.get(i));
}
}
localToUses.put(l, uses);
}
return uses;
}
/**
* Collect definitions of l in body including the definitions of aliases of l. This analysis exploits that the problem is
* flow-insensitive anyway.
*
* In this context an alias is a local that propagates its value to l.
*
* @param l
* the local whose definitions are to collect
*/
protected Set<Unit> collectDefinitionsWithAliases(Local l) {
Set<Unit> defs = localToDefsWithAliases.get(l);
if (defs == null) {
defs = new HashSet<Unit>();
Set<Local> seenLocals = new HashSet<Local>();
List<Local> newLocals = new ArrayList<Local>();
newLocals.add(l);
while (!newLocals.isEmpty()) {
Local curLocal = newLocals.remove(0);
// Definition of l?
BitSet bsDefs = localToDefsBits[localToNumber.get(curLocal)];
if (bsDefs != null) {
for (int i = bsDefs.nextSetBit(0); i >= 0; i = bsDefs.nextSetBit(i + 1)) {
Unit u = unitList.get(i);
defs.add(u);
DefinitionStmt defStmt = (DefinitionStmt) u;
if (defStmt.getRightOp() instanceof Local && seenLocals.add((Local) defStmt.getRightOp())) {
newLocals.add((Local) defStmt.getRightOp());
}
}
}
// Use of l?
BitSet bsUses = localToUsesBits[localToNumber.get(curLocal)];
if (bsUses != null) {
for (int i = bsUses.nextSetBit(0); i >= 0; i = bsUses.nextSetBit(i + 1)) {
Unit use = unitList.get(i);
if (use instanceof AssignStmt) {
AssignStmt assignUse = (AssignStmt) use;
if (assignUse.getRightOp() == curLocal && assignUse.getLeftOp() instanceof Local
&& seenLocals.add((Local) assignUse.getLeftOp())) {
newLocals.add((Local) assignUse.getLeftOp());
}
}
}
}
}
localToDefsWithAliases.put(l, defs);
}
return defs;
}
@Override
public List<Unit> getDefsOfAt(Local l, Unit s) {
return getDefsOf(l);
}
@Override
public List<Unit> getDefsOf(Local l) {
Set<Unit> defs = localToDefs.get(l);
if (defs == null) {
defs = new HashSet<>();
BitSet bs = localToDefsBits[localToNumber.get(l)];
if (bs != null) {
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
Unit u = unitList.get(i);
if (u instanceof DefinitionStmt) {
if (((DefinitionStmt) u).getLeftOp() == l) {
defs.add(u);
}
}
}
}
localToDefs.put(l, defs);
}
return new ArrayList<>(defs);
}
}
| 6,170
| 29.399015
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexField.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.iface.Field;
import org.jf.dexlib2.iface.value.BooleanEncodedValue;
import org.jf.dexlib2.iface.value.ByteEncodedValue;
import org.jf.dexlib2.iface.value.CharEncodedValue;
import org.jf.dexlib2.iface.value.DoubleEncodedValue;
import org.jf.dexlib2.iface.value.EncodedValue;
import org.jf.dexlib2.iface.value.FloatEncodedValue;
import org.jf.dexlib2.iface.value.IntEncodedValue;
import org.jf.dexlib2.iface.value.LongEncodedValue;
import org.jf.dexlib2.iface.value.ShortEncodedValue;
import org.jf.dexlib2.iface.value.StringEncodedValue;
import soot.Scene;
import soot.SootField;
import soot.Type;
import soot.tagkit.DoubleConstantValueTag;
import soot.tagkit.FloatConstantValueTag;
import soot.tagkit.IntegerConstantValueTag;
import soot.tagkit.LongConstantValueTag;
import soot.tagkit.StringConstantValueTag;
import soot.tagkit.Tag;
/**
* This class represents all instance and static fields of a dex class. It holds its name, its modifier, and the type
*/
public class DexField {
private DexField() {
}
/**
* Add constant tag. Should only be called if field is final.
*
* @param df
* @param sf
*/
private static void addConstantTag(SootField df, Field sf) {
Tag tag = null;
EncodedValue ev = sf.getInitialValue();
if (ev instanceof BooleanEncodedValue) {
tag = new IntegerConstantValueTag(((BooleanEncodedValue) ev).getValue() == true ? 1 : 0);
} else if (ev instanceof ByteEncodedValue) {
tag = new IntegerConstantValueTag(((ByteEncodedValue) ev).getValue());
} else if (ev instanceof CharEncodedValue) {
tag = new IntegerConstantValueTag(((CharEncodedValue) ev).getValue());
} else if (ev instanceof DoubleEncodedValue) {
tag = new DoubleConstantValueTag(((DoubleEncodedValue) ev).getValue());
} else if (ev instanceof FloatEncodedValue) {
tag = new FloatConstantValueTag(((FloatEncodedValue) ev).getValue());
} else if (ev instanceof IntEncodedValue) {
tag = new IntegerConstantValueTag(((IntEncodedValue) ev).getValue());
} else if (ev instanceof LongEncodedValue) {
tag = new LongConstantValueTag(((LongEncodedValue) ev).getValue());
} else if (ev instanceof ShortEncodedValue) {
tag = new IntegerConstantValueTag(((ShortEncodedValue) ev).getValue());
} else if (ev instanceof StringEncodedValue) {
tag = new StringConstantValueTag(((StringEncodedValue) ev).getValue());
}
if (tag != null) {
df.addTag(tag);
}
}
/**
*
* @return the Soot equivalent of a field
*/
public static SootField makeSootField(Field f) {
String name = f.getName();
Type type = DexType.toSoot(f.getType());
int flags = f.getAccessFlags();
SootField sf = Scene.v().makeSootField(name, type, flags);
DexField.addConstantTag(sf, f);
return sf;
}
}
| 3,831
| 34.481481
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexFileProvider.java
|
package soot.dexpler;
/*-
* #%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.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.jf.dexlib2.DexFileFactory;
import org.jf.dexlib2.Opcodes;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import org.jf.dexlib2.iface.DexFile;
import org.jf.dexlib2.iface.MultiDexContainer;
import org.jf.dexlib2.iface.MultiDexContainer.DexEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.CompilationDeathException;
import soot.G;
import soot.Scene;
import soot.Singletons;
import soot.options.Options;
/**
* Class providing dex files from a given source, e.g., jar, apk, dex, folder containing multiple dex files
*
* @author Manuel Benz created on 16.10.17
*/
public class DexFileProvider {
private static final Logger logger = LoggerFactory.getLogger(DexFileProvider.class);
private final static Comparator<DexContainer<? extends DexFile>> DEFAULT_PRIORITIZER
= new Comparator<DexContainer<? extends DexFile>>() {
@Override
public int compare(DexContainer<? extends DexFile> o1, DexContainer<? extends DexFile> o2) {
String s1 = o1.getDexName(), s2 = o2.getDexName();
// "classes.dex" has highest priority
if (s1.equals("classes.dex")) {
return 1;
} else if (s2.equals("classes.dex")) {
return -1;
}
// if one of the strings starts with "classes", we give it the edge right here
boolean s1StartsClasses = s1.startsWith("classes");
boolean s2StartsClasses = s2.startsWith("classes");
if (s1StartsClasses && !s2StartsClasses) {
return 1;
} else if (s2StartsClasses && !s1StartsClasses) {
return -1;
}
// otherwise, use natural string ordering
return s1.compareTo(s2);
}
};
/**
* Mapping of filesystem file (apk, dex, etc.) to mapping of dex name to dex file
*/
private final Map<String, Map<String, DexContainer<? extends DexFile>>> dexMap = new HashMap<>();
public DexFileProvider(Singletons.Global g) {
}
public static DexFileProvider v() {
return G.v().soot_dexpler_DexFileProvider();
}
/**
* Returns all dex files found in dex source sorted by the default dex prioritizer
*
* @param dexSource
* Path to a jar, apk, dex, odex or a directory containing multiple dex files
* @return List of dex files derived from source
*/
public List<DexContainer<? extends DexFile>> getDexFromSource(File dexSource) throws IOException {
return getDexFromSource(dexSource, DEFAULT_PRIORITIZER);
}
/**
* Returns all dex files found in dex source sorted by the default dex prioritizer
*
* @param dexSource
* Path to a jar, apk, dex, odex or a directory containing multiple dex files
* @param prioritizer
* A comparator that defines the ordering of dex files in the result list
* @return List of dex files derived from source
*/
public List<DexContainer<? extends DexFile>> getDexFromSource(File dexSource,
Comparator<DexContainer<? extends DexFile>> prioritizer) throws IOException {
ArrayList<DexContainer<? extends DexFile>> resultList = new ArrayList<>();
List<File> allSources = allSourcesFromFile(dexSource);
updateIndex(allSources);
for (File theSource : allSources) {
resultList.addAll(dexMap.get(theSource.getCanonicalPath()).values());
}
if (resultList.size() > 1) {
Collections.sort(resultList, Collections.reverseOrder(prioritizer));
}
return resultList;
}
/**
* Returns the first dex file with the given name found in the given dex source
*
* @param dexSource
* Path to a jar, apk, dex, odex or a directory containing multiple dex files
* @return Dex file with given name in dex source
* @throws CompilationDeathException
* If no dex file with the given name exists
*/
public DexContainer<? extends DexFile> getDexFromSource(File dexSource, String dexName) throws IOException {
List<File> allSources = allSourcesFromFile(dexSource);
updateIndex(allSources);
// we take the first dex we find with the given name
for (File theSource : allSources) {
DexContainer<? extends DexFile> dexFile = dexMap.get(theSource.getCanonicalPath()).get(dexName);
if (dexFile != null) {
return dexFile;
}
}
throw new CompilationDeathException("Dex file with name '" + dexName + "' not found in " + dexSource);
}
private List<File> allSourcesFromFile(File dexSource) throws IOException {
if (dexSource.isDirectory()) {
List<File> dexFiles = getAllDexFilesInDirectory(dexSource);
if (dexFiles.size() > 1 && !Options.v().process_multiple_dex()) {
File file = dexFiles.get(0);
logger.warn("Multiple dex files detected, only processing '" + file.getCanonicalPath()
+ "'. Use '-process-multiple-dex' option to process them all.");
return Collections.singletonList(file);
} else {
return dexFiles;
}
} else {
String ext = com.google.common.io.Files.getFileExtension(dexSource.getName()).toLowerCase();
if ((ext.equals("jar") || ext.equals("zip")) && !Options.v().search_dex_in_archives()) {
return Collections.emptyList();
} else {
return Collections.singletonList(dexSource);
}
}
}
private void updateIndex(List<File> dexSources) throws IOException {
for (File theSource : dexSources) {
String key = theSource.getCanonicalPath();
Map<String, DexContainer<? extends DexFile>> dexFiles = dexMap.get(key);
if (dexFiles == null) {
try {
dexFiles = mappingForFile(theSource);
dexMap.put(key, dexFiles);
} catch (IOException e) {
throw new CompilationDeathException("Error parsing dex source", e);
}
}
}
}
/**
* @param dexSourceFile
* A file containing either one or multiple dex files (apk, zip, etc.) but no directory!
* @return
* @throws IOException
*/
private Map<String, DexContainer<? extends DexFile>> mappingForFile(File dexSourceFile) throws IOException {
int api = Scene.v().getAndroidAPIVersion();
boolean multiple_dex = Options.v().process_multiple_dex();
// load dex files from apk/folder/file
MultiDexContainer<? extends DexBackedDexFile> dexContainer
= DexFileFactory.loadDexContainer(dexSourceFile, Opcodes.forApi(api));
List<String> dexEntryNameList = dexContainer.getDexEntryNames();
int dexFileCount = dexEntryNameList.size();
if (dexFileCount < 1) {
if (Options.v().verbose()) {
logger.debug("" + String.format("Warning: No dex file found in '%s'", dexSourceFile));
}
return Collections.emptyMap();
}
Map<String, DexContainer<? extends DexFile>> dexMap = new HashMap<>(dexFileCount);
// report found dex files and add to list.
// We do this in reverse order to make sure that we add the first entry if there is no classes.dex file in single dex
// mode
ListIterator<String> entryNameIterator = dexEntryNameList.listIterator(dexFileCount);
while (entryNameIterator.hasPrevious()) {
String entryName = entryNameIterator.previous();
DexEntry<? extends DexFile> entry = dexContainer.getEntry(entryName);
entryName = deriveDexName(entryName);
logger.debug("" + String.format("Found dex file '%s' with %d classes in '%s'", entryName,
entry.getDexFile().getClasses().size(), dexSourceFile.getCanonicalPath()));
if (multiple_dex) {
dexMap.put(entryName, new DexContainer<>(entry, entryName, dexSourceFile));
} else if (dexMap.isEmpty() && (entryName.equals("classes.dex") || !entryNameIterator.hasPrevious())) {
// We prefer to have classes.dex in single dex mode.
// If we haven't found a classes.dex until the last element, take the last!
dexMap = Collections.singletonMap(entryName, new DexContainer<>(entry, entryName, dexSourceFile));
if (dexFileCount > 1) {
logger.warn("Multiple dex files detected, only processing '" + entryName
+ "'. Use '-process-multiple-dex' option to process them all.");
}
}
}
return Collections.unmodifiableMap(dexMap);
}
private String deriveDexName(String entryName) {
return new File(entryName).getName();
}
private List<File> getAllDexFilesInDirectory(File path) {
Queue<File> toVisit = new ArrayDeque<File>();
Set<File> visited = new HashSet<File>();
List<File> ret = new ArrayList<File>();
toVisit.add(path);
while (!toVisit.isEmpty()) {
File cur = toVisit.poll();
if (visited.contains(cur)) {
continue;
}
visited.add(cur);
if (cur.isDirectory()) {
toVisit.addAll(Arrays.asList(cur.listFiles()));
} else if (cur.isFile() && cur.getName().endsWith(".dex")) {
ret.add(cur);
}
}
return ret;
}
public static final class DexContainer<T extends DexFile> {
private final DexEntry<T> base;
private final String name;
private final File filePath;
public DexContainer(DexEntry<T> base, String name, File filePath) {
this.base = base;
this.name = name;
this.filePath = filePath;
}
public DexEntry<T> getBase() {
return base;
}
public String getDexName() {
return name;
}
public File getFilePath() {
return filePath;
}
}
}
| 10,639
| 34.348837
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexIfTransformer.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Local;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.Value;
import soot.dexpler.tags.ObjectOpTag;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FieldRef;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.LengthExpr;
import soot.jimple.NeExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.ThrowStmt;
import soot.jimple.internal.AbstractInstanceInvokeExpr;
import soot.jimple.internal.AbstractInvokeExpr;
/**
* BodyTransformer to find and change definition of locals used within an if which contains a condition involving two locals
* ( and not only one local as in DexNullTransformer).
*
* It this case, if any of the two locals leads to an object being def or used, all the appropriate defs of the two locals
* are updated to reflect the use of objects (i.e: 0s are replaced by nulls).
*/
public class DexIfTransformer extends AbstractNullTransformer {
// Note: we need an instance variable for inner class access, treat this as
// a local variable (including initialization before use)
private boolean usedAsObject;
private boolean doBreak = false;
public static DexIfTransformer v() {
return new DexIfTransformer();
}
Local l = null;
@Override
protected void internalTransform(final Body body, String phaseName, Map<String, String> options) {
final DexDefUseAnalysis localDefs = new DexDefUseAnalysis(body);
Set<IfStmt> ifSet = getNullIfCandidates(body);
for (IfStmt ifs : ifSet) {
ConditionExpr ifCondition = (ConditionExpr) ifs.getCondition();
Local[] twoIfLocals = new Local[] { (Local) ifCondition.getOp1(), (Local) ifCondition.getOp2() };
usedAsObject = false;
for (Local loc : twoIfLocals) {
Set<Unit> defs = localDefs.collectDefinitionsWithAliases(loc);
// process normally
doBreak = false;
for (Unit u : defs) {
// put correct local in l
if (u instanceof DefinitionStmt) {
l = (Local) ((DefinitionStmt) u).getLeftOp();
} else {
throw new RuntimeException("ERROR: def can not be something else than Assign or Identity statement! (def: " + u
+ " class: " + u.getClass() + "");
}
// check defs
u.apply(new AbstractStmtSwitch() { // Alex: should also end
// as soon as detected
// as not used as an
// object
@Override
public void caseAssignStmt(AssignStmt stmt) {
Value r = stmt.getRightOp();
if (r instanceof FieldRef) {
usedAsObject = isObject(((FieldRef) r).getFieldRef().type());
if (usedAsObject) {
doBreak = true;
}
return;
} else if (r instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) r;
if (ar.getType() instanceof UnknownType) {
usedAsObject = stmt.hasTag(ObjectOpTag.NAME); // isObject
// (findArrayType
// (g,
// localDefs,
// localUses,
// stmt));
} else {
usedAsObject = isObject(ar.getType());
}
if (usedAsObject) {
doBreak = true;
}
return;
} else if (r instanceof StringConstant || r instanceof NewExpr || r instanceof NewArrayExpr) {
usedAsObject = true;
if (usedAsObject) {
doBreak = true;
}
return;
} else if (r instanceof CastExpr) {
usedAsObject = isObject(((CastExpr) r).getCastType());
if (usedAsObject) {
doBreak = true;
}
return;
} else if (r instanceof InvokeExpr) {
usedAsObject = isObject(((InvokeExpr) r).getType());
if (usedAsObject) {
doBreak = true;
}
return;
} else if (r instanceof LengthExpr) {
usedAsObject = false;
if (usedAsObject) {
doBreak = true;
}
return;
}
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
if (stmt.getLeftOp() == l) {
usedAsObject = isObject(stmt.getRightOp().getType());
if (usedAsObject) {
doBreak = true;
}
return;
}
}
});
if (doBreak) {
break;
}
// check uses
for (Unit use : localDefs.getUsesOf(l)) {
use.apply(new AbstractStmtSwitch() {
private boolean examineInvokeExpr(InvokeExpr e) {
List<Value> args = e.getArgs();
List<Type> argTypes = e.getMethodRef().parameterTypes();
assert args.size() == argTypes.size();
for (int i = 0; i < args.size(); i++) {
if (args.get(i) == l && isObject(argTypes.get(i))) {
return true;
}
}
// check for base
SootMethodRef sm = e.getMethodRef();
if (!sm.isStatic()) {
if (e instanceof AbstractInvokeExpr) {
AbstractInstanceInvokeExpr aiiexpr = (AbstractInstanceInvokeExpr) e;
Value b = aiiexpr.getBase();
if (b == l) {
return true;
}
}
}
return false;
}
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
InvokeExpr e = stmt.getInvokeExpr();
usedAsObject = examineInvokeExpr(e);
if (usedAsObject) {
doBreak = true;
}
return;
}
@Override
public void caseAssignStmt(AssignStmt stmt) {
Value left = stmt.getLeftOp();
Value r = stmt.getRightOp();
if (left instanceof ArrayRef) {
if (((ArrayRef) left).getIndex() == l) {
// doBreak = true;
return;
}
}
// IMPOSSIBLE! WOULD BE DEF!
// // gets value assigned
// if (stmt.getLeftOp() == l) {
// if (r instanceof FieldRef)
// usedAsObject = isObject(((FieldRef)
// r).getFieldRef().type());
// else if (r instanceof ArrayRef)
// usedAsObject = isObject(((ArrayRef)
// r).getType());
// else if (r instanceof StringConstant || r
// instanceof NewExpr || r instanceof
// NewArrayExpr)
// usedAsObject = true;
// else if (r instanceof CastExpr)
// usedAsObject = isObject
// (((CastExpr)r).getCastType());
// else if (r instanceof InvokeExpr)
// usedAsObject = isObject(((InvokeExpr)
// r).getType());
// // introduces alias
// else if (r instanceof Local) {}
//
// }
// used to assign
if (stmt.getRightOp() == l) {
Value l = stmt.getLeftOp();
if (l instanceof StaticFieldRef && isObject(((StaticFieldRef) l).getFieldRef().type())) {
usedAsObject = true;
doBreak = true;
return;
} else if (l instanceof InstanceFieldRef && isObject(((InstanceFieldRef) l).getFieldRef().type())) {
usedAsObject = true;
doBreak = true;
return;
} else if (l instanceof ArrayRef) {
Type aType = ((ArrayRef) l).getType();
if (aType instanceof UnknownType) {
usedAsObject = stmt.hasTag(ObjectOpTag.NAME); // isObject(
// findArrayType(g,
// localDefs,
// localUses,
// stmt));
} else {
usedAsObject = isObject(aType);
}
if (usedAsObject) {
doBreak = true;
}
return;
}
}
// is used as value (does not exclude
// assignment)
if (r instanceof FieldRef) {
usedAsObject = true; // isObject(((FieldRef)
// r).getFieldRef().type());
doBreak = true;
return;
} else if (r instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) r;
if (ar.getBase() == l) {
usedAsObject = true;
doBreak = true;
} else { // used as index
usedAsObject = false;
}
return;
} else if (r instanceof StringConstant || r instanceof NewExpr) {
throw new RuntimeException("NOT POSSIBLE StringConstant or NewExpr at " + stmt);
} else if (r instanceof NewArrayExpr) {
usedAsObject = false;
if (usedAsObject) {
doBreak = true;
}
return;
} else if (r instanceof CastExpr) {
usedAsObject = isObject(((CastExpr) r).getCastType());
if (usedAsObject) {
doBreak = true;
}
return;
} else if (r instanceof InvokeExpr) {
usedAsObject = examineInvokeExpr((InvokeExpr) stmt.getRightOp());
if (usedAsObject) {
doBreak = true;
}
return;
} else if (r instanceof LengthExpr) {
usedAsObject = true;
if (usedAsObject) {
doBreak = true;
}
return;
} else if (r instanceof BinopExpr) {
usedAsObject = false;
if (usedAsObject) {
doBreak = true;
}
return;
}
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
if (stmt.getLeftOp() == l) {
throw new RuntimeException("IMPOSSIBLE 0");
}
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
usedAsObject = stmt.getOp() == l;
if (usedAsObject) {
doBreak = true;
}
return;
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
usedAsObject = stmt.getOp() == l;
if (usedAsObject) {
doBreak = true;
}
return;
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
usedAsObject = stmt.getOp() == l && isObject(body.getMethod().getReturnType());
if (usedAsObject) {
doBreak = true;
}
return;
}
@Override
public void caseThrowStmt(ThrowStmt stmt) {
usedAsObject = stmt.getOp() == l;
if (usedAsObject) {
doBreak = true;
}
return;
}
});
if (doBreak) {
break;
}
} // for uses
if (doBreak) {
break;
}
} // for defs
if (doBreak) {
// all defs from the two locals in the if must
// be updated
break;
}
} // for two locals in if
// change values
if (usedAsObject) {
Set<Unit> defsOp1 = localDefs.collectDefinitionsWithAliases(twoIfLocals[0]);
Set<Unit> defsOp2 = localDefs.collectDefinitionsWithAliases(twoIfLocals[1]);
defsOp1.addAll(defsOp2);
for (Unit u : defsOp1) {
Stmt s = (Stmt) u;
// If we have a[x] = 0 and a is an object, we may not conclude 0 -> null
if (!s.containsArrayRef()
|| (!defsOp1.contains(s.getArrayRef().getBase()) && !defsOp2.contains(s.getArrayRef().getBase()))) {
replaceWithNull(u);
}
Local l = (Local) ((DefinitionStmt) u).getLeftOp();
for (Unit uuse : localDefs.getUsesOf(l)) {
Stmt use = (Stmt) uuse;
// If we have a[x] = 0 and a is an object, we may not conclude 0 -> null
if (!use.containsArrayRef()
|| (twoIfLocals[0] != use.getArrayRef().getBase()) && twoIfLocals[1] != use.getArrayRef().getBase()) {
replaceWithNull(use);
}
}
}
} // end if
} // for if statements
}
/**
* Collect all the if statements comparing two locals with an Eq or Ne expression
*
* @param body
* the body to analyze
*/
private Set<IfStmt> getNullIfCandidates(Body body) {
Set<IfStmt> candidates = new HashSet<IfStmt>();
Iterator<Unit> i = body.getUnits().iterator();
while (i.hasNext()) {
Unit u = i.next();
if (u instanceof IfStmt) {
ConditionExpr expr = (ConditionExpr) ((IfStmt) u).getCondition();
boolean isTargetIf = false;
if (((expr instanceof EqExpr) || (expr instanceof NeExpr))) {
if (expr.getOp1() instanceof Local && expr.getOp2() instanceof Local) {
isTargetIf = true;
}
}
if (isTargetIf) {
candidates.add((IfStmt) u);
}
}
}
return candidates;
}
}
| 16,138
| 34.008677
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexInnerClassParser.java
|
package soot.dexpler;
/*-
* #%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.tagkit.InnerClassTag;
/**
* Utility class for handling inner/outer class references in Dalvik
*
* @author Steven Arzt
*
*/
public class DexInnerClassParser {
/**
* Gets the name of the outer class (in Soot notation) from the given InnerClassTag
*
* @param icTag
* The InnerClassTag from which to read the name of the outer class
* @return The nam,e of the outer class (in Soot notation) as specified in the tag. If the specification is invalid, null
* is returned.
*/
public static String getOuterClassNameFromTag(InnerClassTag icTag) {
String outerClass;
if (icTag.getOuterClass() == null) { // anonymous and local classes
String inner = icTag.getInnerClass().replaceAll("/", ".");
if (inner.contains("$-")) {
/*
* This is a special case for generated lambda classes of jack and jill compiler. Generated lambda classes may
* contain '$' which do not indicate an inner/outer class separator if the '$' occurs after a inner class with a name
* starting with '-'. Thus we search for '$-' and anything after it including '-' is the inner classes name and
* anything before it is the outer classes name.
*/
outerClass = inner.substring(0, inner.indexOf("$-"));
} else if (inner.contains("$")) {
// remove everything after the last '$' including the last '$'
outerClass = inner.substring(0, inner.lastIndexOf('$'));
} else {
// This tag points nowhere
outerClass = null;
}
} else {
outerClass = icTag.getOuterClass().replaceAll("/", ".");
}
return outerClass;
}
}
| 2,515
| 34.43662
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexJumpChainShortener.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Unit;
import soot.jimple.GotoStmt;
import soot.jimple.IfStmt;
/**
* Transformer for reducing goto chains. If there is a chain of jumps in the code before the final target is reached, we
* collapse this chain into a direct jump to the target location.
*
* @author Steven Arzt
*
*/
public class DexJumpChainShortener extends BodyTransformer {
public static DexJumpChainShortener v() {
return new DexJumpChainShortener();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext();) {
Unit u = unitIt.next();
if (u instanceof GotoStmt) {
GotoStmt stmt = (GotoStmt) u;
while (stmt.getTarget() instanceof GotoStmt) {
GotoStmt nextTarget = (GotoStmt) stmt.getTarget();
stmt.setTarget(nextTarget.getTarget());
}
} else if (u instanceof IfStmt) {
IfStmt stmt = (IfStmt) u;
while (stmt.getTarget() instanceof GotoStmt) {
GotoStmt nextTarget = (GotoStmt) stmt.getTarget();
stmt.setTarget(nextTarget.getTarget());
}
}
}
}
}
| 2,130
| 29.884058
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexMethod.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.iface.Annotation;
import org.jf.dexlib2.iface.AnnotationElement;
import org.jf.dexlib2.iface.DexFile;
import org.jf.dexlib2.iface.Method;
import org.jf.dexlib2.iface.MultiDexContainer.DexEntry;
import org.jf.dexlib2.iface.value.ArrayEncodedValue;
import org.jf.dexlib2.iface.value.EncodedValue;
import org.jf.dexlib2.iface.value.TypeEncodedValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.MethodSource;
import soot.Modifier;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.SootResolver;
import soot.Type;
import soot.jimple.Jimple;
import soot.jimple.toolkits.typing.TypeAssigner;
import soot.options.Options;
/**
* DexMethod is a container for all methods that are declared in a class. It holds information about its name, the class it
* belongs to, its access flags, thrown exceptions, the return type and parameter types as well as the encoded method itself.
*
*/
public class DexMethod {
private static final Logger logger = LoggerFactory.getLogger(DexMethod.class);
protected final DexEntry<? extends DexFile> dexEntry;
protected final SootClass declaringClass;
public DexMethod(final DexEntry<? extends DexFile> dexFile, final SootClass declaringClass) {
this.dexEntry = dexFile;
this.declaringClass = declaringClass;
}
/**
* Retrieve the SootMethod equivalent of this method
*
* @return the SootMethod of this method
*/
public SootMethod makeSootMethod(final Method method) {
int accessFlags = method.getAccessFlags();
// get the name of the method
String name = method.getName();
List<SootClass> thrownExceptions = getThrownExceptions(method);
List<Type> parameterTypes = getParameterTypes(method);
// retrieve the return type of this method
Type returnType = DexType.toSoot(method.getReturnType());
// Build soot method by all available parameters
SootMethod sm = declaringClass.getMethodUnsafe(name, parameterTypes, returnType);
if (sm == null) {
sm = Scene.v().makeSootMethod(name, parameterTypes, returnType, accessFlags, thrownExceptions);
}
// if the method is abstract or native, no code needs to be transformed
int flags = method.getAccessFlags();
if (Modifier.isAbstract(flags) || Modifier.isNative(flags)) {
return sm;
}
if (Options.v().oaat() && declaringClass.resolvingLevel() <= SootClass.SIGNATURES) {
return sm;
}
// sets the method source by adding its body as the active body
sm.setSource(createMethodSource(method));
return sm;
}
protected MethodSource createMethodSource(final Method method) {
return new MethodSource() {
@Override
public Body getBody(SootMethod m, String phaseName) {
Body b = Jimple.v().newBody(m);
try {
// add the body of this code item
DexBody dexBody = new DexBody(dexEntry, method, declaringClass.getType());
dexBody.jimplify(b, m);
} catch (InvalidDalvikBytecodeException e) {
String msg = "Warning: Invalid bytecode in method " + m + ": " + e;
logger.debug("" + msg);
Util.emptyBody(b);
Util.addExceptionAfterUnit(b, "java.lang.RuntimeException", b.getUnits().getLast(),
"Soot has detected that this method contains invalid Dalvik bytecode,"
+ " which would have throw an exception at runtime. [" + msg + "]");
TypeAssigner.v().transform(b);
}
m.setActiveBody(b);
return m.getActiveBody();
}
};
}
protected List<Type> getParameterTypes(final Method method) {
// retrieve all parameter types
List<Type> parameterTypes = new ArrayList<Type>();
if (method.getParameters() != null) {
List<? extends CharSequence> parameters = method.getParameterTypes();
for (CharSequence t : parameters) {
Type type = DexType.toSoot(t.toString());
parameterTypes.add(type);
}
}
return parameterTypes;
}
protected List<SootClass> getThrownExceptions(final Method method) {
// the following snippet retrieves all exceptions that this method
// throws by analyzing its annotations
List<SootClass> thrownExceptions = new ArrayList<SootClass>();
for (Annotation a : method.getAnnotations()) {
Type atype = DexType.toSoot(a.getType());
String atypes = atype.toString();
if (!(atypes.equals("dalvik.annotation.Throws"))) {
continue;
}
for (AnnotationElement ae : a.getElements()) {
EncodedValue ev = ae.getValue();
if (ev instanceof ArrayEncodedValue) {
for (EncodedValue evSub : ((ArrayEncodedValue) ev).getValue()) {
if (evSub instanceof TypeEncodedValue) {
TypeEncodedValue valueType = (TypeEncodedValue) evSub;
String exceptionName = valueType.getValue();
String dottedName = Util.dottedClassName(exceptionName);
thrownExceptions.add(SootResolver.v().makeClassRef(dottedName));
}
}
}
}
}
return thrownExceptions;
}
}
| 6,192
| 33.792135
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexNullArrayRefTransformer.java
|
//
// (c) 2012 University of Luxembourg - Interdisciplinary Centre for
// Security Reliability and Trust (SnT) - All rights reserved
//
// Author: Alexandre Bartel
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package soot.dexpler;
/*-
* #%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.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Local;
import soot.RefType;
import soot.Scene;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.DefinitionStmt;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
import soot.jimple.LengthExpr;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.toolkits.scalar.LocalCreation;
import soot.jimple.toolkits.scalar.UnreachableCodeEliminator;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.scalar.LocalDefs;
/**
* If Dalvik bytecode contains statements using a base array which is always null, Soot's fast type resolver will fail with
* the following exception: "Exception in thread " main" java.lang.RuntimeException: Base of array reference is not an
* array!"
*
* Those statements are replaced by a throw statement (this is what will happen in practice if the code is executed).
*
* @author alex
* @author Steven Arzt
*
*/
public class DexNullArrayRefTransformer extends BodyTransformer {
public static DexNullArrayRefTransformer v() {
return new DexNullArrayRefTransformer();
}
protected void internalTransform(final Body body, String phaseName, Map<String, String> options) {
final ExceptionalUnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, DalvikThrowAnalysis.v());
final LocalDefs defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(g);
final LocalCreation lc = Scene.v().createLocalCreation(body.getLocals(), "ex");
boolean changed = false;
for (Iterator<Unit> unitIt = body.getUnits().snapshotIterator(); unitIt.hasNext();) {
Stmt s = (Stmt) unitIt.next();
if (s.containsArrayRef()) {
// Check array reference
Value base = s.getArrayRef().getBase();
if (isAlwaysNullBefore(s, (Local) base, defs)) {
createThrowStmt(body, s, lc);
changed = true;
}
} else if (s instanceof AssignStmt) {
AssignStmt ass = (AssignStmt) s;
Value rightOp = ass.getRightOp();
if (rightOp instanceof LengthExpr) {
// Check lengthof expression
LengthExpr l = (LengthExpr) ass.getRightOp();
Value base = l.getOp();
if (base instanceof IntConstant) {
IntConstant ic = (IntConstant) base;
if (ic.value == 0) {
createThrowStmt(body, s, lc);
changed = true;
}
} else if (base == NullConstant.v() || isAlwaysNullBefore(s, (Local) base, defs)) {
createThrowStmt(body, s, lc);
changed = true;
}
}
}
}
if (changed) {
UnreachableCodeEliminator.v().transform(body);
}
}
/**
* Checks whether the given local is guaranteed to be always null at the given statement
*
* @param s
* The statement at which to check the local
* @param base
* The local to check
* @param defs
* The definition analysis object to use for the check
* @return True if the given local is guaranteed to always be null at the given statement, otherwise false
*/
private boolean isAlwaysNullBefore(Stmt s, Local base, LocalDefs defs) {
List<Unit> baseDefs = defs.getDefsOfAt(base, s);
if (baseDefs.isEmpty()) {
return true;
}
for (Unit u : baseDefs) {
if (!(u instanceof DefinitionStmt)) {
return false;
}
DefinitionStmt defStmt = (DefinitionStmt) u;
if (defStmt.getRightOp() != NullConstant.v()) {
return false;
}
}
return true;
}
/**
* Creates a new statement that throws a NullPointerException
*
* @param body
* The body in which to create the statement
* @param oldStmt
* The old faulty statement that shall be replaced with the exception
* @param lc
* The object for creating new locals
*/
private void createThrowStmt(Body body, Unit oldStmt, LocalCreation lc) {
RefType tp = RefType.v("java.lang.NullPointerException");
Local lcEx = lc.newLocal(tp);
SootMethodRef constructorRef
= Scene.v().makeConstructorRef(tp.getSootClass(), Collections.singletonList((Type) RefType.v("java.lang.String")));
// Create the exception instance
Stmt newExStmt = Jimple.v().newAssignStmt(lcEx, Jimple.v().newNewExpr(tp));
body.getUnits().insertBefore(newExStmt, oldStmt);
Stmt invConsStmt = Jimple.v().newInvokeStmt(Jimple.v().newSpecialInvokeExpr(lcEx, constructorRef,
Collections.singletonList(StringConstant.v("Invalid array reference replaced by Soot"))));
body.getUnits().insertBefore(invConsStmt, oldStmt);
// Throw the exception
body.getUnits().swapWith(oldStmt, Jimple.v().newThrowStmt(lcEx));
}
}
| 6,743
| 34.494737
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexNullIfTransformer.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Unit;
import soot.Value;
import soot.jimple.BinopExpr;
import soot.jimple.IfStmt;
import soot.jimple.IntConstant;
import soot.jimple.NullConstant;
/**
* Transformer that swaps
*
* if null == 0 goto x
*
* with
*
* if null == null goto x
*
* In dex they are the same thing. If we do not do that, soot might assume that the condition is not met and optimize the
* wrong branch away.
*
* @author Marc Miltenberger
*
*/
public class DexNullIfTransformer extends BodyTransformer {
public static DexNullIfTransformer v() {
return new DexNullIfTransformer();
}
private boolean hasModifiedBody;
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
NullConstant nullC = NullConstant.v();
for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext();) {
Unit u = unitIt.next();
if (u instanceof IfStmt) {
IfStmt ifStmt = (IfStmt) u;
Value o = ifStmt.getCondition();
if (o instanceof BinopExpr) {
BinopExpr bop = (BinopExpr) o;
Value l = bop.getOp1();
Value r = bop.getOp2();
if (isNull(l) && isNull(r)) {
if (l instanceof NullConstant || r instanceof NullConstant) {
bop.setOp1(nullC);
bop.setOp2(nullC);
hasModifiedBody = true;
}
}
}
}
}
}
private boolean isNull(Value l) {
if (l instanceof NullConstant) {
return true;
}
if (l instanceof IntConstant && ((IntConstant) l).value == 0) {
return true;
}
return false;
}
public boolean hasModifiedBody() {
return hasModifiedBody;
}
}
| 2,649
| 25.767677
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexNullInstanceofTransformer.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Unit;
import soot.jimple.AssignStmt;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.NullConstant;
/**
* Transformer that swaps
*
* a = 0 instanceof _class_;
*
* with
*
* a = false
*
* @author Steven Arzt
*
*/
public class DexNullInstanceofTransformer extends BodyTransformer {
public static DexNullInstanceofTransformer v() {
return new DexNullInstanceofTransformer();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext();) {
Unit u = unitIt.next();
if (u instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) u;
if (assignStmt.getRightOp() instanceof InstanceOfExpr) {
InstanceOfExpr iof = (InstanceOfExpr) assignStmt.getRightOp();
// If the operand of the "instanceof" expression is null or
// the zero constant, we replace the whole operation with
// its outcome "false"
if (iof.getOp() == NullConstant.v()) {
assignStmt.setRightOp(IntConstant.v(0));
}
if (iof.getOp() instanceof IntConstant && ((IntConstant) iof.getOp()).value == 0) {
assignStmt.setRightOp(IntConstant.v(0));
}
}
}
}
}
}
| 2,306
| 28.576923
| 93
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexNullThrowTransformer.java
|
package soot.dexpler;
/*-
* #%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.Collections;
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Local;
import soot.RefType;
import soot.Scene;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
import soot.jimple.LongConstant;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.ThrowStmt;
import soot.jimple.toolkits.scalar.LocalCreation;
/**
* Some Android applications throw null references, e.g.,
*
* a = null; throw a;
*
* This will make unit graph construction fail as no targets of the throw statement can be found. We therefore replace such
* statements with direct NullPointerExceptions which would happen at runtime anyway.
*
* @author Steven Arzt
*
*/
public class DexNullThrowTransformer extends BodyTransformer {
public static DexNullThrowTransformer v() {
return new DexNullThrowTransformer();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
LocalCreation lc = Scene.v().createLocalCreation(b.getLocals(), "ex");
for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext();) {
Unit u = unitIt.next();
// Check for a null exception
if (u instanceof ThrowStmt) {
ThrowStmt throwStmt = (ThrowStmt) u;
if (throwStmt.getOp() == NullConstant.v() || throwStmt.getOp().equals(IntConstant.v(0))
|| throwStmt.getOp().equals(LongConstant.v(0))) {
createThrowStmt(b, throwStmt, lc);
}
}
}
}
/**
* Creates a new statement that throws a NullPointerException
*
* @param body
* The body in which to create the statement
* @param oldStmt
* The old faulty statement that shall be replaced with the exception
* @param lc
* The object for creating new locals
*/
private void createThrowStmt(Body body, Unit oldStmt, LocalCreation lc) {
RefType tp = RefType.v("java.lang.NullPointerException");
Local lcEx = lc.newLocal(tp);
SootMethodRef constructorRef
= Scene.v().makeConstructorRef(tp.getSootClass(), Collections.singletonList((Type) RefType.v("java.lang.String")));
// Create the exception instance
Stmt newExStmt = Jimple.v().newAssignStmt(lcEx, Jimple.v().newNewExpr(tp));
body.getUnits().insertBefore(newExStmt, oldStmt);
Stmt invConsStmt = Jimple.v().newInvokeStmt(Jimple.v().newSpecialInvokeExpr(lcEx, constructorRef,
Collections.singletonList(StringConstant.v("Null throw statement replaced by Soot"))));
body.getUnits().insertBefore(invConsStmt, oldStmt);
// Throw the exception
body.getUnits().swapWith(oldStmt, Jimple.v().newThrowStmt(lcEx));
}
}
| 3,673
| 32.4
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexNullTransformer.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.ArrayType;
import soot.Body;
import soot.Local;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.Value;
import soot.ValueBox;
import soot.dexpler.tags.ObjectOpTag;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.ClassConstant;
import soot.jimple.ConditionExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FieldRef;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NullConstant;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.ThrowStmt;
import soot.jimple.internal.AbstractInstanceInvokeExpr;
import soot.jimple.internal.AbstractInvokeExpr;
/**
* BodyTransformer to find and change IntConstant(0) to NullConstant where locals are used as objects.
*
* @author Michael Markert
*/
public class DexNullTransformer extends AbstractNullTransformer {
// Note: we need an instance variable for inner class access, treat this as
// a local variable (including initialization before use)
private boolean usedAsObject;
private boolean doBreak = false;
public static DexNullTransformer v() {
return new DexNullTransformer();
}
private Local l = null;
@Override
protected void internalTransform(final Body body, String phaseName, Map<String, String> options) {
final DexDefUseAnalysis localDefs = new DexDefUseAnalysis(body);
AbstractStmtSwitch checkDef = new AbstractStmtSwitch() { // Alex: should also end as
// soon as detected as not
// used as an object
@Override
public void caseAssignStmt(AssignStmt stmt) {
Value r = stmt.getRightOp();
if (r instanceof FieldRef) {
usedAsObject = isObject(((FieldRef) r).getFieldRef().type());
doBreak = true;
return;
} else if (r instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) r;
if (ar.getType() instanceof UnknownType) {
usedAsObject = stmt.hasTag(ObjectOpTag.NAME); // isObject
// (findArrayType
// (g,
// localDefs,
// localUses,
// stmt));
} else {
usedAsObject = isObject(ar.getType());
}
doBreak = true;
return;
} else if (r instanceof StringConstant || r instanceof NewExpr || r instanceof NewArrayExpr
|| r instanceof ClassConstant) {
usedAsObject = true;
doBreak = true;
return;
} else if (r instanceof CastExpr) {
usedAsObject = isObject(((CastExpr) r).getCastType());
doBreak = true;
return;
} else if (r instanceof InvokeExpr) {
usedAsObject = isObject(((InvokeExpr) r).getType());
doBreak = true;
return;
} else if (r instanceof LengthExpr) {
usedAsObject = false;
doBreak = true;
return;
// introduces alias
}
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
if (stmt.getLeftOp() == l) {
usedAsObject = isObject(stmt.getRightOp().getType());
doBreak = true;
return;
}
}
};
AbstractStmtSwitch checkUse = new AbstractStmtSwitch() {
private boolean examineInvokeExpr(InvokeExpr e) {
List<Value> args = e.getArgs();
List<Type> argTypes = e.getMethodRef().parameterTypes();
assert args.size() == argTypes.size();
for (int i = 0; i < args.size(); i++) {
if (args.get(i) == l && isObject(argTypes.get(i))) {
return true;
}
}
// check for base
SootMethodRef sm = e.getMethodRef();
if (!sm.isStatic()) {
if (e instanceof AbstractInvokeExpr) {
AbstractInstanceInvokeExpr aiiexpr = (AbstractInstanceInvokeExpr) e;
Value b = aiiexpr.getBase();
if (b == l) {
return true;
}
}
}
return false;
}
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
InvokeExpr e = stmt.getInvokeExpr();
usedAsObject = examineInvokeExpr(e);
doBreak = true;
return;
}
@Override
public void caseAssignStmt(AssignStmt stmt) {
Value left = stmt.getLeftOp();
Value r = stmt.getRightOp();
if (left instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) left;
if (ar.getIndex() == l) {
doBreak = true;
return;
} else if (ar.getBase() == l) {
usedAsObject = true;
doBreak = true;
return;
}
}
if (left instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) left;
if (ifr.getBase() == l) {
usedAsObject = true;
doBreak = true;
return;
}
}
// used to assign
if (stmt.getRightOp() == l) {
Value l = stmt.getLeftOp();
if (l instanceof StaticFieldRef && isObject(((StaticFieldRef) l).getFieldRef().type())) {
usedAsObject = true;
doBreak = true;
return;
} else if (l instanceof InstanceFieldRef && isObject(((InstanceFieldRef) l).getFieldRef().type())) {
usedAsObject = true;
doBreak = true;
return;
} else if (l instanceof ArrayRef) {
Type aType = ((ArrayRef) l).getType();
if (aType instanceof UnknownType) {
usedAsObject = stmt.hasTag(ObjectOpTag.NAME); // isObject(
// findArrayType(g,
// localDefs,
// localUses,
// stmt));
} else {
usedAsObject = isObject(aType);
}
doBreak = true;
return;
}
}
// is used as value (does not exclude assignment)
if (r instanceof FieldRef) {
usedAsObject = true; // isObject(((FieldRef)
// r).getFieldRef().type());
doBreak = true;
return;
} else if (r instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) r;
if (ar.getBase() == l) {
usedAsObject = true;
} else { // used as index
usedAsObject = false;
}
doBreak = true;
return;
} else if (r instanceof StringConstant || r instanceof NewExpr) {
throw new RuntimeException("NOT POSSIBLE StringConstant or NewExpr at " + stmt);
} else if (r instanceof NewArrayExpr) {
usedAsObject = false;
doBreak = true;
return;
} else if (r instanceof CastExpr) {
usedAsObject = isObject(((CastExpr) r).getCastType());
doBreak = true;
return;
} else if (r instanceof InvokeExpr) {
usedAsObject = examineInvokeExpr((InvokeExpr) stmt.getRightOp());
doBreak = true;
return;
} else if (r instanceof LengthExpr) {
usedAsObject = true;
doBreak = true;
return;
} else if (r instanceof BinopExpr) {
usedAsObject = false;
doBreak = true;
return;
}
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
if (stmt.getLeftOp() == l) {
throw new RuntimeException("IMPOSSIBLE 0");
}
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
usedAsObject = stmt.getOp() == l;
doBreak = true;
return;
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
usedAsObject = stmt.getOp() == l;
doBreak = true;
return;
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
usedAsObject = stmt.getOp() == l && isObject(body.getMethod().getReturnType());
doBreak = true;
return;
}
@Override
public void caseThrowStmt(ThrowStmt stmt) {
usedAsObject = stmt.getOp() == l;
doBreak = true;
return;
}
};
for (Local loc : getNullCandidates(body)) {
usedAsObject = false;
Set<Unit> defs = localDefs.collectDefinitionsWithAliases(loc);
// process normally
doBreak = false;
for (Unit u : defs) {
// put correct local in l
if (u instanceof DefinitionStmt) {
l = (Local) ((DefinitionStmt) u).getLeftOp();
} else if (u instanceof IfStmt) {
throw new RuntimeException("ERROR: def can not be something else than Assign or Identity statement! (def: " + u
+ " class: " + u.getClass() + "");
}
// check defs
u.apply(checkDef);
if (doBreak) {
break;
}
// check uses
for (Unit use : localDefs.getUsesOf(l)) {
use.apply(checkUse);
if (doBreak) {
break;
}
} // for uses
if (doBreak) {
break;
}
} // for defs
// change values
if (usedAsObject) {
for (Unit u : defs) {
replaceWithNull(u);
Set<Value> defLocals = new HashSet<Value>();
for (ValueBox vb : u.getDefBoxes()) {
defLocals.add(vb.getValue());
}
Local l = (Local) ((DefinitionStmt) u).getLeftOp();
for (Unit uuse : localDefs.getUsesOf(l)) {
Stmt use = (Stmt) uuse;
// If we have a[x] = 0 and a is an object, we may not conclude 0 -> null
if (!use.containsArrayRef() || !defLocals.contains(use.getArrayRef().getBase())) {
replaceWithNull(use);
}
}
}
} // end if
}
// Check for inlined zero values
AbstractStmtSwitch inlinedZeroValues = new AbstractStmtSwitch() {
final NullConstant nullConstant = NullConstant.v();
Set<Value> objects = null;
@Override
public void caseAssignStmt(AssignStmt stmt) {
// Case a = 0 with a being an object
if (isObject(stmt.getLeftOp().getType()) && isConstZero(stmt.getRightOp())) {
stmt.setRightOp(nullConstant);
return;
}
// Case a = (Object) 0
if (stmt.getRightOp() instanceof CastExpr) {
CastExpr ce = (CastExpr) stmt.getRightOp();
if (isObject(ce.getCastType()) && isConstZero(ce.getOp())) {
stmt.setRightOp(nullConstant);
}
}
// Case a[0] = 0
if (stmt.getLeftOp() instanceof ArrayRef && isConstZero(stmt.getRightOp())) {
ArrayRef ar = (ArrayRef) stmt.getLeftOp();
if (objects == null) {
objects = getObjectArray(body);
}
if (objects.contains(ar.getBase()) || stmt.hasTag(ObjectOpTag.NAME)) {
stmt.setRightOp(nullConstant);
}
}
}
private boolean isConstZero(Value rightOp) {
if (rightOp instanceof IntConstant && ((IntConstant) rightOp).value == 0) {
return true;
}
if (rightOp instanceof LongConstant && ((LongConstant) rightOp).value == 0) {
return true;
}
return false;
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
if (stmt.getOp() instanceof IntConstant && isObject(body.getMethod().getReturnType())) {
IntConstant iconst = (IntConstant) stmt.getOp();
assert iconst.value == 0;
stmt.setOp(nullConstant);
}
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
if (stmt.getOp() instanceof IntConstant && ((IntConstant) stmt.getOp()).value == 0) {
stmt.setOp(nullConstant);
}
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
if (stmt.getOp() instanceof IntConstant && ((IntConstant) stmt.getOp()).value == 0) {
stmt.setOp(nullConstant);
}
}
};
final NullConstant nullConstant = NullConstant.v();
for (Unit u : body.getUnits()) {
u.apply(inlinedZeroValues);
if (u instanceof Stmt) {
Stmt stmt = (Stmt) u;
if (stmt.containsInvokeExpr()) {
InvokeExpr invExpr = stmt.getInvokeExpr();
for (int i = 0; i < invExpr.getArgCount(); i++) {
if (isObject(invExpr.getMethodRef().parameterType(i))) {
if (invExpr.getArg(i) instanceof IntConstant) {
IntConstant iconst = (IntConstant) invExpr.getArg(i);
assert iconst.value == 0;
invExpr.setArg(i, nullConstant);
}
}
}
}
}
}
}
private static Set<Value> getObjectArray(Body body) {
Set<Value> objArrays = new HashSet<Value>();
for (Unit u : body.getUnits()) {
if (u instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) u;
if (assign.getRightOp() instanceof NewArrayExpr) {
NewArrayExpr nea = (NewArrayExpr) assign.getRightOp();
if (isObject(nea.getBaseType())) {
objArrays.add(assign.getLeftOp());
}
} else if (assign.getRightOp() instanceof FieldRef) {
FieldRef fr = (FieldRef) assign.getRightOp();
if (fr.getType() instanceof ArrayType) {
if (isObject(((ArrayType) fr.getType()).getArrayElementType())) {
objArrays.add(assign.getLeftOp());
}
}
}
}
}
return objArrays;
}
/**
* Collect all the locals which are assigned a IntConstant(0) or are used within a zero comparison.
*
* @param body
* the body to analyze
*/
private Set<Local> getNullCandidates(Body body) {
Set<Local> candidates = null;
for (Unit u : body.getUnits()) {
if (u instanceof AssignStmt) {
AssignStmt a = (AssignStmt) u;
if (!(a.getLeftOp() instanceof Local)) {
continue;
}
Local l = (Local) a.getLeftOp();
Value r = a.getRightOp();
if ((r instanceof IntConstant && ((IntConstant) r).value == 0)
|| (r instanceof LongConstant && ((LongConstant) r).value == 0)) {
if (candidates == null) {
candidates = new HashSet<Local>();
}
candidates.add(l);
}
} else if (u instanceof IfStmt) {
ConditionExpr expr = (ConditionExpr) ((IfStmt) u).getCondition();
if (isZeroComparison(expr) && expr.getOp1() instanceof Local) {
if (candidates == null) {
candidates = new HashSet<Local>();
}
candidates.add((Local) expr.getOp1());
}
}
}
return candidates == null ? Collections.<Local>emptySet() : candidates;
}
}
| 16,435
| 30.668593
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexNumTransformer.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.DoubleType;
import soot.FloatType;
import soot.Local;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.Value;
import soot.dexpler.tags.DoubleOpTag;
import soot.dexpler.tags.FloatOpTag;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.CmpExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.DoubleConstant;
import soot.jimple.FieldRef;
import soot.jimple.FloatConstant;
import soot.jimple.IdentityStmt;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.NewArrayExpr;
import soot.jimple.ReturnStmt;
/**
* BodyTransformer to find and change initialization type of Jimple variables. Dalvik bytecode does not provide enough
* information regarding the type of initialized variables. For instance, using the dexdump disassembler on some Dalvik
* bytecode can produce the following (wrong) output:
*
* 006c : const -wide v6 , #double 0.000000 // #0014404410000000 0071: and-long /2 addr v6 , v4
*
* At 0x6c, the initialized register is not of type double, but of type long because it is used in a long and operation at
* 0x71. Thus, one need to check how the register is used to deduce its type. By default, and since the dexdump disassembler
* does not perform such analysis, it supposes the register is of type double.
*
* Dalvik comes with the following instructions to initialize constants: 0x12 const/4 vx,lit4 0x13 const/16 vx,lit16 0x14
* const vx, lit32 0x15 const/high16 v0, lit16 0x16 const-wide/16 vx, lit16 0x17 const-wide/32 vx, lit32 0x18 const-wide vx,
* lit64 0x19 const-wide/high16 vx,lit16 0x1A const-string vx,string id 0x1B const-string-jumbo vx,string 0x1C const-class
* vx,type id
*
* Instructions 0x12, 0x1A, 0x1B, 0x1C can not produce wrong initialized registers. The other instructions are converted to
* the following Jimple statement: JAssignStmt ( Local, rightValue ). Since at the time of the statement creation the no
* analysis can be performed, a default type is given to rightValue. This default type is "int" for registers whose size is
* less or equal to 32bits and "long" to registers whose size is 64bits. The problem is that 32bits registers could be either
* "int" or "float" and 64bits registers "long" or "double". If the analysis concludes that an "int" has to be changed to a
* "float", rightValue has to change from IntConstant.v(literal) to Float.intBitsToFloat((int) literal). If the analysis
* concludes that an "long" has to be changed to a "double, rightValue has to change from LongConstant.v(literal) to
* DoubleConstant.v(Double.longBitsToDouble(literal)).
*/
public class DexNumTransformer extends DexTransformer {
// Note: we need an instance variable for inner class access, treat this as
// a local variable (including initialization before use)
private boolean usedAsFloatingPoint;
boolean doBreak = false;
public static DexNumTransformer v() {
return new DexNumTransformer();
}
@Override
protected void internalTransform(final Body body, String phaseName, Map<String, String> options) {
final DexDefUseAnalysis localDefs = new DexDefUseAnalysis(body);
for (Local loc : getNumCandidates(body)) {
usedAsFloatingPoint = false;
Set<Unit> defs = localDefs.collectDefinitionsWithAliases(loc);
// process normally
doBreak = false;
for (Unit u : defs) {
// put correct local in l
final Local l = u instanceof DefinitionStmt ? (Local) ((DefinitionStmt) u).getLeftOp() : null;
// check defs
u.apply(new AbstractStmtSwitch() {
@Override
public void caseAssignStmt(AssignStmt stmt) {
Value r = stmt.getRightOp();
if (r instanceof BinopExpr && !(r instanceof CmpExpr)) {
usedAsFloatingPoint = examineBinopExpr(stmt);
doBreak = true;
} else if (r instanceof FieldRef) {
usedAsFloatingPoint = isFloatingPointLike(((FieldRef) r).getFieldRef().type());
doBreak = true;
} else if (r instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) r;
Type t = nae.getType();
usedAsFloatingPoint = isFloatingPointLike(t);
doBreak = true;
} else if (r instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) r;
Type arType = ar.getType();
if (arType instanceof UnknownType) {
Type t = findArrayType(localDefs, stmt, 0, Collections.<Unit>emptySet()); // TODO:
// check
// where
// else
// to
// update
// if(ArrayRef...
usedAsFloatingPoint = isFloatingPointLike(t);
} else {
usedAsFloatingPoint = isFloatingPointLike(ar.getType());
}
doBreak = true;
} else if (r instanceof CastExpr) {
usedAsFloatingPoint = isFloatingPointLike(((CastExpr) r).getCastType());
doBreak = true;
} else if (r instanceof InvokeExpr) {
usedAsFloatingPoint = isFloatingPointLike(((InvokeExpr) r).getType());
doBreak = true;
} else if (r instanceof LengthExpr) {
usedAsFloatingPoint = false;
doBreak = true;
}
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
if (stmt.getLeftOp() == l) {
usedAsFloatingPoint = isFloatingPointLike(stmt.getRightOp().getType());
doBreak = true;
}
}
});
if (doBreak) {
break;
}
// check uses
for (Unit use : localDefs.getUsesOf(l)) {
use.apply(new AbstractStmtSwitch() {
private boolean examineInvokeExpr(InvokeExpr e) {
List<Value> args = e.getArgs();
List<Type> argTypes = e.getMethodRef().parameterTypes();
assert args.size() == argTypes.size();
for (int i = 0; i < args.size(); i++) {
if (args.get(i) == l && isFloatingPointLike(argTypes.get(i))) {
return true;
}
}
return false;
}
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
InvokeExpr e = stmt.getInvokeExpr();
usedAsFloatingPoint = examineInvokeExpr(e);
}
@Override
public void caseAssignStmt(AssignStmt stmt) {
// only case where 'l' could be on the left side is
// arrayRef with 'l' as the index
Value left = stmt.getLeftOp();
if (left instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) left;
if (ar.getIndex() == l) {
doBreak = true;
return;
}
}
// from this point, we only check the right hand
// side of the assignment
Value r = stmt.getRightOp();
if (r instanceof ArrayRef) {
if (((ArrayRef) r).getIndex() == l) {
doBreak = true;
return;
}
} else if (r instanceof InvokeExpr) {
usedAsFloatingPoint = examineInvokeExpr((InvokeExpr) r);
doBreak = true;
return;
} else if (r instanceof BinopExpr) {
usedAsFloatingPoint = examineBinopExpr(stmt);
doBreak = true;
return;
} else if (r instanceof CastExpr) {
usedAsFloatingPoint = stmt.hasTag(FloatOpTag.NAME) || stmt.hasTag(DoubleOpTag.NAME);
doBreak = true;
return;
} else if (r instanceof Local && r == l) {
if (left instanceof FieldRef) {
FieldRef fr = (FieldRef) left;
if (isFloatingPointLike(fr.getType())) {
usedAsFloatingPoint = true;
}
doBreak = true;
return;
} else if (left instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) left;
Type arType = ar.getType();
if (arType instanceof UnknownType) {
arType = findArrayType(localDefs, stmt, 0, Collections.<Unit>emptySet());
}
usedAsFloatingPoint = isFloatingPointLike(arType);
doBreak = true;
return;
}
}
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
usedAsFloatingPoint = stmt.getOp() == l && isFloatingPointLike(body.getMethod().getReturnType());
doBreak = true;
return;
}
});
if (doBreak) {
break;
}
} // for uses
if (doBreak) {
break;
}
} // for defs
// change values
if (usedAsFloatingPoint) {
for (Unit u : defs) {
replaceWithFloatingPoint(u);
}
} // end if
}
}
protected boolean examineBinopExpr(Unit u) {
return u.hasTag(FloatOpTag.NAME) || u.hasTag(DoubleOpTag.NAME);
}
private boolean isFloatingPointLike(Type t) {
return (t instanceof FloatType || t instanceof DoubleType);
}
/**
* Collect all the locals which are assigned a IntConstant(0) or are used within a zero comparison.
*
* @param body
* the body to analyze
*/
private Set<Local> getNumCandidates(Body body) {
Set<Local> candidates = new HashSet<Local>();
for (Unit u : body.getUnits()) {
if (u instanceof AssignStmt) {
AssignStmt a = (AssignStmt) u;
if (!(a.getLeftOp() instanceof Local)) {
continue;
}
Local l = (Local) a.getLeftOp();
Value r = a.getRightOp();
if ((r instanceof IntConstant || r instanceof LongConstant)) {
candidates.add(l);
}
}
}
return candidates;
}
/**
* Replace 0 with null in the given unit.
*
* @param u
* the unit where 0 will be replaced with null.
*/
private void replaceWithFloatingPoint(Unit u) {
if (u instanceof AssignStmt) {
AssignStmt s = (AssignStmt) u;
Value v = s.getRightOp();
if ((v instanceof IntConstant)) {
int vVal = ((IntConstant) v).value;
s.setRightOp(FloatConstant.v(Float.intBitsToFloat(vVal)));
} else if (v instanceof LongConstant) {
long vVal = ((LongConstant) v).value;
s.setRightOp(DoubleConstant.v(Double.longBitsToDouble(vVal)));
}
}
}
}
| 12,169
| 36.331288
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexRefsChecker.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Local;
import soot.Scene;
import soot.SootClass;
import soot.SootField;
import soot.Type;
import soot.Unit;
import soot.jimple.FieldRef;
import soot.jimple.Stmt;
/**
*/
public class DexRefsChecker extends DexTransformer {
// Note: we need an instance variable for inner class access, treat this as
// a local variable (including initialization before use)
public static DexRefsChecker v() {
return new DexRefsChecker();
}
Local l = null;
@Override
protected void internalTransform(final Body body, String phaseName, @SuppressWarnings("rawtypes") Map options) {
// final ExceptionalUnitGraph g = new ExceptionalUnitGraph(body);
// final SmartLocalDefs localDefs = new SmartLocalDefs(g, new
// SimpleLiveLocals(g));
// final SimpleLocalUses localUses = new SimpleLocalUses(g, localDefs);
for (Unit u : getRefCandidates(body)) {
Stmt s = (Stmt) u;
boolean hasField = false;
FieldRef fr = null;
SootField sf = null;
if (s.containsFieldRef()) {
fr = s.getFieldRef();
sf = fr.getField();
if (sf != null) {
hasField = true;
}
} else {
throw new RuntimeException("Unit '" + u + "' does not contain array ref nor field ref.");
}
if (!hasField) {
System.out.println("Warning: add missing field '" + fr + "' to class!");
SootClass sc = null;
String frStr = fr.toString();
if (frStr.contains(".<")) {
sc = Scene.v().getSootClass(frStr.split(".<")[1].split(" ")[0].split(":")[0]);
} else {
sc = Scene.v().getSootClass(frStr.split(":")[0].replaceAll("^<", ""));
}
String fname = fr.toString().split(">")[0].split(" ")[2];
int modifiers = soot.Modifier.PUBLIC;
Type ftype = fr.getType();
sc.addField(Scene.v().makeSootField(fname, ftype, modifiers));
} else {
// System.out.println("field "+ sf.getName() +" '"+ sf +"'
// phantom: "+ isPhantom +" declared: "+ isDeclared);
}
} // for if statements
}
/**
* Collect all the if statements comparing two locals with an Eq or Ne expression
*
* @param body
* the body to analyze
*/
private Set<Unit> getRefCandidates(Body body) {
Set<Unit> candidates = new HashSet<Unit>();
Iterator<Unit> i = body.getUnits().iterator();
while (i.hasNext()) {
Unit u = i.next();
Stmt s = (Stmt) u;
if (s.containsFieldRef()) {
candidates.add(u);
}
}
return candidates;
}
}
| 3,672
| 29.355372
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexResolver.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.util.Map;
import java.util.TreeMap;
import soot.G;
import soot.Singletons;
import soot.SootClass;
import soot.javaToJimple.IInitialResolver.Dependencies;
import soot.tagkit.SourceFileTag;
public class DexResolver {
protected Map<File, DexlibWrapper> cache = new TreeMap<File, DexlibWrapper>();
public DexResolver(Singletons.Global g) {
}
public static DexResolver v() {
return G.v().soot_dexpler_DexResolver();
}
/**
* Resolve the class contained in file into the passed soot class.
*
* @param file
* the path to the dex/apk file to resolve
* @param className
* the name of the class to resolve
* @param sc
* the soot class that will represent the class
* @return the dependencies of this class.
*/
public Dependencies resolveFromFile(File file, String className, SootClass sc) {
DexlibWrapper wrapper = initializeDexFile(file);
Dependencies deps = wrapper.makeSootClass(sc, className);
addSourceFileTag(sc, "dalvik_source_" + file.getName());
return deps;
}
/**
* Initializes the dex wrapper for the given dex file
*
* @param file
* The dex file to load
* @return The wrapper object for the given dex file
*/
protected DexlibWrapper initializeDexFile(File file) {
DexlibWrapper wrapper = cache.get(file);
if (wrapper == null) {
wrapper = new DexlibWrapper(file);
cache.put(file, wrapper);
wrapper.initialize();
}
return wrapper;
}
/**
* adds source file tag to each sootclass
*/
protected static void addSourceFileTag(SootClass sc, String fileName) {
soot.tagkit.SourceFileTag tag = null;
if (sc.hasTag(SourceFileTag.NAME)) {
return; // do not add tag if original class already has debug
// information
} else {
tag = new soot.tagkit.SourceFileTag();
sc.addTag(tag);
}
tag.setSourceFile(fileName);
}
}
| 2,957
| 28
| 82
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexReturnInliner.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Trap;
import soot.Unit;
import soot.UnitBox;
import soot.jimple.GotoStmt;
import soot.jimple.IfStmt;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
/**
* BodyTransformer to inline jumps to return statements. Take the following code: a = b goto label1
*
* label1: return a We inline this to produce a = b return b
*
* @author Steven Arzt
*/
public class DexReturnInliner extends DexTransformer {
public static DexReturnInliner v() {
return new DexReturnInliner();
}
private boolean isInstanceofReturn(Unit u) {
if (u instanceof ReturnStmt || u instanceof ReturnVoidStmt) {
return true;
}
return false;
}
private boolean isInstanceofFlowChange(Unit u) {
if (u instanceof GotoStmt || isInstanceofReturn(u)) {
return true;
}
return false;
}
@Override
protected void internalTransform(final Body body, String phaseName, Map<String, String> options) {
Set<Unit> duplicateIfTargets = getFallThroughReturns(body);
Iterator<Unit> it = body.getUnits().snapshotIterator();
boolean mayBeMore = false;
Unit last = null;
do {
mayBeMore = false;
while (it.hasNext()) {
Unit u = it.next();
if (u instanceof GotoStmt) {
GotoStmt gtStmt = (GotoStmt) u;
if (isInstanceofReturn(gtStmt.getTarget())) {
Stmt stmt = (Stmt) gtStmt.getTarget().clone();
for (Trap t : body.getTraps()) {
for (UnitBox ubox : t.getUnitBoxes()) {
if (ubox.getUnit() == u) {
ubox.setUnit(stmt);
}
}
}
while (!u.getBoxesPointingToThis().isEmpty()) {
u.getBoxesPointingToThis().get(0).setUnit(stmt);
}
// the cloned return stmt gets the tags of u
stmt.addAllTagsOf(u);
body.getUnits().swapWith(u, stmt);
mayBeMore = true;
}
} else if (u instanceof IfStmt) {
IfStmt ifstmt = (IfStmt) u;
Unit t = ifstmt.getTarget();
if (isInstanceofReturn(t)) {
// We only copy this return if it is used more than
// once, otherwise we will end up with unused copies
if (duplicateIfTargets == null) {
duplicateIfTargets = new HashSet<Unit>();
}
if (!duplicateIfTargets.add(t)) {
Unit newTarget = (Unit) t.clone();
body.getUnits().addLast(newTarget);
ifstmt.setTarget(newTarget);
}
}
} else if (isInstanceofReturn(u)) {
// the original return stmt gets the tags of its predecessor
if (last != null) {
u.removeAllTags();
u.addAllTagsOf(last);
}
}
last = u;
}
} while (mayBeMore);
}
/**
* Gets the set of return statements that can be reached via fall-throughs, i.e. normal sequential code execution. Dually,
* these are the statements that can be reached without jumping there.
*
* @param body
* The method body
* @return The set of fall-through return statements
*/
private Set<Unit> getFallThroughReturns(Body body) {
Set<Unit> fallThroughReturns = null;
Unit lastUnit = null;
for (Unit u : body.getUnits()) {
if (lastUnit != null && isInstanceofReturn(u) && !isInstanceofFlowChange(lastUnit)) {
if (fallThroughReturns == null) {
fallThroughReturns = new HashSet<Unit>();
}
fallThroughReturns.add(u);
}
lastUnit = u;
}
return fallThroughReturns;
}
}
| 4,776
| 29.426752
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexReturnPacker.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Unit;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
/**
* This transformer is the inverse of the DexReturnInliner. It looks for unnecessary duplicates of return statements and
* removes them.
*
* @author Steven Arzt
*
*/
public class DexReturnPacker extends BodyTransformer {
public static DexReturnPacker v() {
return new DexReturnPacker();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
// Look for consecutive return statements
Unit lastUnit = null;
for (Iterator<Unit> unitIt = b.getUnits().iterator(); unitIt.hasNext();) {
Unit curUnit = unitIt.next();
if (curUnit instanceof ReturnStmt || curUnit instanceof ReturnVoidStmt) {
// Check for duplicates
if (lastUnit != null && isEqual(lastUnit, curUnit)) {
curUnit.redirectJumpsToThisTo(lastUnit);
unitIt.remove();
} else {
lastUnit = curUnit;
}
} else {
// Start over
lastUnit = null;
}
}
}
/**
* Checks whether the two given units are semantically equal
*
* @param unit1
* The first unit
* @param unit2
* The second unit
* @return True if the two given units are semantically equal, otherwise false
*/
private boolean isEqual(Unit unit1, Unit unit2) {
// Trivial case
if (unit1 == unit2 || unit1.equals(unit2)) {
return true;
}
// Semantic check
if (unit1.getClass() == unit2.getClass()) {
if (unit1 instanceof ReturnVoidStmt) {
return true;
} else if (unit1 instanceof ReturnStmt) {
return ((ReturnStmt) unit1).getOp() == ((ReturnStmt) unit2).getOp();
}
}
return false;
}
}
| 2,717
| 27.020619
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexReturnValuePropagator.java
|
package soot.dexpler;
/*-
* #%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.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Local;
import soot.Scene;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.ReturnStmt;
import soot.jimple.toolkits.scalar.LocalCreation;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.LocalDefs;
import soot.toolkits.scalar.LocalUses;
public class DexReturnValuePropagator extends BodyTransformer {
public static DexReturnValuePropagator v() {
return new DexReturnValuePropagator();
}
@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
ExceptionalUnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, DalvikThrowAnalysis.v(), true);
LocalDefs localDefs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(graph);
LocalUses localUses = null;
LocalCreation localCreation = null;
// If a return statement's operand has only one definition and this is
// a copy statement, we take the original operand
for (Unit u : body.getUnits()) {
if (u instanceof ReturnStmt) {
ReturnStmt retStmt = (ReturnStmt) u;
if (retStmt.getOp() instanceof Local) {
List<Unit> defs = localDefs.getDefsOfAt((Local) retStmt.getOp(), retStmt);
if (defs.size() == 1 && defs.get(0) instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) defs.get(0);
final Value rightOp = assign.getRightOp();
final Value leftOp = assign.getLeftOp();
// Copy over the left side if it is a local
if (rightOp instanceof Local) {
// We must make sure that the definition we propagate to
// the return statement is not overwritten in between
// a = 1; b = a; a = 3; return b; may not be translated
// to return a;
if (!isRedefined((Local) rightOp, u, assign, graph)) {
retStmt.setOp(rightOp);
}
} else if (rightOp instanceof Constant) {
retStmt.setOp(rightOp);
}
// If this is a field access which has no other uses,
// we rename the local to help splitting
else if (rightOp instanceof FieldRef) {
if (localUses == null) {
localUses = LocalUses.Factory.newLocalUses(body, localDefs);
}
if (localUses.getUsesOf(assign).size() == 1) {
if (localCreation == null) {
localCreation = Scene.v().createLocalCreation(body.getLocals(), "ret");
}
Local newLocal = localCreation.newLocal(leftOp.getType());
assign.setLeftOp(newLocal);
retStmt.setOp(newLocal);
}
}
}
}
}
}
}
/**
* Checks whether the given local has been redefined between the original definition unitDef and the use unitUse.
*
* @param l
* The local for which to check for redefinitions
* @param unitUse
* The unit that uses the local
* @param unitDef
* The unit that defines the local
* @param graph
* The unit graph to use for the check
* @return True if there is at least one path between unitDef and unitUse on which local l gets redefined, otherwise false
*/
private boolean isRedefined(Local l, Unit unitUse, AssignStmt unitDef, UnitGraph graph) {
List<Unit> workList = new ArrayList<Unit>();
workList.add(unitUse);
Set<Unit> doneSet = new HashSet<Unit>();
// Check for redefinitions of the local between definition and use
while (!workList.isEmpty()) {
Unit curStmt = workList.remove(0);
if (!doneSet.add(curStmt)) {
continue;
}
for (Unit u : graph.getPredsOf(curStmt)) {
if (u != unitDef) {
if (u instanceof DefinitionStmt) {
DefinitionStmt defStmt = (DefinitionStmt) u;
if (defStmt.getLeftOp() == l) {
return true;
}
}
workList.add(u);
}
}
}
return false;
}
}
| 5,329
| 34.533333
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexTransformer.java
|
//
// (c) 2012 University of Luxembourg - Interdisciplinary Centre for
// Security Reliability and Trust (SnT) - All rights reserved
//
// Author: Alexandre Bartel
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package soot.dexpler;
/*-
* #%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.HashSet;
import java.util.List;
import java.util.Set;
import soot.ArrayType;
import soot.Body;
import soot.BodyTransformer;
import soot.Local;
import soot.NullType;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.Constant;
import soot.jimple.FieldRef;
import soot.jimple.IdentityStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.Stmt;
import soot.toolkits.scalar.LocalDefs;
import soot.toolkits.scalar.LocalUses;
import soot.toolkits.scalar.UnitValueBoxPair;
public abstract class DexTransformer extends BodyTransformer {
/**
* Collect definitions of l in body including the definitions of aliases of l.
*
* In this context an alias is a local that propagates its value to l.
*
* @param l
* the local whose definitions are to collect
* @param localDefs
* the LocalDefs object
* @param body
* the body that contains the local
*/
protected List<Unit> collectDefinitionsWithAliases(Local l, LocalDefs localDefs, LocalUses localUses, Body body) {
Set<Local> seenLocals = new HashSet<Local>();
List<Local> newLocals = new ArrayList<Local>();
List<Unit> defs = new ArrayList<Unit>();
newLocals.add(l);
seenLocals.add(l);
while (!newLocals.isEmpty()) {
Local local = newLocals.remove(0);
for (Unit u : collectDefinitions(local, localDefs)) {
if (u instanceof AssignStmt) {
Value r = ((AssignStmt) u).getRightOp();
if (r instanceof Local && seenLocals.add((Local) r)) {
newLocals.add((Local) r);
}
}
defs.add(u);
//
List<UnitValueBoxPair> usesOf = localUses.getUsesOf(u);
for (UnitValueBoxPair pair : usesOf) {
Unit unit = pair.getUnit();
if (unit instanceof AssignStmt) {
AssignStmt assignStmt = ((AssignStmt) unit);
Value right = assignStmt.getRightOp();
Value left = assignStmt.getLeftOp();
if (right == local && left instanceof Local && seenLocals.add((Local) left)) {
newLocals.add((Local) left);
}
}
}
//
}
}
return defs;
}
/**
* Convenience method that collects all definitions of l.
*
* @param l
* the local whose definitions are to collect
* @param localDefs
* the LocalDefs object
* @param body
* the body that contains the local
*/
private List<Unit> collectDefinitions(Local l, LocalDefs localDefs) {
return localDefs.getDefsOf(l);
}
protected Type findArrayType(LocalDefs localDefs, Stmt arrayStmt, int depth, Set<Unit> alreadyVisitedDefs) {
ArrayRef aRef = null;
if (arrayStmt.containsArrayRef()) {
aRef = arrayStmt.getArrayRef();
}
Local aBase = null;
if (null == aRef) {
if (arrayStmt instanceof AssignStmt) {
AssignStmt stmt = (AssignStmt) arrayStmt;
aBase = (Local) stmt.getRightOp();
} else {
throw new RuntimeException("ERROR: not an assign statement: " + arrayStmt);
}
} else {
aBase = (Local) aRef.getBase();
}
List<Unit> defsOfaBaseList = localDefs.getDefsOfAt(aBase, arrayStmt);
if (defsOfaBaseList == null || defsOfaBaseList.isEmpty()) {
throw new RuntimeException("ERROR: no def statement found for array base local " + arrayStmt);
}
// We should find an answer only by processing the first item of the
// list
Type aType = null;
int nullDefCount = 0;
for (Unit baseDef : defsOfaBaseList) {
if (alreadyVisitedDefs.contains(baseDef)) {
continue;
}
Set<Unit> newVisitedDefs = new HashSet<Unit>(alreadyVisitedDefs);
newVisitedDefs.add(baseDef);
// baseDef is either an assignment statement or an identity
// statement
if (baseDef instanceof AssignStmt) {
AssignStmt stmt = (AssignStmt) baseDef;
Value r = stmt.getRightOp();
if (r instanceof FieldRef) {
Type t = ((FieldRef) r).getFieldRef().type();
if (t instanceof ArrayType) {
ArrayType at = (ArrayType) t;
t = at.getArrayElementType();
}
if (depth == 0) {
aType = t;
break;
} else {
return t;
}
} else if (r instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) r;
if (ar.getType().toString().equals(".unknown") || ar.getType().toString().equals("unknown")) { // ||
// ar.getType())
// {
Type t = findArrayType(localDefs, stmt, ++depth, newVisitedDefs); // TODO: which type should be
// returned?
if (t instanceof ArrayType) {
ArrayType at = (ArrayType) t;
t = at.getArrayElementType();
}
if (depth == 0) {
aType = t;
break;
} else {
return t;
}
} else {
ArrayType at = (ArrayType) stmt.getRightOp().getType();
Type t = at.getArrayElementType();
if (depth == 0) {
aType = t;
break;
} else {
return t;
}
}
} else if (r instanceof NewExpr) {
NewExpr expr = (NewExpr) r;
Type t = expr.getBaseType();
if (depth == 0) {
aType = t;
break;
} else {
return t;
}
} else if (r instanceof NewArrayExpr) {
NewArrayExpr expr = (NewArrayExpr) r;
Type t = expr.getBaseType();
if (depth == 0) {
aType = t;
break;
} else {
return t;
}
} else if (r instanceof CastExpr) {
Type t = (((CastExpr) r).getCastType());
if (t instanceof ArrayType) {
ArrayType at = (ArrayType) t;
t = at.getArrayElementType();
}
if (depth == 0) {
aType = t;
break;
} else {
return t;
}
} else if (r instanceof InvokeExpr) {
Type t = ((InvokeExpr) r).getMethodRef().returnType();
if (t instanceof ArrayType) {
ArrayType at = (ArrayType) t;
t = at.getArrayElementType();
}
if (depth == 0) {
aType = t;
break;
} else {
return t;
}
// introduces alias. We look whether there is any type
// information associated with the alias.
} else if (r instanceof Local) {
Type t = findArrayType(localDefs, stmt, ++depth, newVisitedDefs);
if (depth == 0) {
aType = t;
// break;
} else {
// return t;
aType = t;
}
} else if (r instanceof Constant) {
// If the right side is a null constant, we might have a
// case of broken code, e.g.,
// a = null;
// a[12] = 42;
nullDefCount++;
} else {
throw new RuntimeException(String.format("ERROR: def statement not possible! Statement: %s, right side: %s",
stmt.toString(), r.getClass().getName()));
}
} else if (baseDef instanceof IdentityStmt) {
IdentityStmt stmt = (IdentityStmt) baseDef;
Type t = stmt.getRightOp().getType();
if (t instanceof ArrayType) {
ArrayType at = (ArrayType) t;
t = at.getArrayElementType();
}
if (depth == 0) {
aType = t;
break;
} else {
return t;
}
} else {
throw new RuntimeException("ERROR: base local def must be AssignStmt or IdentityStmt! " + baseDef);
}
if (aType != null) {
break;
}
} // loop
if (depth == 0 && aType == null) {
if (nullDefCount == defsOfaBaseList.size()) {
return NullType.v();
} else {
throw new RuntimeException("ERROR: could not find type of array from statement '" + arrayStmt + "'");
}
} else {
return aType;
}
}
}
| 10,050
| 31.214744
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexTrapStackFixer.java
|
package soot.dexpler;
/*-
* #%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.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Local;
import soot.Scene;
import soot.Trap;
import soot.Unit;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.IdentityStmt;
import soot.jimple.Jimple;
import soot.jimple.Stmt;
/**
* Transformer to ensure that all exception handlers pull the exception object. In other words, if an exception handler must
* always have a unit like
*
* $r10 = @caughtexception
*
* This is especially important if the dex code is later to be translated into Java bytecode. If no one ever accesses the
* exception object, it will reside on the stack forever, potentially leading to mismatching stack heights.
*
* @author Steven Arzt
*
*/
public class DexTrapStackFixer extends BodyTransformer {
public static DexTrapStackFixer v() {
return new DexTrapStackFixer();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
for (Trap t : b.getTraps()) {
// If the first statement already catches the exception, we're fine
if (isCaughtExceptionRef(t.getHandlerUnit())) {
continue;
}
// Add the exception reference
Local l = Scene.v().createLocalGenerator(b).generateLocal(t.getException().getType());
Stmt caughtStmt = Jimple.v().newIdentityStmt(l, Jimple.v().newCaughtExceptionRef());
b.getUnits().add(caughtStmt);
b.getUnits().add(Jimple.v().newGotoStmt(t.getHandlerUnit()));
t.setHandlerUnit(caughtStmt);
}
}
/**
* Checks whether the given statement stores an exception reference
*
* @param handlerUnit
* The statement to check
* @return True if the given statement stores an exception reference, otherwise false
*/
private boolean isCaughtExceptionRef(Unit handlerUnit) {
if (!(handlerUnit instanceof IdentityStmt)) {
return false;
}
IdentityStmt stmt = (IdentityStmt) handlerUnit;
return stmt.getRightOp() instanceof CaughtExceptionRef;
}
}
| 2,856
| 31.101124
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexType.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.iface.reference.TypeReference;
import org.jf.dexlib2.immutable.reference.ImmutableTypeReference;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.RefType;
import soot.ShortType;
import soot.Type;
import soot.UnknownType;
import soot.VoidType;
/**
* Wrapper for a dexlib TypeIdItem.
*
*/
public class DexType {
protected String name;
protected TypeReference type;
public DexType(TypeReference type) {
if (type == null) {
throw new RuntimeException("error: type ref is null!");
}
this.type = type;
this.name = type.getType();
}
public DexType(String type) {
if (type == null) {
throw new RuntimeException("error: type is null!");
}
this.type = new ImmutableTypeReference(type);
this.name = type;
}
public String getName() {
return name;
}
public boolean overwriteEquivalent(DexType field) {
return name.equals(field.getName());
}
public TypeReference getType() {
return type;
}
/**
* Return the appropriate Soot Type for this DexType.
*
* @return the Soot Type
*/
public Type toSoot() {
return toSoot(type.getType(), 0);
}
/**
* Return the appropriate Soot Type for the given TypeReference.
*
* @param type
* the TypeReference to convert
* @return the Soot Type
*/
public static Type toSoot(TypeReference type) {
return toSoot(type.getType(), 0);
}
public static Type toSoot(String type) {
return toSoot(type, 0);
}
/**
* Return if the given TypeIdItem is wide (i.e. occupies 2 registers).
*
* @param typeReference.getType()
* the TypeIdItem to analyze
* @return if type is wide
*/
public static boolean isWide(TypeReference typeReference) {
String t = typeReference.getType();
return isWide(t);
}
public static boolean isWide(String type) {
return type.startsWith("J") || type.startsWith("D");
}
/**
* Determine the soot type from a byte code type descriptor.
*
*/
private static Type toSoot(String typeDescriptor, int pos) {
Type type;
char typeDesignator = typeDescriptor.charAt(pos);
// see https://code.google.com/p/smali/wiki/TypesMethodsAndFields
switch (typeDesignator) {
case 'Z': // boolean
type = BooleanType.v();
break;
case 'B': // byte
type = ByteType.v();
break;
case 'S': // short
type = ShortType.v();
break;
case 'C': // char
type = CharType.v();
break;
case 'I': // int
type = IntType.v();
break;
case 'J': // long
type = LongType.v();
break;
case 'F': // float
type = FloatType.v();
break;
case 'D': // double
type = DoubleType.v();
break;
case 'L': // object
type = RefType.v(Util.dottedClassName(typeDescriptor));
break;
case 'V': // void
type = VoidType.v();
break;
case '[': // array
type = toSoot(typeDescriptor, pos + 1).makeArrayType();
break;
default:
type = UnknownType.v();
}
return type;
}
/**
* Seems that representation of Annotation type in Soot is not consistent with the normal type representation. Normal type
* representation would be a.b.c.ClassName Java bytecode representation is La/b/c/ClassName; Soot Annotation type
* representation (and Jasmin's) is a/b/c/ClassName.
*
* This method transforms the Java bytecode representation into the Soot annotation type representation.
*
* Ljava/lang/Class<Ljava/lang/Enum<*>;>; becomes java/lang/Class<java/lang/Enum<*>>
*
* @param type
* @param pos
* @return
*/
public static String toSootICAT(String type) {
type = type.replace(".", "/");
String r = "";
String[] split1 = type.split(";");
for (String s : split1) {
if (s.startsWith("L")) {
s = s.replaceFirst("L", "");
}
if (s.startsWith("<L")) {
s = s.replaceFirst("<L", "<");
}
r += s;
}
return r;
}
public static String toDalvikICAT(String type) {
type = type.replaceAll("<", "<L");
type = type.replaceAll(">", ">;");
type = "L" + type; // a class name cannot be a primitive
type = type.replaceAll("L\\*;", "*");
if (!type.endsWith(";")) {
type += ";";
}
return type;
}
/**
* Types read from annotations should be converted to Soot type. However, to maintain compatibility with Soot code most
* type will not be converted.
*
* @param type
* @return
*/
public static String toSootAT(String type) {
return type;
}
@Override
public String toString() {
return name;
}
}
| 5,844
| 24.413043
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DexlibWrapper.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import org.jf.dexlib2.dexbacked.reference.DexBackedTypeReference;
import org.jf.dexlib2.iface.ClassDef;
import org.jf.dexlib2.iface.DexFile;
import org.jf.dexlib2.iface.MultiDexContainer.DexEntry;
import soot.ArrayType;
import soot.CompilationDeathException;
import soot.PrimType;
import soot.Scene;
import soot.SootClass;
import soot.SootResolver;
import soot.Type;
import soot.VoidType;
import soot.javaToJimple.IInitialResolver.Dependencies;
/**
* DexlibWrapper provides an entry point to the dexlib library from the smali project. Given a dex file, it will use dexlib
* to retrieve all classes for further processing A call to getClass retrieves the specific class to analyze further.
*/
public class DexlibWrapper {
private final static Set<String> systemAnnotationNames;
static {
Set<String> systemAnnotationNamesModifiable = new HashSet<String>();
// names as defined in the ".dex - Dalvik Executable Format" document
systemAnnotationNamesModifiable.add("dalvik.annotation.AnnotationDefault");
systemAnnotationNamesModifiable.add("dalvik.annotation.EnclosingClass");
systemAnnotationNamesModifiable.add("dalvik.annotation.EnclosingMethod");
systemAnnotationNamesModifiable.add("dalvik.annotation.InnerClass");
systemAnnotationNamesModifiable.add("dalvik.annotation.MemberClasses");
systemAnnotationNamesModifiable.add("dalvik.annotation.Signature");
systemAnnotationNamesModifiable.add("dalvik.annotation.Throws");
systemAnnotationNames = Collections.unmodifiableSet(systemAnnotationNamesModifiable);
}
private final DexClassLoader dexLoader = createDexClassLoader();
private static class ClassInformation {
public DexEntry<? extends DexFile> dexEntry;
public ClassDef classDefinition;
public ClassInformation(DexEntry<? extends DexFile> entry, ClassDef classDef) {
this.dexEntry = entry;
this.classDefinition = classDef;
}
}
private final Map<String, ClassInformation> classesToDefItems = new HashMap<String, ClassInformation>();
private final Collection<DexEntry<? extends DexFile>> dexFiles;
/**
* Construct a DexlibWrapper from a dex file and stores its classes referenced by their name. No further process is done
* here.
*/
public DexlibWrapper(File dexSource) {
try {
List<DexFileProvider.DexContainer<? extends DexFile>> containers = DexFileProvider.v().getDexFromSource(dexSource);
this.dexFiles = new ArrayList<>(containers.size());
for (DexFileProvider.DexContainer<? extends DexFile> container : containers) {
this.dexFiles.add(container.getBase());
}
} catch (IOException e) {
throw new CompilationDeathException("IOException during dex parsing", e);
}
}
/**
* Allow custom implementations to use different class loading strategies. Do not remove this method.
*
* @return
*/
protected DexClassLoader createDexClassLoader() {
return new DexClassLoader();
}
public void initialize() {
// resolve classes in dex files
for (DexEntry<? extends DexFile> dexEntry : dexFiles) {
final DexFile dexFile = dexEntry.getDexFile();
for (ClassDef defItem : dexFile.getClasses()) {
String forClassName = Util.dottedClassName(defItem.getType());
classesToDefItems.put(forClassName, new ClassInformation(dexEntry, defItem));
}
}
// It is important to first resolve the classes, otherwise we will
// produce an error during type resolution.
for (DexEntry<? extends DexFile> dexEntry : dexFiles) {
final DexFile dexFile = dexEntry.getDexFile();
if (dexFile instanceof DexBackedDexFile) {
for (DexBackedTypeReference typeRef : ((DexBackedDexFile) dexFile).getTypeReferences()) {
String t = typeRef.getType();
Type st = DexType.toSoot(t);
if (st instanceof ArrayType) {
st = ((ArrayType) st).baseType;
}
String sootTypeName = st.toString();
if (!Scene.v().containsClass(sootTypeName)) {
if (st instanceof PrimType || st instanceof VoidType || systemAnnotationNames.contains(sootTypeName)) {
// dex files contain references to the Type IDs of void
// primitive types - we obviously do not want them
// to be resolved
/*
* dex files contain references to the Type IDs of the system annotations. They are only visible to the Dalvik
* VM (for reflection, see vm/reflect/Annotations.cpp), and not to the user - so we do not want them to be
* resolved.
*/
continue;
}
SootResolver.v().makeClassRef(sootTypeName);
}
SootResolver.v().resolveClass(sootTypeName, SootClass.SIGNATURES);
}
}
}
}
public Dependencies makeSootClass(SootClass sc, String className) {
if (Util.isByteCodeClassName(className)) {
className = Util.dottedClassName(className);
}
ClassInformation defItem = classesToDefItems.get(className);
if (defItem != null) {
return dexLoader.makeSootClass(sc, defItem.classDefinition, defItem.dexEntry);
}
throw new RuntimeException("Error: class not found in DEX files: " + className);
}
}
| 6,579
| 36.816092
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/DvkTyperBase.java
|
//
// (c) 2012 University of Luxembourg - Interdisciplinary Centre for
// Security Reliability and Trust (SnT) - All rights reserved
//
// Author: Alexandre Bartel
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package soot.dexpler;
/*-
* #%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.ValueBox;
public abstract class DvkTyperBase {
public static boolean ENABLE_DVKTYPER = false;
public abstract void setType(ValueBox v, Type type);
public abstract void setObjectType(ValueBox v);
public abstract void setConstraint(ValueBox box1, ValueBox box2);
abstract void assignType();
public static DvkTyperBase getDvkTyper() {
// TODO Auto-generated method stub
return null;
}
}
| 2,126
| 32.234375
| 78
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/IDalvikTyper.java
|
//
// (c) 2012 University of Luxembourg - Interdisciplinary Centre for
// Security Reliability and Trust (SnT) - All rights reserved
//
// Author: Alexandre Bartel
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package soot.dexpler;
/*-
* #%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.Body;
import soot.Type;
import soot.ValueBox;
public interface IDalvikTyper {
public static final boolean ENABLE_DVKTYPER = false;
public static boolean DEBUG = false;
public abstract void setType(ValueBox v, Type type, boolean isUse);
// public abstract void setObjectType(ValueBox v);
public abstract void addConstraint(ValueBox box1, ValueBox box2);
// public abstract void addStrongConstraint(ValueBox vb, Type t);
abstract void assignType(Body b);
// public static IDalvikTyper getDvkTyper();
// public Stmt captureAssign(JAssignStmt stmt, int current);
}
| 2,280
| 34.640625
| 78
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/InvalidDalvikBytecodeException.java
|
package soot.dexpler;
/*-
* #%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%
*/
public class InvalidDalvikBytecodeException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -1932386032493767303L;
public InvalidDalvikBytecodeException(String msg) {
super(msg);
}
}
| 1,079
| 28.189189
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/TrapMinimizer.java
|
package soot.dexpler;
/*-
* #%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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Singletons;
import soot.Trap;
import soot.Unit;
import soot.jimple.Jimple;
import soot.options.Options;
import soot.toolkits.exceptions.TrapTransformer;
import soot.toolkits.graph.ExceptionalGraph.ExceptionDest;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
/**
* Transformer that splits traps for Dalvik whenever a statements within the trap cannot reach the trap's handler.
*
* Before: trap from label1 to label2 with handler
*
* label1: stmt1 ----> handler stmt2 stmt3 ----> handler label2:
*
* After: trap from label1 to label2 with handler trap from label3 to label4 with handler
*
* label1: stmt1 ----> handler label2: stmt2 label3: stmt3 ----> handler label4:
*
* @author Alexandre Bartel
*/
public class TrapMinimizer extends TrapTransformer {
public TrapMinimizer(Singletons.Global g) {
}
public static TrapMinimizer v() {
return soot.G.v().soot_dexpler_TrapMinimizer();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
// If we have less then two traps, there's nothing to do here
if (b.getTraps().size() == 0) {
return;
}
ExceptionalUnitGraph eug = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b, DalvikThrowAnalysis.v(),
Options.v().omit_excepting_unit_edges());
Set<Unit> unitsWithMonitor = getUnitsWithMonitor(eug);
Map<Trap, List<Trap>> replaceTrapBy = new HashMap<Trap, List<Trap>>(b.getTraps().size());
boolean updateTrap = false;
for (Trap tr : b.getTraps()) {
List<Trap> newTraps = new ArrayList<Trap>(); // will contain the new
// traps
Unit firstTrapStmt = tr.getBeginUnit(); // points to the first unit
// in the trap
boolean goesToHandler = false; // true if there is an edge from the
// unit to the handler of the
// current trap
updateTrap = false;
for (Unit u = tr.getBeginUnit(); u != tr.getEndUnit(); u = b.getUnits().getSuccOf(u)) {
if (goesToHandler) {
goesToHandler = false;
} else {
// if the previous unit has no exceptional edge to the
// handler,
// update firstTrapStmt to point to the current unit
firstTrapStmt = u;
}
// If this is the catch-all block and the current unit has an,
// active monitor, we need to keep the block
if (tr.getException().getName().equals("java.lang.Throwable") && unitsWithMonitor.contains(u)) {
goesToHandler = true;
}
// check if the current unit has an edge to the current trap's
// handler
if (!goesToHandler) {
if (DalvikThrowAnalysis.v().mightThrow(u).catchableAs(tr.getException().getType())) {
// We need to be careful here. The ExceptionalUnitGraph
// will
// always give us an edge from the predecessor of the
// excepting
// unit to the handler. This predecessor, however, does
// not need
// to be inside the new minimized catch block.
for (ExceptionDest<Unit> ed : eug.getExceptionDests(u)) {
if (ed.getTrap() == tr) {
goesToHandler = true;
break;
}
}
}
}
if (!goesToHandler) {
// if the current unit does not have an edge to the current
// trap's handler,
// add a new trap starting at firstTrapStmt ending at the
// unit before the
// current unit 'u'.
updateTrap = true;
if (firstTrapStmt == u) {
// updateTrap to true
continue;
}
Trap t = Jimple.v().newTrap(tr.getException(), firstTrapStmt, u, tr.getHandlerUnit());
newTraps.add(t);
} else {
// if the current unit has an edge to the current trap's
// handler,
// add a trap if the current trap has been updated before
// and if the
// next unit is outside the current trap.
if (b.getUnits().getSuccOf(u) == tr.getEndUnit() && updateTrap) {
Trap t = Jimple.v().newTrap(tr.getException(), firstTrapStmt, tr.getEndUnit(), tr.getHandlerUnit());
newTraps.add(t);
}
}
}
// if updateTrap is true, the current trap has to be replaced by the
// set of newly created traps
// (this set can be empty if the trap covers only instructions that
// cannot throw any exceptions)
if (updateTrap) {
replaceTrapBy.put(tr, newTraps);
}
}
// replace traps where necessary
for (Trap k : replaceTrapBy.keySet()) {
b.getTraps().insertAfter(replaceTrapBy.get(k), k); // we must keep
// the order
b.getTraps().remove(k);
}
}
}
| 5,858
| 34.295181
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/Util.java
|
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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.Arrays;
import java.util.Collections;
import java.util.List;
import soot.ArrayType;
import soot.Body;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Local;
import soot.LocalGenerator;
import soot.LongType;
import soot.RefType;
import soot.Scene;
import soot.ShortType;
import soot.Type;
import soot.Unit;
import soot.VoidType;
import soot.jimple.AssignStmt;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IdentityStmt;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
import soot.jimple.LongConstant;
import soot.jimple.NullConstant;
import soot.jimple.ParameterRef;
import soot.jimple.StringConstant;
import soot.jimple.ThisRef;
import soot.jimple.toolkits.scalar.LocalCreation;
public class Util {
/**
* Return the dotted class name of a type descriptor, i.e. change Ljava/lang/Object; to java.lang.Object.
*
* @raises IllegalArgumentException if classname is not of the form Lpath; or [Lpath;
* @return the dotted name.
*/
public static String dottedClassName(String typeDescriptor) {
if (!isByteCodeClassName(typeDescriptor)) {
// typeDescriptor may not be a class but something like "[[[[[[[[J"
String t = typeDescriptor;
int idx = 0;
while (idx < t.length() && t.charAt(idx) == '[') {
idx++;
}
String c = t.substring(idx);
if (c.length() == 1 && (c.startsWith("I") || c.startsWith("B") || c.startsWith("C") || c.startsWith("S")
|| c.startsWith("J") || c.startsWith("D") || c.startsWith("F") || c.startsWith("Z"))) {
Type ty = getType(t);
return ty == null ? "" : getType(t).toString();
}
throw new IllegalArgumentException("typeDescriptor is not a class typedescriptor: '" + typeDescriptor + "'");
}
String t = typeDescriptor;
int idx = 0;
while (idx < t.length() && t.charAt(idx) == '[') {
idx++;
}
// Debug.printDbg("t ", t ," idx ", idx);
String className = typeDescriptor.substring(idx);
className = className.substring(className.indexOf('L') + 1, className.indexOf(';'));
className = className.replace('/', '.');
// for (int i = 0; i<idx; i++) {
// className += "[]";
// }
return className;
}
public static Type getType(String type) {
int idx = 0;
int arraySize = 0;
Type returnType = null;
boolean notFound = true;
while (idx < type.length() && notFound) {
switch (type.charAt(idx)) {
case '[':
while (idx < type.length() && type.charAt(idx) == '[') {
arraySize++;
idx++;
}
continue;
// break;
case 'L':
String objectName = type.replaceAll("^[^L]*L", "").replaceAll(";$", "");
returnType = RefType.v(objectName.replace("/", "."));
notFound = false;
break;
case 'J':
returnType = LongType.v();
notFound = false;
break;
case 'S':
returnType = ShortType.v();
notFound = false;
break;
case 'D':
returnType = DoubleType.v();
notFound = false;
break;
case 'I':
returnType = IntType.v();
notFound = false;
break;
case 'F':
returnType = FloatType.v();
notFound = false;
break;
case 'B':
returnType = ByteType.v();
notFound = false;
break;
case 'C':
returnType = CharType.v();
notFound = false;
break;
case 'V':
returnType = VoidType.v();
notFound = false;
break;
case 'Z':
returnType = BooleanType.v();
notFound = false;
break;
default:
throw new RuntimeException("unknown type: '" + type + "'");
}
idx++;
}
if (returnType != null && arraySize > 0) {
returnType = ArrayType.v(returnType, arraySize);
}
return returnType;
}
/**
* Check if passed class name is a byte code classname.
*
* @param className
* the classname to check.
*/
public static boolean isByteCodeClassName(String className) {
return ((className.startsWith("L") || className.startsWith("[")) && className.endsWith(";")
&& ((className.indexOf('/') != -1 || className.indexOf('.') == -1)));
}
/**
* Concatenate two arrays.
*
* @param first
* first array
* @param second
* second array.
*/
public static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
/**
* Returns if the type is a floating point type.
*
* @param t
* the type to test
*/
public static boolean isFloatLike(Type t) {
return t.equals(FloatType.v()) || t.equals(DoubleType.v()) || t.equals(RefType.v("java.lang.Float"))
|| t.equals(RefType.v("java.lang.Double"));
}
/**
* Remove all statements except from IdentityStatements for parameters. Return default value (null or zero or nothing
* depending on the return type).
*
* @param jBody
*/
public static void emptyBody(Body jBody) {
// identity statements
List<Unit> idStmts = new ArrayList<Unit>();
List<Local> idLocals = new ArrayList<Local>();
for (Unit u : jBody.getUnits()) {
if (u instanceof IdentityStmt) {
IdentityStmt i = (IdentityStmt) u;
if (i.getRightOp() instanceof ParameterRef || i.getRightOp() instanceof ThisRef) {
idStmts.add(u);
idLocals.add((Local) i.getLeftOp());
}
}
}
jBody.getUnits().clear();
jBody.getLocals().clear();
jBody.getTraps().clear();
final LocalGenerator lg = Scene.v().createLocalGenerator(jBody);
for (Unit u : idStmts) {
jBody.getUnits().add(u);
}
for (Local l : idLocals) {
jBody.getLocals().add(l);
}
Type rType = jBody.getMethod().getReturnType();
jBody.getUnits().add(Jimple.v().newNopStmt());
if (rType instanceof VoidType) {
jBody.getUnits().add(Jimple.v().newReturnVoidStmt());
} else {
Type t = jBody.getMethod().getReturnType();
Local l = lg.generateLocal(t);
AssignStmt ass = null;
if (t instanceof RefType || t instanceof ArrayType) {
ass = Jimple.v().newAssignStmt(l, NullConstant.v());
} else if (t instanceof LongType) {
ass = Jimple.v().newAssignStmt(l, LongConstant.v(0));
} else if (t instanceof FloatType) {
ass = Jimple.v().newAssignStmt(l, FloatConstant.v(0.0f));
} else if (t instanceof IntType) {
ass = Jimple.v().newAssignStmt(l, IntConstant.v(0));
} else if (t instanceof DoubleType) {
ass = Jimple.v().newAssignStmt(l, DoubleConstant.v(0));
} else if (t instanceof BooleanType || t instanceof ByteType || t instanceof CharType || t instanceof ShortType) {
ass = Jimple.v().newAssignStmt(l, IntConstant.v(0));
} else {
throw new RuntimeException("error: return type unknown: " + t + " class: " + t.getClass());
}
jBody.getUnits().add(ass);
jBody.getUnits().add(Jimple.v().newReturnStmt(l));
}
}
/**
* Insert a runtime exception before unit u of body b. Useful to analyze broken code (which make reference to inexisting
* class for instance) exceptionType: e.g., "java.lang.RuntimeException"
*/
public static void addExceptionAfterUnit(Body b, String exceptionType, Unit u, String m) {
LocalCreation lc = Scene.v().createLocalCreation(b.getLocals());
Local l = lc.newLocal(RefType.v(exceptionType));
List<Unit> newUnits = new ArrayList<Unit>();
Unit u1 = Jimple.v().newAssignStmt(l, Jimple.v().newNewExpr(RefType.v(exceptionType)));
Unit u2
= Jimple.v()
.newInvokeStmt(Jimple.v().newSpecialInvokeExpr(l,
Scene.v().makeMethodRef(Scene.v().getSootClass(exceptionType), "<init>",
Collections.singletonList((Type) RefType.v("java.lang.String")), VoidType.v(), false),
StringConstant.v(m)));
Unit u3 = Jimple.v().newThrowStmt(l);
newUnits.add(u1);
newUnits.add(u2);
newUnits.add(u3);
b.getUnits().insertBefore(newUnits, u);
}
public static List<String> splitParameters(String parameters) {
List<String> pList = new ArrayList<String>();
int idx = 0;
boolean object = false;
String curr = "";
while (idx < parameters.length()) {
char c = parameters.charAt(idx);
curr += c;
switch (c) {
// array
case '[':
break;
// end of object
case ';':
object = false;
pList.add(curr);
curr = "";
break;
// start of object
case 'L':
object = true;
break;
default:
if (object) {
// caracter part of object
} else { // primitive
pList.add(curr);
curr = "";
}
break;
}
idx++;
}
return pList;
}
}
| 10,331
| 28.775216
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/AgetInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.OneRegisterInstruction;
import org.jf.dexlib2.iface.instruction.formats.Instruction23x;
import soot.IntType;
import soot.Local;
import soot.dexpler.DexBody;
import soot.dexpler.IDalvikTyper;
import soot.dexpler.InvalidDalvikBytecodeException;
import soot.dexpler.tags.ObjectOpTag;
import soot.dexpler.typing.DalvikTyper;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.Jimple;
public class AgetInstruction extends DexlibAbstractInstruction {
public AgetInstruction(Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
@Override
public void jimplify(DexBody body) throws InvalidDalvikBytecodeException {
if (!(instruction instanceof Instruction23x)) {
throw new IllegalArgumentException("Expected Instruction23x but got: " + instruction.getClass());
}
Instruction23x aGetInstr = (Instruction23x) instruction;
int dest = aGetInstr.getRegisterA();
Local arrayBase = body.getRegisterLocal(aGetInstr.getRegisterB());
Local index = body.getRegisterLocal(aGetInstr.getRegisterC());
ArrayRef arrayRef = Jimple.v().newArrayRef(arrayBase, index);
Local l = body.getRegisterLocal(dest);
AssignStmt assign = Jimple.v().newAssignStmt(l, arrayRef);
if (aGetInstr.getOpcode() == Opcode.AGET_OBJECT) {
assign.addTag(new ObjectOpTag());
}
setUnit(assign);
addTags(assign);
body.add(assign);
if (IDalvikTyper.ENABLE_DVKTYPER) {
DalvikTyper.v().addConstraint(assign.getLeftOpBox(), assign.getRightOpBox());
DalvikTyper.v().setType(arrayRef.getIndexBox(), IntType.v(), true);
}
}
@Override
boolean overridesRegister(int register) {
OneRegisterInstruction i = (OneRegisterInstruction) instruction;
int dest = i.getRegisterA();
return register == dest;
}
}
| 2,954
| 32.202247
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/AputInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.formats.Instruction23x;
import soot.ArrayType;
import soot.IntType;
import soot.Local;
import soot.Type;
import soot.UnknownType;
import soot.dexpler.DexBody;
import soot.dexpler.IDalvikTyper;
import soot.dexpler.tags.ObjectOpTag;
import soot.dexpler.typing.DalvikTyper;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.Jimple;
public class AputInstruction extends FieldInstruction {
public AputInstruction(Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
@Override
public void jimplify(DexBody body) {
if (!(instruction instanceof Instruction23x)) {
throw new IllegalArgumentException("Expected Instruction23x but got: " + instruction.getClass());
}
Instruction23x aPutInstr = (Instruction23x) instruction;
int source = aPutInstr.getRegisterA();
Local arrayBase = body.getRegisterLocal(aPutInstr.getRegisterB());
Local index = body.getRegisterLocal(aPutInstr.getRegisterC());
ArrayRef arrayRef = Jimple.v().newArrayRef(arrayBase, index);
Local sourceValue = body.getRegisterLocal(source);
AssignStmt assign = getAssignStmt(body, sourceValue, arrayRef);
if (aPutInstr.getOpcode() == Opcode.APUT_OBJECT) {
assign.addTag(new ObjectOpTag());
}
setUnit(assign);
addTags(assign);
body.add(assign);
if (IDalvikTyper.ENABLE_DVKTYPER) {
DalvikTyper.v().addConstraint(assign.getLeftOpBox(), assign.getRightOpBox());
DalvikTyper.v().setType(arrayRef.getIndexBox(), IntType.v(), true);
}
}
@Override
protected Type getTargetType(DexBody body) {
Instruction23x aPutInstr = (Instruction23x) instruction;
Type t = body.getRegisterLocal(aPutInstr.getRegisterB()).getType();
if (t instanceof ArrayType) {
return ((ArrayType) t).getElementType();
} else {
return UnknownType.v();
}
}
}
| 3,010
| 31.376344
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/ArrayLengthInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.TwoRegisterInstruction;
import org.jf.dexlib2.iface.instruction.formats.Instruction12x;
import soot.IntType;
import soot.Local;
import soot.dexpler.DexBody;
import soot.dexpler.IDalvikTyper;
import soot.dexpler.typing.DalvikTyper;
import soot.jimple.AssignStmt;
import soot.jimple.Jimple;
import soot.jimple.LengthExpr;
public class ArrayLengthInstruction extends DexlibAbstractInstruction {
public ArrayLengthInstruction(Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
@Override
public void jimplify(DexBody body) {
if (!(instruction instanceof Instruction12x)) {
throw new IllegalArgumentException("Expected Instruction12x but got: " + instruction.getClass());
}
Instruction12x lengthOfArrayInstruction = (Instruction12x) instruction;
int dest = lengthOfArrayInstruction.getRegisterA();
Local arrayReference = body.getRegisterLocal(lengthOfArrayInstruction.getRegisterB());
LengthExpr lengthExpr = Jimple.v().newLengthExpr(arrayReference);
AssignStmt assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), lengthExpr);
setUnit(assign);
addTags(assign);
body.add(assign);
if (IDalvikTyper.ENABLE_DVKTYPER) {
DalvikTyper.v().setType(assign.getLeftOpBox(), IntType.v(), false);
}
}
@Override
boolean overridesRegister(int register) {
TwoRegisterInstruction i = (TwoRegisterInstruction) instruction;
int dest = i.getRegisterA();
return register == dest;
}
}
| 2,599
| 31.5
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/Binop2addrInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.TwoRegisterInstruction;
import org.jf.dexlib2.iface.instruction.formats.Instruction12x;
import soot.Local;
import soot.Value;
import soot.dexpler.DexBody;
import soot.dexpler.tags.DoubleOpTag;
import soot.dexpler.tags.FloatOpTag;
import soot.dexpler.tags.IntOpTag;
import soot.dexpler.tags.LongOpTag;
import soot.jimple.AssignStmt;
import soot.jimple.Jimple;
public class Binop2addrInstruction extends TaggedInstruction {
public Binop2addrInstruction(Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
@Override
public void jimplify(DexBody body) {
if (!(instruction instanceof Instruction12x)) {
throw new IllegalArgumentException("Expected Instruction12x but got: " + instruction.getClass());
}
Instruction12x binOp2AddrInstr = (Instruction12x) instruction;
int dest = binOp2AddrInstr.getRegisterA();
Local source1 = body.getRegisterLocal(binOp2AddrInstr.getRegisterA());
Local source2 = body.getRegisterLocal(binOp2AddrInstr.getRegisterB());
Value expr = getExpression(source1, source2);
AssignStmt assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), expr);
assign.addTag(getTag());
setUnit(assign);
addTags(assign);
body.add(assign);
/*
* if (IDalvikTyper.ENABLE_DVKTYPER) { BinopExpr bexpr = (BinopExpr)expr; short op = instruction.getOpcode().value;
* DalvikTyper.v().setType(bexpr.getOp1Box(), op1BinType[op-0xb0], true); DalvikTyper.v().setType(bexpr.getOp2Box(),
* op2BinType[op-0xb0], true); DalvikTyper.v().setType(assign.getLeftOpBox(), resBinType[op-0xb0], false); }
*/
}
private Value getExpression(Local source1, Local source2) {
Opcode opcode = instruction.getOpcode();
switch (opcode) {
case ADD_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newAddExpr(source1, source2);
case ADD_FLOAT_2ADDR:
setTag(new FloatOpTag());
return Jimple.v().newAddExpr(source1, source2);
case ADD_DOUBLE_2ADDR:
setTag(new DoubleOpTag());
return Jimple.v().newAddExpr(source1, source2);
case ADD_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newAddExpr(source1, source2);
case SUB_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newSubExpr(source1, source2);
case SUB_FLOAT_2ADDR:
setTag(new FloatOpTag());
return Jimple.v().newSubExpr(source1, source2);
case SUB_DOUBLE_2ADDR:
setTag(new DoubleOpTag());
return Jimple.v().newSubExpr(source1, source2);
case SUB_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newSubExpr(source1, source2);
case MUL_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newMulExpr(source1, source2);
case MUL_FLOAT_2ADDR:
setTag(new FloatOpTag());
return Jimple.v().newMulExpr(source1, source2);
case MUL_DOUBLE_2ADDR:
setTag(new DoubleOpTag());
return Jimple.v().newMulExpr(source1, source2);
case MUL_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newMulExpr(source1, source2);
case DIV_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newDivExpr(source1, source2);
case DIV_FLOAT_2ADDR:
setTag(new FloatOpTag());
return Jimple.v().newDivExpr(source1, source2);
case DIV_DOUBLE_2ADDR:
setTag(new DoubleOpTag());
return Jimple.v().newDivExpr(source1, source2);
case DIV_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newDivExpr(source1, source2);
case REM_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newRemExpr(source1, source2);
case REM_FLOAT_2ADDR:
setTag(new FloatOpTag());
return Jimple.v().newRemExpr(source1, source2);
case REM_DOUBLE_2ADDR:
setTag(new DoubleOpTag());
return Jimple.v().newRemExpr(source1, source2);
case REM_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newRemExpr(source1, source2);
case AND_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newAndExpr(source1, source2);
case AND_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newAndExpr(source1, source2);
case OR_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newOrExpr(source1, source2);
case OR_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newOrExpr(source1, source2);
case XOR_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newXorExpr(source1, source2);
case XOR_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newXorExpr(source1, source2);
case SHL_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newShlExpr(source1, source2);
case SHL_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newShlExpr(source1, source2);
case SHR_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newShrExpr(source1, source2);
case SHR_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newShrExpr(source1, source2);
case USHR_LONG_2ADDR:
setTag(new LongOpTag());
return Jimple.v().newUshrExpr(source1, source2);
case USHR_INT_2ADDR:
setTag(new IntOpTag());
return Jimple.v().newUshrExpr(source1, source2);
default:
throw new RuntimeException("Invalid Opcode: " + opcode);
}
}
@Override
boolean overridesRegister(int register) {
TwoRegisterInstruction i = (TwoRegisterInstruction) instruction;
int dest = i.getRegisterA();
return register == dest;
}
}
| 6,901
| 33.168317
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/BinopInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.ThreeRegisterInstruction;
import org.jf.dexlib2.iface.instruction.formats.Instruction23x;
import soot.Local;
import soot.Value;
import soot.dexpler.DexBody;
import soot.dexpler.tags.DoubleOpTag;
import soot.dexpler.tags.FloatOpTag;
import soot.dexpler.tags.IntOpTag;
import soot.dexpler.tags.LongOpTag;
import soot.jimple.AssignStmt;
import soot.jimple.Jimple;
public class BinopInstruction extends TaggedInstruction {
public BinopInstruction(Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
@Override
public void jimplify(DexBody body) {
if (!(instruction instanceof Instruction23x)) {
throw new IllegalArgumentException("Expected Instruction23x but got: " + instruction.getClass());
}
Instruction23x binOpInstr = (Instruction23x) instruction;
int dest = binOpInstr.getRegisterA();
Local source1 = body.getRegisterLocal(binOpInstr.getRegisterB());
Local source2 = body.getRegisterLocal(binOpInstr.getRegisterC());
Value expr = getExpression(source1, source2);
AssignStmt assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), expr);
assign.addTag(getTag());
setUnit(assign);
addTags(assign);
body.add(assign);
/*
* if (IDalvikTyper.ENABLE_DVKTYPER) { int op = (int)instruction.getOpcode().value; BinopExpr bexpr = (BinopExpr)expr;
* JAssignStmt jassign = (JAssignStmt)assign; DalvikTyper.v().setType(bexpr.getOp1Box(), op1BinType[op-0x90], true);
* DalvikTyper.v().setType(bexpr.getOp2Box(), op2BinType[op-0x90], true); DalvikTyper.v().setType(jassign.leftBox,
* resBinType[op-0x90], false); }
*/
}
private Value getExpression(Local source1, Local source2) {
Opcode opcode = instruction.getOpcode();
switch (opcode) {
case ADD_LONG:
setTag(new LongOpTag());
return Jimple.v().newAddExpr(source1, source2);
case ADD_FLOAT:
setTag(new FloatOpTag());
return Jimple.v().newAddExpr(source1, source2);
case ADD_DOUBLE:
setTag(new DoubleOpTag());
return Jimple.v().newAddExpr(source1, source2);
case ADD_INT:
setTag(new IntOpTag());
return Jimple.v().newAddExpr(source1, source2);
case SUB_LONG:
setTag(new LongOpTag());
return Jimple.v().newSubExpr(source1, source2);
case SUB_FLOAT:
setTag(new FloatOpTag());
return Jimple.v().newSubExpr(source1, source2);
case SUB_DOUBLE:
setTag(new DoubleOpTag());
return Jimple.v().newSubExpr(source1, source2);
case SUB_INT:
setTag(new IntOpTag());
return Jimple.v().newSubExpr(source1, source2);
case MUL_LONG:
setTag(new LongOpTag());
return Jimple.v().newMulExpr(source1, source2);
case MUL_FLOAT:
setTag(new FloatOpTag());
return Jimple.v().newMulExpr(source1, source2);
case MUL_DOUBLE:
setTag(new DoubleOpTag());
return Jimple.v().newMulExpr(source1, source2);
case MUL_INT:
setTag(new IntOpTag());
return Jimple.v().newMulExpr(source1, source2);
case DIV_LONG:
setTag(new LongOpTag());
return Jimple.v().newDivExpr(source1, source2);
case DIV_FLOAT:
setTag(new FloatOpTag());
return Jimple.v().newDivExpr(source1, source2);
case DIV_DOUBLE:
setTag(new DoubleOpTag());
return Jimple.v().newDivExpr(source1, source2);
case DIV_INT:
setTag(new IntOpTag());
return Jimple.v().newDivExpr(source1, source2);
case REM_LONG:
setTag(new LongOpTag());
return Jimple.v().newRemExpr(source1, source2);
case REM_FLOAT:
setTag(new FloatOpTag());
return Jimple.v().newRemExpr(source1, source2);
case REM_DOUBLE:
setTag(new DoubleOpTag());
return Jimple.v().newRemExpr(source1, source2);
case REM_INT:
setTag(new IntOpTag());
return Jimple.v().newRemExpr(source1, source2);
case AND_LONG:
setTag(new LongOpTag());
return Jimple.v().newAndExpr(source1, source2);
case AND_INT:
setTag(new IntOpTag());
return Jimple.v().newAndExpr(source1, source2);
case OR_LONG:
setTag(new LongOpTag());
return Jimple.v().newOrExpr(source1, source2);
case OR_INT:
setTag(new IntOpTag());
return Jimple.v().newOrExpr(source1, source2);
case XOR_LONG:
setTag(new LongOpTag());
return Jimple.v().newXorExpr(source1, source2);
case XOR_INT:
setTag(new IntOpTag());
return Jimple.v().newXorExpr(source1, source2);
case SHL_LONG:
setTag(new LongOpTag());
return Jimple.v().newShlExpr(source1, source2);
case SHL_INT:
setTag(new IntOpTag());
return Jimple.v().newShlExpr(source1, source2);
case SHR_LONG:
setTag(new LongOpTag());
return Jimple.v().newShrExpr(source1, source2);
case SHR_INT:
setTag(new IntOpTag());
return Jimple.v().newShrExpr(source1, source2);
case USHR_LONG:
setTag(new LongOpTag());
return Jimple.v().newUshrExpr(source1, source2);
case USHR_INT:
setTag(new IntOpTag());
return Jimple.v().newUshrExpr(source1, source2);
default:
throw new RuntimeException("Invalid Opcode: " + opcode);
}
}
@Override
boolean overridesRegister(int register) {
ThreeRegisterInstruction i = (ThreeRegisterInstruction) instruction;
int dest = i.getRegisterA();
return register == dest;
}
}
| 6,732
| 32.167488
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/BinopLitInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.NarrowLiteralInstruction;
import org.jf.dexlib2.iface.instruction.TwoRegisterInstruction;
import org.jf.dexlib2.iface.instruction.formats.Instruction22b;
import org.jf.dexlib2.iface.instruction.formats.Instruction22s;
import soot.Local;
import soot.Value;
import soot.dexpler.DexBody;
import soot.dexpler.tags.IntOpTag;
import soot.jimple.AssignStmt;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
public class BinopLitInstruction extends TaggedInstruction {
public BinopLitInstruction(Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
@Override
public void jimplify(DexBody body) {
if (!(instruction instanceof Instruction22s) && !(instruction instanceof Instruction22b)) {
throw new IllegalArgumentException("Expected Instruction22s or Instruction22b but got: " + instruction.getClass());
}
NarrowLiteralInstruction binOpLitInstr = (NarrowLiteralInstruction) this.instruction;
int dest = ((TwoRegisterInstruction) instruction).getRegisterA();
int source = ((TwoRegisterInstruction) instruction).getRegisterB();
Local source1 = body.getRegisterLocal(source);
IntConstant constant = IntConstant.v(binOpLitInstr.getNarrowLiteral());
Value expr = getExpression(source1, constant);
AssignStmt assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), expr);
assign.addTag(getTag());
setUnit(assign);
addTags(assign);
body.add(assign);
/*
* if (IDalvikTyper.ENABLE_DVKTYPER) { Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ assign);
*
* int op = (int)instruction.getOpcode().value; if (op >= 0xd8) { op -= 0xd8; } else { op -= 0xd0; } BinopExpr bexpr =
* (BinopExpr)expr; //body.dvkTyper.setType((op == 1) ? bexpr.getOp2Box() : bexpr.getOp1Box(), op1BinType[op]);
* DalvikTyper.v().setType(((JAssignStmt)assign).leftBox, op1BinType[op], false);
*
* }
*/
}
@SuppressWarnings("fallthrough")
private Value getExpression(Local source1, Value source2) {
Opcode opcode = instruction.getOpcode();
switch (opcode) {
case ADD_INT_LIT16:
setTag(new IntOpTag());
case ADD_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newAddExpr(source1, source2);
case RSUB_INT:
setTag(new IntOpTag());
case RSUB_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newSubExpr(source2, source1);
case MUL_INT_LIT16:
setTag(new IntOpTag());
case MUL_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newMulExpr(source1, source2);
case DIV_INT_LIT16:
setTag(new IntOpTag());
case DIV_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newDivExpr(source1, source2);
case REM_INT_LIT16:
setTag(new IntOpTag());
case REM_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newRemExpr(source1, source2);
case AND_INT_LIT8:
setTag(new IntOpTag());
case AND_INT_LIT16:
setTag(new IntOpTag());
return Jimple.v().newAndExpr(source1, source2);
case OR_INT_LIT16:
setTag(new IntOpTag());
case OR_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newOrExpr(source1, source2);
case XOR_INT_LIT16:
setTag(new IntOpTag());
case XOR_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newXorExpr(source1, source2);
case SHL_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newShlExpr(source1, source2);
case SHR_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newShrExpr(source1, source2);
case USHR_INT_LIT8:
setTag(new IntOpTag());
return Jimple.v().newUshrExpr(source1, source2);
default:
throw new RuntimeException("Invalid Opcode: " + opcode);
}
}
@Override
boolean overridesRegister(int register) {
TwoRegisterInstruction i = (TwoRegisterInstruction) instruction;
int dest = i.getRegisterA();
return register == dest;
}
}
| 5,220
| 31.428571
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/CastInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.TwoRegisterInstruction;
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.dexpler.DexBody;
import soot.dexpler.IDalvikTyper;
import soot.dexpler.tags.DoubleOpTag;
import soot.dexpler.tags.FloatOpTag;
import soot.dexpler.tags.IntOpTag;
import soot.dexpler.tags.LongOpTag;
import soot.dexpler.typing.DalvikTyper;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.Jimple;
public class CastInstruction extends TaggedInstruction {
public CastInstruction(Instruction instruction, int codeAddress) {
super(instruction, codeAddress);
}
@Override
public void jimplify(DexBody body) {
TwoRegisterInstruction i = (TwoRegisterInstruction) instruction;
int dest = i.getRegisterA();
int source = i.getRegisterB();
Type targetType = getTargetType();
CastExpr cast = Jimple.v().newCastExpr(body.getRegisterLocal(source), targetType);
AssignStmt assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), cast);
assign.addTag(getTag());
setUnit(assign);
addTags(assign);
body.add(assign);
if (IDalvikTyper.ENABLE_DVKTYPER) {
DalvikTyper.v().setType(assign.getLeftOpBox(), cast.getType(), false);
// DalvikTyper.v().captureAssign((JAssignStmt)assign, op);
}
}
/**
* Return the appropriate target type for the covered opcodes.
*
* Note: the tag represents the original type before the cast. The cast type is not lost in Jimple and can be retrieved by
* calling the getCastType() method.
*/
private Type getTargetType() {
Opcode opcode = instruction.getOpcode();
switch (opcode) {
case INT_TO_BYTE:
setTag(new IntOpTag());
return ByteType.v();
case INT_TO_CHAR:
setTag(new IntOpTag());
return CharType.v();
case INT_TO_SHORT:
setTag(new IntOpTag());
return ShortType.v();
case LONG_TO_INT:
setTag(new LongOpTag());
return IntType.v();
case DOUBLE_TO_INT:
setTag(new DoubleOpTag());
return IntType.v();
case FLOAT_TO_INT:
setTag(new FloatOpTag());
return IntType.v();
case INT_TO_LONG:
setTag(new IntOpTag());
return LongType.v();
case DOUBLE_TO_LONG:
setTag(new DoubleOpTag());
return LongType.v();
case FLOAT_TO_LONG:
setTag(new FloatOpTag());
return LongType.v();
case LONG_TO_FLOAT:
setTag(new LongOpTag());
return FloatType.v();
case DOUBLE_TO_FLOAT:
setTag(new DoubleOpTag());
return FloatType.v();
case INT_TO_FLOAT:
setTag(new IntOpTag());
return FloatType.v();
case INT_TO_DOUBLE:
setTag(new IntOpTag());
return DoubleType.v();
case FLOAT_TO_DOUBLE:
setTag(new FloatOpTag());
return DoubleType.v();
case LONG_TO_DOUBLE:
setTag(new LongOpTag());
return DoubleType.v();
default:
throw new RuntimeException("Invalid Opcode: " + opcode);
}
}
@Override
boolean overridesRegister(int register) {
TwoRegisterInstruction i = (TwoRegisterInstruction) instruction;
int dest = i.getRegisterA();
return register == dest;
}
}
| 4,484
| 28.9
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/CheckCastInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.Set;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.ReferenceInstruction;
import org.jf.dexlib2.iface.instruction.formats.Instruction21c;
import org.jf.dexlib2.iface.reference.TypeReference;
import soot.Local;
import soot.Type;
import soot.dexpler.DexBody;
import soot.dexpler.DexType;
import soot.dexpler.IDalvikTyper;
import soot.dexpler.typing.DalvikTyper;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.Jimple;
public class CheckCastInstruction extends DexlibAbstractInstruction {
public CheckCastInstruction(Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
@Override
public void jimplify(DexBody body) {
if (!(instruction instanceof Instruction21c)) {
throw new IllegalArgumentException("Expected Instruction21c but got: " + instruction.getClass());
}
Instruction21c checkCastInstr = (Instruction21c) instruction;
Local castValue = body.getRegisterLocal(checkCastInstr.getRegisterA());
Type checkCastType = DexType.toSoot((TypeReference) checkCastInstr.getReference());
CastExpr castExpr = Jimple.v().newCastExpr(castValue, checkCastType);
// generate "x = (Type) x"
// splitter will take care of the rest
AssignStmt assign = Jimple.v().newAssignStmt(castValue, castExpr);
setUnit(assign);
addTags(assign);
body.add(assign);
if (IDalvikTyper.ENABLE_DVKTYPER) {
DalvikTyper.v().setType(assign.getLeftOpBox(), checkCastType, false);
}
}
@Override
public Set<Type> introducedTypes() {
ReferenceInstruction i = (ReferenceInstruction) instruction;
Set<Type> types = new HashSet<Type>();
types.add(DexType.toSoot((TypeReference) i.getReference()));
return types;
}
}
| 2,841
| 30.577778
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/CmpInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.ThreeRegisterInstruction;
import org.jf.dexlib2.iface.instruction.formats.Instruction23x;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.Type;
import soot.dexpler.DexBody;
import soot.dexpler.IDalvikTyper;
import soot.dexpler.tags.DoubleOpTag;
import soot.dexpler.tags.FloatOpTag;
import soot.dexpler.tags.LongOpTag;
import soot.dexpler.typing.DalvikTyper;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.Expr;
import soot.jimple.Jimple;
import soot.jimple.internal.JAssignStmt;
public class CmpInstruction extends TaggedInstruction {
public CmpInstruction(Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
@Override
public void jimplify(DexBody body) {
if (!(instruction instanceof Instruction23x)) {
throw new IllegalArgumentException("Expected Instruction23x but got: " + instruction.getClass());
}
Instruction23x cmpInstr = (Instruction23x) instruction;
int dest = cmpInstr.getRegisterA();
Local first = body.getRegisterLocal(cmpInstr.getRegisterB());
Local second = body.getRegisterLocal(cmpInstr.getRegisterC());
// Expr cmpExpr;
// Type type = null
Opcode opcode = instruction.getOpcode();
Expr cmpExpr = null;
Type type = null;
switch (opcode) {
case CMPL_DOUBLE:
setTag(new DoubleOpTag());
type = DoubleType.v();
cmpExpr = Jimple.v().newCmplExpr(first, second);
break;
case CMPL_FLOAT:
setTag(new FloatOpTag());
type = FloatType.v();
cmpExpr = Jimple.v().newCmplExpr(first, second);
break;
case CMPG_DOUBLE:
setTag(new DoubleOpTag());
type = DoubleType.v();
cmpExpr = Jimple.v().newCmpgExpr(first, second);
break;
case CMPG_FLOAT:
setTag(new FloatOpTag());
type = FloatType.v();
cmpExpr = Jimple.v().newCmpgExpr(first, second);
break;
case CMP_LONG:
setTag(new LongOpTag());
type = LongType.v();
cmpExpr = Jimple.v().newCmpExpr(first, second);
break;
default:
throw new RuntimeException("no opcode for CMP: " + opcode);
}
AssignStmt assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), cmpExpr);
assign.addTag(getTag());
setUnit(assign);
addTags(assign);
body.add(assign);
if (IDalvikTyper.ENABLE_DVKTYPER) {
getTag().getName();
BinopExpr bexpr = (BinopExpr) cmpExpr;
DalvikTyper.v().setType(bexpr.getOp1Box(), type, true);
DalvikTyper.v().setType(bexpr.getOp2Box(), type, true);
DalvikTyper.v().setType(((JAssignStmt) assign).getLeftOpBox(), IntType.v(), false);
}
}
@Override
boolean overridesRegister(int register) {
ThreeRegisterInstruction i = (ThreeRegisterInstruction) instruction;
int dest = i.getRegisterA();
return register == dest;
}
}
| 4,096
| 30.515385
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/dexpler/instructions/ConditionalJumpInstruction.java
|
package soot.dexpler.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2012 Michael Markert, Frank Hartmann
*
* (c) 2012 University of Luxembourg - Interdisciplinary Centre for
* Security Reliability and Trust (SnT) - All rights reserved
* Alexandre Bartel
*
* %%
* 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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.Instruction;
import soot.Immediate;
import soot.Local;
import soot.dexpler.DexBody;
import soot.jimple.ConditionExpr;
import soot.jimple.IfStmt;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
public abstract class ConditionalJumpInstruction extends JumpInstruction implements DeferableInstruction {
public ConditionalJumpInstruction(Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
/**
* Return an if statement depending on the instruction.
*/
protected abstract IfStmt ifStatement(DexBody body);
public void jimplify(DexBody body) {
// check if target instruction has been jimplified
DexlibAbstractInstruction ins = getTargetInstruction(body);
if (ins != null && ins.getUnit() != null) {
IfStmt s = ifStatement(body);
body.add(s);
setUnit(s);
} else {
// set marker unit to swap real gotostmt with otherwise
body.addDeferredJimplification(this);
markerUnit = Jimple.v().newNopStmt();
unit = markerUnit;
// beginUnit = markerUnit;
// endUnit = markerUnit;
// beginUnit = markerUnit;
body.add(markerUnit);
// Unit end = Jimple.v().newNopStmt();
// body.add(end);
// endUnit = end;
}
}
// DalvikTyper.v() here?
public void deferredJimplify(DexBody body) {
IfStmt s = ifStatement(body);
body.getBody().getUnits().swapWith(markerUnit, s); // insertAfter(s, markerUnit);
setUnit(s);
}
/**
* Get comparison expression depending on opcode against zero or null.
*
* If the register is used as an object this will create a comparison with null, not zero.
*
* @param body
* the containing DexBody
* @param reg
* the register to compare against zero.
*/
protected ConditionExpr getComparisonExpr(DexBody body, int reg) {
Local one = body.getRegisterLocal(reg);
return getComparisonExpr(one, IntConstant.v(0));
}
/**
* Get comparison expression depending on opcode between two immediates
*
* @param one
* first immediate
* @param other
* second immediate
* @throws RuntimeException
* if this is not a IfTest or IfTestz instruction.
*/
protected ConditionExpr getComparisonExpr(Immediate one, Immediate other) {
Opcode opcode = instruction.getOpcode();
switch (opcode) {
case IF_EQ:
case IF_EQZ:
return Jimple.v().newEqExpr(one, other);
case IF_NE:
case IF_NEZ:
return Jimple.v().newNeExpr(one, other);
case IF_LT:
case IF_LTZ:
return Jimple.v().newLtExpr(one, other);
case IF_GE:
case IF_GEZ:
return Jimple.v().newGeExpr(one, other);
case IF_GT:
case IF_GTZ:
return Jimple.v().newGtExpr(one, other);
case IF_LE:
case IF_LEZ:
return Jimple.v().newLeExpr(one, other);
default:
throw new RuntimeException("Instruction is not an IfTest(z) instruction.");
}
}
}
| 4,085
| 29.492537
| 106
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.