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/toDex/PrimitiveType.java
|
package soot.toDex;
/*-
* #%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.Locale;
/**
* An enumeration for the primitive types the Dalvik VM can handle.
*/
public enum PrimitiveType {
// NOTE: the order is relevant for cast code generation, so do not change it
BOOLEAN, BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE;
public String getName() {
// return lower case name that is locale-insensitive
return this.name().toLowerCase(Locale.ENGLISH);
}
public static PrimitiveType getByName(String name) {
for (PrimitiveType p : values()) {
if (p.getName().equals(name)) {
return p;
}
}
throw new RuntimeException("not found: " + name);
}
}
| 1,472
| 29.061224
| 78
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/Register.java
|
package soot.toDex;
/*-
* #%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.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Type;
/**
* A register for the Dalvik VM. It has a number and a type.
*/
public class Register implements Cloneable {
public static final int MAX_REG_NUM_UNCONSTRAINED = 65535;
public static final int MAX_REG_NUM_SHORT = 255;
public static final int MAX_REG_NUM_BYTE = 15;
public static final Register EMPTY_REGISTER = new Register(IntType.v(), 0);
private static boolean fitsInto(int regNumber, int maxNumber, boolean isWide) {
if (isWide) {
// reg occupies number and number + 1, hence the "<"
return regNumber >= 0 && regNumber < maxNumber;
}
return regNumber >= 0 && regNumber <= maxNumber;
}
public static boolean fitsUnconstrained(int regNumber, boolean isWide) {
return fitsInto(regNumber, MAX_REG_NUM_UNCONSTRAINED, isWide);
}
public static boolean fitsShort(int regNumber, boolean isWide) {
return fitsInto(regNumber, MAX_REG_NUM_SHORT, isWide);
}
public static boolean fitsByte(int regNumber, boolean isWide) {
return fitsInto(regNumber, MAX_REG_NUM_BYTE, isWide);
}
private final Type type;
private int number;
public Register(Type type, int number) {
this.type = type;
this.number = number;
}
public boolean isEmptyReg() {
return this == EMPTY_REGISTER;
}
public boolean isWide() {
return SootToDexUtils.isWide(type);
}
public boolean isObject() {
return SootToDexUtils.isObject(type);
}
public boolean isFloat() {
return type instanceof FloatType;
}
public boolean isDouble() {
return type instanceof DoubleType;
}
public Type getType() {
return type;
}
public String getTypeString() {
return type.toString();
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
if (isEmptyReg()) {
// number of empty register stays at zero - that's part of its purpose
return;
}
this.number = number;
}
private boolean fitsInto(int maxNumber) {
if (isEmptyReg()) {
// empty reg fits into anything
return true;
}
return fitsInto(number, maxNumber, isWide());
}
public boolean fitsUnconstrained() {
return fitsInto(MAX_REG_NUM_UNCONSTRAINED);
}
public boolean fitsShort() {
return fitsInto(MAX_REG_NUM_SHORT);
}
public boolean fitsByte() {
return fitsInto(MAX_REG_NUM_BYTE);
}
@Override
public Register clone() {
return new Register(this.type, this.number);
}
@Override
public String toString() {
if (isEmptyReg()) {
return "the empty reg";
}
return "reg(" + number + "):" + type.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + number;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Register other = (Register) obj;
if (number != other.number) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
return true;
}
}
| 4,225
| 22.477778
| 81
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/RegisterAllocator.java
|
package soot.toDex;
/*-
* #%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.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import soot.Local;
import soot.SootMethod;
import soot.Type;
import soot.Value;
import soot.jimple.ClassConstant;
import soot.jimple.Constant;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.NullConstant;
import soot.jimple.StringConstant;
/**
* An allocator for registers. It keeps track of locals to re-use their registers.<br>
* <br>
* Note that a register number can increase beyond 65535 / 16 bit, since the instruction formats should check for their
* register limits themselves.
*/
public class RegisterAllocator {
private int nextRegNum;
private Map<Local, Integer> localToLastRegNum;
private int paramRegCount;
public RegisterAllocator() {
localToLastRegNum = new HashMap<Local, Integer>();
}
//
// Keep the same register for immediate constants.
// Tested on application uk.co.nickfines.RealCalc.apk, sha256:
// 5386d024d135d270ecba3ac5c11b23609b8510184c440647a60690d6b2c957ab
//
// Results on 992 methods:
// - on average 4.89 less registers
// - bigger differences in methods initializing a lot of data:
// from 603 to 16
// from 482 to 6
// from 376 to 14
// from 142 to 74
//
// Having the smallest number of registers is important.
// If there are too many register, the VM can reject the method.
// In fact that is what happens with RealCalc and the method with
// 603 registers (Android 2.2 on emulator); the VM stops and prints
// the following message:
// "W/dalvikvm( 804): VFY: arbitrarily rejecting large method
// (regs=603 count=4980)"
//
// The following constants are considered here:
//
// soot.Constant
// |- ClassConstant,
// |- NullConstant,
// |- NumericConstant,
// |- FloatConstant
// ...
// |- StringConstant
//
// In some cases there can be multiple constants of the same type:
// - method invocation with multiple parameters
// - array reference in assignment (ex: a[1] = 2)
// - multi-dimension array initialization (ex: a = new int[1][2][3])
//
private List<Register> classConstantReg = new ArrayList<Register>();
private List<Register> nullConstantReg = new ArrayList<Register>();
private List<Register> floatConstantReg = new ArrayList<Register>();
private List<Register> intConstantReg = new ArrayList<Register>();
private List<Register> longConstantReg = new ArrayList<Register>();
private List<Register> doubleConstantReg = new ArrayList<Register>();
private List<Register> stringConstantReg = new ArrayList<Register>();
private AtomicInteger classI = new AtomicInteger(0);
private AtomicInteger nullI = new AtomicInteger(0);
private AtomicInteger floatI = new AtomicInteger(0);
private AtomicInteger intI = new AtomicInteger(0);
private AtomicInteger longI = new AtomicInteger(0);
private AtomicInteger doubleI = new AtomicInteger(0);
private AtomicInteger stringI = new AtomicInteger(0);
private Set<Register> lockedRegisters = new HashSet<Register>();
private int lastReg;
private Register currentLocalRegister;
private Register asConstant(Constant c, ConstantVisitor constantV) {
Register constantRegister = null;
List<Register> rArray = null;
AtomicInteger iI = null;
if (c instanceof ClassConstant) {
rArray = classConstantReg;
iI = classI;
} else if (c instanceof NullConstant) {
rArray = nullConstantReg;
iI = nullI;
} else if (c instanceof FloatConstant) {
rArray = floatConstantReg;
iI = floatI;
} else if (c instanceof IntConstant) {
rArray = intConstantReg;
iI = intI;
} else if (c instanceof LongConstant) {
rArray = longConstantReg;
iI = longI;
} else if (c instanceof DoubleConstant) {
rArray = doubleConstantReg;
iI = doubleI;
} else if (c instanceof StringConstant) {
rArray = stringConstantReg;
iI = stringI;
} else {
throw new RuntimeException("Error. Unknown constant type: '" + c.getType() + "'");
}
boolean inConflict = true;
while (inConflict) {
if (rArray.size() == 0 || iI.intValue() >= rArray.size()) {
rArray.add(new Register(c.getType(), nextRegNum));
nextRegNum += SootToDexUtils.getDexWords(c.getType());
}
constantRegister = rArray.get(iI.getAndIncrement()).clone();
inConflict = lockedRegisters.contains(constantRegister);
}
// "load" constant into the register...
constantV.setDestination(constantRegister);
c.apply(constantV);
// get an independent clone in case we got a cached reguster
return constantRegister.clone();
}
public void resetImmediateConstantsPool() {
classI = new AtomicInteger(0);
nullI = new AtomicInteger(0);
floatI = new AtomicInteger(0);
intI = new AtomicInteger(0);
longI = new AtomicInteger(0);
doubleI = new AtomicInteger(0);
stringI = new AtomicInteger(0);
}
public Map<Local, Integer> getLocalToRegisterMapping() {
return localToLastRegNum;
}
public Register asLocal(Local local) {
Register localRegister;
Integer oldRegNum = localToLastRegNum.get(local);
if (oldRegNum != null) {
// reuse the reg num last seen for this local, since this is where the content is
localRegister = new Register(local.getType(), oldRegNum);
} else {
// use a new reg num for this local
localRegister = new Register(local.getType(), nextRegNum);
localToLastRegNum.put(local, nextRegNum);
nextRegNum += SootToDexUtils.getDexWords(local.getType());
}
return localRegister;
}
public void asParameter(SootMethod sm, Local l) {
// If we already have a register for this parameter, there is nothing
// more to be done here.
if (localToLastRegNum.containsKey(l)) {
return;
}
// since a parameter in dex always has a register, we handle it like a new local without the need of a new register
// Register allocation is fixed! 0 for this, 1...n for parameters. We do not expect
// the IdentityStmts in the body in any fixed order, so we directly calculate
// the correct register number.
int paramRegNum = 0;
boolean found = false;
if (!sm.isStatic()) {
// there might be bodies that do not have a this-local; ignore these gracefully
try {
if (sm.getActiveBody().getThisLocal() == l) {
paramRegNum = 0;
found = true;
}
} catch (RuntimeException e) {
// ignore
}
}
if (!found) {
for (int i = 0; i < sm.getParameterCount(); i++) {
if (sm.getActiveBody().getParameterLocal(i) == l) {
// For a non-static method, p0 is <this>.
if (!sm.isStatic()) {
paramRegNum++;
}
found = true;
break;
}
// Long and Double values consume two registers
Type paramType = sm.getParameterType(i);
paramRegNum += SootToDexUtils.getDexWords(paramType);
}
}
if (!found) {
throw new RuntimeException("Parameter local not found");
}
localToLastRegNum.put(l, paramRegNum);
int wordsforParameters = SootToDexUtils.getDexWords(l.getType());
nextRegNum = Math.max(nextRegNum + wordsforParameters, paramRegNum + wordsforParameters);
paramRegCount += wordsforParameters;
}
public Register asImmediate(Value v, ConstantVisitor constantV) {
if (v instanceof Constant) {
return asConstant((Constant) v, constantV);
} else if (v instanceof Local) {
return asLocal((Local) v);
} else {
throw new RuntimeException("expected Immediate (Constant or Local), but was: " + v.getClass());
}
}
public Register asTmpReg(Type regType) {
int newRegCount = getRegCount();
if (lastReg == newRegCount) {
return currentLocalRegister;
}
currentLocalRegister = asLocal(new TemporaryRegisterLocal(regType));
lastReg = newRegCount;
return currentLocalRegister;
}
public void increaseRegCount(int amount) {
nextRegNum += amount;
}
public int getParamRegCount() {
return paramRegCount;
}
public int getRegCount() {
return nextRegNum;
}
/**
* Locks the given register. This prevents the register from being re-used for storing constants.
*
* @param reg
* The register to lock
*/
public void lockRegister(Register reg) {
lockedRegisters.add(reg);
}
}
| 9,482
| 31.587629
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/RegisterAssigner.java
|
package soot.toDex;
/*-
* #%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.BitSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.jf.dexlib2.Opcode;
import soot.jimple.Stmt;
import soot.toDex.instructions.AddressInsn;
import soot.toDex.instructions.Insn;
import soot.toDex.instructions.Insn11n;
import soot.toDex.instructions.Insn21s;
import soot.toDex.instructions.Insn23x;
import soot.toDex.instructions.TwoRegInsn;
/**
* Assigns final register numbers in instructions so that they fit into their format and obey the calling convention (that
* is, the last registers are for the parameters).<br>
* <br>
* Note that the final instruction list can contain additional "move" instructions.<br>
* <br>
* IMPLEMENTATION NOTE: The algorithm is heavily inspired by com.android.dx.dex.code.OutputFinisher.
*/
class RegisterAssigner {
private class InstructionIterator implements Iterator<Insn> {
private final ListIterator<Insn> insnsIterator;
private final Map<Insn, Stmt> insnStmtMap;
private final Map<Insn, LocalRegisterAssignmentInformation> insnRegisterMap;
public InstructionIterator(List<Insn> insns, Map<Insn, Stmt> insnStmtMap,
Map<Insn, LocalRegisterAssignmentInformation> insnRegisterMap) {
this.insnStmtMap = insnStmtMap;
this.insnsIterator = insns.listIterator();
this.insnRegisterMap = insnRegisterMap;
}
@Override
public boolean hasNext() {
return insnsIterator.hasNext();
}
@Override
public Insn next() {
return insnsIterator.next();
}
public Insn previous() {
return insnsIterator.previous();
}
@Override
public void remove() {
this.insnsIterator.remove();
}
public void add(Insn element, Insn forOriginal, Register newRegister) {
LocalRegisterAssignmentInformation originalRegisterLocal = this.insnRegisterMap.get(forOriginal);
if (originalRegisterLocal != null) {
if (newRegister != null) {
this.insnRegisterMap.put(element,
LocalRegisterAssignmentInformation.v(newRegister, this.insnRegisterMap.get(forOriginal).getLocal()));
} else {
this.insnRegisterMap.put(element, originalRegisterLocal);
}
}
if (this.insnStmtMap.containsKey(forOriginal)) {
this.insnStmtMap.put(element, insnStmtMap.get(forOriginal));
}
this.insnsIterator.add(element);
}
public void set(Insn element, Insn forOriginal) {
LocalRegisterAssignmentInformation originalRegisterLocal = this.insnRegisterMap.get(forOriginal);
if (originalRegisterLocal != null) {
this.insnRegisterMap.put(element, originalRegisterLocal);
this.insnRegisterMap.remove(forOriginal);
}
if (this.insnStmtMap.containsKey(forOriginal)) {
this.insnStmtMap.put(element, insnStmtMap.get(forOriginal));
this.insnStmtMap.remove(forOriginal);
}
this.insnsIterator.set(element);
}
}
private RegisterAllocator regAlloc;
public RegisterAssigner(RegisterAllocator regAlloc) {
this.regAlloc = regAlloc;
}
public List<Insn> finishRegs(List<Insn> insns, Map<Insn, Stmt> insnsStmtMap,
Map<Insn, LocalRegisterAssignmentInformation> instructionRegisterMap,
List<LocalRegisterAssignmentInformation> parameterInstructionsList) {
renumParamRegsToHigh(insns, parameterInstructionsList);
reserveRegisters(insns, insnsStmtMap, parameterInstructionsList);
InstructionIterator insnIter = new InstructionIterator(insns, insnsStmtMap, instructionRegisterMap);
while (insnIter.hasNext()) {
Insn oldInsn = insnIter.next();
if (oldInsn.hasIncompatibleRegs()) {
Insn fittingInsn = findFittingInsn(oldInsn);
if (fittingInsn != null) {
insnIter.set(fittingInsn, oldInsn);
} else {
fixIncompatRegs(oldInsn, insnIter);
}
}
}
return insns;
}
private void renumParamRegsToHigh(List<Insn> insns, List<LocalRegisterAssignmentInformation> parameterInstructionsList) {
int regCount = regAlloc.getRegCount();
int paramRegCount = regAlloc.getParamRegCount();
if (paramRegCount == 0 || paramRegCount == regCount) {
return; // no params or no locals -> nothing to do
}
for (Insn insn : insns) {
for (Register r : insn.getRegs()) {
renumParamRegToHigh(r, regCount, paramRegCount);
}
}
for (LocalRegisterAssignmentInformation parameter : parameterInstructionsList) {
renumParamRegToHigh(parameter.getRegister(), regCount, paramRegCount);
}
}
private void renumParamRegToHigh(Register r, int regCount, int paramRegCount) {
int oldNum = r.getNumber();
if (oldNum >= paramRegCount) {
// not a parameter -> "move" down
int newNormalRegNum = oldNum - paramRegCount;
r.setNumber(newNormalRegNum);
} else {
// parameter -> "move" up
int newParamRegNum = oldNum + regCount - paramRegCount;
r.setNumber(newParamRegNum);
}
}
/**
* Reserves low registers in case we later find an instruction that has short operands. We can then move the real operands
* into the reserved low ones and use those instead.
*
* @param insns
* @param insnsStmtMap
* @param parameterInstructionsList
*/
private void reserveRegisters(List<Insn> insns, Map<Insn, Stmt> insnsStmtMap,
List<LocalRegisterAssignmentInformation> parameterInstructionsList) {
// reserve registers as long as new ones are needed
int reservedRegs = 0;
while (true) {
int regsNeeded = getRegsNeeded(reservedRegs, insns, insnsStmtMap);
int regsToReserve = regsNeeded - reservedRegs;
if (regsToReserve <= 0) {
break;
}
regAlloc.increaseRegCount(regsToReserve);
// "reservation": shift the old regs to higher numbers
for (Insn insn : insns) {
shiftRegs(insn, regsToReserve);
}
for (LocalRegisterAssignmentInformation info : parameterInstructionsList) {
Register r = info.getRegister();
r.setNumber(r.getNumber() + regsToReserve);
}
reservedRegs += regsToReserve;
}
}
/**
* Gets the maximum number of registers needed by a single instruction in the given list of instructions.
*
* @param regsAlreadyReserved
* @param insns
* @param insnsStmtMap
* @return
*/
private int getRegsNeeded(int regsAlreadyReserved, List<Insn> insns, Map<Insn, Stmt> insnsStmtMap) {
int regsNeeded = regsAlreadyReserved; // we only need regs that weren't
// reserved yet
for (int i = 0; i < insns.size(); i++) {
Insn insn = insns.get(i);
if (insn instanceof AddressInsn) {
continue; // needs no regs/fitting
}
// first try to find a better opcode
Insn fittingInsn = findFittingInsn(insn);
if (fittingInsn != null) {
// use the fitting instruction and continue with next one
insns.set(i, fittingInsn);
insnsStmtMap.put(fittingInsn, insnsStmtMap.get(insn));
insnsStmtMap.remove(insn);
continue;
}
// no fitting instruction -> save if we need more registers
int newRegsNeeded = insn.getMinimumRegsNeeded();
if (newRegsNeeded > regsNeeded) {
regsNeeded = newRegsNeeded;
}
}
return regsNeeded;
}
private void shiftRegs(Insn insn, int shiftAmount) {
for (Register r : insn.getRegs()) {
r.setNumber(r.getNumber() + shiftAmount);
}
}
private void fixIncompatRegs(Insn insn, InstructionIterator allInsns) {
List<Register> regs = insn.getRegs();
BitSet incompatRegs = insn.getIncompatibleRegs();
Register resultReg = regs.get(0);
// do we have an incompatible result reg?
boolean hasResultReg = insn.getOpcode().setsRegister() || insn.getOpcode().setsWideRegister();
boolean isResultRegIncompat = incompatRegs.get(0);
// is there an incompat result reg which is not also used as a source
// (like in /2addr)?
if (hasResultReg && isResultRegIncompat && !insn.getOpcode().name.endsWith("/2addr")
&& !insn.getOpcode().name.equals("check-cast")) {
// yes, so pretend result reg is compatible, since it will get a
// special move
incompatRegs.clear(0);
}
// handle normal incompatible regs, if any: add moves
if (incompatRegs.cardinality() > 0) {
addMovesForIncompatRegs(insn, allInsns, regs, incompatRegs);
}
// handle incompatible result reg. This is for three-operand
// instructions
// in which the result register is out of scope. For /2addr
// instructions,
// we need to coherently move source and result, so this is already done
// in addMovesForIncompatRegs.
if (hasResultReg && isResultRegIncompat) {
Register resultRegClone = resultReg.clone();
addMoveForIncompatResultReg(allInsns, resultRegClone, resultReg, insn);
}
}
private void addMoveForIncompatResultReg(InstructionIterator insns, Register destReg, Register origResultReg,
Insn curInsn) {
if (destReg.getNumber() == 0) {
// destination reg is already where we want it: avoid "move r0, r0"
return;
}
origResultReg.setNumber(0); // fix reg in original insn
Register sourceReg = new Register(destReg.getType(), 0);
Insn extraMove = StmtVisitor.buildMoveInsn(destReg, sourceReg);
insns.add(extraMove, curInsn, destReg);
}
/**
* Adds move instructions to put values into lower registers before using them in an instruction. This assumes that enough
* registers have been reserved at 0...n.
*
* @param curInsn
* @param insns
* @param regs
* @param incompatRegs
*/
private void addMovesForIncompatRegs(Insn curInsn, InstructionIterator insns, List<Register> regs, BitSet incompatRegs) {
Register newRegister = null;
final Register resultReg = regs.get(0);
final boolean hasResultReg = curInsn.getOpcode().setsRegister() || curInsn.getOpcode().setsWideRegister();
Insn moveResultInsn = null;
insns.previous(); // extra MOVEs are added _before_ the current insn
int nextNewDestination = 0;
for (int regIdx = 0; regIdx < regs.size(); regIdx++) {
if (incompatRegs.get(regIdx)) {
// reg is incompatible -> add extra MOVE
Register incompatReg = regs.get(regIdx);
if (incompatReg.isEmptyReg()) {
/*
* second half of a wide reg: do not add a move, since the empty reg is only considered incompatible to reserve the
* subsequent reg number
*/
continue;
}
Register source = incompatReg.clone();
Register destination = new Register(source.getType(), nextNewDestination);
nextNewDestination += SootToDexUtils.getDexWords(source.getType());
if (source.getNumber() != destination.getNumber()) {
Insn extraMove = StmtVisitor.buildMoveInsn(destination, source);
insns.add(extraMove, curInsn, null); // advances the cursor,
// so no next()
// needed
// finally patch the original, incompatible reg
incompatReg.setNumber(destination.getNumber());
// If this is the result register, we need to save the
// result as well
if (hasResultReg && regIdx == resultReg.getNumber()) {
moveResultInsn = StmtVisitor.buildMoveInsn(source, destination);
newRegister = destination;
}
}
}
}
insns.next(); // get past current insn again
if (moveResultInsn != null) {
insns.add(moveResultInsn, curInsn, newRegister); // advances the
// cursor, so no
// next() needed
}
}
private Insn findFittingInsn(Insn insn) {
if (!insn.hasIncompatibleRegs()) {
return null; // no incompatible regs -> no fitting needed
}
// we expect the dex specification to rarely change, so we hard-code the
// mapping "unfitting -> fitting"
Opcode opc = insn.getOpcode();
if (insn instanceof Insn11n && opc.equals(Opcode.CONST_4)) {
// const-4 (11n, byteReg) -> const-16 (21s, shortReg)
Insn11n unfittingInsn = (Insn11n) insn;
if (unfittingInsn.getRegA().fitsShort()) {
return new Insn21s(Opcode.CONST_16, unfittingInsn.getRegA(), unfittingInsn.getLitB());
}
} else if (insn instanceof TwoRegInsn && opc.name.endsWith("_2ADDR")) {
// */2addr (12x, byteReg,byteReg) -> * (23x,
// shortReg,shortReg,shortReg)
Register regA = ((TwoRegInsn) insn).getRegA();
Register regB = ((TwoRegInsn) insn).getRegB();
if (regA.fitsShort() && regB.fitsShort()) {
// use new opcode without the "/2addr"
int oldOpcLength = opc.name.length();
String newOpcName = opc.name.substring(0, oldOpcLength - 6);
Opcode newOpc = Opcode.valueOf(newOpcName);
Register regAClone = regA.clone();
return new Insn23x(newOpc, regA, regAClone, regB);
}
} else if (insn instanceof TwoRegInsn && SootToDexUtils.isNormalMove(opc)) {
/*
* move+ (12x, byteReg,byteReg) -> move+/from16 (22x, shortReg,unconstReg) -> move+/16 (32x, unconstReg,unconstReg)
* where "+" is "", "-object" or "-wide"
*/
Register regA = ((TwoRegInsn) insn).getRegA();
Register regB = ((TwoRegInsn) insn).getRegB();
if (regA.getNumber() != regB.getNumber()) {
return StmtVisitor.buildMoveInsn(regA, regB);
}
}
// no fitting insn found
return null;
}
}
| 14,319
| 36.098446
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/SootToDexUtils.java
|
package soot.toDex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jf.dexlib2.Opcode;
import soot.ArrayType;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.Modifier;
import soot.RefLikeType;
import soot.RefType;
import soot.ShortType;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.VoidType;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
/**
* Utility class for the conversion from soot to dex.
*/
public class SootToDexUtils {
private static final Map<Class<? extends Type>, String> sootToDexTypeDescriptor;
static {
sootToDexTypeDescriptor = new HashMap<Class<? extends Type>, String>();
sootToDexTypeDescriptor.put(BooleanType.class, "Z");
sootToDexTypeDescriptor.put(ByteType.class, "B");
sootToDexTypeDescriptor.put(CharType.class, "C");
sootToDexTypeDescriptor.put(DoubleType.class, "D");
sootToDexTypeDescriptor.put(FloatType.class, "F");
sootToDexTypeDescriptor.put(IntType.class, "I");
sootToDexTypeDescriptor.put(LongType.class, "J");
sootToDexTypeDescriptor.put(ShortType.class, "S");
sootToDexTypeDescriptor.put(VoidType.class, "V");
}
public static String getDexTypeDescriptor(Type sootType) {
if (sootType == null) {
throw new NullPointerException("Soot type was null");
}
final String typeDesc;
if (sootType instanceof RefType) {
typeDesc = getDexClassName(((RefType) sootType).getClassName());
} else if (sootType instanceof ArrayType) {
typeDesc = getDexArrayTypeDescriptor((ArrayType) sootType);
} else {
typeDesc = sootToDexTypeDescriptor.get(sootType.getClass());
}
if (typeDesc == null || typeDesc.isEmpty()) {
throw new RuntimeException("Could not create type descriptor for class " + sootType);
}
return typeDesc;
}
public static String getDexClassName(String dottedClassName) {
if (dottedClassName == null || dottedClassName.isEmpty()) {
throw new RuntimeException("Empty class name detected");
}
String slashedName = dottedClassName.replace('.', '/');
if (slashedName.startsWith("L") && slashedName.endsWith(";")) {
return slashedName;
}
return "L" + slashedName + ";";
}
public static int getDexAccessFlags(SootMethod m) {
int dexAccessFlags = m.getModifiers();
// dex constructor flag is not included in the Soot modifiers, so add it if
// necessary
if (m.isConstructor() || m.getName().equals(SootMethod.staticInitializerName)) {
dexAccessFlags |= Modifier.CONSTRUCTOR;
}
// add declared_synchronized for dex if synchronized
if (m.isSynchronized()) {
dexAccessFlags |= Modifier.DECLARED_SYNCHRONIZED;
// even remove synchronized if not native, since only allowed there
if (!m.isNative()) {
dexAccessFlags &= ~Modifier.SYNCHRONIZED;
}
}
return dexAccessFlags;
}
public static String getArrayTypeDescriptor(ArrayType type) {
Type baseType;
if (type.numDimensions > 1) {
baseType = ArrayType.v(type.baseType, 1);
} else {
baseType = type.baseType;
}
return getDexTypeDescriptor(baseType);
}
private static String getDexArrayTypeDescriptor(ArrayType sootArray) {
if (sootArray.numDimensions > 255) {
throw new RuntimeException(
"dex does not support more than 255 dimensions! " + sootArray + " has " + sootArray.numDimensions);
}
String baseTypeDescriptor = getDexTypeDescriptor(sootArray.baseType);
StringBuilder sb = new StringBuilder(sootArray.numDimensions + baseTypeDescriptor.length());
for (int i = 0; i < sootArray.numDimensions; i++) {
sb.append('[');
}
sb.append(baseTypeDescriptor);
return sb.toString();
}
public static boolean isObject(String typeDescriptor) {
if (typeDescriptor.isEmpty()) {
return false;
}
char first = typeDescriptor.charAt(0);
return first == 'L' || first == '[';
}
public static boolean isObject(Type sootType) {
return sootType instanceof RefLikeType;
}
public static boolean isWide(String typeDescriptor) {
return typeDescriptor.equals("J") || typeDescriptor.equals("D");
}
public static boolean isWide(Type sootType) {
return sootType instanceof LongType || sootType instanceof DoubleType;
}
public static int getRealRegCount(List<Register> regs) {
int regCount = 0;
for (Register r : regs) {
Type regType = r.getType();
regCount += getDexWords(regType);
}
return regCount;
}
public static int getDexWords(Type sootType) {
return isWide(sootType) ? 2 : 1;
}
public static int getDexWords(List<Type> sootTypes) {
int dexWords = 0;
for (Type t : sootTypes) {
dexWords += getDexWords(t);
}
return dexWords;
}
public static int getOutWordCount(Collection<Unit> units) {
int outWords = 0;
for (Unit u : units) {
Stmt stmt = (Stmt) u;
if (stmt.containsInvokeExpr()) {
int wordsForParameters = 0;
InvokeExpr invocation = stmt.getInvokeExpr();
List<Value> args = invocation.getArgs();
for (Value arg : args) {
wordsForParameters += getDexWords(arg.getType());
}
if (!invocation.getMethod().isStatic()) {
wordsForParameters++; // extra word for "this"
}
if (wordsForParameters > outWords) {
outWords = wordsForParameters;
}
}
}
return outWords;
}
// we could use some fancy shift operations...
public static boolean fitsSigned4(long literal) {
return literal >= -8 && literal <= 7;
}
public static boolean fitsSigned8(long literal) {
return literal >= -128 && literal <= 127;
}
public static boolean fitsSigned16(long literal) {
return literal >= -32768 && literal <= 32767;
}
public static boolean fitsSigned32(long literal) {
return literal >= -2147483648 && literal <= 2147483647;
}
public static boolean isNormalMove(Opcode opc) {
return opc.name.startsWith("move") && !opc.name.startsWith("move-result");
}
/**
* Split the signature string using the same algorithm as in method 'Annotation makeSignature(CstString signature)' in dx
* (dx/src/com/android/dx/dex/file/AnnotationUtils.java)
*
* Rules are: "" - scan to ';' or '<'. Consume ';' but not '<'. - scan to 'L' without consuming it. ""
*
* @param sig
* @return
*/
public static List<String> splitSignature(String sig) {
List<String> split = new ArrayList<String>();
int len = sig.length();
int i = 0;
int j = 0;
while (i < len) {
char c = sig.charAt(i);
if (c == 'L') {
j = i + 1;
while (j < len) {
c = sig.charAt(j);
if (c == ';') {
j++;
break;
} else if (c == '<') {
break;
}
j++;
}
} else {
for (j = i + 1; j < len && sig.charAt(j) != 'L'; j++) {
}
}
split.add(sig.substring(i, j));
i = j;
}
return split;
}
}
| 8,097
| 28.881919
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/StmtVisitor.java
|
package soot.toDex;
/*-
* #%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.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.reference.FieldReference;
import soot.ArrayType;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.ShortType;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BreakpointStmt;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.ConcreteRef;
import soot.jimple.Constant;
import soot.jimple.DoubleConstant;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GotoStmt;
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.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.MonitorStmt;
import soot.jimple.NopStmt;
import soot.jimple.ParameterRef;
import soot.jimple.RetStmt;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.StmtSwitch;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThisRef;
import soot.jimple.ThrowStmt;
import soot.toDex.instructions.AbstractPayload;
import soot.toDex.instructions.AddressInsn;
import soot.toDex.instructions.ArrayDataPayload;
import soot.toDex.instructions.Insn;
import soot.toDex.instructions.Insn10t;
import soot.toDex.instructions.Insn10x;
import soot.toDex.instructions.Insn11x;
import soot.toDex.instructions.Insn12x;
import soot.toDex.instructions.Insn21c;
import soot.toDex.instructions.Insn22c;
import soot.toDex.instructions.Insn22x;
import soot.toDex.instructions.Insn23x;
import soot.toDex.instructions.Insn31t;
import soot.toDex.instructions.Insn32x;
import soot.toDex.instructions.InsnWithOffset;
import soot.toDex.instructions.PackedSwitchPayload;
import soot.toDex.instructions.SparseSwitchPayload;
import soot.toDex.instructions.SwitchPayload;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
import soot.util.Switchable;
/**
* A visitor that builds a list of instructions from the Jimple statements it visits.<br>
* <br>
* Use {@link Switchable#apply(soot.util.Switch)} with this visitor to add statements and {@link #getFinalInsns()} to get the
* final dexlib instructions.<br>
* <br>
* These final instructions do have correct offsets, jump targets and register numbers.
*
* @see Insn intermediate representation of an instruction
* @see Instruction final representation of an instruction
*/
public class StmtVisitor implements StmtSwitch {
private final SootMethod belongingMethod;
private final DexArrayInitDetector arrayInitDetector;
protected ConstantVisitor constantV;
protected RegisterAllocator regAlloc;
protected ExprVisitor exprV;
private String lastReturnTypeDescriptor;
private List<Insn> insns;
private List<AbstractPayload> payloads;
// maps used to map Jimple statements to dalvik instructions
private Map<Insn, Stmt> insnStmtMap = new HashMap<>();
private Map<Instruction, LocalRegisterAssignmentInformation> instructionRegisterMap = new IdentityHashMap<>();
private Map<Instruction, Insn> instructionInsnMap = new IdentityHashMap<>();
private Map<Insn, LocalRegisterAssignmentInformation> insnRegisterMap = new IdentityHashMap<>();
private Map<Instruction, AbstractPayload> instructionPayloadMap = new IdentityHashMap<>();
private List<LocalRegisterAssignmentInformation> parameterInstructionsList = new ArrayList<>();
private Map<Constant, Register> monitorRegs = new HashMap<>();
private static final Opcode[] OPCODES = Opcode.values();
// The following are the base opcode values
private static final int AGET_OPCODE = Opcode.AGET.ordinal();
private static final int APUT_OPCODE = Opcode.APUT.ordinal();
private static final int IGET_OPCODE = Opcode.IGET.ordinal();
private static final int IPUT_OPCODE = Opcode.IPUT.ordinal();
private static final int SGET_OPCODE = Opcode.SGET.ordinal();
private static final int SPUT_OPCODE = Opcode.SPUT.ordinal();
// The following modifiers can be added to the opcodes above:
private static final int WIDE_OFFSET = 1; // e.g., AGET_WIDE is AGET_OPCODE + 1
private static final int OBJECT_OFFSET = 2; // e.g., AGET_OBJECT is AGET_OPCODE + 2
private static final int BOOLEAN_OFFSET = 3;
private static final int BYTE_OFFSET = 4;
private static final int CHAR_OFFSET = 5;
private static final int SHORT_OFFSET = 6;
public StmtVisitor(SootMethod belongingMethod, DexArrayInitDetector arrayInitDetector) {
this.belongingMethod = belongingMethod;
this.arrayInitDetector = arrayInitDetector;
constantV = new ConstantVisitor(this);
regAlloc = new RegisterAllocator();
exprV = new ExprVisitor(this, constantV, regAlloc);
insns = new ArrayList<>();
payloads = new ArrayList<>();
}
protected void setLastReturnTypeDescriptor(String typeDescriptor) {
lastReturnTypeDescriptor = typeDescriptor;
}
protected SootClass getBelongingClass() {
return belongingMethod.getDeclaringClass();
}
public Stmt getStmtForInstruction(Instruction instruction) {
Insn insn = this.instructionInsnMap.get(instruction);
if (insn == null) {
return null;
}
return this.insnStmtMap.get(insn);
}
public Insn getInsnForInstruction(Instruction instruction) {
return instructionInsnMap.get(instruction);
}
public Map<Instruction, LocalRegisterAssignmentInformation> getInstructionRegisterMap() {
return this.instructionRegisterMap;
}
public List<LocalRegisterAssignmentInformation> getParameterInstructionsList() {
return parameterInstructionsList;
}
public Map<Instruction, AbstractPayload> getInstructionPayloadMap() {
return this.instructionPayloadMap;
}
public int getInstructionCount() {
return insns.size();
}
public void addInsn(Insn insn, Stmt s) {
insns.add(insn);
if (s != null) {
if (insnStmtMap.put(insn, s) != null) {
throw new RuntimeException("Duplicate instruction");
}
}
}
protected void beginNewStmt(Stmt s) {
// It's a new statement, so we can re-use registers
regAlloc.resetImmediateConstantsPool();
addInsn(new AddressInsn(s), null);
}
public void finalizeInstructions(Set<Unit> trapReferences) {
addPayloads();
finishRegs();
reduceInstructions(trapReferences);
}
/**
* Reduces the instruction list by removing unnecessary instruction pairs such as move v0 v1; move v1 v0;
*
* @param trapReferences
*/
private void reduceInstructions(Set<Unit> trapReferences) {
MultiMap<Stmt, Insn> jumpsToTarget = new HashMultiMap<>();
for (Insn insn : this.insns) {
if (insn instanceof InsnWithOffset) {
Stmt t = ((InsnWithOffset) insn).getTarget();
jumpsToTarget.put(t, insn);
}
}
for (int i = 0; i < this.insns.size() - 1; i++) {
Insn curInsn = this.insns.get(i);
// Only consider real instructions
if (curInsn instanceof AddressInsn) {
continue;
}
if (!isReducableMoveInstruction(curInsn.getOpcode())) {
continue;
}
// Skip over following address instructions
Insn nextInsn = null;
int nextIndex = -1;
for (int j = i + 1; j < this.insns.size(); j++) {
Insn candidate = this.insns.get(j);
if (candidate instanceof AddressInsn) {
continue;
}
nextInsn = candidate;
nextIndex = j;
break;
}
if (nextInsn == null || !isReducableMoveInstruction(nextInsn.getOpcode())) {
continue;
}
// Do not remove the last instruction in the body as we need to
// remap
// jump targets to the successor
if (nextIndex == this.insns.size() - 1) {
continue;
}
// Check if we have a <- b; b <- a;
Register firstTarget = curInsn.getRegs().get(0);
Register firstSource = curInsn.getRegs().get(1);
Register secondTarget = nextInsn.getRegs().get(0);
Register secondSource = nextInsn.getRegs().get(1);
if (firstTarget.equals(secondSource) && secondTarget.equals(firstSource)) {
Stmt nextStmt = insnStmtMap.get(nextInsn);
// Remove the second instruction as it does not change any
// state. We cannot remove the first instruction as other
// instructions may depend on the register being set.
boolean isNotJumpTarget = jumpsToTarget.get(nextStmt).isEmpty();
if (nextStmt == null || (isNotJumpTarget && !trapReferences.contains(nextStmt))) {
Insn removed = insns.remove(nextIndex);
if (removed instanceof InsnWithOffset) {
Stmt t = ((InsnWithOffset) removed).getTarget();
jumpsToTarget.remove(t, removed);
}
if (nextStmt != null) {
if (nextIndex == this.insns.size() - 1) {
// we are now at the end of the list
continue;
}
Insn nextInst = this.insns.get(nextIndex + 1);
insnStmtMap.remove(nextInsn);
insnStmtMap.put(nextInst, nextStmt);
}
}
}
}
}
private boolean isReducableMoveInstruction(Opcode opcode) {
switch (opcode) {
case MOVE:
case MOVE_16:
case MOVE_FROM16:
case MOVE_OBJECT:
case MOVE_OBJECT_16:
case MOVE_OBJECT_FROM16:
case MOVE_WIDE:
case MOVE_WIDE_16:
case MOVE_WIDE_FROM16:
return true;
default:
return false;
}
// Should be equivalent to
// return opcode.startsWith("move/") || opcode.startsWith("move-object/") || opcode.startsWith("move-wide/");
}
private void addPayloads() {
// add switch payloads to the end of the insns
for (AbstractPayload payload : payloads) {
addInsn(new AddressInsn(payload), null);
addInsn(payload, null);
}
}
public List<BuilderInstruction> getRealInsns(LabelAssigner labelAssigner) {
List<BuilderInstruction> finalInsns = new ArrayList<>();
for (Insn i : insns) {
if (i instanceof AddressInsn) {
continue; // skip non-insns
}
BuilderInstruction realInsn = i.getRealInsn(labelAssigner);
finalInsns.add(realInsn);
if (insnStmtMap.containsKey(i)) { // get tags
instructionInsnMap.put(realInsn, i);
}
LocalRegisterAssignmentInformation assignmentInfo = insnRegisterMap.get(i);
if (assignmentInfo != null) {
instructionRegisterMap.put(realInsn, assignmentInfo);
}
if (i instanceof AbstractPayload) {
instructionPayloadMap.put(realInsn, (AbstractPayload) i);
}
}
return finalInsns;
}
public void fakeNewInsn(Stmt s, Insn insn, Instruction instruction) {
this.insnStmtMap.put(insn, s);
this.instructionInsnMap.put(instruction, insn);
}
private void finishRegs() {
// fit registers into insn formats, potentially replacing insns
RegisterAssigner regAssigner = new RegisterAssigner(regAlloc);
insns = regAssigner.finishRegs(insns, insnStmtMap, insnRegisterMap, parameterInstructionsList);
}
protected int getRegisterCount() {
return regAlloc.getRegCount();
}
@Override
public void defaultCase(Object o) {
// not-int and not-long aren't implemented because soot converts "~x" to
// "x ^ (-1)"
// fill-array-data isn't implemented since soot converts "new int[]{x,
// y}" to individual "array put" expressions for x and y
throw new Error("unknown Object (" + o.getClass() + ") as Stmt: " + o);
}
@Override
public void caseBreakpointStmt(BreakpointStmt stmt) {
return; // there are no breakpoints in dex bytecode
}
@Override
public void caseNopStmt(NopStmt stmt) {
addInsn(new Insn10x(Opcode.NOP), stmt);
}
@Override
public void caseRetStmt(RetStmt stmt) {
throw new Error("ret statements are deprecated!");
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
addInsn(buildMonitorInsn(stmt, Opcode.MONITOR_ENTER), stmt);
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
addInsn(buildMonitorInsn(stmt, Opcode.MONITOR_EXIT), stmt);
}
private Insn buildMonitorInsn(MonitorStmt stmt, Opcode opc) {
Value lockValue = stmt.getOp();
constantV.setOrigStmt(stmt);
// When leaving a monitor, we must make sure to re-use the old
// register. If we assign the same class constant to a new register
// before leaving the monitor, Android's bytecode verifier will assume
// that this constant assignment can throw an exception, leaving us
// with a dangling monitor. Imprecise static analyzers ftw.
Register lockReg = null;
if (lockValue instanceof Constant) {
if ((lockReg = monitorRegs.get(lockValue)) != null) {
lockReg = lockReg.clone();
}
}
if (lockReg == null) {
lockReg = regAlloc.asImmediate(lockValue, constantV);
regAlloc.lockRegister(lockReg);
if (lockValue instanceof Constant) {
monitorRegs.put((Constant) lockValue, lockReg);
regAlloc.lockRegister(lockReg);
}
}
return new Insn11x(opc, lockReg);
}
@Override
public void caseThrowStmt(ThrowStmt stmt) {
Value exception = stmt.getOp();
constantV.setOrigStmt(stmt);
Register exceptionReg = regAlloc.asImmediate(exception, constantV);
addInsn(new Insn11x(Opcode.THROW, exceptionReg), stmt);
}
@Override
public void caseAssignStmt(AssignStmt stmt) {
// If this is the beginning of an array initialization, we shortcut the
// normal translation process
List<Value> arrayValues = arrayInitDetector.getValuesForArrayInit(stmt);
if (arrayValues != null) {
Insn insn = buildArrayFillInsn((ArrayRef) stmt.getLeftOp(), arrayValues);
if (insn != null) {
addInsn(insn, stmt);
return;
}
}
if (arrayInitDetector.getIgnoreUnits().contains(stmt)) {
return;
}
constantV.setOrigStmt(stmt);
exprV.setOrigStmt(stmt);
Value lhs = stmt.getLeftOp();
if (lhs instanceof ConcreteRef) {
// special cases that lead to *put* opcodes
Value source = stmt.getRightOp();
addInsn(buildPutInsn((ConcreteRef) lhs, source), stmt);
return;
}
// other cases, where lhs is a local
if (!(lhs instanceof Local)) {
throw new Error("left-hand side of AssignStmt is not a Local: " + lhs.getClass());
}
Local lhsLocal = (Local) lhs;
final Insn newInsn;
Register lhsReg = regAlloc.asLocal(lhsLocal);
Value rhs = stmt.getRightOp();
if (rhs instanceof Local) {
// move rhs local to lhs local, if different
Local rhsLocal = (Local) rhs;
if (lhsLocal == rhsLocal) {
return;
}
Register sourceReg = regAlloc.asLocal(rhsLocal);
newInsn = buildMoveInsn(lhsReg, sourceReg);
addInsn(newInsn, stmt);
} else if (rhs instanceof Constant) {
// move rhs constant into the lhs local
constantV.setDestination(lhsReg);
rhs.apply(constantV);
newInsn = insns.get(insns.size() - 1);
} else if (rhs instanceof ConcreteRef) {
newInsn = buildGetInsn((ConcreteRef) rhs, lhsReg);
addInsn(newInsn, stmt);
} else {
// evaluate rhs expression, saving the result in the lhs local
exprV.setDestinationReg(lhsReg);
rhs.apply(exprV);
if (rhs instanceof InvokeExpr) {
// do the actual "assignment" for an invocation: move its result
// to the lhs reg (it was not used yet)
Insn moveResultInsn = buildMoveResultInsn(lhsReg);
int invokeInsnIndex = exprV.getLastInvokeInstructionPosition();
insns.add(invokeInsnIndex + 1, moveResultInsn);
}
newInsn = insns.get(insns.size() - 1);
}
this.insnRegisterMap.put(newInsn, LocalRegisterAssignmentInformation.v(lhsReg, lhsLocal));
}
private Insn buildGetInsn(ConcreteRef sourceRef, Register destinationReg) {
if (sourceRef instanceof StaticFieldRef) {
return buildStaticFieldGetInsn(destinationReg, (StaticFieldRef) sourceRef);
} else if (sourceRef instanceof InstanceFieldRef) {
return buildInstanceFieldGetInsn(destinationReg, (InstanceFieldRef) sourceRef);
} else if (sourceRef instanceof ArrayRef) {
return buildArrayGetInsn(destinationReg, (ArrayRef) sourceRef);
} else {
throw new RuntimeException("unsupported type of ConcreteRef: " + sourceRef.getClass());
}
}
private Insn buildPutInsn(ConcreteRef destRef, Value source) {
if (destRef instanceof StaticFieldRef) {
return buildStaticFieldPutInsn((StaticFieldRef) destRef, source);
} else if (destRef instanceof InstanceFieldRef) {
return buildInstanceFieldPutInsn((InstanceFieldRef) destRef, source);
} else if (destRef instanceof ArrayRef) {
return buildArrayPutInsn((ArrayRef) destRef, source);
} else {
throw new RuntimeException("unsupported type of ConcreteRef: " + destRef.getClass());
}
}
public static Insn buildMoveInsn(Register destinationReg, Register sourceReg) {
// get the optional opcode suffix, depending on the sizes of the regs
if (!destinationReg.fitsShort()) {
Opcode opc;
if (sourceReg.isObject()) {
opc = Opcode.MOVE_OBJECT_16;
} else if (sourceReg.isWide()) {
opc = Opcode.MOVE_WIDE_16;
} else {
opc = Opcode.MOVE_16;
}
return new Insn32x(opc, destinationReg, sourceReg);
} else if (!destinationReg.fitsByte() || !sourceReg.fitsByte()) {
Opcode opc;
if (sourceReg.isObject()) {
opc = Opcode.MOVE_OBJECT_FROM16;
} else if (sourceReg.isWide()) {
opc = Opcode.MOVE_WIDE_FROM16;
} else {
opc = Opcode.MOVE_FROM16;
}
return new Insn22x(opc, destinationReg, sourceReg);
}
Opcode opc;
if (sourceReg.isObject()) {
opc = Opcode.MOVE_OBJECT;
} else if (sourceReg.isWide()) {
opc = Opcode.MOVE_WIDE;
} else {
opc = Opcode.MOVE;
}
return new Insn12x(opc, destinationReg, sourceReg);
}
private Insn buildStaticFieldPutInsn(StaticFieldRef destRef, Value source) {
Register sourceReg = regAlloc.asImmediate(source, constantV);
FieldReference destField = DexPrinter.toFieldReference(destRef.getFieldRef());
Opcode opc = getPutGetOpcodeWithTypeSuffix(SPUT_OPCODE, destField.getType());
return new Insn21c(opc, sourceReg, destField);
}
private Insn buildInstanceFieldPutInsn(InstanceFieldRef destRef, Value source) {
FieldReference destField = DexPrinter.toFieldReference(destRef.getFieldRef());
Local instance = (Local) destRef.getBase();
Register instanceReg = regAlloc.asLocal(instance);
Register sourceReg = regAlloc.asImmediate(source, constantV);
Opcode opc = getPutGetOpcodeWithTypeSuffix(IPUT_OPCODE, destField.getType());
return new Insn22c(opc, sourceReg, instanceReg, destField);
}
private Insn buildArrayPutInsn(ArrayRef destRef, Value source) {
Local array = (Local) destRef.getBase();
Register arrayReg = regAlloc.asLocal(array);
Value index = destRef.getIndex();
Register indexReg = regAlloc.asImmediate(index, constantV);
Register sourceReg = regAlloc.asImmediate(source, constantV);
String arrayTypeDescriptor = SootToDexUtils.getArrayTypeDescriptor((ArrayType) array.getType());
Opcode opc = getPutGetOpcodeWithTypeSuffix(APUT_OPCODE, arrayTypeDescriptor);
return new Insn23x(opc, sourceReg, arrayReg, indexReg);
}
private Insn buildArrayFillInsn(ArrayRef destRef, List<Value> values) {
Local array = (Local) destRef.getBase();
Register arrayReg = regAlloc.asLocal(array);
// Convert the list of values into a list of numbers
int elementSize = 0;
List<Number> numbers = new ArrayList<Number>(values.size());
for (Value val : values) {
if (val instanceof IntConstant) {
elementSize = Math.max(elementSize, 4);
numbers.add(((IntConstant) val).value);
} else if (val instanceof LongConstant) {
elementSize = Math.max(elementSize, 8);
numbers.add(((LongConstant) val).value);
} else if (val instanceof FloatConstant) {
elementSize = Math.max(elementSize, 4);
numbers.add(((FloatConstant) val).value);
} else if (val instanceof DoubleConstant) {
elementSize = Math.max(elementSize, 8);
numbers.add(((DoubleConstant) val).value);
} else {
return null;
}
}
// For some local types, we know the size upfront
if (destRef.getType() instanceof BooleanType) {
elementSize = 1;
} else if (destRef.getType() instanceof ByteType) {
elementSize = 1;
} else if (destRef.getType() instanceof CharType) {
elementSize = 2;
} else if (destRef.getType() instanceof ShortType) {
elementSize = 2;
} else if (destRef.getType() instanceof IntType) {
elementSize = 4;
} else if (destRef.getType() instanceof FloatType) {
elementSize = 4;
} else if (destRef.getType() instanceof LongType) {
elementSize = 8;
} else if (destRef.getType() instanceof DoubleType) {
elementSize = 8;
}
ArrayDataPayload payload = new ArrayDataPayload(elementSize, numbers);
payloads.add(payload);
Insn31t insn = new Insn31t(Opcode.FILL_ARRAY_DATA, arrayReg);
insn.setPayload(payload);
return insn;
}
private Insn buildStaticFieldGetInsn(Register destinationReg, StaticFieldRef sourceRef) {
FieldReference sourceField = DexPrinter.toFieldReference(sourceRef.getFieldRef());
Opcode opc = getPutGetOpcodeWithTypeSuffix(SGET_OPCODE, sourceField.getType());
return new Insn21c(opc, destinationReg, sourceField);
}
private Insn buildInstanceFieldGetInsn(Register destinationReg, InstanceFieldRef sourceRef) {
Local instance = (Local) sourceRef.getBase();
Register instanceReg = regAlloc.asLocal(instance);
FieldReference sourceField = DexPrinter.toFieldReference(sourceRef.getFieldRef());
Opcode opc = getPutGetOpcodeWithTypeSuffix(IGET_OPCODE, sourceField.getType());
return new Insn22c(opc, destinationReg, instanceReg, sourceField);
}
private Insn buildArrayGetInsn(Register destinationReg, ArrayRef sourceRef) {
Value index = sourceRef.getIndex();
Register indexReg = regAlloc.asImmediate(index, constantV);
Local array = (Local) sourceRef.getBase();
Register arrayReg = regAlloc.asLocal(array);
String arrayTypeDescriptor = SootToDexUtils.getArrayTypeDescriptor((ArrayType) array.getType());
Opcode opc = getPutGetOpcodeWithTypeSuffix(AGET_OPCODE, arrayTypeDescriptor);
return new Insn23x(opc, destinationReg, arrayReg, indexReg);
}
private Opcode getPutGetOpcodeWithTypeSuffix(int opcodeBase, String fieldType) {
if (fieldType.equals("Z")) {
return OPCODES[opcodeBase + BOOLEAN_OFFSET];
} else if (fieldType.equals("I") || fieldType.equals("F")) {
return OPCODES[opcodeBase];
} else if (fieldType.equals("B")) {
return OPCODES[opcodeBase + BYTE_OFFSET];
} else if (fieldType.equals("C")) {
return OPCODES[opcodeBase + CHAR_OFFSET];
} else if (fieldType.equals("S")) {
return OPCODES[opcodeBase + SHORT_OFFSET];
} else if (SootToDexUtils.isWide(fieldType)) {
return OPCODES[opcodeBase + WIDE_OFFSET];
} else if (SootToDexUtils.isObject(fieldType)) {
return OPCODES[opcodeBase + OBJECT_OFFSET];
} else {
throw new RuntimeException("unsupported field type for *put*/*get* opcode: " + fieldType);
}
}
private Insn buildMoveResultInsn(Register destinationReg) {
// build it right after the invoke instruction (more than one
// instruction could have been generated)
Opcode opc;
if (SootToDexUtils.isObject(lastReturnTypeDescriptor)) {
opc = Opcode.MOVE_RESULT_OBJECT;
} else if (SootToDexUtils.isWide(lastReturnTypeDescriptor)) {
opc = Opcode.MOVE_RESULT_WIDE;
} else {
opc = Opcode.MOVE_RESULT;
}
return new Insn11x(opc, destinationReg);
}
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
exprV.setOrigStmt(stmt);
stmt.getInvokeExpr().apply(exprV);
}
@Override
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
addInsn(new Insn10x(Opcode.RETURN_VOID), stmt);
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
Value returnValue = stmt.getOp();
constantV.setOrigStmt(stmt);
Register returnReg = regAlloc.asImmediate(returnValue, constantV);
Opcode opc;
Type retType = returnValue.getType();
if (SootToDexUtils.isObject(retType)) {
opc = Opcode.RETURN_OBJECT;
} else if (SootToDexUtils.isWide(retType)) {
opc = Opcode.RETURN_WIDE;
} else {
opc = Opcode.RETURN;
}
addInsn(new Insn11x(opc, returnReg), stmt);
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
Local lhs = (Local) stmt.getLeftOp();
Value rhs = stmt.getRightOp();
if (rhs instanceof CaughtExceptionRef) {
// save the caught exception with move-exception
Register localReg = regAlloc.asLocal(lhs);
addInsn(new Insn11x(Opcode.MOVE_EXCEPTION, localReg), stmt);
this.insnRegisterMap.put(insns.get(insns.size() - 1), LocalRegisterAssignmentInformation.v(localReg, lhs));
} else if (rhs instanceof ThisRef || rhs instanceof ParameterRef) {
/*
* do not save the ThisRef or ParameterRef in a local, because it always has a parameter register already. at least use
* the local for further reference in the statements
*/
Local localForThis = lhs;
regAlloc.asParameter(belongingMethod, localForThis);
parameterInstructionsList
.add(LocalRegisterAssignmentInformation.v(regAlloc.asLocal(localForThis).clone(), localForThis));
} else {
throw new Error("unknown Value as right-hand side of IdentityStmt: " + rhs);
}
}
@Override
public void caseGotoStmt(GotoStmt stmt) {
Stmt target = (Stmt) stmt.getTarget();
addInsn(buildGotoInsn(target), stmt);
}
private Insn buildGotoInsn(Stmt target) {
if (target == null) {
throw new RuntimeException("Cannot jump to a NULL target");
}
Insn10t insn = new Insn10t(Opcode.GOTO);
insn.setTarget(target);
return insn;
}
@Override
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
exprV.setOrigStmt(stmt);
constantV.setOrigStmt(stmt);
// create payload that references the switch's targets
List<IntConstant> keyValues = stmt.getLookupValues();
int[] keys = new int[keyValues.size()];
for (int i = 0; i < keys.length; i++) {
keys[i] = keyValues.get(i).value;
}
List<Unit> targets = stmt.getTargets();
SparseSwitchPayload payload = new SparseSwitchPayload(keys, targets);
payloads.add(payload);
// create sparse-switch instruction that references the payload
Value key = stmt.getKey();
Stmt defaultTarget = (Stmt) stmt.getDefaultTarget();
if (defaultTarget == stmt) {
throw new RuntimeException("Looping switch block detected");
}
addInsn(buildSwitchInsn(Opcode.SPARSE_SWITCH, key, defaultTarget, payload, stmt), stmt);
}
@Override
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
exprV.setOrigStmt(stmt);
constantV.setOrigStmt(stmt);
// create payload that references the switch's targets
int firstKey = stmt.getLowIndex();
List<Unit> targets = stmt.getTargets();
PackedSwitchPayload payload = new PackedSwitchPayload(firstKey, targets);
payloads.add(payload);
// create packed-switch instruction that references the payload
Value key = stmt.getKey();
Stmt defaultTarget = (Stmt) stmt.getDefaultTarget();
addInsn(buildSwitchInsn(Opcode.PACKED_SWITCH, key, defaultTarget, payload, stmt), stmt);
}
private Insn buildSwitchInsn(Opcode opc, Value key, Stmt defaultTarget, SwitchPayload payload, Stmt stmt) {
Register keyReg = regAlloc.asImmediate(key, constantV);
Insn31t switchInsn = new Insn31t(opc, keyReg);
switchInsn.setPayload(payload);
payload.setSwitchInsn(switchInsn);
addInsn(switchInsn, stmt);
// create instruction to jump to the default target, always follows the
// switch instruction
return buildGotoInsn(defaultTarget);
}
@Override
public void caseIfStmt(IfStmt stmt) {
Stmt target = stmt.getTarget();
exprV.setOrigStmt(stmt);
exprV.setTargetForOffset(target);
stmt.getCondition().apply(exprV);
}
/**
* Pre-allocates and locks registers for the constants used in monitor expressions
*
* @param monitorConsts
* The set of monitor constants fow which to assign fixed registers
*/
public void preAllocateMonitorConsts(Set<ClassConstant> monitorConsts) {
for (ClassConstant c : monitorConsts) {
Register lhsReg = regAlloc.asImmediate(c, constantV);
regAlloc.lockRegister(lhsReg);
monitorRegs.put(c, lhsReg);
}
}
}
| 30,342
| 34.824085
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/SynchronizedMethodTransformer.java
|
package soot.toDex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Singletons;
import soot.Unit;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.Jimple;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.UnitGraph;
/**
* The Dalvik VM requires synchronized methods to explicitly enter a monitor and leave it in a finally block again after
* execution. See http://milk.com/kodebase/dalvik-docs-mirror/docs/debugger.html for more details
*
* @author Steven Arzt
*
*/
public class SynchronizedMethodTransformer extends BodyTransformer {
public SynchronizedMethodTransformer(Singletons.Global g) {
}
public static SynchronizedMethodTransformer v() {
return G.v().soot_toDex_SynchronizedMethodTransformer();
}
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
if (!b.getMethod().isSynchronized() || b.getMethod().isStatic()) {
return;
}
Iterator<Unit> it = b.getUnits().snapshotIterator();
while (it.hasNext()) {
Unit u = it.next();
if (u instanceof IdentityStmt) {
continue;
}
// This the first real statement. If it is not a MonitorEnter
// instruction, we generate one
if (!(u instanceof EnterMonitorStmt)) {
b.getUnits().insertBeforeNoRedirect(Jimple.v().newEnterMonitorStmt(b.getThisLocal()), u);
// We also need to leave the monitor when the method terminates
UnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b);
for (Unit tail : graph.getTails()) {
b.getUnits().insertBefore(Jimple.v().newExitMonitorStmt(b.getThisLocal()), tail);
}
}
break;
}
}
}
| 2,632
| 31.506173
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/TemporaryRegisterLocal.java
|
package soot.toDex;
/*-
* #%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.List;
import soot.Local;
import soot.Type;
import soot.UnitPrinter;
import soot.ValueBox;
import soot.jimple.JimpleValueSwitch;
import soot.util.Switch;
public class TemporaryRegisterLocal implements Local {
private static final long serialVersionUID = 1L;
private Type type;
public TemporaryRegisterLocal(Type regType) {
setType(regType);
}
public Local clone() {
throw new RuntimeException("Not implemented");
}
@Override
public final List<ValueBox> getUseBoxes() {
return Collections.emptyList();
}
@Override
public Type getType() {
return type;
}
@Override
public void toString(UnitPrinter up) {
throw new RuntimeException("Not implemented.");
}
@Override
public void apply(Switch sw) {
((JimpleValueSwitch) sw).caseLocal(this);
}
@Override
public boolean equivTo(Object o) {
return this.equals(o);
}
@Override
public int equivHashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public void setNumber(int number) {
throw new RuntimeException("Not implemented.");
}
@Override
public int getNumber() {
throw new RuntimeException("Not implemented.");
}
@Override
public String getName() {
throw new RuntimeException("Not implemented.");
}
@Override
public void setName(String name) {
throw new RuntimeException("Not implemented.");
}
@Override
public void setType(Type t) {
this.type = t;
}
@Override
public boolean isStackLocal() {
throw new RuntimeException("Not implemented.");
}
}
| 2,533
| 21.828829
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/TrapSplitter.java
|
package soot.toDex;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
/*-
* #%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 java.util.Set;
import soot.Body;
import soot.BodyTransformer;
import soot.Singletons;
import soot.Trap;
import soot.Unit;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.IdentityStmt;
import soot.jimple.Jimple;
import soot.jimple.NullConstant;
import soot.jimple.toolkits.scalar.UnreachableCodeEliminator;
/**
* Transformer that splits nested traps for Dalvik which does not support hierarchies of traps. If we have a trap (1-3) with
* handler A and a trap (2) with handler B, we transform them into three new traps: (1) and (3) with A, (2) with A+B.
*
* @author Steven Arzt
*/
public class TrapSplitter extends BodyTransformer {
public TrapSplitter(Singletons.Global g) {
}
public static TrapSplitter v() {
return soot.G.v().soot_toDex_TrapSplitter();
}
private class TrapOverlap {
private Trap t1;
private Trap t2;
private Unit t2Start;
public TrapOverlap(Trap t1, Trap t2, Unit t2Start) {
this.t1 = t1;
this.t2 = t2;
this.t2Start = t2Start;
}
}
@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() < 2) {
return;
}
Set<Unit> potentiallyUselessTrapHandlers = null;
// Look for overlapping traps
TrapOverlap to;
while ((to = getNextOverlap(b)) != null) {
// If one of the two traps is empty, we remove it
if (to.t1.getBeginUnit() == to.t1.getEndUnit()) {
b.getTraps().remove(to.t1);
if (potentiallyUselessTrapHandlers == null) {
potentiallyUselessTrapHandlers = new HashSet<>();
}
potentiallyUselessTrapHandlers.add(to.t1.getHandlerUnit());
continue;
}
if (to.t2.getBeginUnit() == to.t2.getEndUnit()) {
b.getTraps().remove(to.t2);
if (potentiallyUselessTrapHandlers == null) {
potentiallyUselessTrapHandlers = new HashSet<>();
}
potentiallyUselessTrapHandlers.add(to.t2.getHandlerUnit());
continue;
}
// t1start..t2start -> t1'start...t1'end,t2start...
if (to.t1.getBeginUnit() != to.t2Start) {
// We need to split off t1.start - predOf(t2.splitUnit). If both traps
// start at the same statement, this range is empty, so we have checked
// that.
Trap newTrap = Jimple.v().newTrap(to.t1.getException(), to.t1.getBeginUnit(), to.t2Start, to.t1.getHandlerUnit());
safeAddTrap(b, newTrap, to.t1);
to.t1.setBeginUnit(to.t2Start);
}
// (t1start, t2start) ... t1end ... t2end
else if (to.t1.getBeginUnit() == to.t2.getBeginUnit()) {
Unit firstEndUnit = to.t1.getBeginUnit();
while (firstEndUnit != to.t1.getEndUnit() && firstEndUnit != to.t2.getEndUnit()) {
firstEndUnit = b.getUnits().getSuccOf(firstEndUnit);
}
if (firstEndUnit == to.t1.getEndUnit()) {
if (to.t1.getException() != to.t2.getException()) {
Trap newTrap
= Jimple.v().newTrap(to.t2.getException(), to.t1.getBeginUnit(), firstEndUnit, to.t2.getHandlerUnit());
safeAddTrap(b, newTrap, to.t2);
} else if (to.t1.getHandlerUnit() != to.t2.getHandlerUnit()) {
// Traps t1 and t2 catch the same exception, but have different handlers
//
// The JVM specification (2.10 Exceptions) says:
// "At run time, when an exception is thrown, the Java
// Virtual Machine searches the exception handlers of the current method in the order
// that they appear in the corresponding exception handler table in the class file,
// starting from the beginning of that table. Note that the Java Virtual Machine does
// not enforce nesting of or any ordering of the exception table entries of a method.
// The exception handling semantics of the Java programming language are implemented
// only through cooperation with the compiler (3.12)."
//
// 3.12
// "The nesting of catch clauses is represented only in the exception table. The Java
// Virtual Machine does not enforce nesting of or any ordering of the exception table
// entries (2.10). However, because try-catch constructs are structured, a compiler
// can always order the entries of the exception handler table such that, for any thrown
// exception and any program counter value in that method, the first exception handler
// that matches the thrown exception corresponds to the innermost matching catch clause."
//
// t1 is first, so it stays the same.
// t2 is reduced
Trap newTrap
= Jimple.v().newTrap(to.t1.getException(), to.t1.getBeginUnit(), firstEndUnit, to.t1.getHandlerUnit());
safeAddTrap(b, newTrap, to.t1);
}
to.t2.setBeginUnit(firstEndUnit);
} else if (firstEndUnit == to.t2.getEndUnit()) {
if (to.t1.getException() != to.t2.getException()) {
Trap newTrap2
= Jimple.v().newTrap(to.t1.getException(), to.t1.getBeginUnit(), firstEndUnit, to.t1.getHandlerUnit());
safeAddTrap(b, newTrap2, to.t1);
to.t1.setBeginUnit(firstEndUnit);
} else if (to.t1.getHandlerUnit() != to.t2.getHandlerUnit()) {
// If t2 ends first, t2 is useless.
b.getTraps().remove(to.t2);
if (potentiallyUselessTrapHandlers == null) {
potentiallyUselessTrapHandlers = new HashSet<>();
}
potentiallyUselessTrapHandlers.add(to.t2.getHandlerUnit());
} else {
to.t1.setBeginUnit(firstEndUnit);
}
}
}
}
removePotentiallyUselassTraps(b, potentiallyUselessTrapHandlers);
}
/**
* Changes the given body so that trap handlers, which are contained in the given set, are removed in case they are not
* referenced by any trap. The list is changed so that it contains the unreferenced trap handlers.
*
* @param b
* the body
* @param potentiallyUselessTrapHandlers
* potentially useless trap handlers
*/
public static void removePotentiallyUselassTraps(Body b, Set<Unit> potentiallyUselessTrapHandlers) {
if (potentiallyUselessTrapHandlers == null) {
return;
}
for (Trap t : b.getTraps()) {
// Trap is used by another trap handler, so it is not useless
potentiallyUselessTrapHandlers.remove(t.getHandlerUnit());
}
boolean removedUselessTrap = false;
for (Unit uselessTrapHandler : potentiallyUselessTrapHandlers) {
if (uselessTrapHandler instanceof IdentityStmt) {
IdentityStmt assign = (IdentityStmt) uselessTrapHandler;
if (assign.getRightOp() instanceof CaughtExceptionRef) {
// Make sure that the useless trap handler, which is not used
// anywhere else still gets a valid value.
Unit newStmt = Jimple.v().newAssignStmt(assign.getLeftOp(), NullConstant.v());
b.getUnits().swapWith(assign, newStmt);
removedUselessTrap = true;
}
}
}
if (removedUselessTrap) {
// We cleaned up the useless trap, it hopefully is unreachable
UnreachableCodeEliminator.v().transform(b);
}
}
/**
* Adds a new trap to the given body only if the given trap is not empty
*
* @param b
* The body to which to add the trap
* @param newTrap
* The trap to add
* @param position
* The position after which to insert the trap
*/
private void safeAddTrap(Body b, Trap newTrap, Trap position) {
// Do not create any empty traps
if (newTrap.getBeginUnit() != newTrap.getEndUnit()) {
if (position != null) {
b.getTraps().insertAfter(newTrap, position);
} else {
b.getTraps().add(newTrap);
}
}
}
/**
* Gets two arbitrary overlapping traps t1, t2 in the given method body. The begin unit of the t2 should be equal to or
* occurring after the begin unit of t1.
*
* @param b
* The body in which to look for overlapping traps
* @return Two overlapping traps if they exist, otherwise null
*/
private TrapOverlap getNextOverlap(Body b) {
Map<Unit, LinkedHashSet<Trap>> trapsContainingThisUnit = new HashMap<>();
for (Trap t1 : b.getTraps()) {
// Look whether one of our trapped statements is the begin
// statement of another trap
for (Unit splitUnit = t1.getBeginUnit(); splitUnit != t1.getEndUnit() && splitUnit != null; splitUnit
= b.getUnits().getSuccOf(splitUnit)) {
LinkedHashSet<Trap> otherTrapsContainingUnit = trapsContainingThisUnit.get(splitUnit);
if (otherTrapsContainingUnit != null) {
for (Trap t2 : otherTrapsContainingUnit) {
// if we got here, this unit is already contained inside another trap.
// the other traps were added earlier
if (t2.getEndUnit() != t1.getEndUnit() || t2.getException() == t1.getException()) {
// this restores the old function behavior
if (splitUnit == t1.getBeginUnit()) {
return new TrapOverlap(t2, t1, splitUnit);
} else {
return new TrapOverlap(t1, t2, splitUnit);
}
}
}
otherTrapsContainingUnit.add(t1);
} else {
LinkedHashSet<Trap> newSet = new LinkedHashSet<>();
newSet.add(t1);
trapsContainingThisUnit.put(splitUnit, newSet);
}
}
}
return null;
}
}
| 10,687
| 38.150183
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/AbstractInsn.java
|
package soot.toDex.instructions;
/*-
* #%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.List;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
import soot.toDex.SootToDexUtils;
/**
* Abstract implementation of an {@link Insn}.
*/
public abstract class AbstractInsn implements Insn {
protected Opcode opc;
protected List<Register> regs;
public AbstractInsn(Opcode opc) {
if (opc == null) {
throw new IllegalArgumentException("opcode must not be null");
}
this.opc = opc;
regs = new ArrayList<Register>();
}
public Opcode getOpcode() {
return opc;
}
public List<Register> getRegs() {
return regs;
}
public BitSet getIncompatibleRegs() {
return new BitSet(0);
}
public boolean hasIncompatibleRegs() {
return getIncompatibleRegs().cardinality() > 0;
}
public int getMinimumRegsNeeded() {
BitSet incompatRegs = getIncompatibleRegs();
int resultNeed = 0;
int miscRegsNeed = 0;
boolean hasResult = opc.setsRegister();
if (hasResult && incompatRegs.get(0)) {
resultNeed = SootToDexUtils.getDexWords(regs.get(0).getType());
}
for (int i = hasResult ? 1 : 0; i < regs.size(); i++) {
if (incompatRegs.get(i)) {
miscRegsNeed += SootToDexUtils.getDexWords(regs.get(i).getType());
}
}
// The /2addr instruction format takes two operands and overwrites the
// first operand register with the result. The result register is thus
// not free to overlap as we still need to provide input data in it.
// add-long/2addr r0 r0 -> 2 registers
// add-int r0 r0 r2 -> 2 registers, re-use result register
if (opc.name.endsWith("/2addr")) {
return resultNeed + miscRegsNeed;
} else {
return Math.max(resultNeed, miscRegsNeed);
}
}
@Override
public BuilderInstruction getRealInsn(LabelAssigner assigner) {
if (hasIncompatibleRegs()) {
throw new RuntimeException("the instruction still has incompatible registers: " + getIncompatibleRegs());
}
return getRealInsn0(assigner);
}
protected abstract BuilderInstruction getRealInsn0(LabelAssigner assigner);
@Override
public String toString() {
return opc.toString() + " " + regs;
}
public int getSize() {
return opc.format.size / 2; // the format size is in byte count, we need word count
}
}
| 3,267
| 27.666667
| 111
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/AbstractPayload.java
|
package soot.toDex.instructions;
/*-
* #%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 org.jf.dexlib2.Opcode;
/**
* Abstract base class for all payloads (switch, fill-array) in dex instructions
*
* @author Steven Arzt
*
*/
public abstract class AbstractPayload extends InsnWithOffset {
public AbstractPayload() {
super(Opcode.NOP);
}
}
| 1,125
| 27.15
| 80
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/AddressInsn.java
|
package soot.toDex.instructions;
/*-
* #%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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import soot.toDex.LabelAssigner;
/**
* Inspired by com.android.dx.dex.code.CodeAddress: pseudo instruction for use as jump target or start/end of an exception
* handler range. It has size zero, so that its offset is the same as the following real instruction.
*/
public class AddressInsn extends AbstractInsn {
private Object originalSource;
public AddressInsn(Object originalSource) {
super(Opcode.NOP);
this.originalSource = originalSource;
}
public Object getOriginalSource() {
return originalSource;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return null;
}
@Override
public int getSize() {
return 0;
}
@Override
public String toString() {
return "address instruction for " + originalSource;
}
}
| 1,732
| 26.951613
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/ArrayDataPayload.java
|
package soot.toDex.instructions;
/*-
* #%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 org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderArrayPayload;
import soot.toDex.LabelAssigner;
/**
* Payload for the fill-array-data instructions in dex
*
* @author Steven Arzt
*
*/
public class ArrayDataPayload extends AbstractPayload {
private final int elementWidth;
private final List<Number> arrayElements;
public ArrayDataPayload(int elementWidth, List<Number> arrayElements) {
super();
this.elementWidth = elementWidth;
this.arrayElements = arrayElements;
}
@Override
public int getSize() {
// size = (identFieldSize+sizeFieldSize) + numValues * (valueSize)
return 4 + (arrayElements.size() * elementWidth + 1) / 2;
}
@Override
public int getMaxJumpOffset() {
return Short.MAX_VALUE;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderArrayPayload(elementWidth, arrayElements);
}
}
| 1,831
| 26.757576
| 73
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/FiveRegInsn.java
|
package soot.toDex.instructions;
/*-
* #%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.toDex.Register;
/**
* Interface for instructions that need five registers.<br>
* <br>
* Note that the interface does not inherit from {@link ThreeRegInsn} due to the unusual register naming - the register
* indices cannot be overwritten here.
*/
public interface FiveRegInsn extends Insn {
static final int REG_D_IDX = 0;
static final int REG_E_IDX = REG_D_IDX + 1;
static final int REG_F_IDX = REG_E_IDX + 1;
static final int REG_G_IDX = REG_F_IDX + 1;
static final int REG_A_IDX = REG_G_IDX + 1;
Register getRegD();
Register getRegE();
Register getRegF();
Register getRegG();
Register getRegA();
}
| 1,500
| 26.290909
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import java.util.List;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* Interface for the dalvik instruction formats.
*/
public interface Insn extends Cloneable {
Opcode getOpcode();
List<Register> getRegs();
BitSet getIncompatibleRegs();
boolean hasIncompatibleRegs();
int getMinimumRegsNeeded();
BuilderInstruction getRealInsn(LabelAssigner assigner);
int getSize();
}
| 1,372
| 24.90566
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn10t.java
|
package soot.toDex.instructions;
/*-
* #%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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction10t;
import soot.toDex.LabelAssigner;
/**
* The "10t" instruction format: It needs one 16-bit code unit, does not have any registers and is used for jump targets
* (hence the "t").<br>
* <br>
* It is used by the "goto" opcode for jumps to offsets up to 8 bits away.
*/
public class Insn10t extends InsnWithOffset {
public Insn10t(Opcode opc) {
super(opc);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
if (target == null) {
throw new RuntimeException("Cannot jump to a NULL target");
}
return new BuilderInstruction10t(opc, assigner.getOrCreateLabel(target));
}
@Override
public int getMaxJumpOffset() {
return Byte.MAX_VALUE;
}
}
| 1,710
| 29.017544
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn10x.java
|
package soot.toDex.instructions;
/*-
* #%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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction10x;
import soot.toDex.LabelAssigner;
/**
* The "10x" instruction format: It needs one 16-bit code unit, does not have any registers and is used for general purposes
* (hence the "x").<br>
* <br>
* It is used by the opcodes "nop" and "return-void".
*/
public class Insn10x extends AbstractInsn {
public Insn10x(Opcode opc) {
super(opc);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction10x(opc);
}
}
| 1,479
| 29.833333
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn11n.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction11n;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "11n" instruction format: It needs one 16-bit code unit, has one register and is used for a 4-bit literal (hence the
* "n" for "nibble").<br>
* <br>
* It is used by the opcode "const/4".
*/
public class Insn11n extends AbstractInsn implements OneRegInsn {
private byte litB;
public Insn11n(Opcode opc, Register regA, byte litB) {
super(opc);
regs.add(regA);
this.litB = litB;
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public byte getLitB() {
return litB;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction11n(opc, (byte) getRegA().getNumber(), getLitB());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(1);
if (!getRegA().fitsByte()) {
incompatRegs.set(REG_A_IDX);
}
return incompatRegs;
}
@Override
public String toString() {
return super.toString() + " lit: " + getLitB();
}
}
| 2,082
| 26.051948
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn11x.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction11x;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "11x" instruction format: It needs one 16-bit code unit, has one register and is used for general purposes (hence the
* "x").<br>
* <br>
* It is used e.g. by the opcodes "monitor-enter", "monitor-exit", "move-result" and "return".
*/
public class Insn11x extends AbstractInsn implements OneRegInsn {
public Insn11x(Opcode opc, Register regA) {
super(opc);
regs.add(regA);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction11x(opc, (short) getRegA().getNumber());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(1);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
return incompatRegs;
}
}
| 1,916
| 28.492308
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn12x.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction12x;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "12x" instruction format: It needs one 16-bit code unit, has two registers and is used for general purposes (hence the
* "x").<br>
* <br>
* It is used e.g. by the opcodes "move-object", "array-length", the unary operations and the "/2addr" binary operations.
*/
public class Insn12x extends AbstractInsn implements TwoRegInsn {
public Insn12x(Opcode opc, Register regA, Register regB) {
super(opc);
regs.add(regA);
regs.add(regB);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public Register getRegB() {
return regs.get(REG_B_IDX);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction12x(opc, (byte) getRegA().getNumber(), (byte) getRegB().getNumber());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(2);
if (!getRegA().fitsByte()) {
incompatRegs.set(REG_A_IDX);
}
if (!getRegB().fitsByte()) {
incompatRegs.set(REG_B_IDX);
}
return incompatRegs;
}
}
| 2,148
| 28.438356
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn20t.java
|
package soot.toDex.instructions;
/*-
* #%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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction20t;
import soot.toDex.LabelAssigner;
/**
* The "20t" instruction format: It needs two 16-bit code units, does not have any registers and is used for jump targets
* (hence the "t").<br>
* <br>
* It is used by the "goto/16" opcode for jumps to a 16-bit wide offset.
*/
public class Insn20t extends InsnWithOffset {
public Insn20t(Opcode opc) {
super(opc);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction20t(opc, assigner.getOrCreateLabel(target));
}
@Override
public int getMaxJumpOffset() {
return Short.MAX_VALUE;
}
}
| 1,612
| 28.87037
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn21c.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction21c;
import org.jf.dexlib2.iface.reference.Reference;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "21c" instruction format: It needs two 16-bit code units, has one register and is used for class/string/type items
* (hence the "c" for "constant pool").<br>
* <br>
* It is used e.g. by the opcodes "check-cast", "new-instance" and "const-string".
*/
public class Insn21c extends AbstractInsn implements OneRegInsn {
private Reference referencedItem;
public Insn21c(Opcode opc, Register regA, Reference referencedItem) {
super(opc);
regs.add(regA);
this.referencedItem = referencedItem;
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction21c(opc, (short) getRegA().getNumber(), referencedItem);
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(1);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
return incompatRegs;
}
@Override
public String toString() {
return super.toString() + " ref: " + referencedItem;
}
}
| 2,205
| 28.810811
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn21s.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction21s;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "21s" instruction format: It needs two 16-bit code units, has one register and is used for a 16-bit literal (hence the
* "s" for "short").<br>
* <br>
* It is used by the opcodes "const/16" and "const-wide/16".
*/
public class Insn21s extends AbstractInsn implements OneRegInsn {
private short litB;
public Insn21s(Opcode opc, Register regA, short litB) {
super(opc);
regs.add(regA);
this.litB = litB;
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public short getLitB() {
return litB;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction21s(opc, (short) getRegA().getNumber(), getLitB());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(1);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
return incompatRegs;
}
@Override
public String toString() {
return super.toString() + " lit: " + getLitB();
}
}
| 2,110
| 26.415584
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn21t.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction21t;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "21t" instruction format: It needs two 16-bit code units, has one register and is used for jump targets (hence the
* "t").<br>
* <br>
* It is used e.g. by the opcode "if-eqz" for conditional jumps to a 16-bit wide offset.
*/
public class Insn21t extends InsnWithOffset implements OneRegInsn {
public Insn21t(Opcode opc, Register regA) {
super(opc);
regs.add(regA);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction21t(opc, (short) getRegA().getNumber(), assigner.getOrCreateLabel(target));
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(1);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
return incompatRegs;
}
@Override
public int getMaxJumpOffset() {
return Short.MAX_VALUE;
}
}
| 2,024
| 27.521127
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn22b.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction22b;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "22b" instruction format: It needs two 16-bit code units, has two registers and is used for a 8-bit literal (hence the
* "b" for "byte").<br>
* <br>
* It is used by the "/lit8" opcodes for binary operations.
*/
public class Insn22b extends AbstractInsn implements TwoRegInsn {
private byte litC;
public Insn22b(Opcode opc, Register regA, Register regB, byte litC) {
super(opc);
regs.add(regA);
regs.add(regB);
this.litC = litC;
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public Register getRegB() {
return regs.get(REG_B_IDX);
}
public byte getLitC() {
return litC;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction22b(opc, (short) getRegA().getNumber(), (short) getRegB().getNumber(), getLitC());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(2);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
if (!getRegB().fitsShort()) {
incompatRegs.set(REG_B_IDX);
}
return incompatRegs;
}
@Override
public String toString() {
return super.toString() + " lit: " + getLitC();
}
}
| 2,313
| 26.223529
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn22c.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction22c;
import org.jf.dexlib2.iface.reference.Reference;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "22c" instruction format: It needs two 16-bit code units, has two registers and is used for class/type items (hence
* the "c" for "constant pool").<br>
* <br>
* It is used e.g. by the opcodes "instance-of", "new-array" and "iget".
*/
public class Insn22c extends AbstractInsn implements TwoRegInsn {
private Reference referencedItem;
public Insn22c(Opcode opc, Register regA, Register regB, Reference referencedItem) {
super(opc);
regs.add(regA);
regs.add(regB);
this.referencedItem = referencedItem;
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public Register getRegB() {
return regs.get(REG_B_IDX);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction22c(opc, getRegA().getNumber(), getRegB().getNumber(), referencedItem);
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(2);
if (!getRegA().fitsByte()) {
incompatRegs.set(REG_A_IDX);
}
if (!getRegB().fitsByte()) {
incompatRegs.set(REG_B_IDX);
}
return incompatRegs;
}
@Override
public String toString() {
return super.toString() + " ref: " + referencedItem;
}
}
| 2,379
| 28.02439
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn22s.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction22s;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "22s" instruction format: It needs two 16-bit code units, has two registers and is used for a 16-bit literal (hence
* the "s" for "short").<br>
* <br>
* It is used by the "/lit16" opcodes for binary operations.
*/
public class Insn22s extends AbstractInsn implements TwoRegInsn {
private short litC;
public Insn22s(Opcode opc, Register regA, Register regB, short litC) {
super(opc);
regs.add(regA);
regs.add(regB);
this.litC = litC;
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public Register getRegB() {
return regs.get(REG_B_IDX);
}
public short getLitC() {
return litC;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction22s(opc, (byte) getRegA().getNumber(), (byte) getRegB().getNumber(), getLitC());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(2);
if (!getRegA().fitsByte()) {
incompatRegs.set(REG_A_IDX);
}
if (!getRegB().fitsByte()) {
incompatRegs.set(REG_B_IDX);
}
return incompatRegs;
}
@Override
public String toString() {
return super.toString() + " lit: " + getLitC();
}
}
| 2,315
| 26.247059
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn22t.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction22t;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "22t" instruction format: It needs two 16-bit code units, has two registers and is used for jump targets (hence the
* "t").<br>
* <br>
* It is used e.g. by the opcode "if-eq" for conditional jumps to a 16-bit wide offset.
*/
public class Insn22t extends InsnWithOffset implements TwoRegInsn {
public Insn22t(Opcode opc, Register regA, Register regB) {
super(opc);
regs.add(regA);
regs.add(regB);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public Register getRegB() {
return regs.get(REG_B_IDX);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction22t(opc, (byte) getRegA().getNumber(), (byte) getRegB().getNumber(),
assigner.getOrCreateLabel(target));
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(2);
if (!getRegA().fitsByte()) {
incompatRegs.set(REG_A_IDX);
}
if (!getRegB().fitsByte()) {
incompatRegs.set(REG_B_IDX);
}
return incompatRegs;
}
@Override
public int getMaxJumpOffset() {
return Short.MAX_VALUE;
}
}
| 2,236
| 26.9625
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn22x.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction22x;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "22x" instruction format: It needs two 16-bit code units, has two registers and is used for general purposes (hence
* the "x").<br>
* <br>
* It is used by the opcodes "move/from16", "move-wide/from16" and "move-object/from16".
*/
public class Insn22x extends AbstractInsn implements TwoRegInsn {
public Insn22x(Opcode opc, Register regA, Register regB) {
super(opc);
regs.add(regA);
regs.add(regB);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public Register getRegB() {
return regs.get(REG_B_IDX);
}
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction22x(opc, (short) getRegA().getNumber(), getRegB().getNumber());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(2);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
if (!getRegB().fitsUnconstrained()) {
incompatRegs.set(REG_B_IDX);
}
return incompatRegs;
}
}
| 2,108
| 28.291667
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn23x.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction23x;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "23x" instruction format: It needs two 16-bit code units, has three registers and is used for general purposes (hence
* the "x").<br>
* <br>
* It is used e.g. by the opcodes "cmp-long", "aput" and "add-int".
*/
public class Insn23x extends AbstractInsn implements ThreeRegInsn {
public Insn23x(Opcode opc, Register regA, Register regB, Register regC) {
super(opc);
regs.add(regA);
regs.add(regB);
regs.add(regC);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public Register getRegB() {
return regs.get(REG_B_IDX);
}
public Register getRegC() {
return regs.get(REG_C_IDX);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction23x(opc, (short) getRegA().getNumber(), (short) getRegB().getNumber(),
(short) getRegC().getNumber());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(3);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
if (!getRegB().fitsShort()) {
incompatRegs.set(REG_B_IDX);
}
if (!getRegC().fitsShort()) {
incompatRegs.set(REG_C_IDX);
}
return incompatRegs;
}
}
| 2,319
| 27.292683
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn30t.java
|
package soot.toDex.instructions;
/*-
* #%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 org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction30t;
import soot.toDex.LabelAssigner;
/**
* The "30t" instruction format: It needs three 16-bit code units, does not have any registers and is used for jump targets
* (hence the "t").<br>
* <br>
* It is used by the "goto/32" opcode for jumps to a 32-bit wide offset.
*/
public class Insn30t extends InsnWithOffset {
public Insn30t(Opcode opc) {
super(opc);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction30t(opc, assigner.getOrCreateLabel(target));
}
@Override
public int getMaxJumpOffset() {
return Integer.MAX_VALUE;
}
}
| 1,616
| 28.944444
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn31i.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction31i;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "31i" instruction format: It needs three 16-bit code units, has one register and is used for a 32-bit literal (hence
* the "i" for "integer").<br>
* <br>
* It is used by the opcodes "const" and "const-wide/32".
*/
public class Insn31i extends AbstractInsn implements OneRegInsn {
private int litB;
public Insn31i(Opcode opc, Register regA, int litB) {
super(opc);
regs.add(regA);
this.litB = litB;
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public int getLitB() {
return litB;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction31i(opc, (short) getRegA().getNumber(), getLitB());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(1);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
return incompatRegs;
}
@Override
public String toString() {
return super.toString() + " lit: " + getLitB();
}
}
| 2,105
| 26.350649
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn31t.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction31t;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "31t" instruction format: It needs three 16-bit code units, has one register and is used for jump targets (hence the
* "t").<br>
* <br>
* It is used e.g. by the opcodes "packed-switch" and "sparse-switch".
*/
public class Insn31t extends InsnWithOffset implements OneRegInsn {
public AbstractPayload payload = null;
public Insn31t(Opcode opc, Register regA) {
super(opc);
regs.add(regA);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public void setPayload(AbstractPayload payload) {
this.payload = payload;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction31t(opc, (short) getRegA().getNumber(), assigner.getOrCreateLabel(payload));
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(1);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
return incompatRegs;
}
@Override
public int getMaxJumpOffset() {
return Short.MAX_VALUE;
}
}
| 2,136
| 26.753247
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn32x.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction32x;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "32x" instruction format: It needs three 16-bit code units, has two registers and is used for general purposes (hence
* the "x").<br>
* <br>
* It is used by the opcodes "move/16", "move-wide/16" and "move-object/16".
*/
public class Insn32x extends AbstractInsn implements TwoRegInsn {
public Insn32x(Opcode opc, Register regA, Register regB) {
super(opc);
regs.add(regA);
regs.add(regB);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public Register getRegB() {
return regs.get(REG_B_IDX);
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction32x(opc, getRegA().getNumber(), getRegB().getNumber());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(2);
if (!getRegA().fitsUnconstrained()) {
incompatRegs.set(REG_A_IDX);
}
if (!getRegB().fitsUnconstrained()) {
incompatRegs.set(REG_B_IDX);
}
return incompatRegs;
}
}
| 2,110
| 27.917808
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn35c.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction35c;
import org.jf.dexlib2.iface.reference.Reference;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "35c" instruction format: It needs three 16-bit code units, has five registers and is used for method/type items
* (hence the "c" for "constant pool").<br>
* <br>
* It is used by the "filled-new-array" opcode and the various "invoke-" opcodes.<br>
* <br>
* IMPLEMENTATION NOTE: the wide args for "35c" must be explicitly stated - internally, such args are implicitly represented
* by e.g. "regD = wide, regE = emptyReg" to avoid using null and to distinguish the first "half" of a wide reg from the
* second one. this is made explicit ("regD.num, regD.num + 1") while building the real insn and while getting the "real"
* explicit reg numbers.
*/
public class Insn35c extends AbstractInsn implements FiveRegInsn {
private int regCount;
private final Reference referencedItem;
public Insn35c(Opcode opc, int regCount, Register regD, Register regE, Register regF, Register regG, Register regA,
Reference referencedItem) {
super(opc);
this.regCount = regCount;
regs.add(regD);
regs.add(regE);
regs.add(regF);
regs.add(regG);
regs.add(regA);
this.referencedItem = referencedItem;
}
public Register getRegD() {
return regs.get(REG_D_IDX);
}
public Register getRegE() {
return regs.get(REG_E_IDX);
}
public Register getRegF() {
return regs.get(REG_F_IDX);
}
public Register getRegG() {
return regs.get(REG_G_IDX);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
private static boolean isImplicitWide(Register firstReg, Register secondReg) {
return firstReg.isWide() && secondReg.isEmptyReg();
}
private static int getPossiblyWideNumber(Register reg, Register previousReg) {
if (isImplicitWide(previousReg, reg)) {
// we cannot use reg.getNumber(), since the empty reg's number is always 0
return previousReg.getNumber() + 1;
}
return reg.getNumber();
}
private int[] getRealRegNumbers() {
int[] realRegNumbers = new int[5];
Register regD = getRegD();
Register regE = getRegE();
Register regF = getRegF();
Register regG = getRegG();
Register regA = getRegA();
realRegNumbers[REG_D_IDX] = regD.getNumber();
realRegNumbers[REG_E_IDX] = getPossiblyWideNumber(regE, regD);
realRegNumbers[REG_F_IDX] = getPossiblyWideNumber(regF, regE);
realRegNumbers[REG_G_IDX] = getPossiblyWideNumber(regG, regF);
realRegNumbers[REG_A_IDX] = getPossiblyWideNumber(regA, regG);
return realRegNumbers;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
int[] realRegNumbers = getRealRegNumbers();
byte regDNumber = (byte) realRegNumbers[REG_D_IDX];
byte regENumber = (byte) realRegNumbers[REG_E_IDX];
byte regFNumber = (byte) realRegNumbers[REG_F_IDX];
byte regGNumber = (byte) realRegNumbers[REG_G_IDX];
byte regANumber = (byte) realRegNumbers[REG_A_IDX];
return new BuilderInstruction35c(opc, regCount, regDNumber, regENumber, regFNumber, regGNumber, regANumber,
referencedItem);
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(5);
int[] realRegNumbers = getRealRegNumbers();
for (int i = 0; i < realRegNumbers.length; i++) {
// real regs aren't wide, because those are represented as two non-wide regs
boolean isCompatible = Register.fitsByte(realRegNumbers[i], false);
if (!isCompatible) {
incompatRegs.set(i);
// if second half of a wide reg is incompatible, so is its first half
Register possibleSecondHalf = regs.get(i);
if (possibleSecondHalf.isEmptyReg() && i > 0) {
Register possibleFirstHalf = regs.get(i - 1);
if (possibleFirstHalf.isWide()) {
incompatRegs.set(i - 1);
}
}
}
}
return incompatRegs;
}
@Override
public String toString() {
return super.toString() + " (" + regCount + " regs), ref: " + referencedItem;
}
}
| 5,106
| 33.046667
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn3rc.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import java.util.List;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction3rc;
import org.jf.dexlib2.iface.reference.Reference;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
import soot.toDex.SootToDexUtils;
/**
* The "3rc" instruction format: It needs three 16-bit code units, has a whole range of registers (hence the "r" for
* "ranged") and is used for method/type items (hence the "c" for "constant pool").<br>
* <br>
* It is used by the "filled-new-array/range" opcode and the various ranged "invoke-" opcodes.
*/
public class Insn3rc extends AbstractInsn {
private short regCount;
private Reference referencedItem;
public Insn3rc(Opcode opc, List<Register> regs, short regCount, Reference referencedItem) {
super(opc);
this.regs = regs;
this.regCount = regCount;
this.referencedItem = referencedItem;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
Register startReg = regs.get(0);
return new BuilderInstruction3rc(opc, startReg.getNumber(), regCount, referencedItem);
}
@Override
public BitSet getIncompatibleRegs() {
// if there is one problem -> all regs are incompatible (this could be optimized in reg allocation, probably)
int regCount = SootToDexUtils.getRealRegCount(regs);
if (hasHoleInRange()) {
return getAllIncompatible(regCount);
}
for (Register r : regs) {
if (!r.fitsUnconstrained()) {
return getAllIncompatible(regCount);
}
if (r.isWide()) {
boolean secondWideHalfFits = Register.fitsUnconstrained(r.getNumber() + 1, false);
if (!secondWideHalfFits) {
return getAllIncompatible(regCount);
}
}
}
return new BitSet(regCount);
}
private static BitSet getAllIncompatible(int regCount) {
BitSet incompatRegs = new BitSet(regCount);
incompatRegs.flip(0, regCount);
return incompatRegs;
}
private boolean hasHoleInRange() {
// the only "hole" that is allowed: if regN is wide -> regN+1 must not be there
Register startReg = regs.get(0);
int nextExpectedRegNum = startReg.getNumber() + 1;
if (startReg.isWide()) {
nextExpectedRegNum++;
}
// loop starts at 1, since the first reg alone cannot have a hole
for (int i = 1; i < regs.size(); i++) {
Register r = regs.get(i);
int regNum = r.getNumber();
if (regNum != nextExpectedRegNum) {
return true;
}
nextExpectedRegNum++;
if (r.isWide()) {
nextExpectedRegNum++;
}
}
return false;
}
@Override
public String toString() {
return super.toString() + " ref: " + referencedItem;
}
}
| 3,642
| 30.405172
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/Insn51l.java
|
package soot.toDex.instructions;
/*-
* #%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.BitSet;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.instruction.BuilderInstruction51l;
import soot.toDex.LabelAssigner;
import soot.toDex.Register;
/**
* The "51l" instruction format: It needs five 16-bit code units, has one register and is used for a 64-bit literal (hence
* the "l" for "long").<br>
* <br>
* It is used by the opcode "const-wide".
*/
public class Insn51l extends AbstractInsn implements OneRegInsn {
private long litB;
public Insn51l(Opcode opc, Register regA, long litB) {
super(opc);
regs.add(regA);
this.litB = litB;
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public long getLitB() {
return litB;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction51l(opc, (short) getRegA().getNumber(), getLitB());
}
@Override
public BitSet getIncompatibleRegs() {
BitSet incompatRegs = new BitSet(1);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
return incompatRegs;
}
@Override
public String toString() {
return super.toString() + " lit: " + getLitB();
}
}
| 2,088
| 26.12987
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/InsnWithOffset.java
|
package soot.toDex.instructions;
/*-
* #%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 org.jf.dexlib2.Opcode;
import soot.jimple.Stmt;
/**
* An abstract implementation for instructions that have a jump label.
*/
public abstract class InsnWithOffset extends AbstractInsn {
protected Stmt target;
public InsnWithOffset(Opcode opc) {
super(opc);
}
public void setTarget(Stmt target) {
if (target == null) {
throw new RuntimeException("Cannot jump to a NULL target");
}
this.target = target;
}
public Stmt getTarget() {
return this.target;
}
/**
* Gets the maximum number of words available for the jump offset
*
* @return The maximum number of words available for the jump offset
*/
public abstract int getMaxJumpOffset();
}
| 1,561
| 25.474576
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/OneRegInsn.java
|
package soot.toDex.instructions;
/*-
* #%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.toDex.Register;
/**
* Interface for instructions that need one register.
*/
public interface OneRegInsn extends Insn {
static final int REG_A_IDX = 0;
Register getRegA();
}
| 1,046
| 28.083333
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/PackedSwitchPayload.java
|
package soot.toDex.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.Label;
import org.jf.dexlib2.builder.instruction.BuilderPackedSwitchPayload;
import soot.Unit;
import soot.jimple.Stmt;
import soot.toDex.LabelAssigner;
/**
* The payload for a packed-switch instruction.
*
* @see SwitchPayload
*/
public class PackedSwitchPayload extends SwitchPayload {
private int firstKey;
public PackedSwitchPayload(int firstKey, List<Unit> targets) {
super(targets);
this.firstKey = firstKey;
}
@Override
public int getSize() {
// size = (identFieldSize+sizeFieldSize+firstKeyFieldSize) + (numTargets * targetFieldSize)
return 4 + targets.size() * 2;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
List<Label> elements = new ArrayList<Label>();
for (int i = 0; i < targets.size(); i++) {
elements.add(assigner.getOrCreateLabel((Stmt) targets.get(i)));
}
return new BuilderPackedSwitchPayload(firstKey, elements);
}
}
| 1,922
| 28.584615
| 95
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/SparseSwitchPayload.java
|
package soot.toDex.instructions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import org.jf.dexlib2.builder.BuilderInstruction;
import org.jf.dexlib2.builder.SwitchLabelElement;
import org.jf.dexlib2.builder.instruction.BuilderSparseSwitchPayload;
import soot.Unit;
import soot.jimple.Stmt;
import soot.toDex.LabelAssigner;
/**
* The payload for a sparse-switch instruction.
*
* @see SwitchPayload
*/
public class SparseSwitchPayload extends SwitchPayload {
private int[] keys;
public SparseSwitchPayload(int[] keys, List<Unit> targets) {
super(targets);
this.keys = keys;
}
@Override
public int getSize() {
// size = (identFieldSize+sizeFieldSize) + numTargets * (keyFieldSize+targetFieldSize)
return 2 + targets.size() * 4;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
List<SwitchLabelElement> elements = new ArrayList<SwitchLabelElement>();
for (int i = 0; i < keys.length; i++) {
elements.add(new SwitchLabelElement(keys[i], assigner.getOrCreateLabel((Stmt) targets.get(i))));
}
return new BuilderSparseSwitchPayload(elements);
}
}
| 1,965
| 28.787879
| 102
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/SwitchPayload.java
|
package soot.toDex.instructions;
/*-
* #%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.Unit;
/**
* The payload for switch instructions, usually placed at the end of a method. This is where the jump targets are stored.<br>
* <br>
* Note that this is an {@link InsnWithOffset} with multiple offsets.
*/
public abstract class SwitchPayload extends AbstractPayload {
protected Insn31t switchInsn;
protected List<Unit> targets;
public SwitchPayload(List<Unit> targets) {
super();
this.targets = targets;
}
public void setSwitchInsn(Insn31t switchInsn) {
this.switchInsn = switchInsn;
}
@Override
public int getMaxJumpOffset() {
return Short.MAX_VALUE;
}
}
| 1,497
| 26.236364
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/ThreeRegInsn.java
|
package soot.toDex.instructions;
/*-
* #%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.toDex.Register;
/**
* Interface for instructions that need three registers.
*/
public interface ThreeRegInsn extends TwoRegInsn {
static final int REG_C_IDX = REG_B_IDX + 1;
Register getRegC();
}
| 1,069
| 28.722222
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toDex/instructions/TwoRegInsn.java
|
package soot.toDex.instructions;
/*-
* #%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.toDex.Register;
/**
* Interface for instructions that need two registers.
*/
public interface TwoRegInsn extends OneRegInsn {
static final int REG_B_IDX = REG_A_IDX + 1;
Register getRegB();
}
| 1,065
| 28.611111
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/ASTMetric.java
|
package soot.toolkits.astmetrics;
/*-
* #%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 polyglot.ast.ClassDecl;
import polyglot.ast.Node;
import polyglot.util.CodeWriter;
import polyglot.visit.NodeVisitor;
import soot.G;
public abstract class ASTMetric extends NodeVisitor implements MetricInterface {
polyglot.ast.Node astNode;
String className = null; // name of Class being currently processed
public ASTMetric(polyglot.ast.Node astNode) {
this.astNode = astNode;
reset();
}
/*
* Taking care of the change in classes within a polyglot ast
*/
public final NodeVisitor enter(Node n) {
if (n instanceof ClassDecl) {
className = ((ClassDecl) n).name();
System.out.println("Starting processing: " + className);
}
return this;
}
/*
* When we leave a classDecl all the metrics for this classDecl must be stored and the metrics reset
*
* This is done by invoking the addMetrics abstract method
*/
public final Node leave(Node parent, Node old, Node n, NodeVisitor v) {
if (n instanceof ClassDecl) {
if (className == null) {
throw new RuntimeException("className is null");
}
System.out.println("Done with class " + className);
// get the classData object for this class
ClassData data = getClassData();
addMetrics(data);
reset();
}
return leave(old, n, v);
}
public abstract void reset();
public abstract void addMetrics(ClassData data);
/*
* Should be used to execute the traversal which will find the metric being calculated
*/
public final void execute() {
astNode.visit(this);
// Testing testing testing
System.out.println("\n\n\n PRETTY P{RINTING");
if (this instanceof StmtSumWeightedByDepth) {
metricPrettyPrinter p = new metricPrettyPrinter(this);
p.printAst(astNode, new CodeWriter(System.out, 80));
}
}
public void printAstMetric(Node n, CodeWriter w) {
}
/*
* Returns the classData object if one if present in the globals Metrics List otherwise creates new adds to globals metric
* list and returns that
*/
public final ClassData getClassData() {
if (className == null) {
throw new RuntimeException("className is null");
}
Iterator<ClassData> it = G.v().ASTMetricsData.iterator();
while (it.hasNext()) {
ClassData tempData = it.next();
if (tempData.classNameEquals(className)) {
return tempData;
}
}
ClassData data = new ClassData(className);
G.v().ASTMetricsData.add(data);
return data;
}
}
| 3,359
| 27.235294
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/AbruptEdgesMetric.java
|
package soot.toolkits.astmetrics;
/*-
* #%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 polyglot.ast.Branch;
import polyglot.ast.Node;
import polyglot.visit.NodeVisitor;
/*
* Should take care of the following metrics:
*
* Break Statements
1. of implicit breaks (breaking inner most loop) DONE
2. of explicit breaks (breaking an outer loop) NOTQUITE DONE
3. of explicit breaks (breaking other constructs) DONE (any explicit break)
* Continue Statements
1. of implicit continues (breaking inner most loop) DONE
2. of explicit continues (breaking outer loops) DONE
*/
public class AbruptEdgesMetric extends ASTMetric {
private int iBreaks, eBreaks;
private int iContinues, eContinues;
public AbruptEdgesMetric(polyglot.ast.Node astNode) {
super(astNode);
}
/*
* (non-Javadoc)
*
* @see soot.toolkits.astmetrics.ASTMetric#reset() Implementation of the abstract method which is invoked by parent
* constructor and whenever the classDecl in the polyglot changes
*/
public void reset() {
iBreaks = eBreaks = iContinues = eContinues = 0;
}
/*
* Implementation of the abstract method
*
* Should add the metrics to the data object sent
*/
public void addMetrics(ClassData data) {
data.addMetric(new MetricData("Total-breaks", new Integer(iBreaks + eBreaks)));
data.addMetric(new MetricData("I-breaks", new Integer(iBreaks)));
data.addMetric(new MetricData("E-breaks", new Integer(eBreaks)));
data.addMetric(new MetricData("Total-continues", new Integer(iContinues + eContinues)));
data.addMetric(new MetricData("I-continues", new Integer(iContinues)));
data.addMetric(new MetricData("E-continues", new Integer(eContinues)));
data.addMetric(new MetricData("Total-Abrupt", new Integer(iBreaks + eBreaks + iContinues + eContinues)));
}
/*
* A branch in polyglot is either a break or continue
*/
public NodeVisitor enter(Node parent, Node n) {
if (n instanceof Branch) {
Branch branch = (Branch) n;
if (branch.kind().equals(Branch.BREAK)) {
if (branch.label() != null) {
eBreaks++;
} else {
iBreaks++;
}
} else if (branch.kind().equals(Branch.CONTINUE)) {
if (branch.label() != null) {
eContinues++;
} else {
iContinues++;
}
} else {
System.out.println("\t Error:'" + branch.toString() + "'");
}
}
return enter(n);
}
}
| 3,266
| 30.114286
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/ClassData.java
|
package soot.toolkits.astmetrics;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Nomair A. Naeem
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
/*
* Should store general information about the class
* Size? number of nodes?
* Plus a list of MetricData objects
*/
public class ClassData {
String className; // the name of the class whose data is being stored
ArrayList<MetricData> metricData; // each element should be a MetricData
public ClassData(String name) {
className = name;
metricData = new ArrayList<MetricData>();
}
public String getClassName() {
return className;
}
/*
* returns true if this className has the same name as the string sent as argument
*/
public boolean classNameEquals(String className) {
return (this.className.equals(className));
}
/*
* Only add new metric if this is not already present Else dont add
*/
public void addMetric(MetricData data) {
Iterator<MetricData> it = metricData.iterator();
while (it.hasNext()) {
MetricData temp = it.next();
if (temp.metricName.equals(data.metricName)) {
// System.out.println("Not adding same metric again......"+temp.metricName);
return;
}
}
metricData.add(data);
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append("<Class>\n");
b.append("<ClassName>" + className + "</ClassName>\n");
Iterator<MetricData> it = metricData.iterator();
while (it.hasNext()) {
b.append(it.next().toString());
}
b.append("</Class>");
return b.toString();
}
}
| 2,330
| 28.1375
| 84
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/ComputeASTMetrics.java
|
package soot.toolkits.astmetrics;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Nomair A. Naeem
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import polyglot.ast.Node;
import soot.options.Options;
/*
* Add all metrics to be computed here.
*/
public class ComputeASTMetrics {
ArrayList<ASTMetric> metrics;
/*
* New metrics should be added into the metrics linked list
*/
public ComputeASTMetrics(Node astNode) {
metrics = new ArrayList<ASTMetric>();
// add new metrics below this line
// REMEMBER ALL METRICS NEED TO implement MetricInterface
// abrupt edges metric calculator
metrics.add(new AbruptEdgesMetric(astNode));
metrics.add(new NumLocalsMetric(astNode));
metrics.add(new ConstructNumbersMetric(astNode));
metrics.add(new StmtSumWeightedByDepth(astNode));
metrics.add(new ConditionComplexityMetric(astNode));
metrics.add(new ExpressionComplexityMetric(astNode));
metrics.add(new IdentifiersMetric(astNode));
}
public void apply() {
if (!Options.v().ast_metrics()) {
return;
}
Iterator<ASTMetric> metricIt = metrics.iterator();
while (metricIt.hasNext()) {
metricIt.next().execute();
}
}
}
| 1,950
| 27.275362
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/ConditionComplexityMetric.java
|
package soot.toolkits.astmetrics;
/*-
* #%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 polyglot.ast.Binary;
import polyglot.ast.Expr;
import polyglot.ast.If;
import polyglot.ast.Loop;
import polyglot.ast.Node;
import polyglot.ast.Unary;
import polyglot.visit.NodeVisitor;
/*
* TODO compute avarge complexity weighted by depth similar to expression complexity
*
*
* A unary boolean condition should have the complexity (BooleanLit) 1
* A noted condition (!) +0.5
* A binary relational operation ( < > <= >= == !=) +0.5
* A boolean logical operator ( AND and OR) +1.0
*/
public class ConditionComplexityMetric extends ASTMetric {
int loopComplexity;
int ifComplexity;
public ConditionComplexityMetric(polyglot.ast.Node node) {
super(node);
}
public void reset() {
loopComplexity = ifComplexity = 0;
}
public void addMetrics(ClassData data) {
data.addMetric(new MetricData("Loop-Cond-Complexity", new Integer(loopComplexity)));
data.addMetric(new MetricData("If-Cond-Complexity", new Integer(ifComplexity)));
data.addMetric(new MetricData("Total-Cond-Complexity", new Integer(loopComplexity + ifComplexity)));
}
public NodeVisitor enter(Node parent, Node n) {
if (n instanceof Loop) {
Expr expr = ((Loop) n).cond();
loopComplexity += condComplexity(expr);
} else if (n instanceof If) {
Expr expr = ((If) n).cond();
ifComplexity += condComplexity(expr);
}
return enter(n);
}
private double condComplexity(Expr expr) {
// boolean literal
// binary check for AND and OR ... else its relational!!
// unary (Check for NOT)
if (expr instanceof Binary) {
Binary b = (Binary) expr;
if (b.operator() == Binary.COND_AND || b.operator() == Binary.COND_OR) {
// System.out.println(">>>>>>>> Binary (AND or OR) "+expr);
return 1.0 + condComplexity(b.left()) + condComplexity(b.right());
} else {
// System.out.println(">>>>>>>> Binary (relatinal) "+expr);
return 0.5 + condComplexity(b.left()) + condComplexity(b.right());
}
} else if (expr instanceof Unary) {
if (((Unary) expr).operator() == Unary.NOT) {
// System.out.println(">>>>>>>>>>>>>>Unary: !"+expr);
return 0.5 + condComplexity(((Unary) expr).expr());
} else {
// System.out.println(">>>>>>>>>>>>>>unary but Not ! "+expr);
return condComplexity(((Unary) expr).expr());
}
} else {
return 1;// should return something as it is a condition after all
}
}
}
| 3,317
| 31.851485
| 104
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/ConstructNumbersMetric.java
|
package soot.toolkits.astmetrics;
/*-
* #%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 polyglot.ast.Block;
import polyglot.ast.Do;
import polyglot.ast.For;
import polyglot.ast.If;
import polyglot.ast.Labeled;
import polyglot.ast.Node;
import polyglot.ast.Stmt;
import polyglot.ast.While;
import polyglot.visit.NodeVisitor;
/*
* Calculate the number of different Java Constructs present in the
* code
*/
public class ConstructNumbersMetric extends ASTMetric {
private int numIf, numIfElse;
private int numLabeledBlocks;
private int doLoop, forLoop, whileLoop, whileTrue;
public ConstructNumbersMetric(Node node) {
super(node);
}
public void reset() {
numIf = numIfElse = 0;
numLabeledBlocks = 0;
doLoop = forLoop = whileLoop = whileTrue = 0;
}
public void addMetrics(ClassData data) {
// TODO Auto-generated method stub
// conditionals
data.addMetric(new MetricData("If", new Integer(numIf)));
data.addMetric(new MetricData("IfElse", new Integer(numIfElse)));
data.addMetric(new MetricData("Total-Conditionals", new Integer(numIf + numIfElse)));
// labels
data.addMetric(new MetricData("LabelBlock", new Integer(numLabeledBlocks)));
// loops
data.addMetric(new MetricData("Do", new Integer(doLoop)));
data.addMetric(new MetricData("For", new Integer(forLoop)));
data.addMetric(new MetricData("While", new Integer(whileLoop)));
data.addMetric(new MetricData("UnConditional", new Integer(whileTrue)));
data.addMetric(new MetricData("Total Loops", new Integer(whileTrue + whileLoop + forLoop + doLoop)));
}
public NodeVisitor enter(Node parent, Node n) {
/*
* Num if and ifelse
*/
if (n instanceof If) {
// check if there is the "optional" else branch present
If ifNode = (If) n;
Stmt temp = ifNode.alternative();
if (temp == null) {
// else branch is empty
// System.out.println("This was an if stmt"+n);
numIf++;
} else {
// else branch has something
// System.out.println("This was an ifElse stmt"+n);
numIfElse++;
}
}
/*
* Num Labeled Blocks
*/
if (n instanceof Labeled) {
Stmt s = ((Labeled) n).statement();
// System.out.println("labeled"+((Labeled)n).label());
if (s instanceof Block) {
// System.out.println("labeled block with label"+((Labeled)n).label());
numLabeledBlocks++;
}
}
/*
* Do
*/
if (n instanceof Do) {
// System.out.println((Do)n);
doLoop++;
}
/*
* For
*/
if (n instanceof For) {
// System.out.println((For)n);
forLoop++;
}
/*
* While and While True loop
*/
if (n instanceof While) {
// System.out.println((While)n);
if (((While) n).condIsConstantTrue()) {
whileTrue++;
} else {
whileLoop++;
}
}
return enter(n);
}
}
| 3,701
| 25.826087
| 105
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/ExpressionComplexityMetric.java
|
package soot.toolkits.astmetrics;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import polyglot.ast.Expr;
import polyglot.ast.Node;
import polyglot.visit.NodeVisitor;
/**
* @author Michael Batchelder
*
* Created on 7-Mar-2006
*/
public class ExpressionComplexityMetric extends ASTMetric {
int currentExprDepth;
int exprDepthSum;
int exprCount;
int inExpr;
public ExpressionComplexityMetric(polyglot.ast.Node node) {
super(node);
}
public void reset() {
currentExprDepth = 0;
exprDepthSum = 0;
exprCount = 0;
inExpr = 0;
}
public void addMetrics(ClassData data) {
double a = exprDepthSum;
double b = exprCount;
data.addMetric(new MetricData("Expr-Complexity", new Double(a)));
data.addMetric(new MetricData("Expr-Count", new Double(b)));
}
public NodeVisitor enter(Node parent, Node n) {
if (n instanceof Expr) {
inExpr++;
currentExprDepth++;
}
return enter(n);
}
public Node leave(Node old, Node n, NodeVisitor v) {
if (n instanceof Expr) {
if (currentExprDepth == 1) {
exprCount++;
exprDepthSum += inExpr;
inExpr = 0;
}
currentExprDepth--;
}
return super.leave(old, n, v);
}
}
| 2,005
| 23.463415
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/IdentifiersMetric.java
|
package soot.toolkits.astmetrics;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import polyglot.ast.ClassDecl;
import polyglot.ast.FieldDecl;
import polyglot.ast.Formal;
import polyglot.ast.LocalDecl;
import polyglot.ast.MethodDecl;
import polyglot.ast.Node;
import polyglot.visit.NodeVisitor;
import soot.options.Options;
/**
* @author Michael Batchelder
*
* Created on 5-Mar-2006
*/
public class IdentifiersMetric extends ASTMetric {
private static final Logger logger = LoggerFactory.getLogger(IdentifiersMetric.class);
double nameComplexity = 0;
double nameCount = 0;
int dictionarySize = 0;
ArrayList<String> dictionary;
// cache of names so no recomputation
HashMap<String, Double> names;
/**
* @param astNode
*
* This metric will take a measure of the "complexity" of each identifier used within the program. An identifier's
* complexity is computed as follows:
*
* First the alpha tokens are parsed by splitting on non-alphas and capitals:
*
* example identifier: getASTNode alpha tokens: get, AST, Node example identifier: ___Junk$$name alpha tokens:
* Junk, name)
*
* The alpha tokens are then counted and a 'token complexity' is formed by the ratio of total tokens to the number
* of tokens found in the dictionary:
*
* example identifier: getASTNode Total: 3, Found: 2, Complexity: 1.5
*
* Then the 'character complexity' is computed, which is a ratio of total number of characters to the number of
* non-complex characters. Non-complex characters are those which are NOT part of a multiple string of non-alphas.
*
* example identifier: ___Junk$$name complex char strings: '___', '$$' number of non-complex (Junk + name): 8,
* total: 13, Complexity: 1.625
*
* Finally, the total identifier complexity is the sum of the token and character complexities multipled by the
* 'importance' of an identifier:
*
* Multipliers are as follows:
*
* Class multiplier = 3; Method multiplier = 4; Field multiplier = 2; Formal multiplier = 1.5; Local multiplier =
* 1;
*
*/
public IdentifiersMetric(Node astNode) {
super(astNode);
initializeDictionary();
}
private void initializeDictionary() {
String line;
BufferedReader br = null;
dictionary = new ArrayList<String>();
names = new HashMap<String, Double>();
InputStream is = ClassLoader.getSystemResourceAsStream("mydict.txt");
if (is != null) {
br = new BufferedReader(new InputStreamReader(is));
try {
while ((line = br.readLine()) != null) {
addWord(line);
}
} catch (IOException ioexc) {
logger.debug("" + ioexc.getMessage());
}
}
is = ClassLoader.getSystemResourceAsStream("soot/toolkits/astmetrics/dict.txt");
if (is != null) {
br = new BufferedReader(new InputStreamReader(is));
try {
while ((line = br.readLine()) != null) {
addWord(line.trim().toLowerCase());
}
} catch (IOException ioexc) {
logger.debug("" + ioexc.getMessage());
}
}
if ((dictionarySize = dictionary.size()) == 0) {
logger.debug("Error reading in dictionary file(s)");
} else if (Options.v().verbose()) {
logger.debug("Read " + dictionarySize + " words in from dictionary file(s)");
}
try {
is.close();
} catch (IOException e) {
logger.debug("" + e.getMessage());
}
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
logger.debug("" + e.getMessage());
}
}
private void addWord(String word) {
if (dictionarySize == 0 || word.compareTo(dictionary.get(dictionarySize - 1)) > 0) {
dictionary.add(word);
} else {
int i = 0;
while (i < dictionarySize && word.compareTo(dictionary.get(i)) > 0) {
i++;
}
if (word.compareTo(dictionary.get(i)) == 0) {
return;
}
dictionary.add(i, word);
}
dictionarySize++;
}
/*
* (non-Javadoc)
*
* @see soot.toolkits.astmetrics.ASTMetric#reset()
*/
public void reset() {
nameComplexity = 0;
nameCount = 0;
}
/*
* (non-Javadoc)
*
* @see soot.toolkits.astmetrics.ASTMetric#addMetrics(soot.toolkits.astmetrics.ClassData)
*/
public void addMetrics(ClassData data) {
data.addMetric(new MetricData("NameComplexity", new Double(nameComplexity)));
data.addMetric(new MetricData("NameCount", new Double(nameCount)));
}
public NodeVisitor enter(Node parent, Node n) {
double multiplier = 1;
String name = null;
if (n instanceof ClassDecl) {
name = ((ClassDecl) n).name();
multiplier = 3;
nameCount++;
} else if (n instanceof MethodDecl) {
name = ((MethodDecl) n).name();
multiplier = 4;
nameCount++;
} else if (n instanceof FieldDecl) {
name = ((FieldDecl) n).name();
multiplier = 2;
nameCount++;
} else if (n instanceof Formal) { // this is locals and formals
name = ((Formal) n).name();
multiplier = 1.5;
nameCount++;
} else if (n instanceof LocalDecl) { // this is locals and formals
name = ((LocalDecl) n).name();
nameCount++;
}
if (name != null) {
nameComplexity += (multiplier * computeNameComplexity(name));
}
return enter(n);
}
private double computeNameComplexity(String name) {
if (names.containsKey(name)) {
return names.get(name).doubleValue();
}
ArrayList<String> strings = new ArrayList<String>();
// throw out non-alpha characters
String tmp = "";
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if ((c > 64 && c < 91) || (c > 96 && c < 123)) {
tmp += c;
} else if (tmp.length() > 0) {
strings.add(tmp);
tmp = "";
}
}
if (tmp.length() > 0) {
strings.add(tmp);
}
ArrayList<String> tokens = new ArrayList<String>();
for (int i = 0; i < strings.size(); i++) {
tmp = strings.get(i);
while (tmp.length() > 0) {
int caps = countCaps(tmp);
if (caps == 0) {
int idx = findCap(tmp);
if (idx > 0) {
tokens.add(tmp.substring(0, idx));
tmp = tmp.substring(idx, tmp.length());
} else {
tokens.add(tmp.substring(0, tmp.length()));
break;
}
} else if (caps == 1) {
int idx = findCap(tmp.substring(1)) + 1;
if (idx > 0) {
tokens.add(tmp.substring(0, idx));
tmp = tmp.substring(idx, tmp.length());
} else {
tokens.add(tmp.substring(0, tmp.length()));
break;
}
} else {
if (caps < tmp.length()) {
// count seq of capitals as one token
tokens.add(tmp.substring(0, caps - 1).toLowerCase());
tmp = tmp.substring(caps);
} else {
tokens.add(tmp.substring(0, caps).toLowerCase());
break;
}
}
}
}
double words = 0;
double complexity = 0;
for (int i = 0; i < tokens.size(); i++) {
if (dictionary.contains(tokens.get(i))) {
words++;
}
}
if (words > 0) {
complexity = (tokens.size()) / words;
}
names.put(name, new Double(complexity + computeCharComplexity(name)));
return complexity;
}
private double computeCharComplexity(String name) {
int count = 0, index = 0, last = 0, lng = name.length();
while (index < lng) {
char c = name.charAt(index);
if ((c < 65 || c > 90) && (c < 97 || c > 122)) {
last++;
} else {
if (last > 1) {
count += last;
}
last = 0;
}
index++;
}
double complexity = lng - count;
if (complexity > 0) {
return ((lng) / complexity);
} else {
return lng;
}
}
/*
* @author Michael Batchelder
*
* Created on 6-Mar-2006
*
* @param name string to parse
*
* @return number of leading capital letters
*/
private int countCaps(String name) {
int caps = 0;
while (caps < name.length()) {
char c = name.charAt(caps);
if (c > 64 && c < 91) {
caps++;
} else {
break;
}
}
return caps;
}
/*
* @author Michael Batchelder
*
* Created on 6-Mar-2006
*
* @param name string to parse
*
* @return index of first capital letter
*/
private int findCap(String name) {
int idx = 0;
while (idx < name.length()) {
char c = name.charAt(idx);
if (c > 64 && c < 91) {
return idx;
} else {
idx++;
}
}
return -1;
}
}
| 9,878
| 25.991803
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/MetricData.java
|
package soot.toolkits.astmetrics;
/*-
* #%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%
*/
/*
* Information about a particular metric
*/
public class MetricData {
String metricName;
Object value;
public MetricData(String name, Object val) {
metricName = name;
value = val;
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append("<Metric>\n");
b.append(" <MetricName>" + metricName + "</MetricName>\n");
b.append(" <Value>" + value.toString() + "</Value>\n");
b.append("</Metric>\n");
return b.toString();
}
}
| 1,323
| 27.782609
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/MetricInterface.java
|
package soot.toolkits.astmetrics;
/*-
* #%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 interface MetricInterface {
public void execute();
}
| 916
| 30.62069
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/NumLocalsMetric.java
|
package soot.toolkits.astmetrics;
/*-
* #%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 polyglot.ast.LocalDecl;
import polyglot.ast.Node;
import polyglot.visit.NodeVisitor;
public class NumLocalsMetric extends ASTMetric {
int numLocals; // store the current number of locals for this CLASS
public NumLocalsMetric(polyglot.ast.Node node) {
super(node);
}
/*
* Will be invoked by the super as well as whenever a new class is entered
*
*/
public void reset() {
numLocals = 0;
}
/*
* Will be invoked whenever we are leaving a subtree which was a classDecl
*/
public void addMetrics(ClassData data) {
data.addMetric(new MetricData("Number-Locals", new Integer(numLocals)));
}
public NodeVisitor enter(Node parent, Node n) {
if (n instanceof LocalDecl) {
// System.out.println("Local declared is"+ ((LocalDecl)n).name() );
numLocals++;
}
return enter(n);
}
}
| 1,688
| 26.688525
| 76
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/StmtSumWeightedByDepth.java
|
package soot.toolkits.astmetrics;
/*-
* #%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.Stack;
import polyglot.ast.Block;
import polyglot.ast.Branch;
import polyglot.ast.CodeDecl;
import polyglot.ast.Expr;
import polyglot.ast.Formal;
import polyglot.ast.If;
import polyglot.ast.Initializer;
import polyglot.ast.Labeled;
import polyglot.ast.LocalClassDecl;
import polyglot.ast.Loop;
import polyglot.ast.Node;
import polyglot.ast.ProcedureDecl;
import polyglot.ast.Stmt;
import polyglot.ast.Switch;
import polyglot.ast.Synchronized;
import polyglot.ast.Try;
import polyglot.util.CodeWriter;
import polyglot.visit.NodeVisitor;
public class StmtSumWeightedByDepth extends ASTMetric {
int currentDepth;
int sum;
int maxDepth;
int numNodes;
Stack<ArrayList> labelNodesSoFar = new Stack<ArrayList>();
ArrayList<Node> blocksWithAbruptFlow = new ArrayList<Node>();
HashMap<Node, Integer> stmtToMetric = new HashMap<Node, Integer>();
HashMap<Node, Integer> stmtToMetricDepth = new HashMap<Node, Integer>();
public static boolean tmpAbruptChecker = false;
public StmtSumWeightedByDepth(Node node) {
super(node);
}
public void printAstMetric(Node n, CodeWriter w) {
if (n instanceof Stmt) {
if (stmtToMetric.containsKey(n)) {
w.write(" // sum= " + stmtToMetric.get(n) + " : depth= " + stmtToMetricDepth.get(n) + "\t");
}
}
}
public void reset() {
// if not one, then fields and method sigs don't get counted
currentDepth = 1; // inside a class
maxDepth = 1;
sum = 0;
numNodes = 0;
}
public void addMetrics(ClassData data) {
// data.addMetric(new MetricData("MaxDepth",new Integer(maxDepth)));
data.addMetric(new MetricData("D-W-Complexity", new Double(sum)));
data.addMetric(new MetricData("AST-Node-Count", new Integer(numNodes)));
}
private void increaseDepth() {
System.out.println("Increasing depth");
currentDepth++;
if (currentDepth > maxDepth) {
maxDepth = currentDepth;
}
}
private void decreaseDepth() {
System.out.println("Decreasing depth");
currentDepth--;
}
/*
* List of Node types which increase depth of traversal!!! Any construct where one can have a { } increases the depth hence
* even though if(cond) stmt doesnt expicitly use a block its depth is still +1 when executing the stmt
*
* If the "if" stmt has code if(cond) { stmt } OR if(cond) stmt this will only increase the depth by 1 (ignores compound
* stmt blocks)
*
* If, Loop, Try, Synch, ProcDecl, Init, Switch, LocalClassDecl .... add currentDepth to sum and then increase depth by one
* irrespective of how many stmts there are in the body
*
* Block ... if it is a block within a block, add currentDepth plus increment depth ONLY if it has abrupt flow out of it.
*/
public NodeVisitor enter(Node parent, Node n) {
numNodes++;
if (n instanceof CodeDecl) {
// maintain stack of label arrays (can't have label from inside method to outside)
labelNodesSoFar.push(new ArrayList());
} else if (n instanceof Labeled) {
// add any labels we find to the array
labelNodesSoFar.peek().add(((Labeled) n).label());
}
if (n instanceof If || n instanceof Loop || n instanceof Try || n instanceof Switch || n instanceof LocalClassDecl
|| n instanceof Synchronized || n instanceof ProcedureDecl || n instanceof Initializer) {
sum += currentDepth * 2;
System.out.println(n);
increaseDepth();
} else if (parent instanceof Block && n instanceof Block) {
StmtSumWeightedByDepth.tmpAbruptChecker = false;
n.visit(new NodeVisitor() {
// extended NodeVisitor that checks for branching out of a block
public NodeVisitor enter(Node parent, Node node) {
if (node instanceof Branch) {
Branch b = (Branch) node;
// null branching out of a plain block is NOT ALLOWED!
if (b.label() != null && labelNodesSoFar.peek().contains(b.label())) {
StmtSumWeightedByDepth.tmpAbruptChecker = true;
}
}
return enter(node);
}
// this method simply stops further node visiting if we found our info
public Node override(Node parent, Node node) {
if (StmtSumWeightedByDepth.tmpAbruptChecker) {
return node;
}
return null;
}
});
if (StmtSumWeightedByDepth.tmpAbruptChecker) {
blocksWithAbruptFlow.add(n);
sum += currentDepth * 2;
System.out.println(n);
increaseDepth();
}
}
// switch from Stmt to Expr here, since Expr is the smallest unit
else if (n instanceof Expr || n instanceof Formal) {
System.out.print(sum + " " + n + " ");
sum += currentDepth * 2;
System.out.println(sum);
}
// carry metric cummulative for each statement for metricPrettyPrinter
if (n instanceof Stmt) {
stmtToMetric.put(n, new Integer(sum));
stmtToMetricDepth.put(n, new Integer(currentDepth));
}
return enter(n);
}
public Node leave(Node old, Node n, NodeVisitor v) {
// stack maintenance, if leaving a method
if (n instanceof CodeDecl) {
labelNodesSoFar.pop();
}
if (n instanceof If || n instanceof Loop || n instanceof Try || n instanceof Switch || n instanceof LocalClassDecl
|| n instanceof Synchronized || n instanceof ProcedureDecl || n instanceof Initializer) {
decreaseDepth();
} else if (n instanceof Block && blocksWithAbruptFlow.contains(n)) {
decreaseDepth();
}
return n;
}
}
| 6,457
| 32.46114
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/metricPrettyPrinter.java
|
package soot.toolkits.astmetrics;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import polyglot.ast.Node;
import polyglot.util.CodeWriter;
import polyglot.visit.PrettyPrinter;
/**
* @author Michael Batchelder
*
* Created on 12-Apr-2006
*/
public class metricPrettyPrinter extends PrettyPrinter {
ASTMetric astMetric;
/**
*
*/
public metricPrettyPrinter(ASTMetric astMetric) {
this.astMetric = astMetric;
}
public void print(Node parent, Node child, CodeWriter w) {
astMetric.printAstMetric(child, w);
super.print(parent, child, w);
}
}
| 1,346
| 25.94
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/astmetrics/DataHandlingApplication/ProcessData.java
|
package soot.toolkits.astmetrics.DataHandlingApplication;
/*-
* #%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.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import soot.CompilationDeathException;
public class ProcessData {
// when printing class names what is the max size of each class name
private static final int CLASSNAMESIZE = 15;
private static final int CLASS = 0;
private static final int BENCHMARK = 1;
private static String metricListFileName = null;
private static final ArrayList<String> xmlFileList = new ArrayList<String>();
private static int aggregationMechanism = -1;
private static OutputStream streamOut;
private static PrintWriter bench;
// set to true to getcsv instead of tex
private static final boolean CSV = true;
private static final boolean decompiler = false; // else it is obfuscated
/**
* @param args
*/
public static void main(String[] args) {
int argLength = args.length;
if (argLength == 0) {
printIntro();
useHelp();
System.exit(1);
}
if (args[0].equals("--help")) {
printHelp();
System.exit(1);
} else if (args[0].equals("-metricList")) {
metricListFileName(args);
System.out.println("A list of metrics will be stored in: " + metricListFileName);
readXMLFileNames(2, args);
try {
OutputStream streamOut = new FileOutputStream(metricListFileName);
PrintWriter writerOut = new PrintWriter(new OutputStreamWriter(streamOut));
writeMetricLists(writerOut);
writerOut.flush();
streamOut.close();
} catch (IOException e) {
throw new CompilationDeathException("Cannot output file " + metricListFileName);
}
} else if (args[0].equals("-tables")) {
metricListFileName(args);
System.out.println("Will read column table headings from: " + metricListFileName);
// read aggregation option
aggregationOption(args);
if (aggregationMechanism == ProcessData.BENCHMARK) {
System.out.println("Aggregating over benchmarks...each row is one of the xml files");
System.out.println("Only one tex file with the name" + metricListFileName + ".tex will be created");
} else if (aggregationMechanism == ProcessData.CLASS) {
System.out.println("Aggregating over class...each row is one class...");
System.out.println("Each benchmark (xml file) will have its own tex file");
}
readXMLFileNames(3, args);
// TODO: hello
generateMetricsTables();
} else {
System.out.println("Incorrect argument number 1: expecting -metricList or -tables");
System.exit(1);
}
}
/*
* check if there is a 3rd argument and it should be either -class or -benchmark
*/
private static void aggregationOption(String[] args) {
if (args.length < 3) {
System.out.println("Expecting -class or -benchmark at argument number 3");
System.exit(1);
}
if (args[2].equals("-class")) {
aggregationMechanism = ProcessData.CLASS;
} else if (args[2].equals("-benchmark")) {
aggregationMechanism = ProcessData.BENCHMARK;
} else {
System.out.println("Expecting -class or -benchmark at argument number 3");
System.exit(1);
}
}
/*
* Check if there is a 3rd argument if not complain
*
* @param startIndex is the first args element where we expect to have an xml file or a *
*/
private static void readXMLFileNames(int startIndex, String args[]) {
if (args.length < startIndex + 1) {
System.out.println("Expecting an xml file OR * symbol as argument number" + (startIndex + 1));
System.exit(1);
}
// check if its a *
if (args[startIndex].equals("*")) {
System.out.println("Will read all xml files from directory");
// READ DIRECTORY STRUCTURE
readStar();
} else {
for (int i = startIndex; i < args.length; i++) {
String temp = args[i];
if (!temp.endsWith(".xml")) {
// System.out.println("Argument number "+(startIndex+1) + ": '" + temp+"' is not a valid xml file");
// System.exit(1);
} else {
xmlFileList.add(temp);
}
}
}
Iterator<String> it = xmlFileList.iterator();
while (it.hasNext()) {
System.out.println("Will be reading: " + it.next());
}
}
/*
* Check if args1 exists and if so store the metric List FileName
*/
private static void metricListFileName(String[] args) {
if (args.length < 2) {
System.out.println("Expecting name of metricList as argumnet number 2");
System.exit(1);
}
metricListFileName = args[1];
}
public static void printHelp() {
printIntro();
System.out.println("There are two main modes of execution");
System.out.println("To execute the program the first argument should be one of these modes");
System.out.println("-metricList and -tables");
System.out.println("\n\n The -metricList mode");
System.out.println("The argument at location 1 should be name of a file where the list of metrics will be stored");
System.out.println("All arguments following argument 1 have to be xml files to be processed");
System.out.println(
"If argument at location 2 is * then the current directory is searched and all xml files will be processed");
System.out.println("\n\n The -tables mode");
System.out.println("The argument at location 1 should be name of a file where the list of metrics are stored");
System.out.println("These metrics will become the COLUMNS in the tables created");
System.out.println("Argument at location 2 is the choice of aggregation");
System.out.println("\t -class for class level metrics");
System.out.println("\t -benchmark for benchmark level metrics");
System.out.println("Each xml file is considered to be a benchmark with a bunch of classes in it");
System.out.println("All arguments following argument 2 have to be xml files to be processed");
System.out.println(
"If argument at location 3 is * then the current directory is searched and all xml files will be processed");
}
public static void printIntro() {
System.out.println("Welcome to the processData application");
System.out.println("The application is an xml document parser.");
System.out.println("Its primary aim is to create pretty tex tables");
}
public static void useHelp() {
System.out.println("Use the --help flag for more details");
}
/*
* Read all the xml files from current directory into the xmlFileList arraylist
*/
private static void readStar() {
String curDir = System.getProperty("user.dir");
System.out.println("Current system directory is" + curDir);
File dir = new File(curDir);
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
};
children = dir.list(filter);
if (children != null) {
for (String element : children) {
xmlFileList.add(element);
}
}
}
}
private static void writeMetricLists(PrintWriter out) {
ArrayList<String> metricList = new ArrayList<String>();
Iterator<String> it = xmlFileList.iterator();
while (it.hasNext()) {
String fileName = it.next();
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(fileName));
System.out.println("Retrieving Metric List from xml file: " + fileName);
// normalize text representation
doc.getDocumentElement().normalize();
NodeList metrics = doc.getElementsByTagName("Metric");
for (int s = 0; s < metrics.getLength(); s++) {
Node metricNode = metrics.item(s);
if (metricNode.getNodeType() == Node.ELEMENT_NODE) {
Element metricElement = (Element) metricNode;
NodeList metricName = metricElement.getElementsByTagName("MetricName");
Element name = (Element) metricName.item(0);
NodeList textFNList = name.getChildNodes();
// System.out.println("MetricName: " + ((Node)textFNList.item(0)).getNodeValue().trim());
if (!metricList.contains(((Node) textFNList.item(0)).getNodeValue().trim())) {
metricList.add(((Node) textFNList.item(0)).getNodeValue().trim());
}
} // end of if clause
} // end of for loop with s var
} catch (SAXParseException err) {
System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
} catch (SAXException e) {
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
}
it = metricList.iterator();
while (it.hasNext()) {
out.println(it.next());
}
System.out.println(metricListFileName + " created.");
}
@SuppressWarnings("fallthrough")
private static void generateMetricsTables() {
Vector<String> columns = new Vector<String>();
/*
* create the columns which are the metriclist
*/
try {
FileReader file = new FileReader(metricListFileName);
BufferedReader fileInput = new BufferedReader(file);
String text;
// System.out.println("Columns");
while ((text = fileInput.readLine()) != null) {
// System.out.print(text+"\t");
columns.add(text);
}
fileInput.close();
} catch (Exception e) {
System.out.println("Exception while reading from metricList" + metricListFileName);
System.exit(1);
}
Vector<String> allMetrics = new Vector<String>();
try {
FileReader file = new FileReader("myList");
BufferedReader fileInput = new BufferedReader(file);
String text;
// System.out.println("Columns");
while ((text = fileInput.readLine()) != null) {
// System.out.print(text+"\t");
allMetrics.add(text);
}
fileInput.close();
} catch (Exception e) {
System.out.println("Exception while reading from metricList" + metricListFileName);
System.exit(1);
}
String newClassName = "";
if (aggregationMechanism == ProcessData.BENCHMARK) {
// TODO: create a metricListfileName.xml with metric info
newClassName = metricListFileName;
if (CSV) {
newClassName += ".csv";
System.out.println("Creating csv file" + newClassName + " from metrics info");
} else {
newClassName += ".tex";
System.out.println("Creating tex file" + newClassName + " from metrics info");
}
bench = openWriteFile(newClassName);
/*
* For benchmarks we want to print xml files dealing with same benchmark in one table hence fft-enabled.xml
* fft-disabled.xml should be in one table where as matrix-enabled.xml matrix-disabled.xml should be in another table
*/
Map<String, List<String>> benchMarkToFiles = new HashMap<String, List<String>>();
Iterator<String> it = xmlFileList.iterator();
while (it.hasNext()) {
String fileName = it.next();
if (fileName.indexOf('-') < 0) {
System.out.println("XML files should have following syntax:\n "
+ "<BENCHMARKNAME>-<PROPERTY>.xml\n PROPERTY should be enabled disabled etc");
return;
}
String benchmark = fileName.substring(0, fileName.indexOf('-'));
List<String> temp = benchMarkToFiles.get(benchmark);
List<String> tempList = null;
if (temp == null) {
tempList = new ArrayList<String>();
} else {
tempList = temp;
}
tempList.add(fileName);
benchMarkToFiles.put(benchmark, tempList);
/*
* if csv check that xml files have proper "property names"
*/
if (CSV) {
if (fileName.indexOf('-') < 0 || fileName.lastIndexOf(".xml") < 0) {
System.out.println("XML files should have following syntax:\n <BENCHMARKNAME>-<PROPERTY>.xml\n "
+ "PROPERTY should be enabled disabled etc");
return;
}
String xmlfileColumnType = fileName.substring(fileName.lastIndexOf('-') + 1, fileName.lastIndexOf(".xml"));
System.out.println("XML FILE COLUMN TYPE" + xmlfileColumnType);
if (xmlfileColumnType.equals("Jad") || xmlfileColumnType.equals("original")
|| xmlfileColumnType.equals("SourceAgain") || xmlfileColumnType.equals("disabled")
|| xmlfileColumnType.equals("enabled")) {
// TODO will have to change this when dealin with obfuscator xml file names
} else {
throw new RuntimeException("XML FILE <property> not recognized");
}
}
}
if (CSV) {
printCSVHeader(bench);
}
Iterator<String> keys = benchMarkToFiles.keySet().iterator();
while (keys.hasNext()) {
// each key gets its own table
String key = keys.next();
if (!CSV) {
printTexTableHeader(bench, key, columns);
}
// go through each value which is an xml file
List<String> tempValue = benchMarkToFiles.get(key);
if (tempValue == null) {
continue;
}
List<String> files = tempValue;
/*
* We want the files to be read in a specific order depending on decompiler or obfuscator
*/
if (decompiler) {
// coming from decompiler ordering is: original, Jad, SourceAgain, Dava(enabled), Dava(disabled)
if (files.size() != 5) {
throw new RuntimeException("not all xml files available for this benchmark!!");
}
System.out.println("old order" + files.toString());
String[] newFileOrder = new String[files.size()];
Iterator<String> tempIt = files.iterator();
while (tempIt.hasNext()) {
String fileSort = tempIt.next();
if (fileSort.indexOf("Jad") > -1) {
newFileOrder[1] = fileSort;
} else if (fileSort.indexOf("original") > -1) {
newFileOrder[0] = fileSort;
} else if (fileSort.indexOf("SourceAgain") > -1) {
newFileOrder[2] = fileSort;
} else if (fileSort.indexOf("disabled") > -1) {
newFileOrder[4] = fileSort;
} else if (fileSort.indexOf("enabled") > -1) {
newFileOrder[3] = fileSort;
} else {
throw new RuntimeException("property xml not correct");
}
}
files = new ArrayList<String>();
files.add(newFileOrder[0]);
files.add(newFileOrder[1]);
files.add(newFileOrder[2]);
files.add(newFileOrder[3]);
files.add(newFileOrder[4]);
System.out.println("new order" + files.toString());
} else {
// coming from obfuscator ordering is: original, jbco enabled, jbco disabled, klassmaster enabled,klassmaster
// disabled,
if (files.size() != 5) {
throw new RuntimeException("not all xml files available for this benchmark!!");
}
System.out.println("old order" + files.toString());
String[] newFileOrder = new String[files.size()];
Iterator<String> tempIt = files.iterator();
while (tempIt.hasNext()) {
String fileSort = tempIt.next();
if (fileSort.indexOf("original") > -1) {
newFileOrder[0] = fileSort;
} else if (fileSort.indexOf("jbco-enabled") > -1) {
newFileOrder[1] = fileSort;
} else if (fileSort.indexOf("jbco-disabled") > -1) {
newFileOrder[2] = fileSort;
} else if (fileSort.indexOf("klassmaster-enabled") > -1) {
newFileOrder[3] = fileSort;
} else if (fileSort.indexOf("klassmaster-disabled") > -1) {
newFileOrder[4] = fileSort;
} else {
throw new RuntimeException("property xml not correct");
}
}
files = new ArrayList<String>();
files.add(newFileOrder[0]);
files.add(newFileOrder[1]);
files.add(newFileOrder[2]);
files.add(newFileOrder[3]);
files.add(newFileOrder[4]);
System.out.println("new order" + files.toString());
}
Iterator<String> fileIt = files.iterator();
int count = -1;
while (fileIt.hasNext()) {
String fileName = fileIt.next();
count++;
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(fileName));
System.out.println("Gethering metric info from from xml file: " + fileName);
// normalize text representation
if (!CSV) {
// print the name of the xml file as the name of the benchmark
if (fileName.endsWith(".xml")) {
bench.print(fileName.substring(0, fileName.length() - 4));
} else {
bench.print(fileName);
}
}
HashMap<String, Number> aggregatedValues = new HashMap<String, Number>();
// TODO Should compute all metrics always
// only print out the one we want
Iterator<String> tempIt = allMetrics.iterator();
while (tempIt.hasNext()) {
aggregatedValues.put(tempIt.next(), new Integer(0));
}
int numClasses = aggregateXMLFileMetrics(doc, aggregatedValues);
// at this point the hashmap contains aggregatedValue of all metrics
// get the metrics we might need to divide
Object myTemp = aggregatedValues.get("Total-Conditionals");
if (myTemp == null) {
System.out.println("Total-Conditionals not found in aggregatedValues");
System.exit(1);
}
double total_if_ifelse = ((Integer) myTemp).doubleValue();
myTemp = aggregatedValues.get("Total Loops");
if (myTemp == null) {
System.out.println("Total Loops not found in aggregatedValues");
System.exit(1);
}
double totalLoops = ((Integer) myTemp).doubleValue();
double totalConditional = total_if_ifelse + totalLoops;
myTemp = aggregatedValues.get("AST-Node-Count");
if (myTemp == null) {
System.out.println("AST-Node-Count not found in aggregatedValues");
System.exit(1);
}
double astCount = ((Integer) myTemp).doubleValue();
myTemp = aggregatedValues.get("NameCount");
if (myTemp == null) {
System.out.println("NameCount not found in aggregatedValues");
System.exit(1);
}
double nameCount = ((Double) myTemp).doubleValue();
myTemp = aggregatedValues.get("Expr-Count");
if (myTemp == null) {
System.out.println("ExprCount not found in aggregatedValues");
System.exit(1);
}
double exprCount = ((Double) myTemp).doubleValue();
tempIt = columns.iterator();
while (tempIt.hasNext()) {
String nexttempit = tempIt.next();
Object temp = aggregatedValues.get(nexttempit);
// System.out.println("NEXT TEMP IT ISSSSSSSSSSSSSSSSSSSSSS"+nexttempit);
if (temp instanceof Integer) {
int val = ((Integer) temp).intValue();
if (CSV) {
switch (count) {
case 0:// original
bench.print(fileName.substring(0, fileName.indexOf('-')));
case 1:
case 2:
case 3:
case 4:
if (nexttempit.equals("Total-Abrupt")) {
// no averaging
bench.print("," + val);
} else if (nexttempit.equals("Total-Cond-Complexity")) {
if (totalConditional != 0) {
// average by dividing total-cond-complexity for sum of if+ifelse+loops
System.out.println("conditional complexit is" + val);
System.out.println("totalConditionals are" + totalConditional);
bench.print("," + val / totalConditional);
} else if (val == 0) {
bench.print("," + val);
} else {
// val not 0 but toalconds are 0...not good
System.out.println("Val not 0 but totalConditionals are zero!!!");
System.exit(1);
}
} else if (nexttempit.equals("D-W-Complexity")) {
if (astCount != 0) {
// average by dividing D-W-Complexity by node count
bench.print("," + val / astCount);
} else if (val == 0) {
bench.print("," + val);
} else {
// val not 0 but astcount is 0...not good
System.out.println("Val not 0 but astcount is zero!!!");
System.exit(1);
}
} else if (nexttempit.equals("Expr-Complexity")) {
if (exprCount != 0) {
// average by dividing expr-complexity for exprCount
bench.print("," + val / exprCount);
} else if (val == 0) {
bench.print("," + val);
} else {
// val not 0 but expr-count are 0...not good
System.out.println("Val not 0 but exprcount is zero!!!");
System.exit(1);
}
} else if (nexttempit.equals("Name-Complexity")) {
if (nameCount != 0) {
// average by dividing name-complexity for nameCount
bench.print("," + val / nameCount);
} else if (val == 0) {
bench.print("," + val);
} else {
// val not 0 but name-count are 0...not good
System.out.println("Val not 0 but name-count is zero!!!");
System.exit(1);
}
} else {
// labeled blocks, locals, if-ifelse, ASTNodeCount
bench.print("," + val);
}
break;
default:
System.out.println("unhandled count value");
System.exit(1);
}
} else {
// not CSV
bench.print("&" + val);
}
} else if (temp instanceof Double) {
double val = ((Double) temp).doubleValue();
if (CSV) {
switch (count) {
case 0:// original
bench.print(fileName.substring(0, fileName.indexOf('-')));
case 1:
case 2:
case 3:
case 4:
if (nexttempit.equals("Total-Abrupt")) {
// no averaging
bench.print("," + val);
} else if (nexttempit.equals("Total-Cond-Complexity")) {
if (totalConditional != 0) {
// average by dividing total-cond-complexity for sum of if+ifelse+loops
System.out.println("conditional complexit is" + val);
System.out.println("totalConditionals are" + totalConditional);
bench.print("," + val / totalConditional);
} else if (val == 0) {
bench.print("," + val);
} else {
// val not 0 but toalconds are 0...not good
System.out.println("Val not 0 but totalConditionals are zero!!!");
System.exit(1);
}
} else if (nexttempit.equals("D-W-Complexity")) {
if (astCount != 0) {
// average by dividing D-W-Complexity by node count
bench.print("," + val / astCount);
} else if (val == 0) {
bench.print("," + val);
} else {
// val not 0 but astcount is 0...not good
System.out.println("Val not 0 but astcount is zero!!!");
System.exit(1);
}
} else if (nexttempit.equals("Expr-Complexity")) {
if (exprCount != 0) {
// average by dividing expr-complexity for exprCount
bench.print("," + val / exprCount);
} else if (val == 0) {
bench.print("," + val);
} else {
// val not 0 but expr-count are 0...not good
System.out.println("Val not 0 but exprcount is zero!!!");
System.exit(1);
}
} else if (nexttempit.equals("Name-Complexity")) {
if (nameCount != 0) {
// average by dividing name-complexity for nameCount
bench.print("," + val / nameCount);
} else if (val == 0) {
bench.print("," + val);
} else {
// val not 0 but name-count are 0...not good
System.out.println("Val not 0 but name-count is zero!!!");
System.exit(1);
}
} else {
// labeled blocks, locals, if-ifelse, ASTNodeCount
bench.print("," + val);
}
break;
default:
System.out.println("unhandled count value");
System.exit(1);
}
} else {
bench.print("&" + val);
}
} else {
throw new RuntimeException("Unknown type of object stored!!!");
}
if (CSV) {
if (tempIt.hasNext()) {
System.out.println("Only allowed one metric for CSV");
System.exit(1);
}
} else {
if (tempIt.hasNext()) {
bench.print(" ");
} else {
bench.println("\\\\");
}
}
}
} catch (SAXParseException err) {
System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
} catch (SAXException e) {
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
} // done with all files for this benchmark
// print closing for the table for this benchmark
if (CSV) {
bench.println("");
} else {
printTexTableFooter(bench, "");
}
} // done with all benchmarks
closeWriteFile(bench, newClassName);
} else {
Iterator<String> it = xmlFileList.iterator();
while (it.hasNext()) {
String fileName = it.next();
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(fileName));
System.out.println("Gethering metric info from from xml file: " + fileName);
// normalize text representation
doc.getDocumentElement().normalize();
if (aggregationMechanism == ProcessData.CLASS) {
getClassMetrics(fileName, doc, columns);
} else {
System.out.println("Unknown aggregation Mechanism");
System.exit(1);
}
} catch (SAXParseException err) {
System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
} catch (SAXException e) {
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
private static PrintWriter openWriteFile(String fileName) {
PrintWriter writerOut;
try {
streamOut = new FileOutputStream(fileName);
writerOut = new PrintWriter(new OutputStreamWriter(streamOut));
} catch (IOException e) {
throw new CompilationDeathException("Cannot output file " + fileName);
}
return writerOut;
}
private static void closeWriteFile(PrintWriter writerOut, String fileName) {
try {
writerOut.flush();
streamOut.close();
} catch (IOException e) {
throw new CompilationDeathException("Cannot output file " + fileName);
}
}
/*
* This method is called for each xml class sent as input.
*
* Should read all of its metrics and add them to the aggregated values
*/
private static int aggregateXMLFileMetrics(Document doc, HashMap<String, Number> aggregated) {
NodeList classes = doc.getElementsByTagName("Class");
int numClasses = classes.getLength();
System.out.println("NumClasses for this document are" + numClasses);
NodeList metrics = doc.getElementsByTagName("Metric");
for (int s = 0; s < metrics.getLength(); s++) {
Node metricNode = metrics.item(s);
if (metricNode.getNodeType() == Node.ELEMENT_NODE) {
Element metricElement = (Element) metricNode;
NodeList metricName = metricElement.getElementsByTagName("MetricName");
Element name = (Element) metricName.item(0);
NodeList textFNList = name.getChildNodes();
String tempName = ((Node) textFNList.item(0)).getNodeValue().trim();
Object tempObj = aggregated.get(tempName);
if (tempObj == null) {
// not found in hashmap so we dont care about this metric
continue;
}
// We get to this point only if the metric is important
NodeList value = metricElement.getElementsByTagName("Value");
Element name1 = (Element) value.item(0);
NodeList textFNList1 = name1.getChildNodes();
String valToPrint = ((Node) textFNList1.item(0)).getNodeValue().trim();
boolean notInt = false;
try {
int temp = Integer.parseInt(valToPrint);
if (tempObj instanceof Integer) {
Integer valSoFar = (Integer) tempObj;
aggregated.put(tempName, new Integer(valSoFar.intValue() + temp));
} else if (tempObj instanceof Double) {
Double valSoFar = (Double) tempObj;
aggregated.put(tempName, new Double(valSoFar.doubleValue() + temp));
} else {
throw new RuntimeException("\n\nobject type not found");
}
} catch (Exception e) {
// temp was not an int
notInt = true;
}
if (notInt) {
// probably a double
try {
double temp = Double.parseDouble(valToPrint);
if (tempObj instanceof Integer) {
Integer valSoFar = (Integer) tempObj;
aggregated.put(tempName, new Double(valSoFar.intValue() + temp));
} else if (tempObj instanceof Double) {
Double valSoFar = (Double) tempObj;
aggregated.put(tempName, new Double(valSoFar.doubleValue() + temp));
} else {
throw new RuntimeException("\n\nobject type not found");
}
} catch (Exception e) {
throw new RuntimeException("\n\n not an integer not a double unhandled!!!!");
}
}
} // end of if metricNode is an element_Node
} // end of for loop with s var
return numClasses;
}
private static void getClassMetrics(String fileName, Document doc, Vector<String> columns) {
// create a tex file with name (fileName - xml + tex)
String newClassName = fileName;
if (newClassName.endsWith(".xml")) {
newClassName = newClassName.substring(0, newClassName.length() - 4);
}
newClassName += ".tex";
System.out.println("Creating tex file" + newClassName + " from metrics info in file" + fileName);
PrintWriter writerOut = openWriteFile(newClassName);
printTexTableHeader(writerOut, "Classes", columns);
/*
* In order to print all class info alphabetically we will create a map of className to data to be displayed
*/
ArrayList<String> classNames = new ArrayList<String>();
HashMap<String, String> classData = new HashMap<String, String>();
// each row is a class the name is obtained from the tag Class
NodeList classes = doc.getElementsByTagName("Class");
for (int cl = 0; cl < classes.getLength(); cl++) {
// going through each class node
Node classNode = classes.item(cl);
if (classNode.getNodeType() == Node.ELEMENT_NODE) {
Element classElement = (Element) classNode;
/*
* Class Name
*/
NodeList classNameNodeList = classElement.getElementsByTagName("ClassName");
Element classNameElement = (Element) classNameNodeList.item(0);
NodeList classNameTextFNList = classNameElement.getChildNodes();
String className = ((Node) classNameTextFNList.item(0)).getNodeValue().trim();
// writerOut.println("");
className = className.replace('_', '-');
if (className.length() > CLASSNAMESIZE) {
// writerOut.print(className.substring(0,CLASSNAMESIZE)+" ");
className = className.substring(0, CLASSNAMESIZE);
classNames.add(className);
} else {
// writerOut.print(className+" ");
classNames.add(className);
}
System.out.print("\nclassName " + className);
String data = " ";
/*
* Metrics
*/
NodeList metrics = classElement.getElementsByTagName("Metric");
int columnIndex = 0; // which one we are printing right now
for (int s = 0; s < metrics.getLength() && columnIndex < columns.size(); s++) {
Node metricNode = metrics.item(s);
if (metricNode.getNodeType() == Node.ELEMENT_NODE) {
Element metricElement = (Element) metricNode;
NodeList metricName = metricElement.getElementsByTagName("MetricName");
Element name = (Element) metricName.item(0);
NodeList textFNList = name.getChildNodes();
String tempName = ((Node) textFNList.item(0)).getNodeValue().trim();
/*
* If the name of this metric is not the next column name in the columns simply skip over it and continue
*/
if (!tempName.equals(columns.elementAt(columnIndex))) {
// System.out.println("here");
continue;
}
// We get to this point only if the metric name is the same as the column name
NodeList value = metricElement.getElementsByTagName("Value");
Element name1 = (Element) value.item(0);
NodeList textFNList1 = name1.getChildNodes();
String valToPrint = ((Node) textFNList1.item(0)).getNodeValue().trim();
System.out.print(" " + valToPrint);
// writerOut.print("&"+valToPrint);
data += "&" + valToPrint;
columnIndex++;
if (columns.size() > columnIndex) {
// writerOut.print(" ");
data += " ";
} else {
// writerOut.println("\\\\");
data += "\\\\";
}
} // end of if metricNode is an element_Node
} // end of for loop with s var
classData.put(className, data);
} // end of if classNode is an element_Node
} // end of for loop with cl
// writerOut.println();
// writerOut.println();
// writerOut.println();
Collections.sort(classNames);
Iterator<String> tempIt = classNames.iterator();
while (tempIt.hasNext()) {
String className = tempIt.next();
String data = classData.get(className);
writerOut.print(className);
writerOut.println(data);
}
printTexTableFooter(writerOut, fileName);
closeWriteFile(writerOut, metricListFileName);
}
private static void printTexTableFooter(PrintWriter out, String tableCaption) {
out.println("");
out.println("\\hline");
out.println("\\end{tabular}");
out.println("\\caption{ ..." + tableCaption + "..... }");
out.println("\\end{table}");
// out.println("\\end{figure}");
}
/*
* Prints the name of??
*/
private static void printCSVHeader(PrintWriter out) {
if (decompiler) {
out.println(",Original,Jad,SourceAgain,Dava(enabled),Dava(disabled)");
} else {
out.println(",Original,JBCO-enabled,JBCO-disabled,klassmaster-enabled,klassmaster-disabled");
}
}
private static void printTexTableHeader(PrintWriter out, String rowHeading, Vector<String> columns) {
// out.println("\\begin{figure}[hbtp]");
out.println("\\begin{table}[hbtp]");
out.print("\\begin{tabular}{");
for (int i = 0; i <= columns.size(); i++) {
out.print("|l");
}
out.println("|}");
out.println("\\hline");
out.print(rowHeading + " ");
Iterator<String> it = columns.iterator();
while (it.hasNext()) {
out.print("&" + it.next());
if (it.hasNext()) {
out.print(" ");
}
}
out.println("\\\\");
out.println("\\hline");
}
}
| 40,638
| 36.55915
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/exceptions/AbstractThrowAnalysis.java
|
package soot.toolkits.exceptions;
import java.util.Set;
import java.util.stream.Collectors;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of 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.AnySubType;
import soot.Local;
import soot.NullType;
import soot.RefType;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.Value;
import soot.baf.ThrowInst;
import soot.grimp.NewInvokeExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.NewExpr;
import soot.jimple.ThrowStmt;
/**
* Abstract class implementing parts of the {@link ThrowAnalysis} interface which may be common to multiple concrete
* <code>ThrowAnalysis</code> classes. <code>AbstractThrowAnalysis</code> provides straightforward implementations of
* {@link mightThrowExplicitly(ThrowInst)} and {@link mightThrowExplicitly(ThrowStmt)}, since concrete implementations of
* <code>ThrowAnalysis</code> seem likely to differ mainly in their treatment of implicit exceptions.
*/
public abstract class AbstractThrowAnalysis implements ThrowAnalysis {
abstract public ThrowableSet mightThrow(Unit u);
@Override
public ThrowableSet mightThrowExplicitly(ThrowInst t) {
// Deducing the type at the top of the Baf stack is beyond me, so...
return ThrowableSet.Manager.v().ALL_THROWABLES;
}
@Override
public ThrowableSet mightThrowExplicitly(ThrowStmt t) {
return mightThrowExplicitly(t, null);
}
public ThrowableSet mightThrowExplicitly(ThrowStmt t, SootMethod sm) {
Value thrownExpression = t.getOp();
Type thrownType = thrownExpression.getType();
if (thrownType == null || thrownType instanceof UnknownType) {
// We can't identify the type of thrownExpression, so...
return ThrowableSet.Manager.v().ALL_THROWABLES;
} else if (thrownType instanceof NullType) {
ThrowableSet result = ThrowableSet.Manager.v().EMPTY;
result = result.add(ThrowableSet.Manager.v().NULL_POINTER_EXCEPTION);
return result;
} else if (!(thrownType instanceof RefType)) {
throw new IllegalStateException("UnitThrowAnalysis StmtSwitch: type of throw argument is not a RefType!");
} else {
ThrowableSet result = ThrowableSet.Manager.v().EMPTY;
if (thrownExpression instanceof NewInvokeExpr) {
// In this case, we know the exact type of the
// argument exception.
result = result.add((RefType) thrownType);
} else {
RefType preciseType = null;
// If there is only one allocation site, we know the type as well
if (thrownExpression instanceof Local && sm != null) {
Set<RefType> types = sm.getActiveBody().getUnits().stream().filter(u -> u instanceof DefinitionStmt)
.map(u -> (DefinitionStmt) u).filter(d -> d.getLeftOp() == thrownExpression).map(d -> d.getRightOp())
.filter(o -> o instanceof NewExpr).map(o -> (NewExpr) o).map(n -> n.getType())
.filter(r -> r instanceof RefType).map(r -> (RefType) r).collect(Collectors.toSet());
if (types.size() == 1) {
preciseType = types.iterator().next();
}
}
if (preciseType == null) {
result = result.add(AnySubType.v((RefType) thrownType));
} else {
result = result.add(preciseType);
}
}
return result;
}
}
abstract public ThrowableSet mightThrowImplicitly(ThrowInst t);
abstract public ThrowableSet mightThrowImplicitly(ThrowStmt t);
}
| 4,192
| 37.46789
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/exceptions/DuplicateCatchAllTrapRemover.java
|
package soot.toolkits.exceptions;
/*-
* #%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.Singletons;
import soot.Trap;
import soot.Unit;
/**
* Some compilers generate duplicate traps:
*
* Exception table: from to target type 9 30 37 Class java/lang/Throwable 9 30 44 any 37 46 44 any
*
* The semantics is as follows:
*
* try { // block } catch { // handler 1 } finally { // handler 2 }
*
* In this case, the first trap covers the block and jumps to handler 1. The second trap also covers the block and jumps to
* handler 2. The third trap covers handler 1 and jumps to handler 2. If we treat "any" as java.lang. Throwable, the second
* handler is clearly unnecessary. Worse, it violates Soot's invariant that there may only be one handler per combination of
* covered code region and jump target.
*
* This transformer detects and removes such unnecessary traps.
*
* @author Steven Arzt
*
*/
public class DuplicateCatchAllTrapRemover extends BodyTransformer {
public DuplicateCatchAllTrapRemover(Singletons.Global g) {
}
public static DuplicateCatchAllTrapRemover v() {
return soot.G.v().soot_toolkits_exceptions_DuplicateCatchAllTrapRemover();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
// Find two traps that use java.lang.Throwable as their type and that
// span the same code region
for (Iterator<Trap> t1It = b.getTraps().snapshotIterator(); t1It.hasNext();) {
Trap t1 = t1It.next();
if (t1.getException().getName().equals("java.lang.Throwable")) {
for (Iterator<Trap> t2It = b.getTraps().snapshotIterator(); t2It.hasNext();) {
Trap t2 = t2It.next();
if (t1 != t2 && t1.getBeginUnit() == t2.getBeginUnit() && t1.getEndUnit() == t2.getEndUnit()
&& t2.getException().getName().equals("java.lang.Throwable")) {
// Both traps (t1, t2) span the same code and catch java.lang.Throwable.
// Check if one trap jumps to a target that then jumps to the target of
// the other trap.
for (Trap t3 : b.getTraps()) {
if (t3 != t1 && t3 != t2 && t3.getException().getName().equals("java.lang.Throwable")) {
if (trapCoversUnit(b, t3, t1.getHandlerUnit()) && t3.getHandlerUnit() == t2.getHandlerUnit()) {
// c -> t1 -> t3 -> t2 && c -> t2
b.getTraps().remove(t2);
break;
} else if (trapCoversUnit(b, t3, t2.getHandlerUnit()) && t3.getHandlerUnit() == t1.getHandlerUnit()) {
// c -> t2 -> t3 -> t1 && c -> t1
b.getTraps().remove(t1);
break;
}
}
}
}
}
}
}
}
/**
* Checks whether the given trap covers the given unit, i.e., there is an exceptional control flow from the given unit to
* the given trap
*
* @param b
* The body containing the unit and the trap
* @param trap
* The trap
* @param unit
* The unit
* @return True if there can be an exceptional control flow from the given unit to the given trap
*/
private boolean trapCoversUnit(Body b, Trap trap, Unit unit) {
for (Iterator<Unit> unitIt = b.getUnits().iterator(trap.getBeginUnit(), trap.getEndUnit()); unitIt.hasNext();) {
Unit u = unitIt.next();
if (u == unit) {
return true;
}
}
return false;
}
}
| 4,361
| 35.655462
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/exceptions/PedanticThrowAnalysis.java
|
package soot.toolkits.exceptions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.G;
import soot.Singletons;
import soot.Unit;
import soot.baf.ThrowInst;
import soot.jimple.ThrowStmt;
/**
* A {@link ThrowAnalysis} that says that every unit can throw every possible exception type. Strictly speaking, this is
* correct, since the deprecated {@link java.lang.Thread#stop(Throwable)} method allows one thread to cause any
* {@link Throwable} it wants to be thrown in another thread, meaning that all {@link Throwable}s may arrive asynchronously
* from the perspective of the victim thread.
*/
public class PedanticThrowAnalysis extends AbstractThrowAnalysis {
/**
* Constructs a <code>PedanticThrowAnalysis</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 PedanticThrowAnalysis(Singletons.Global g) {
}
/**
* Returns the single instance of <code>PedanticThrowAnalysis</code>.
*
* @return Soot's <code>PedanticThrowAnalysis</code>.
*/
public static PedanticThrowAnalysis v() {
return G.v().soot_toolkits_exceptions_PedanticThrowAnalysis();
}
/**
* Returns the set of all <code>Throwable</code>s as the set of types that the specified unit might throw, regardless of
* the unit's identity.
*
* @param u
* {@link Unit} whose exceptions are to be returned.
*
* @return the set of all <code>Throwable</code>s.
*/
@Override
public ThrowableSet mightThrow(Unit u) {
return ThrowableSet.Manager.v().ALL_THROWABLES;
}
/**
* Returns the set of all <code>Throwable</code>s as the set of types that a <code>throw</code> instruction may throw
* implicitly, that is, the possible types of errors which might arise in the course of executing the <code>throw</code>
* instruction, rather than the type of the <code>throw</code>'s operand.
*
* @param t
* the {@link ThrowInst} whose exceptions are to be returned.
*
* @return the set of all <code>Throwable</code>s.
*/
@Override
public ThrowableSet mightThrowImplicitly(ThrowInst t) {
return ThrowableSet.Manager.v().ALL_THROWABLES;
}
/**
* Returns the set of all <code>Throwable</code>s as the set of types that a <code>throw</code> statement may throw
* implicitly, that is, the possible types of errors which might arise in the course of executing the <code>throw</code>
* statement, rather than the type of the <code>throw</code>'s operand.
*
* @param t
* the {@link ThrowStmt} whose exceptions are to be returned.
*
* @return the set of all <code>Throwable</code>s.
*/
@Override
public ThrowableSet mightThrowImplicitly(ThrowStmt t) {
return ThrowableSet.Manager.v().ALL_THROWABLES;
}
}
| 3,609
| 34.742574
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/exceptions/ThrowAnalysis.java
|
package soot.toolkits.exceptions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of 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.Unit;
import soot.baf.ThrowInst;
import soot.jimple.ThrowStmt;
/**
* <p>
* A source of information about the exceptions that {@link Unit}s might throw.
* </p>
*
* <p>
* The <code>Unit</code>s corresponding to <code>athrow</code> instructions may throw exceptions either
* explicitly—because the exception is the <code>athrow</code>'s argument— or implicitly—because some error
* arises in the course of executing the instruction (only implicit exceptions are possible for bytecode instructions other
* than <code>athrow</code>). The <code>mightThrowExplicitly()</code> and <code>mightThrowImplicitly()</code> methods allow
* analyses to exploit any extra precision that may be gained by distinguishing between an <code>athrow</code>'s implicit and
* explicit exceptions.
* </p>
*/
public interface ThrowAnalysis {
/**
* Returns a set representing the {@link Throwable} types that the specified unit might throw.
*
* @param u
* {@link Unit} whose exceptions are to be returned.
*
* @return a representation of the <code>Throwable</code> types that <code>u</code> might throw.
*/
ThrowableSet mightThrow(Unit u);
/**
* Returns a set representing the {@link Throwable} types that the specified throw instruction might throw explicitly, that
* is, the possible types for its <code>Throwable</code> argument.
*
* @param t
* {@link ThrowInst} whose explicit exceptions are to be returned.
*
* @return a representation of the possible types of <code>t</code>'s <code>Throwable</code> operand.
*/
ThrowableSet mightThrowExplicitly(ThrowInst t);
/**
* Returns a set representing the {@link Throwable} types that the specified throw statement might throw explicitly, that
* is, the possible types for its <code>Throwable</code> argument.
*
* @param t
* {@link ThrowStmt} whose explicit exceptions are to be returned.
*
* @return a representation of the possible types of <code>t</code>'s <code>Throwable</code> operand.
*/
ThrowableSet mightThrowExplicitly(ThrowStmt t);
/**
* Returns a set representing the {@link Throwable} types that the specified throw instruction might throw implicitly, that
* is, the possible types of errors which might arise in the course of executing the <code>throw</code> instruction, rather
* than the type of the <code>throw</code>'s operand.
*
* @param t
* {@link ThrowStmt} whose implicit exceptions are to be returned.
*
* @return a representation of the types of exceptions that <code>t</code> might throw implicitly.
*/
ThrowableSet mightThrowImplicitly(ThrowInst t);
/**
* Returns a set representing the {@link Throwable} types that the specified throw statement might throw implicitly, that
* is, the possible types of errors which might arise in the course of executing the <code>throw</code> statement, rather
* than the type of the <code>throw</code>'s operand.
*
* @param t
* {@link ThrowStmt} whose implicit exceptions are to be returned.
*
* @return a representation of the types of exceptions that <code>t</code> might throw implicitly.
*/
ThrowableSet mightThrowImplicitly(ThrowStmt t);
}
| 4,097
| 39.176471
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/exceptions/ThrowAnalysisFactory.java
|
/* Soot - a Java Optimization Framework
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that 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 library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot.toolkits.exceptions;
/*-
* #%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.dexpler.DalvikThrowAnalysis;
import soot.options.Options;
/**
* Factory that returns an appropriate ThrowAnalysis instances for a given task.
*/
public class ThrowAnalysisFactory {
/**
* Resolve the ThrowAnalysis to be used for initialization checking (e.g. soot.Body.checkInit())
*/
public static ThrowAnalysis checkInitThrowAnalysis() {
final Options opts = Options.v();
switch (opts.check_init_throw_analysis()) {
case Options.check_init_throw_analysis_auto:
if (!opts.android_jars().isEmpty() || !opts.force_android_jar().isEmpty()) {
// If Android related options are set, use 'dalvik' throw analysis.
return DalvikThrowAnalysis.v();
} else {
return PedanticThrowAnalysis.v();
}
case Options.check_init_throw_analysis_pedantic:
return PedanticThrowAnalysis.v();
case Options.check_init_throw_analysis_unit:
return UnitThrowAnalysis.v();
case Options.check_init_throw_analysis_dalvik:
return DalvikThrowAnalysis.v();
default:
assert false; // The above cases should cover all posible options
return PedanticThrowAnalysis.v();
}
}
private ThrowAnalysisFactory() {
}
}
| 2,881
| 35.481013
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/exceptions/ThrowableSet.java
|
package soot.toolkits.exceptions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import com.google.common.cache.CacheBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import soot.AnySubType;
import soot.FastHierarchy;
import soot.G;
import soot.RefLikeType;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.Unit;
import soot.options.Options;
/**
* <p>
* A class for representing the set of exceptions that an instruction may throw.
* </p>
*
* <p>
* <code>ThrowableSet</code> does not implement the {@link java.util.Set} interface, so perhaps it is misnamed. Instead, it
* provides only the operations that we require for determining whether a given statement might throw an exception that would
* be caught by a given handler.
* </p>
*
* <p>
* There is a limitation on the combinations of operations permitted on a <code>ThrowableSet</code>. The
* <code>ThrowableSet</code>s returned by {@link #whichCatchableAs(RefType)} cannot be involved in subsequent
* <code>add()</code> or <code>whichCatchableAs()</code> operations. That is, given
*
* <blockquote> <code>p = s.whichCatchableAs(r)</code> </blockquote>
*
* for any <code>ThrowableSet</code> <code>s</code> and {@link soot.RefType RefType} <code>r</code>, and
*
* <blockquote> <code>t == p.getUncaught()</code> or <code>t == p.getCaught()</code> </blockquote>
*
* then calls to <code>t.add(r)</code>, <code>t.add(a)</code>, and <code>s.add(t)</code>, will throw an
* {@link ThrowableSet.AlreadyHasExclusionsException}, for any <code>RefType</code> <code>r</code>, {@link AnySubType}
* <code>a</code>, and <code>ThrowableSet</code> <code>t</code>.
* </p>
*
* <p>
* Actually the restrictions implemented are not quite so strict (there are some combinations of
* <code>whichCatchableAs()</code> followed by <code>add()</code> which will not raise an exception), but a more accurate
* description would require reference to the internals of the current implementation. The restrictions should not be too
* onerous for <code>ThrowableSet</code>'s anticipated uses: we expect <code>ThrowableSet</code>s to grow by accumulating all
* the exception types that a given {@link Unit} may throw, then, shrink as the types caught by different exception handlers
* are removed to yield the sets representing exceptions which escape those handlers.
* </p>
*
* <p>
* The <code>ThrowableSet</code> class is intended to be immutable (hence the <code>final</code> modifier on its
* declaration). It does not take the step of guaranteeing immutability by cloning the <code>RefLikeType</code> objects it
* contains, though, because we trust {@link Scene} to enforce the existence of only one <code>RefLikeType</code> instance
* with a given name.
* </p>
*/
public class ThrowableSet {
private static final boolean INSTRUMENTING = false;
private final SootClass JAVA_LANG_OBJECT_CLASS = Scene.v().getObjectType().getSootClass();
/**
* Set of exception types included within the set.
*/
protected final Set<RefLikeType> exceptionsIncluded;
/**
* Set of exception types which, though members of exceptionsIncluded, are to be excluded from the types represented by
* this <code>ThrowableSet</code>. To simplify the implementation, once a <code>ThrowableSet</code> has any excluded types,
* the various <code>add()</code> methods of this class must bar additions of subtypes of those excluded types.
*/
protected final Set<AnySubType> exceptionsExcluded;
/**
* A map from ({@link RefLikeType} \\union <code>ThrowableSet</code>) to <code>ThrowableSet</code>. If the mapping (k,v) is
* in <code>memoizedAdds</code> and k is a <code>ThrowableSet</code>, then v is the set that results from adding all
* elements in k to <code>this</code>. If (k,v) is in <code>memoizedAdds</code> and k is a {@link RefLikeType}, then v is
* the set that results from adding k to <code>this</code>.
*/
protected Map<Object, ThrowableSet> memoizedAdds;
/**
* Constructs a <code>ThrowableSet</code> which contains the exception types represented in <code>include</code>, except
* for those which are also in <code>exclude</code>. The constructor is private to ensure that the only way to get a new
* <code>ThrowableSet</code> is by adding elements to or removing them from an existing set.
*
* @param include
* The set of {@link RefType} and {@link AnySubType} objects representing the types to be included in the set.
* @param exclude
* The set of {@link AnySubType} objects representing the types to be excluded from the set.
*/
protected ThrowableSet(Set<RefLikeType> include, Set<AnySubType> exclude) {
exceptionsIncluded = getImmutable(include);
exceptionsExcluded = getImmutable(exclude);
// We don't need to clone include and exclude to guarantee
// immutability since ThrowableSet(Set,Set) is private to this
// class, where it is only called (via
// Manager.v().registerSetIfNew()) with arguments which the
// callers do not subsequently modify.
}
private static <T> Set<T> getImmutable(Set<T> in) {
if ((null == in) || in.isEmpty()) {
return Collections.emptySet();
}
if (1 == in.size()) {
return Collections.singleton(in.iterator().next());
}
return Collections.unmodifiableSet(in);
}
/**
* Returns an {@link Iterator} over a {@link Collection} of Throwable types which iterates over its elements in a
* consistent order (maintaining an ordering that is consistent across different runs makes it easier to compare sets
* generated by different implementations of the CFG classes).
*
* @param coll
* The collection to iterate over.
*
* @return An iterator which presents the elements of <code>coll</code> in order.
*/
private static <T extends RefLikeType> Iterator<T> sortedThrowableIterator(Collection<T> coll) {
if (coll.size() <= 1) {
return coll.iterator();
} else {
@SuppressWarnings("unchecked")
T[] array = (T[]) coll.toArray(new RefLikeType[coll.size()]);
Arrays.sort(array, new ThrowableComparator<T>());
return Arrays.asList(array).iterator();
}
}
private ThrowableSet getMemoizedAdds(Object key) {
return memoizedAdds == null ? null : memoizedAdds.get(key);
}
private void addToMemoizedAdds(Object key, ThrowableSet value) {
if (memoizedAdds == null) {
memoizedAdds = new ConcurrentHashMap<>();
}
memoizedAdds.put(key, value);
}
/**
* Returns a <code>ThrowableSet</code> which contains <code>e</code> in addition to the exceptions in this
* <code>ThrowableSet</code>.
*
* <p>
* Add <code>e</code> as a {@link RefType} when you know that the run-time class of the exception you are representing is
* necessarily <code>e</code> and cannot be a subclass of <code>e</code>.
*
* <p>
* For example, if you were recording the type of the exception thrown by
*
* <pre>
* throw new IOException("Permission denied");
* </pre>
*
* you would call
*
* <pre>
* <code>add(Scene.v().getRefType("java.lang.Exception.IOException"))</code>
* </pre>
*
* since the class of the exception is necessarily <code>IOException</code>.
*
* @param e
* the exception class
*
* @return a set containing <code>e</code> as well as the exceptions in this set.
*
* @throws {@link
* ThrowableSet.IllegalStateException} if this <code>ThrowableSet</code> is the result of a
* {@link #whichCatchableAs(RefType)} operation and, thus, unable to represent the addition of <code>e</code>.
*/
public ThrowableSet add(RefType e) throws ThrowableSet.AlreadyHasExclusionsException {
if (INSTRUMENTING) {
Manager.v().addsOfRefType++;
}
if (this.exceptionsIncluded.contains(e)) {
if (INSTRUMENTING) {
Manager.v().addsInclusionFromMap++;
Manager.v().addsExclusionWithoutSearch++;
}
return this;
}
ThrowableSet result = getMemoizedAdds(e);
if (result != null) {
if (INSTRUMENTING) {
Manager.v().addsInclusionFromMemo++;
Manager.v().addsExclusionWithoutSearch++;
}
return result;
}
if (INSTRUMENTING) {
Manager.v().addsInclusionFromSearch++;
if (exceptionsExcluded.isEmpty()) {
Manager.v().addsExclusionWithoutSearch++;
} else {
Manager.v().addsExclusionWithSearch++;
}
}
FastHierarchy hierarchy = Scene.v().getOrMakeFastHierarchy();
boolean eHasNoHierarchy = hasNoHierarchy(e);
for (AnySubType excludedType : exceptionsExcluded) {
RefType exclusionBase = excludedType.getBase();
if ((eHasNoHierarchy && exclusionBase.equals(e)) || (!eHasNoHierarchy && hierarchy.canStoreType(e, exclusionBase))) {
throw new AlreadyHasExclusionsException("ThrowableSet.add(RefType): adding" + e.toString() + " to the set [ "
+ this.toString() + "] where " + exclusionBase.toString() + " is excluded.");
}
}
// If this is a real class, we need to check whether we already have it
// in the list through subtyping.
if (!eHasNoHierarchy) {
for (RefLikeType incumbent : exceptionsIncluded) {
if (incumbent instanceof AnySubType) {
// Need to use incumbent.getBase() because
// hierarchy.canStoreType() assumes that parent
// is not an AnySubType.
RefType incumbentBase = ((AnySubType) incumbent).getBase();
if (hierarchy.canStoreType(e, incumbentBase)) {
addToMemoizedAdds(e, this);
return this;
}
} else if (!(incumbent instanceof RefType)) {
// assertion failure.
throw new IllegalStateException(
"ThrowableSet.add(RefType): Set element " + incumbent.toString() + " is neither a RefType nor an AnySubType.");
}
}
}
Set<RefLikeType> resultSet = new HashSet<>(this.exceptionsIncluded);
resultSet.add(e);
result = Manager.v().registerSetIfNew(resultSet, this.exceptionsExcluded);
addToMemoizedAdds(e, result);
return result;
}
private boolean hasNoHierarchy(RefType type) {
final SootClass sootClass = type.getSootClass();
return !(sootClass.hasSuperclass() || JAVA_LANG_OBJECT_CLASS == sootClass);
}
/**
* Returns a <code>ThrowableSet</code> which contains <code>e</code> and all of its subclasses as well as the exceptions in
* this set.
*
* <p>
* <code>e</code> should be an instance of {@link AnySubType} if you know that the compile-time type of the exception you
* are representing is <code>e</code>, but the exception may be instantiated at run-time by a subclass of <code>e</code>.
*
* <p>
* For example, if you were recording the type of the exception thrown by
*
* <pre>
* catch (IOException e) {
* throw e;
* }
* </pre>
*
* you would call
*
* <pre>
* <code>add(AnySubtype.v(Scene.v().getRefType("java.lang.Exception.IOException")))</code>
* </pre>
*
* since the handler might rethrow any subclass of <code>IOException</code>.
*
* @param e
* represents a subtree of the exception class hierarchy to add to this set.
*
* @return a set containing <code>e</code> and all its subclasses, as well as the exceptions represented by this set.
*
* @throws ThrowableSet.AlreadyHasExclusionsException
* if this <code>ThrowableSet</code> is the result of a {@link #whichCatchableAs(RefType)} operation and, thus,
* unable to represent the addition of <code>e</code>.
*/
public ThrowableSet add(AnySubType e) throws ThrowableSet.AlreadyHasExclusionsException {
if (INSTRUMENTING) {
Manager.v().addsOfAnySubType++;
}
ThrowableSet result = getMemoizedAdds(e);
if (result != null) {
if (INSTRUMENTING) {
Manager.v().addsInclusionFromMemo++;
Manager.v().addsExclusionWithoutSearch++;
}
return result;
}
// java.lang.Object is managed by the Scene -> guaranteed to only have one instance of the Object class
final SootClass objectClass = Scene.v().getObjectType().getSootClass();
FastHierarchy hierarchy = Scene.v().getOrMakeFastHierarchy();
RefType newBase = e.getBase();
boolean newBaseHasNoHierarchy = hasNoHierarchy(newBase);
if (INSTRUMENTING) {
if (exceptionsExcluded.isEmpty()) {
Manager.v().addsExclusionWithoutSearch++;
} else {
Manager.v().addsExclusionWithSearch++;
}
}
for (AnySubType excludedType : exceptionsExcluded) {
RefType exclusionBase = excludedType.getBase();
boolean exclusionBaseHasNoHierarchy = !(exclusionBase.getSootClass().hasSuperclass() || //
exclusionBase.getSootClass() == objectClass);
boolean isExcluded = exclusionBaseHasNoHierarchy && exclusionBase.equals(newBase);
isExcluded |= !exclusionBaseHasNoHierarchy
&& (hierarchy.canStoreType(newBase, exclusionBase) || hierarchy.canStoreType(exclusionBase, newBase));
if (isExcluded) {
if (INSTRUMENTING) {
// To ensure that the subcategories total properly:
Manager.v().addsInclusionInterrupted++;
}
throw new AlreadyHasExclusionsException("ThrowableSet.add(" + e.toString() + ") to the set [ " + this.toString()
+ "] where " + exclusionBase.toString() + " is excluded.");
}
}
if (this.exceptionsIncluded.contains(e)) {
if (INSTRUMENTING) {
Manager.v().addsInclusionFromMap++;
}
return this;
}
if (INSTRUMENTING) {
Manager.v().addsInclusionFromSearch++;
}
int changes = 0;
boolean addNewException = true;
Set<RefLikeType> resultSet = new HashSet<>();
for (RefLikeType incumbent : this.exceptionsIncluded) {
if (incumbent instanceof RefType) {
if (hierarchy.canStoreType(incumbent, newBase)) {
// Omit incumbent from result.
changes++;
} else {
resultSet.add(incumbent);
}
} else if (incumbent instanceof AnySubType) {
RefType incumbentBase = ((AnySubType) incumbent).getBase();
if (newBaseHasNoHierarchy) {
if (!incumbentBase.equals(newBase)) {
resultSet.add(incumbent);
}
}
// We have to use the base types in these hierarchy
// calls
// because we want to know if _all_ possible
// types represented by e can be represented by
// the incumbent, or vice versa.
else if (hierarchy.canStoreType(newBase, incumbentBase)) {
addNewException = false;
resultSet.add(incumbent);
} else if (hierarchy.canStoreType(incumbentBase, newBase)) {
// Omit incumbent from result;
changes++;
} else {
resultSet.add(incumbent);
}
} else { // assertion failure.
throw new IllegalStateException("ThrowableSet.add(AnySubType): Set element " + incumbent.toString()
+ " is neither a RefType nor an AnySubType.");
}
}
if (addNewException) {
resultSet.add(e);
changes++;
}
if (changes > 0) {
result = Manager.v().registerSetIfNew(resultSet, this.exceptionsExcluded);
} else {
result = this;
}
addToMemoizedAdds(e, result);
return result;
}
/**
* Returns a <code>ThrowableSet</code> which contains all the exceptions in <code>s</code> in addition to those in this
* <code>ThrowableSet</code>.
*
* @param s
* set of exceptions to add to this set.
*
* @return the union of this set with <code>s</code>
*
* @throws ThrowableSet.AlreadyHasExclusionsException
* if this <code>ThrowableSet</code> or <code>s</code> is the result of a {@link #whichCatchableAs(RefType)}
* operation, so that it is not possible to represent the addition of <code>s</code> to this
* <code>ThrowableSet</code>.
*/
public ThrowableSet add(ThrowableSet s) throws ThrowableSet.AlreadyHasExclusionsException {
if (INSTRUMENTING) {
Manager.v().addsOfSet++;
}
if ((exceptionsExcluded.size() > 0) || (s.exceptionsExcluded.size() > 0)) {
throw new AlreadyHasExclusionsException(
"ThrowableSet.Add(ThrowableSet): attempt to add to [" + this.toString() + "] after removals recorded.");
}
ThrowableSet result = getMemoizedAdds(s);
if (result == null) {
if (INSTRUMENTING) {
Manager.v().addsInclusionFromSearch++;
Manager.v().addsExclusionWithoutSearch++;
}
result = this.add(s.exceptionsIncluded);
addToMemoizedAdds(s, result);
} else if (INSTRUMENTING) {
Manager.v().addsInclusionFromMemo++;
Manager.v().addsExclusionWithoutSearch++;
}
return result;
}
/**
* Returns true if the throwable set is empty and false otherwise.
*
* @return true if the throwable set is empty.
*/
public boolean isEmpty() {
return exceptionsIncluded.isEmpty();
}
/**
* Returns a <code>ThrowableSet</code> which contains all the exceptions in <code>addedExceptions</code> in addition to
* those in this <code>ThrowableSet</code>.
*
* @param addedExceptions
* a set of {@link RefLikeType} and {@link AnySubType} objects to be added to the types included in this
* <code>ThrowableSet</code>.
*
* @return a set containing all the <code>addedExceptions</code> as well as the exceptions in this set.
*/
private ThrowableSet add(Set<RefLikeType> addedExceptions) {
Set<RefLikeType> resultSet = new HashSet<>(this.exceptionsIncluded);
int changes = 0;
FastHierarchy hierarchy = Scene.v().getOrMakeFastHierarchy();
// This algorithm is O(n m), where n and m are the sizes of the
// two sets, so hope that the sets are small.
for (RefLikeType newType : addedExceptions) {
if (!resultSet.contains(newType)) {
boolean addNewType = true;
if (newType instanceof RefType) {
for (RefLikeType incumbentType : resultSet) {
if (incumbentType instanceof RefType) {
if (newType == incumbentType) {
// assertion failure.
throw new IllegalStateException(
"ThrowableSet.add(Set): resultSet.contains() failed to screen duplicate RefType " + newType);
}
} else if (incumbentType instanceof AnySubType) {
RefType incumbentBase = ((AnySubType) incumbentType).getBase();
if (hierarchy.canStoreType(newType, incumbentBase)) {
// No need to add this class.
addNewType = false;
}
} else { // assertion failure.
throw new IllegalStateException("ThrowableSet.add(Set): incumbent Set element " + incumbentType
+ " is neither a RefType nor an AnySubType.");
}
}
} else if (newType instanceof AnySubType) {
RefType newBase = ((AnySubType) newType).getBase();
for (Iterator<RefLikeType> j = resultSet.iterator(); j.hasNext();) {
RefLikeType incumbentType = j.next();
if (incumbentType instanceof RefType) {
RefType incumbentBase = (RefType) incumbentType;
if (hierarchy.canStoreType(incumbentBase, newBase)) {
j.remove();
changes++;
}
} else if (incumbentType instanceof AnySubType) {
RefType incumbentBase = ((AnySubType) incumbentType).getBase();
if (newBase == incumbentBase) {
// assertion failure.
throw new IllegalStateException(
"ThrowableSet.add(Set): resultSet.contains() failed to screen duplicate AnySubType " + newBase);
} else if (hierarchy.canStoreType(incumbentBase, newBase)) {
j.remove();
changes++;
} else if (hierarchy.canStoreType(newBase, incumbentBase)) {
// No need to add this class.
addNewType = false;
}
} else { // assertion failure.
throw new IllegalStateException(
"ThrowableSet.add(Set): old Set element " + incumbentType + " is neither a RefType nor an AnySubType.");
}
}
} else { // assertion failure.
throw new IllegalArgumentException(
"ThrowableSet.add(Set): new Set element " + newType + " is neither a RefType nor an AnySubType.");
}
if (addNewType) {
changes++;
resultSet.add(newType);
}
}
}
ThrowableSet result = null;
if (changes > 0) {
result = Manager.v().registerSetIfNew(resultSet, this.exceptionsExcluded);
} else {
result = this;
}
return result;
}
/**
* Returns a <code>ThrowableSet</code> which contains all the exceptions in this <code>ThrowableSet</code> except for those
* in <code>removedExceptions</code>.
*
* @param removedExceptions
* a set of {@link RefLikeType} and {@link AnySubType} objects to be added to the types included in this
* <code>ThrowableSet</code>.
*
* @return a set containing all the <code>addedExceptions</code> as well as the exceptions in this set.
*/
private ThrowableSet remove(Set<RefLikeType> removedExceptions) {
// Is there anything to remove?
if (removedExceptions.isEmpty()) {
return this;
}
int changes = 0;
Set<RefLikeType> resultSet = new HashSet<>(this.exceptionsIncluded);
for (RefLikeType tp : removedExceptions) {
if (tp instanceof RefType) {
if (resultSet.remove(tp)) {
changes++;
}
}
}
ThrowableSet result = null;
if (changes > 0) {
result = Manager.v().registerSetIfNew(resultSet, this.exceptionsExcluded);
} else {
result = this;
}
return result;
}
/**
* Returns a <code>ThrowableSet</code> which contains all the exceptions from the current set except for those in the given
* <code>ThrowableSet</code>.
*
* @param s
* The set containing the exceptions to exclude from the new set
*
* @return The exceptions that are only in this set, but not in the given set
*
* @throws ThrowableSet.AlreadyHasExclusionsException
* if this <code>ThrowableSet</code> or <code>s</code> is the result of a {@link #whichCatchableAs(RefType)}
* operation, so that it is not possible to represent the addition of <code>s</code> to this
* <code>ThrowableSet</code>.
*/
public ThrowableSet remove(ThrowableSet s) {
if ((exceptionsExcluded.size() > 0) || (s.exceptionsExcluded.size() > 0)) {
throw new AlreadyHasExclusionsException(
"ThrowableSet.Add(ThrowableSet): attempt to add to [" + this.toString() + "] after removals recorded.");
}
// Remove the exceptions
return this.remove(s.exceptionsIncluded);
}
/**
* Indicates whether this ThrowableSet includes some exception that might be caught by a handler argument of the type
* <code>catcher</code>.
*
* @param catcher
* type of the handler parameter to be tested.
*
* @return <code>true</code> if this set contains an exception type that might be caught by <code>catcher</code>, false if
* it does not.
*/
public boolean catchableAs(RefType catcher) {
if (INSTRUMENTING) {
Manager.v().catchableAsQueries++;
}
FastHierarchy h = Scene.v().getOrMakeFastHierarchy();
/**
* Originally this implementation had checked if the catcher.getSootClass() is a phantom class. However this makes
* problems in case the soot option no_bodies_for_excluded==true because certain library classes will be marked as
* phantom classes even if they have a hierarchy. The workaround for this problem is to check for the suerClass. As every
* class except java.lang.Object have a superClass (even interfaces have!) only real phantom classes can be identified
* using this method.
*/
boolean catcherHasNoHierarchy = hasNoHierarchy(catcher);
if (exceptionsExcluded.size() > 0) {
if (INSTRUMENTING) {
Manager.v().catchableAsFromSearch++;
}
for (AnySubType exclusion : exceptionsExcluded) {
if (catcherHasNoHierarchy) {
if (exclusion.getBase().equals(catcher)) {
return false;
}
} else if (h.canStoreType(catcher, exclusion.getBase())) {
return false;
}
}
}
if (exceptionsIncluded.contains(catcher)) {
if (INSTRUMENTING) {
if (exceptionsExcluded.size() == 0) {
Manager.v().catchableAsFromMap++;
} else {
Manager.v().catchableAsFromSearch++;
}
}
return true;
} else {
if (INSTRUMENTING) {
if (exceptionsExcluded.size() == 0) {
Manager.v().catchableAsFromSearch++;
}
}
for (RefLikeType thrownType : exceptionsIncluded) {
if (thrownType instanceof RefType) {
if (thrownType == catcher) {
// assertion failure.
throw new IllegalStateException(
"ThrowableSet.catchableAs(RefType): exceptions.contains() failed to match contained RefType " + catcher);
} else if (!catcherHasNoHierarchy && h.canStoreType(thrownType, catcher)) {
return true;
}
} else {
RefType thrownBase = ((AnySubType) thrownType).getBase();
if (catcherHasNoHierarchy) {
if (thrownBase.equals(catcher) || thrownBase.getClassName().equals("java.lang.Throwable")) {
return true;
}
}
// At runtime, thrownType might be instantiated by any
// of thrownBase's subtypes, so:
else if (h.canStoreType(thrownBase, catcher) || h.canStoreType(catcher, thrownBase)) {
return true;
}
}
}
return false;
}
}
/**
* Partitions the exceptions in this <code>ThrowableSet</code> into those which would be caught by a handler with the
* passed <code>catch</code> parameter type and those which would not.
*
* @param catcher
* type of the handler parameter to be tested.
*
* @return a pair of <code>ThrowableSet</code>s, one containing the types in this <code>ThrowableSet</code> which would be
* be caught as <code>catcher</code> and the other containing the types in this <code>ThrowableSet</code> which
* would not be caught as <code>catcher</code>.
*/
public Pair whichCatchableAs(RefType catcher) {
if (INSTRUMENTING) {
Manager.v().removesOfAnySubType++;
}
FastHierarchy h = Scene.v().getOrMakeFastHierarchy();
Set<RefLikeType> caughtIncluded = null;
Set<AnySubType> caughtExcluded = null;
Set<RefLikeType> uncaughtIncluded = null;
Set<AnySubType> uncaughtExcluded = null;
if (INSTRUMENTING) {
Manager.v().removesFromSearch++;
}
boolean catcherHasNoHierarchy = hasNoHierarchy(catcher);
for (AnySubType exclusion : exceptionsExcluded) {
RefType exclusionBase = exclusion.getBase();
// Is the current type explicitly excluded?
if (catcherHasNoHierarchy && exclusionBase.equals(catcher)) {
return new Pair(ThrowableSet.Manager.v().EMPTY, this);
}
if (h.canStoreType(catcher, exclusionBase)) {
// Because the add() operations ban additions to sets
// with exclusions, we can be sure no types in this are
// caught by catcher.
return new Pair(ThrowableSet.Manager.v().EMPTY, this);
} else if (h.canStoreType(exclusionBase, catcher)) {
// exclusion wouldn't be in exceptionsExcluded if one
// of its supertypes were not in exceptionsIncluded,
// so we know the next loop will add either that supertype
// or catcher to caughtIncluded. Thus:
caughtExcluded = addExceptionToSet(exclusion, caughtExcluded);
} else {
uncaughtExcluded = addExceptionToSet(exclusion, uncaughtExcluded);
}
}
for (RefLikeType inclusion : exceptionsIncluded) {
if (inclusion instanceof RefType) {
// If the current type is has no hierarchy, we catch it if and
// only if it is in the inclusion list and ignore any hierarchy.
if (catcherHasNoHierarchy) {
if (inclusion.equals(catcher)) {
caughtIncluded = addExceptionToSet(inclusion, caughtIncluded);
} else {
uncaughtIncluded = addExceptionToSet(inclusion, uncaughtIncluded);
}
} else if (h.canStoreType(inclusion, catcher)) {
caughtIncluded = addExceptionToSet(inclusion, caughtIncluded);
} else {
uncaughtIncluded = addExceptionToSet(inclusion, uncaughtIncluded);
}
} else {
RefType base = ((AnySubType) inclusion).getBase();
// If the current type is has no hierarchy, we catch it if and
// only if it is in the inclusion list and ignore any hierarchy.
if (catcherHasNoHierarchy) {
if (base.equals(catcher)) {
caughtIncluded = addExceptionToSet(inclusion, caughtIncluded);
} else {
if (base.getClassName().equals("java.lang.Throwable")) {
caughtIncluded = addExceptionToSet(catcher, caughtIncluded);
}
uncaughtIncluded = addExceptionToSet(inclusion, uncaughtIncluded);
}
} else if (h.canStoreType(base, catcher)) {
// All subtypes of base will be caught. Any exclusions
// will already have been copied to caughtExcluded by
// the preceding loop.
caughtIncluded = addExceptionToSet(inclusion, caughtIncluded);
} else if (h.canStoreType(catcher, base)) {
// Some subtypes of base will be caught, and
// we know that not all of those catchable subtypes
// are among exceptionsExcluded, since in that case we
// would already have returned from within the
// preceding loop. So, remove AnySubType(catcher)
// from the uncaught types.
uncaughtIncluded = addExceptionToSet(inclusion, uncaughtIncluded);
uncaughtExcluded = addExceptionToSet(AnySubType.v(catcher), uncaughtExcluded);
caughtIncluded = addExceptionToSet(AnySubType.v(catcher), caughtIncluded);
// Any already excluded subtypes of inclusion
// which are subtypes of catcher will have been
// added to caughtExcluded by the previous loop.
} else {
uncaughtIncluded = addExceptionToSet(inclusion, uncaughtIncluded);
}
}
}
ThrowableSet caughtSet = Manager.v().registerSetIfNew(caughtIncluded, caughtExcluded);
ThrowableSet uncaughtSet = Manager.v().registerSetIfNew(uncaughtIncluded, uncaughtExcluded);
return new Pair(caughtSet, uncaughtSet);
}
/**
* Utility method for building sets of exceptional types for a {@link Pair}.
*
* @param e
* The exceptional type to add to the set.
*
* @param set
* The <code>Set</code> to which to add the types, or <code>null</code> if no <code>Set</code> has yet been
* allocated.
*
* @return A <code>Set</code> containing the elements in <code>set</code> plus <code>e</code>.
*/
private <T> Set<T> addExceptionToSet(T e, Set<T> set) {
if (set == null) {
set = new HashSet<>();
}
set.add(e);
return set;
}
/**
* Returns a string representation of this <code>ThrowableSet</code>.
*/
@Override
public String toString() {
StringBuffer buffer = new StringBuffer(this.toBriefString());
buffer.append(":\n ");
for (RefLikeType ei : exceptionsIncluded) {
buffer.append('+');
buffer.append(ei == null ? "null" : ei.toString());
// buffer.append(i.next().toString());
}
for (RefLikeType ee : exceptionsExcluded) {
buffer.append('-');
buffer.append(ee.toString());
}
return buffer.toString();
}
/**
* Returns a cryptic identifier for this <code>ThrowableSet</code>, used to identify a set when it appears in a collection.
*/
public String toBriefString() {
return super.toString();
}
/**
* <p>
* Produce an abbreviated representation of this <code>ThrowableSet</code>, suitable for human consumption. The
* abbreviations include:
* </p>
*
* <ul>
*
* <li>The strings “<code>java.lang.</code>” is stripped from the beginning of exception names.</li>
*
* <li>The string “<code>Exception</code>” is stripped from the ends of exception names.</li>
*
* <li>Instances of <code>AnySubType</code> are indicated by surrounding the base type name with parentheses, rather than
* with the string “ <code>Any_subtype_of_</code>”</li>
*
* <li>If this <code>ThrowableSet</code> includes all the elements of {@link ThrowableSet.Manager#VM_ERRORS VM_ERRORS},
* they are abbreviated as “<code>vmErrors</code>” rather than listed individually.</li>
*
* @return An abbreviated representation of the contents of this set.
*/
public String toAbbreviatedString() {
return toAbbreviatedString(exceptionsIncluded, '+') + toAbbreviatedString(exceptionsExcluded, '-');
}
/**
* <p>
* Utility method which prints the abbreviations of the elements in a passed {@link Set} of exception types.
* </p>
*
* @param s
* The exceptions to print.
*
* @param connector
* The character to insert between exceptions.
*
* @return An abbreviated representation of the exceptions.
*/
private String toAbbreviatedString(Set<? extends RefLikeType> s, char connector) {
final String JAVA_LANG = "java.lang.";
final String EXCEPTION = "Exception";
Collection<RefLikeType> vmErrorThrowables = ThrowableSet.Manager.v().VM_ERRORS.exceptionsIncluded;
boolean containsAllVmErrors = s.containsAll(vmErrorThrowables);
StringBuffer buf = new StringBuffer();
if (containsAllVmErrors) {
buf.append(connector);
buf.append("vmErrors");
}
for (Iterator<? extends RefLikeType> it = sortedThrowableIterator(s); it.hasNext();) {
RefLikeType reflikeType = it.next();
RefType baseType = null;
if (reflikeType instanceof RefType) {
baseType = (RefType) reflikeType;
if (containsAllVmErrors && vmErrorThrowables.contains(baseType)) {
continue; // Already accounted for vmErrors.
} else {
buf.append(connector);
}
} else if (reflikeType instanceof AnySubType) {
buf.append(connector);
buf.append('(');
baseType = ((AnySubType) reflikeType).getBase();
} else {
throw new RuntimeException("Unsupported type " + reflikeType.getClass().getName());
}
String typeName = baseType.toString();
int start = 0;
int end = typeName.length();
if (typeName.startsWith(JAVA_LANG)) {
start += JAVA_LANG.length();
}
if (typeName.endsWith(EXCEPTION)) {
end -= EXCEPTION.length();
}
buf.append(typeName, start, end);
if (reflikeType instanceof AnySubType) {
buf.append(')');
}
}
return buf.toString();
}
/**
* A package-private method to provide unit tests with access to the {@link RefLikeType} objects which represent the
* <code>Throwable</code> types included in this set.
*
* @return an unmodifiable collection view of the <code>Throwable</code> types in this set.
*/
Collection<RefLikeType> typesIncluded() {
return exceptionsIncluded;
}
/**
* A package-private method to provide unit tests with access to the {@link RefLikeType} objects which represent the
* <code>Throwable</code> types excluded from this set.
*
* @return an unmodifiable collection view of the <code>Throwable</code> types excluded from this set.
*/
Collection<AnySubType> typesExcluded() {
return exceptionsExcluded;
}
/**
* A package-private method to provide unit tests with access to ThrowableSet's internals.
*/
Map<Object, ThrowableSet> getMemoizedAdds() {
if (memoizedAdds == null) {
return Collections.emptyMap();
} else {
return Collections.unmodifiableMap(memoizedAdds);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + exceptionsIncluded.hashCode();
result = (prime * result) + exceptionsExcluded.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ThrowableSet other = (ThrowableSet) obj;
return exceptionsIncluded.equals(other.exceptionsIncluded) && exceptionsExcluded.equals(other.exceptionsExcluded);
}
/**
* Singleton class for fields and initializers common to all ThrowableSet objects (i.e., these would be static fields and
* initializers, in the absence of soot's {@link G} and {@link Singletons} classes).
*/
public static class Manager {
/**
* <code>ThrowableSet</code> containing no exception classes.
*/
public final ThrowableSet EMPTY;
/**
* <code>ThrowableSet</code> containing all the exceptions that may be thrown in the course of resolving a reference to
* another class, including the process of loading, preparing, and verifying the referenced class.
*/
public final ThrowableSet RESOLVE_CLASS_ERRORS;
public final RefType RUNTIME_EXCEPTION;
public final RefType ARITHMETIC_EXCEPTION;
public final RefType ARRAY_STORE_EXCEPTION;
public final RefType CLASS_CAST_EXCEPTION;
public final RefType ILLEGAL_MONITOR_STATE_EXCEPTION;
public final RefType INDEX_OUT_OF_BOUNDS_EXCEPTION;
public final RefType ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION;
public final RefType NEGATIVE_ARRAY_SIZE_EXCEPTION;
public final RefType NULL_POINTER_EXCEPTION;
public final RefType INSTANTIATION_ERROR;
/**
* <code>ThrowableSet</code> representing all possible Throwables.
*/
final ThrowableSet ALL_THROWABLES;
/**
* <code>ThrowableSet</code> containing all the asynchronous and virtual machine errors, which may be thrown by any
* bytecode instruction at any point in the computation.
*/
final ThrowableSet VM_ERRORS;
/**
* <code>ThrowableSet</code> containing all the exceptions that may be thrown in the course of resolving a reference to a
* field.
*/
final ThrowableSet RESOLVE_FIELD_ERRORS;
/**
* <code>ThrowableSet</code> containing all the exceptions that may be thrown in the course of resolving a reference to a
* non-static method.
*/
final ThrowableSet RESOLVE_METHOD_ERRORS;
/**
* <code>ThrowableSet</code> containing all the exceptions which may be thrown by instructions that have the potential to
* cause a new class to be loaded and initialized (including UnsatisfiedLinkError, which is raised at runtime rather than
* linking type).
*/
final ThrowableSet INITIALIZATION_ERRORS;
/**
* This map stores all referenced <code>ThrowableSet</code>s.
*/
private final Map<ThrowableSet, ThrowableSet> registry
= CacheBuilder.newBuilder().weakValues().<ThrowableSet, ThrowableSet>build().asMap();
private final int removesFromMap = 0;
private final int removesFromMemo = 0;
// counts for instrumenting:
private int addsOfRefType = 0;
private int addsOfAnySubType = 0;
private int addsOfSet = 0;
private int addsInclusionFromMap = 0;
private int addsInclusionFromMemo = 0;
private int addsInclusionFromSearch = 0;
private int addsInclusionInterrupted = 0;
private int addsExclusionWithSearch = 0;
private int addsExclusionWithoutSearch = 0;
private int removesOfAnySubType = 0;
private int removesFromSearch = 0;
private int registrationCalls = 0;
private int catchableAsQueries = 0;
private int catchableAsFromMap = 0;
private int catchableAsFromSearch = 0;
/**
* Constructs a <code>ThrowableSet.Manager</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 Manager(Singletons.Global g) {
// First ensure the Exception classes are represented in Soot. Note that Soot supports multiple target platforms such
// as .net, which may use different exception classes. In that case, we just use null for the Java exception types.
final Scene scene = Scene.v();
// Runtime errors:
RUNTIME_EXCEPTION = scene.getRefTypeUnsafe("java.lang.RuntimeException");
ARITHMETIC_EXCEPTION = scene.getRefTypeUnsafe("java.lang.ArithmeticException");
ARRAY_STORE_EXCEPTION = scene.getRefTypeUnsafe("java.lang.ArrayStoreException");
CLASS_CAST_EXCEPTION = scene.getRefTypeUnsafe("java.lang.ClassCastException");
ILLEGAL_MONITOR_STATE_EXCEPTION = scene.getRefTypeUnsafe("java.lang.IllegalMonitorStateException");
INDEX_OUT_OF_BOUNDS_EXCEPTION = scene.getRefTypeUnsafe("java.lang.IndexOutOfBoundsException");
ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION = scene.getRefTypeUnsafe("java.lang.ArrayIndexOutOfBoundsException");
NEGATIVE_ARRAY_SIZE_EXCEPTION = scene.getRefTypeUnsafe("java.lang.NegativeArraySizeException");
NULL_POINTER_EXCEPTION = scene.getRefTypeUnsafe("java.lang.NullPointerException");
INSTANTIATION_ERROR = scene.getRefType("java.lang.InstantiationError");
EMPTY = registerSetIfNew(null, null);
Set<RefLikeType> allThrowablesSet = new HashSet<>();
allThrowablesSet.add(AnySubType.v(scene.getRefType("java.lang.Throwable")));
ALL_THROWABLES = registerSetIfNew(allThrowablesSet, null);
Set<RefLikeType> vmErrorSet = new HashSet<>();
vmErrorSet.add(scene.getRefTypeUnsafe("java.lang.InternalError"));
vmErrorSet.add(scene.getRefTypeUnsafe("java.lang.OutOfMemoryError"));
vmErrorSet.add(scene.getRefTypeUnsafe("java.lang.StackOverflowError"));
vmErrorSet.add(scene.getRefTypeUnsafe("java.lang.UnknownError"));
// The Java library's deprecated Thread.stop(Throwable) method
// would actually allow _any_ Throwable to be delivered
// asynchronously, not just java.lang.ThreadDeath.
vmErrorSet.add(scene.getRefTypeUnsafe("java.lang.ThreadDeath"));
VM_ERRORS = registerSetIfNew(vmErrorSet, null);
Set<RefLikeType> resolveClassErrorSet = new HashSet<>();
resolveClassErrorSet.add(scene.getRefType("java.lang.ClassCircularityError"));
// We add AnySubType(ClassFormatError) so that we can
// avoid adding its subclass,
// UnsupportedClassVersionError, explicitly. This is a
// hack to allow Soot to analyze older class libraries
// (UnsupportedClassVersionError was added in JDK 1.2).
if (!Options.v().j2me()) {
resolveClassErrorSet.add(AnySubType.v(Scene.v().getRefTypeUnsafe("java.lang.ClassFormatError")));
}
resolveClassErrorSet.add(scene.getRefTypeUnsafe("java.lang.IllegalAccessError"));
resolveClassErrorSet.add(scene.getRefTypeUnsafe("java.lang.IncompatibleClassChangeError"));
resolveClassErrorSet.add(scene.getRefTypeUnsafe("java.lang.LinkageError"));
resolveClassErrorSet.add(scene.getRefTypeUnsafe("java.lang.NoClassDefFoundError"));
resolveClassErrorSet.add(scene.getRefTypeUnsafe("java.lang.VerifyError"));
RESOLVE_CLASS_ERRORS = registerSetIfNew(resolveClassErrorSet, null);
Set<RefLikeType> resolveFieldErrorSet = new HashSet<>(resolveClassErrorSet);
resolveFieldErrorSet.add(scene.getRefTypeUnsafe("java.lang.NoSuchFieldError"));
RESOLVE_FIELD_ERRORS = registerSetIfNew(resolveFieldErrorSet, null);
Set<RefLikeType> resolveMethodErrorSet = new HashSet<>(resolveClassErrorSet);
resolveMethodErrorSet.add(scene.getRefTypeUnsafe("java.lang.AbstractMethodError"));
resolveMethodErrorSet.add(scene.getRefTypeUnsafe("java.lang.NoSuchMethodError"));
resolveMethodErrorSet.add(scene.getRefTypeUnsafe("java.lang.UnsatisfiedLinkError"));
RESOLVE_METHOD_ERRORS = registerSetIfNew(resolveMethodErrorSet, null);
// The static initializers of a newly loaded class might
// throw any Error (if they threw an Exception---even a
// RuntimeException---it would be replaced by an
// ExceptionInInitializerError):
//
Set<RefLikeType> initializationErrorSet = new HashSet<>();
initializationErrorSet.add(AnySubType.v(scene.getRefTypeUnsafe("java.lang.Error")));
INITIALIZATION_ERRORS = registerSetIfNew(initializationErrorSet, null);
}
/**
* Returns the single instance of <code>ThrowableSet.Manager</code>.
*
* @return Soot's <code>ThrowableSet.Manager</code>.
*/
public static Manager v() {
return G.v().soot_toolkits_exceptions_ThrowableSet_Manager();
}
/**
* <p>
* Returns a <code>ThrowableSet</code> representing the set of exceptions included in <code>include</code> minus the set
* of exceptions included in <code>exclude</code>. Creates a new <code>ThrowableSet</code> only if there was not already
* one whose contents correspond to <code>include</code> - <code>exclude</code>.
* </p>
*
* @param include
* A set of {@link RefLikeType} objects representing exception types included in the result; may be
* <code>null</code> if there are no included types.
*
* @param exclude
* A set of {@link AnySubType} objects representing exception types excluded from the result; may be
* <code>null</code> if there are no excluded types.
*
* @return a <code>ThrowableSet</code> representing the set of exceptions corresponding to <code>include</code> -
* <code>exclude</code>.
*/
protected ThrowableSet registerSetIfNew(Set<RefLikeType> include, Set<AnySubType> exclude) {
if (INSTRUMENTING) {
registrationCalls++;
}
ThrowableSet result = new ThrowableSet(include, exclude);
ThrowableSet ref = registry.get(result);
if (null != ref) {
return ref;
}
registry.put(result, result);
return result;
}
/**
* Report the counts collected by instrumentation (for now, at least, there is no need to provide access to the
* individual values as numbers).
*
* @return a string listing the counts.
*/
public String reportInstrumentation() {
int setCount = registry.size();
StringBuffer buf = new StringBuffer("registeredSets: ").append(setCount).append("\naddsOfRefType: ")
.append(addsOfRefType).append("\naddsOfAnySubType: ").append(addsOfAnySubType).append("\naddsOfSet: ")
.append(addsOfSet).append("\naddsInclusionFromMap: ").append(addsInclusionFromMap)
.append("\naddsInclusionFromMemo: ").append(addsInclusionFromMemo).append("\naddsInclusionFromSearch: ")
.append(addsInclusionFromSearch).append("\naddsInclusionInterrupted: ").append(addsInclusionInterrupted)
.append("\naddsExclusionWithoutSearch: ").append(addsExclusionWithoutSearch).append("\naddsExclusionWithSearch: ")
.append(addsExclusionWithSearch).append("\nremovesOfAnySubType: ").append(removesOfAnySubType)
.append("\nremovesFromMap: ").append(removesFromMap).append("\nremovesFromMemo: ").append(removesFromMemo)
.append("\nremovesFromSearch: ").append(removesFromSearch).append("\nregistrationCalls: ")
.append(registrationCalls).append("\ncatchableAsQueries: ").append(catchableAsQueries)
.append("\ncatchableAsFromMap: ").append(catchableAsFromMap).append("\ncatchableAsFromSearch: ")
.append(catchableAsFromSearch).append('\n');
return buf.toString();
}
/**
* A package-private method to provide unit tests with access to the collection of ThrowableSets.
*/
Set<ThrowableSet> getThrowableSets() {
return registry.keySet();
}
}
public static class AlreadyHasExclusionsException extends IllegalStateException {
private static final long serialVersionUID = 6785184160868722359L;
public AlreadyHasExclusionsException(String s) {
super(s);
}
}
/**
* The return type for {@link ThrowableSet#whichCatchableAs(RefType)}, consisting of a pair of ThrowableSets.
*/
public static class Pair {
private ThrowableSet caught;
private ThrowableSet uncaught;
/**
* Constructs a <code>ThrowableSet.Pair</code>.
*
* @param caught
* The set of exceptions to be returned when {@link #getCaught()} is called on the constructed
* <code>ThrowableSet.Pair</code>.
*
* @param uncaught
* The set of exceptions to be returned when {@link #getUncaught()} is called on the constructed
* <code>ThrowableSet.Pair</code>.
*/
protected Pair(ThrowableSet caught, ThrowableSet uncaught) {
this.caught = caught;
this.uncaught = uncaught;
}
/**
* @return the set of caught exceptions.
*/
public ThrowableSet getCaught() {
return caught;
}
/**
* @return the set of uncaught exceptions.
*/
public ThrowableSet getUncaught() {
return uncaught;
}
/**
* Indicates whether two {@link Object}s are <code>ThrowableSet.Pair</code>s representing the same set of caught and
* uncaught exception types.
*
* @param o
* the <code>Object</code> to compare to this <code>ThrowableSet.Pair</code>.
*
* @return <code>true</code> if <code>o</code> is a <code>ThrowableSet.Pair</code> representing the same set of caught
* and uncaught types as this <code>ThrowableSet.Pair</code>.
*/
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Pair)) {
return false;
}
Pair tsp = (Pair) o;
if (this.caught.equals(tsp.caught) && this.uncaught.equals(tsp.uncaught)) {
return true;
}
return false;
}
@Override
public int hashCode() {
int result = 31;
result = (37 * result) + caught.hashCode();
result = (37 * result) + uncaught.hashCode();
return result;
}
}
/**
* Comparator used to implement sortedThrowableIterator().
*
*/
private static class ThrowableComparator<T extends RefLikeType> implements java.util.Comparator<T> {
private static RefType baseType(RefLikeType o) {
if (o instanceof AnySubType) {
return ((AnySubType) o).getBase();
} else {
return (RefType) o; // ClassCastException if o is not a RefType.
}
}
@Override
public int compare(T o1, T o2) {
RefType t1 = baseType(o1);
RefType t2 = baseType(o2);
if (t1.equals(t2)) {
// There should never be both AnySubType(t) and
// t in a ThrowableSet, but if it happens, put
// AnySubType(t) first:
if (o1 instanceof AnySubType) {
if (o2 instanceof AnySubType) {
return 0;
} else {
return -1;
}
} else if (o2 instanceof AnySubType) {
return 1;
} else {
return 0;
}
} else {
return t1.toString().compareTo(t2.toString());
}
}
}
}
| 52,892
| 38.590569
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/exceptions/TrapTightener.java
|
package soot.toolkits.exceptions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of 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 java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.Scene;
import soot.Singletons;
import soot.Trap;
import soot.Unit;
import soot.jimple.toolkits.scalar.UnreachableCodeEliminator;
import soot.options.Options;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraph.ExceptionDest;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.util.Chain;
/**
* A {@link BodyTransformer} that shrinks the protected area covered by each {@link Trap} in the {@link Body} so that it
* begins at the first of the {@link Body}'s {@link Unit}s which might throw an exception caught by the {@link Trap} and ends
* just after the last {@link Unit} which might throw an exception caught by the {@link Trap}. In the case where none of the
* {@link Unit}s protected by a {@link Trap} can throw the exception it catches, the {@link Trap}'s protected area is left
* completely empty, which will likely cause the {@link UnreachableCodeEliminator} to remove the {@link Trap} completely.
*
* The {@link TrapTightener} is used to reduce the risk of unverifiable code which can result from the use of
* {@link ExceptionalUnitGraph}s from which unrealizable exceptional control flow edges have been removed.
*/
public final class TrapTightener extends TrapTransformer {
private static final Logger logger = LoggerFactory.getLogger(TrapTightener.class);
protected ThrowAnalysis throwAnalysis = null;
public TrapTightener(Singletons.Global g) {
}
public static TrapTightener v() {
return soot.G.v().soot_toolkits_exceptions_TrapTightener();
}
public TrapTightener(ThrowAnalysis ta) {
this.throwAnalysis = ta;
}
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
if (this.throwAnalysis == null) {
this.throwAnalysis = Scene.v().getDefaultThrowAnalysis();
}
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Tightening trap boundaries...");
}
Chain<Trap> trapChain = body.getTraps();
Chain<Unit> unitChain = body.getUnits();
if (trapChain.size() > 0) {
ExceptionalUnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, throwAnalysis);
Set<Unit> unitsWithMonitor = getUnitsWithMonitor(graph);
for (Iterator<Trap> trapIt = trapChain.iterator(); trapIt.hasNext();) {
Trap trap = trapIt.next();
boolean isCatchAll = trap.getException().getName().equals("java.lang.Throwable");
Unit firstTrappedUnit = trap.getBeginUnit();
Unit firstTrappedThrower = null;
Unit firstUntrappedUnit = trap.getEndUnit();
Unit lastTrappedUnit = unitChain.getPredOf(firstUntrappedUnit);
Unit lastTrappedThrower = null;
for (Unit u = firstTrappedUnit; u != null && u != firstUntrappedUnit; u = unitChain.getSuccOf(u)) {
if (mightThrowTo(graph, u, trap)) {
firstTrappedThrower = u;
break;
}
// If this is the catch-all block and the current unit has
// an,
// active monitor, we need to keep the block
if (isCatchAll && unitsWithMonitor.contains(u)) {
if (firstTrappedThrower == null) {
firstTrappedThrower = u;
}
break;
}
}
if (firstTrappedThrower != null) {
for (Unit u = lastTrappedUnit; u != null; u = unitChain.getPredOf(u)) {
if (mightThrowTo(graph, u, trap)) {
lastTrappedThrower = u;
break;
}
// If this is the catch-all block and the current unit
// has an, active monitor, we need to keep the block
if (isCatchAll && unitsWithMonitor.contains(u)) {
lastTrappedThrower = u;
break;
}
}
}
// If no statement inside the trap can throw an exception, we
// remove the complete trap.
if (firstTrappedThrower == null) {
trapIt.remove();
} else {
if (firstTrappedThrower != null && firstTrappedUnit != firstTrappedThrower) {
trap.setBeginUnit(firstTrappedThrower);
}
if (lastTrappedThrower == null) {
lastTrappedThrower = firstTrappedUnit;
}
if (lastTrappedUnit != lastTrappedThrower) {
trap.setEndUnit(unitChain.getSuccOf(lastTrappedThrower));
}
}
}
}
}
/**
* A utility routine which determines if a particular {@link Unit} might throw an exception to a particular {@link Trap},
* according to the information supplied by a particular control flow graph.
*
* @param g
* The control flow graph providing information about exceptions.
* @param u
* The unit being inquired about.
* @param t
* The trap being inquired about.
* @return <tt>true</tt> if <tt>u</tt> might throw an exception caught by <tt>t</tt>, according to <tt>g</tt.
*/
protected boolean mightThrowTo(ExceptionalUnitGraph g, Unit u, Trap t) {
for (ExceptionDest dest : g.getExceptionDests(u)) {
if (dest.getTrap() == t) {
return true;
}
}
return false;
}
}
| 6,225
| 36.506024
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/exceptions/TrapTransformer.java
|
package soot.toolkits.exceptions;
/*-
* #%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.BodyTransformer;
import soot.Unit;
import soot.Value;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.ExitMonitorStmt;
import soot.toolkits.graph.UnitGraph;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
/**
* Common abstract base class for all body transformers that change the trap list to, e.g., minimize the trap list
*
* @author Steven Arzt
*
*/
public abstract class TrapTransformer extends BodyTransformer {
public Set<Unit> getUnitsWithMonitor(UnitGraph ug) {
// Idea: Associate each unit with a set of monitors held at that
// statement
MultiMap<Unit, Value> unitMonitors = new HashMultiMap<>();
// Start at the heads of the unit graph
List<Unit> workList = new ArrayList<>();
Set<Unit> doneSet = new HashSet<>();
for (Unit head : ug.getHeads()) {
workList.add(head);
}
while (!workList.isEmpty()) {
Unit curUnit = workList.remove(0);
boolean hasChanged = false;
Value exitValue = null;
if (curUnit instanceof EnterMonitorStmt) {
// We enter a new monitor
EnterMonitorStmt ems = (EnterMonitorStmt) curUnit;
hasChanged = unitMonitors.put(curUnit, ems.getOp());
} else if (curUnit instanceof ExitMonitorStmt) {
// We leave a monitor
ExitMonitorStmt ems = (ExitMonitorStmt) curUnit;
exitValue = ems.getOp();
}
// Copy over the monitors from the predecessors
for (Unit pred : ug.getPredsOf(curUnit)) {
for (Value v : unitMonitors.get(pred)) {
if (v != exitValue) {
if (unitMonitors.put(curUnit, v)) {
hasChanged = true;
}
}
}
}
// Work on the successors
if (doneSet.add(curUnit) || hasChanged) {
workList.addAll(ug.getSuccsOf(curUnit));
}
}
return unitMonitors.keySet();
}
}
| 2,835
| 28.852632
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/exceptions/UnitThrowAnalysis.java
|
package soot.toolkits.exceptions;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import heros.solver.IDESolver;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.FastHierarchy;
import soot.G;
import soot.IntegerType;
import soot.Local;
import soot.LongType;
import soot.NullType;
import soot.PatchingChain;
import soot.RefLikeType;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Trap;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.Value;
import soot.ValueBox;
import soot.baf.AddInst;
import soot.baf.AndInst;
import soot.baf.ArrayLengthInst;
import soot.baf.ArrayReadInst;
import soot.baf.ArrayWriteInst;
import soot.baf.CmpInst;
import soot.baf.CmpgInst;
import soot.baf.CmplInst;
import soot.baf.DivInst;
import soot.baf.Dup1Inst;
import soot.baf.Dup1_x1Inst;
import soot.baf.Dup1_x2Inst;
import soot.baf.Dup2Inst;
import soot.baf.Dup2_x1Inst;
import soot.baf.Dup2_x2Inst;
import soot.baf.DynamicInvokeInst;
import soot.baf.EnterMonitorInst;
import soot.baf.ExitMonitorInst;
import soot.baf.FieldGetInst;
import soot.baf.FieldPutInst;
import soot.baf.GotoInst;
import soot.baf.IdentityInst;
import soot.baf.IfCmpEqInst;
import soot.baf.IfCmpGeInst;
import soot.baf.IfCmpGtInst;
import soot.baf.IfCmpLeInst;
import soot.baf.IfCmpLtInst;
import soot.baf.IfCmpNeInst;
import soot.baf.IfEqInst;
import soot.baf.IfGeInst;
import soot.baf.IfGtInst;
import soot.baf.IfLeInst;
import soot.baf.IfLtInst;
import soot.baf.IfNeInst;
import soot.baf.IfNonNullInst;
import soot.baf.IfNullInst;
import soot.baf.IncInst;
import soot.baf.InstSwitch;
import soot.baf.InstanceCastInst;
import soot.baf.InstanceOfInst;
import soot.baf.InterfaceInvokeInst;
import soot.baf.JSRInst;
import soot.baf.LoadInst;
import soot.baf.LookupSwitchInst;
import soot.baf.MulInst;
import soot.baf.NegInst;
import soot.baf.NewArrayInst;
import soot.baf.NewInst;
import soot.baf.NewMultiArrayInst;
import soot.baf.NopInst;
import soot.baf.OrInst;
import soot.baf.PopInst;
import soot.baf.PrimitiveCastInst;
import soot.baf.PushInst;
import soot.baf.RemInst;
import soot.baf.ReturnInst;
import soot.baf.ReturnVoidInst;
import soot.baf.ShlInst;
import soot.baf.ShrInst;
import soot.baf.SpecialInvokeInst;
import soot.baf.StaticGetInst;
import soot.baf.StaticInvokeInst;
import soot.baf.StaticPutInst;
import soot.baf.StoreInst;
import soot.baf.SubInst;
import soot.baf.SwapInst;
import soot.baf.TableSwitchInst;
import soot.baf.ThrowInst;
import soot.baf.UshrInst;
import soot.baf.VirtualInvokeInst;
import soot.baf.XorInst;
import soot.grimp.GrimpValueSwitch;
import soot.grimp.NewInvokeExpr;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.DynamicInvokeExpr;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MethodHandle;
import soot.jimple.MethodType;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.ParameterRef;
import soot.jimple.RemExpr;
import soot.jimple.RetStmt;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StmtSwitch;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThisRef;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.XorExpr;
import soot.shimple.PhiExpr;
import soot.shimple.ShimpleValueSwitch;
import soot.toolkits.exceptions.ThrowableSet.Pair;
/**
* A {@link ThrowAnalysis} which returns the set of runtime exceptions and errors that might be thrown by the bytecode
* instructions represented by a unit, as indicated by the Java Virtual Machine specification. I.e. this analysis is based
* entirely on the “opcode” of the unit, the types of its arguments, and the values of constant arguments.
*
* <p>
* The <code>mightThrow</code> methods could be declared static. They are left virtual to facilitate testing. For example, to
* verify that the expressions in a method call are actually being examined, a test case can override the
* mightThrow(SootMethod) with an implementation which returns the empty set instead of all possible exceptions.
*/
public class UnitThrowAnalysis extends AbstractThrowAnalysis {
protected final ThrowableSet.Manager mgr = ThrowableSet.Manager.v();
// Cache the response to mightThrowImplicitly():
private final ThrowableSet implicitThrowExceptions = ThrowableSet.Manager.v().VM_ERRORS
.add(ThrowableSet.Manager.v().NULL_POINTER_EXCEPTION).add(ThrowableSet.Manager.v().ILLEGAL_MONITOR_STATE_EXCEPTION);
/**
* Constructs a <code>UnitThrowAnalysis</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 UnitThrowAnalysis(Singletons.Global g) {
this(false);
}
/**
* A protected constructor for use by unit tests.
*/
protected UnitThrowAnalysis() {
this(false);
}
/**
* Returns the single instance of <code>UnitThrowAnalysis</code>.
*
* @return Soot's <code>UnitThrowAnalysis</code>.
*/
public static UnitThrowAnalysis v() {
return G.v().soot_toolkits_exceptions_UnitThrowAnalysis();
}
protected final boolean isInterproc;
protected UnitThrowAnalysis(boolean isInterproc) {
this.isInterproc = isInterproc;
}
public static UnitThrowAnalysis interproceduralAnalysis = null;
public static UnitThrowAnalysis interproc() {
if (interproceduralAnalysis == null) {
interproceduralAnalysis = new UnitThrowAnalysis(true);
}
return interproceduralAnalysis;
}
protected ThrowableSet defaultResult() {
return mgr.VM_ERRORS;
}
protected UnitSwitch unitSwitch(SootMethod sm) {
return new UnitSwitch(sm);
}
protected ValueSwitch valueSwitch() {
return new ValueSwitch();
}
@Override
public ThrowableSet mightThrow(Unit u) {
return mightThrow(u, null);
}
public ThrowableSet mightThrow(Unit u, SootMethod sm) {
UnitSwitch sw = unitSwitch(sm);
u.apply(sw);
return sw.getResult();
}
@Override
public ThrowableSet mightThrowImplicitly(ThrowInst t) {
return implicitThrowExceptions;
}
@Override
public ThrowableSet mightThrowImplicitly(ThrowStmt t) {
return implicitThrowExceptions;
}
protected ThrowableSet mightThrow(Value v) {
ValueSwitch sw = valueSwitch();
v.apply(sw);
return sw.getResult();
}
protected ThrowableSet mightThrow(SootMethodRef m) {
// The throw analysis is used in the front-ends. Conseqeuently, some
// methods might not yet be loaded. If this is the case, we make
// conservative assumptions.
SootMethod sm = m.tryResolve();
if (sm != null) {
return mightThrow(sm);
} else {
return mgr.ALL_THROWABLES;
}
}
/**
* Returns the set of types that might be thrown as a result of calling the specified method.
*
* @param sm
* method whose exceptions are to be returned.
*
* @return a representation of the set of {@link java.lang.Throwable Throwable} types that <code>m</code> might throw.
*/
protected ThrowableSet mightThrow(SootMethod sm) {
if (!isInterproc) {
return ThrowableSet.Manager.v().ALL_THROWABLES;
}
return methodToThrowSet.getUnchecked(sm);
}
protected final LoadingCache<SootMethod, ThrowableSet> methodToThrowSet
= IDESolver.DEFAULT_CACHE_BUILDER.build(new CacheLoader<SootMethod, ThrowableSet>() {
@Override
public ThrowableSet load(SootMethod sm) throws Exception {
return mightThrow(sm, new HashSet<SootMethod>());
}
});
/**
* Returns the set of types that might be thrown as a result of calling the specified method.
*
* @param sm
* method whose exceptions are to be returned.
* @param doneSet
* The set of methods that were already processed
*
* @return a representation of the set of {@link java.lang.Throwable Throwable} types that <code>m</code> might throw.
*/
private ThrowableSet mightThrow(SootMethod sm, Set<SootMethod> doneSet) {
// Do not run in loops
if (!doneSet.add(sm)) {
return ThrowableSet.Manager.v().EMPTY;
}
// If we don't have body, we silently ignore the method. This is
// unsound, but would otherwise always bloat our result set.
if (!sm.hasActiveBody()) {
return ThrowableSet.Manager.v().EMPTY;
}
// We need a mapping between unit and exception
final PatchingChain<Unit> units = sm.getActiveBody().getUnits();
Map<Unit, Collection<Trap>> unitToTraps
= sm.getActiveBody().getTraps().isEmpty() ? null : new HashMap<Unit, Collection<Trap>>();
for (Trap t : sm.getActiveBody().getTraps()) {
for (Iterator<Unit> unitIt = units.iterator(t.getBeginUnit(), units.getPredOf(t.getEndUnit())); unitIt.hasNext();) {
Unit unit = unitIt.next();
Collection<Trap> unitsForTrap = unitToTraps.get(unit);
if (unitsForTrap == null) {
unitsForTrap = new ArrayList<Trap>();
unitToTraps.put(unit, unitsForTrap);
}
unitsForTrap.add(t);
}
}
ThrowableSet methodSet = ThrowableSet.Manager.v().EMPTY;
if (sm.hasActiveBody()) {
Body methodBody = sm.getActiveBody();
for (Unit u : methodBody.getUnits()) {
if (u instanceof Stmt) {
Stmt stmt = (Stmt) u;
ThrowableSet curStmtSet;
if (stmt.containsInvokeExpr()) {
InvokeExpr inv = stmt.getInvokeExpr();
curStmtSet = mightThrow(inv.getMethod(), doneSet);
} else {
curStmtSet = mightThrow(u, sm);
}
// The exception might be caught along the way
if (unitToTraps != null) {
Collection<Trap> trapsForUnit = unitToTraps.get(stmt);
if (trapsForUnit != null) {
for (Trap t : trapsForUnit) {
Pair p = curStmtSet.whichCatchableAs(t.getException().getType());
curStmtSet = curStmtSet.remove(p.getCaught());
}
}
}
methodSet = methodSet.add(curStmtSet);
}
}
}
return methodSet;
}
private static final IntConstant INT_CONSTANT_ZERO = IntConstant.v(0);
private static final LongConstant LONG_CONSTANT_ZERO = LongConstant.v(0);
protected class UnitSwitch implements InstSwitch, StmtSwitch {
// Asynchronous errors are always possible:
protected ThrowableSet result = defaultResult();
protected SootMethod sm;
public UnitSwitch(SootMethod sm) {
this.sm = sm;
}
ThrowableSet getResult() {
return result;
}
@Override
public void caseReturnVoidInst(ReturnVoidInst i) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
}
@Override
public void caseReturnInst(ReturnInst i) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
}
@Override
public void caseNopInst(NopInst i) {
}
@Override
public void caseGotoInst(GotoInst i) {
}
@Override
public void caseJSRInst(JSRInst i) {
}
@Override
public void casePushInst(PushInst i) {
}
@Override
public void casePopInst(PopInst i) {
}
@Override
public void caseIdentityInst(IdentityInst i) {
}
@Override
public void caseStoreInst(StoreInst i) {
}
@Override
public void caseLoadInst(LoadInst i) {
}
@Override
public void caseArrayWriteInst(ArrayWriteInst i) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mgr.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
if (i.getOpType() instanceof RefType) {
result = result.add(mgr.ARRAY_STORE_EXCEPTION);
}
}
@Override
public void caseArrayReadInst(ArrayReadInst i) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mgr.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
}
@Override
public void caseIfNullInst(IfNullInst i) {
}
@Override
public void caseIfNonNullInst(IfNonNullInst i) {
}
@Override
public void caseIfEqInst(IfEqInst i) {
}
@Override
public void caseIfNeInst(IfNeInst i) {
}
@Override
public void caseIfGtInst(IfGtInst i) {
}
@Override
public void caseIfGeInst(IfGeInst i) {
}
@Override
public void caseIfLtInst(IfLtInst i) {
}
@Override
public void caseIfLeInst(IfLeInst i) {
}
@Override
public void caseIfCmpEqInst(IfCmpEqInst i) {
}
@Override
public void caseIfCmpNeInst(IfCmpNeInst i) {
}
@Override
public void caseIfCmpGtInst(IfCmpGtInst i) {
}
@Override
public void caseIfCmpGeInst(IfCmpGeInst i) {
}
@Override
public void caseIfCmpLtInst(IfCmpLtInst i) {
}
@Override
public void caseIfCmpLeInst(IfCmpLeInst i) {
}
@Override
public void caseStaticGetInst(StaticGetInst i) {
result = result.add(mgr.INITIALIZATION_ERRORS);
}
@Override
public void caseStaticPutInst(StaticPutInst i) {
result = result.add(mgr.INITIALIZATION_ERRORS);
}
@Override
public void caseFieldGetInst(FieldGetInst i) {
result = result.add(mgr.RESOLVE_FIELD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
@Override
public void caseFieldPutInst(FieldPutInst i) {
result = result.add(mgr.RESOLVE_FIELD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
@Override
public void caseInstanceCastInst(InstanceCastInst i) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
result = result.add(mgr.CLASS_CAST_EXCEPTION);
}
@Override
public void caseInstanceOfInst(InstanceOfInst i) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
}
@Override
public void casePrimitiveCastInst(PrimitiveCastInst i) {
}
@Override
public void caseDynamicInvokeInst(DynamicInvokeInst i) {
result = result.add(mgr.RESOLVE_METHOD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mgr.INITIALIZATION_ERRORS);
// might throw anything
result = result.add(ThrowableSet.Manager.v().ALL_THROWABLES);
}
@Override
public void caseStaticInvokeInst(StaticInvokeInst i) {
result = result.add(mgr.INITIALIZATION_ERRORS);
result = result.add(mightThrow(i.getMethodRef()));
}
@Override
public void caseVirtualInvokeInst(VirtualInvokeInst i) {
result = result.add(mgr.RESOLVE_METHOD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(i.getMethodRef()));
}
@Override
public void caseInterfaceInvokeInst(InterfaceInvokeInst i) {
result = result.add(mgr.RESOLVE_METHOD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(i.getMethodRef()));
}
@Override
public void caseSpecialInvokeInst(SpecialInvokeInst i) {
result = result.add(mgr.RESOLVE_METHOD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(i.getMethodRef()));
}
@Override
public void caseThrowInst(ThrowInst i) {
result = mightThrowImplicitly(i);
result = result.add(mightThrowExplicitly(i));
}
@Override
public void caseAddInst(AddInst i) {
}
@Override
public void caseAndInst(AndInst i) {
}
@Override
public void caseOrInst(OrInst i) {
}
@Override
public void caseXorInst(XorInst i) {
}
@Override
public void caseArrayLengthInst(ArrayLengthInst i) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
@Override
public void caseCmpInst(CmpInst i) {
}
@Override
public void caseCmpgInst(CmpgInst i) {
}
@Override
public void caseCmplInst(CmplInst i) {
}
@Override
public void caseDivInst(DivInst i) {
if (i.getOpType() instanceof IntegerType || i.getOpType() == LongType.v()) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
}
}
@Override
public void caseIncInst(IncInst i) {
}
@Override
public void caseMulInst(MulInst i) {
}
@Override
public void caseRemInst(RemInst i) {
if (i.getOpType() instanceof IntegerType || i.getOpType() == LongType.v()) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
}
}
@Override
public void caseSubInst(SubInst i) {
}
@Override
public void caseShlInst(ShlInst i) {
}
@Override
public void caseShrInst(ShrInst i) {
}
@Override
public void caseUshrInst(UshrInst i) {
}
@Override
public void caseNewInst(NewInst i) {
result = result.add(mgr.INITIALIZATION_ERRORS);
}
@Override
public void caseNegInst(NegInst i) {
}
@Override
public void caseSwapInst(SwapInst i) {
}
@Override
public void caseDup1Inst(Dup1Inst i) {
}
@Override
public void caseDup2Inst(Dup2Inst i) {
}
@Override
public void caseDup1_x1Inst(Dup1_x1Inst i) {
}
@Override
public void caseDup1_x2Inst(Dup1_x2Inst i) {
}
@Override
public void caseDup2_x1Inst(Dup2_x1Inst i) {
}
@Override
public void caseDup2_x2Inst(Dup2_x2Inst i) {
}
@Override
public void caseNewArrayInst(NewArrayInst i) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS); // Could be omitted for primitive arrays.
result = result.add(mgr.NEGATIVE_ARRAY_SIZE_EXCEPTION);
}
@Override
public void caseNewMultiArrayInst(NewMultiArrayInst i) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
result = result.add(mgr.NEGATIVE_ARRAY_SIZE_EXCEPTION);
}
@Override
public void caseLookupSwitchInst(LookupSwitchInst i) {
}
@Override
public void caseTableSwitchInst(TableSwitchInst i) {
}
@Override
public void caseEnterMonitorInst(EnterMonitorInst i) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
@Override
public void caseExitMonitorInst(ExitMonitorInst i) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
}
@Override
public void caseAssignStmt(AssignStmt s) {
Value lhs = s.getLeftOp();
if (lhs instanceof ArrayRef && (lhs.getType() instanceof UnknownType || lhs.getType() instanceof RefType)) {
// This corresponds to an aastore byte code.
result = result.add(mgr.ARRAY_STORE_EXCEPTION);
}
result = result.add(mightThrow(s.getLeftOp()));
result = result.add(mightThrow(s.getRightOp()));
}
@Override
public void caseBreakpointStmt(BreakpointStmt s) {
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt s) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(s.getOp()));
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt s) {
result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(s.getOp()));
}
@Override
public void caseGotoStmt(GotoStmt s) {
}
@Override
public void caseIdentityStmt(IdentityStmt s) {
}
// Perhaps IdentityStmt shouldn't even return VM_ERRORS,
// since it corresponds to no bytecode instructions whatsoever.
@Override
public void caseIfStmt(IfStmt s) {
result = result.add(mightThrow(s.getCondition()));
}
@Override
public void caseInvokeStmt(InvokeStmt s) {
result = result.add(mightThrow(s.getInvokeExpr()));
}
@Override
public void caseLookupSwitchStmt(LookupSwitchStmt s) {
result = result.add(mightThrow(s.getKey()));
}
@Override
public void caseNopStmt(NopStmt s) {
}
@Override
public void caseRetStmt(RetStmt s) {
// Soot should never produce any RetStmt, since
// it implements jsr with gotos.
}
@Override
public void caseReturnStmt(ReturnStmt s) {
// result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
// result = result.add(mightThrow(s.getOp()));
}
@Override
public void caseReturnVoidStmt(ReturnVoidStmt s) {
// result = result.add(mgr.ILLEGAL_MONITOR_STATE_EXCEPTION);
}
@Override
public void caseTableSwitchStmt(TableSwitchStmt s) {
result = result.add(mightThrow(s.getKey()));
}
@Override
public void caseThrowStmt(ThrowStmt s) {
result = mightThrowImplicitly(s);
result = result.add(mightThrowExplicitly(s, sm));
}
@Override
public void defaultCase(Object obj) {
}
}
protected class ValueSwitch implements GrimpValueSwitch, ShimpleValueSwitch {
// Asynchronous errors are always possible:
protected ThrowableSet result = defaultResult();
ThrowableSet getResult() {
return result;
}
// Declared by ConstantSwitch interface:
@Override
public void caseDoubleConstant(DoubleConstant c) {
}
@Override
public void caseFloatConstant(FloatConstant c) {
}
@Override
public void caseIntConstant(IntConstant c) {
}
@Override
public void caseLongConstant(LongConstant c) {
}
@Override
public void caseNullConstant(NullConstant c) {
}
@Override
public void caseStringConstant(StringConstant c) {
}
@Override
public void caseClassConstant(ClassConstant c) {
}
@Override
public void caseMethodHandle(MethodHandle handle) {
}
@Override
public void caseMethodType(MethodType type) {
}
// Declared by ExprSwitch interface:
@Override
public void caseAddExpr(AddExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseAndExpr(AndExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseCmpExpr(CmpExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseCmpgExpr(CmpgExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseCmplExpr(CmplExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseDivExpr(DivExpr expr) {
caseBinopDivExpr(expr);
}
@Override
public void caseEqExpr(EqExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseNeExpr(NeExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseGeExpr(GeExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseGtExpr(GtExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseLeExpr(LeExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseLtExpr(LtExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseMulExpr(MulExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseOrExpr(OrExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseRemExpr(RemExpr expr) {
caseBinopDivExpr(expr);
}
@Override
public void caseShlExpr(ShlExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseShrExpr(ShrExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseUshrExpr(UshrExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseSubExpr(SubExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseXorExpr(XorExpr expr) {
caseBinopExpr(expr);
}
@Override
public void caseInterfaceInvokeExpr(InterfaceInvokeExpr expr) {
caseInstanceInvokeExpr(expr);
}
@Override
public void caseSpecialInvokeExpr(SpecialInvokeExpr expr) {
caseInstanceInvokeExpr(expr);
}
@Override
public void caseStaticInvokeExpr(StaticInvokeExpr expr) {
result = result.add(mgr.INITIALIZATION_ERRORS);
for (int i = 0; i < expr.getArgCount(); i++) {
result = result.add(mightThrow(expr.getArg(i)));
}
result = result.add(mightThrow(expr.getMethodRef()));
}
@Override
public void caseVirtualInvokeExpr(VirtualInvokeExpr expr) {
caseInstanceInvokeExpr(expr);
}
// INSERTED for invokedynamic UnitThrowAnalysis.java
@Override
public void caseDynamicInvokeExpr(DynamicInvokeExpr expr) {
// caseInstanceInvokeExpr(expr);
}
@Override
public void caseCastExpr(CastExpr expr) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
Type fromType = expr.getOp().getType();
Type toType = expr.getCastType();
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()));
}
@Override
public void caseInstanceOfExpr(InstanceOfExpr expr) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
result = result.add(mightThrow(expr.getOp()));
}
@Override
public void caseNewArrayExpr(NewArrayExpr expr) {
if (expr.getBaseType() instanceof RefLikeType) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
}
Value count = expr.getSize();
if ((!(count instanceof IntConstant)) || (((IntConstant) count).isLessThan(INT_CONSTANT_ZERO))) {
result = result.add(mgr.NEGATIVE_ARRAY_SIZE_EXCEPTION);
}
result = result.add(mightThrow(count));
}
@Override
public void caseNewMultiArrayExpr(NewMultiArrayExpr expr) {
result = result.add(mgr.RESOLVE_CLASS_ERRORS);
for (int i = 0; i < expr.getSizeCount(); i++) {
Value count = expr.getSize(i);
if ((!(count instanceof IntConstant)) || (((IntConstant) count).isLessThan(INT_CONSTANT_ZERO))) {
result = result.add(mgr.NEGATIVE_ARRAY_SIZE_EXCEPTION);
}
result = result.add(mightThrow(count));
}
}
@SuppressWarnings("rawtypes")
@Override
public void caseNewExpr(NewExpr expr) {
result = result.add(mgr.INITIALIZATION_ERRORS);
for (ValueBox box : expr.getUseBoxes()) {
result = result.add(mightThrow(box.getValue()));
}
}
@Override
public void caseLengthExpr(LengthExpr expr) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(expr.getOp()));
}
@Override
public void caseNegExpr(NegExpr expr) {
result = result.add(mightThrow(expr.getOp()));
}
// Declared by RefSwitch interface:
@Override
public void caseArrayRef(ArrayRef ref) {
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mgr.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
result = result.add(mightThrow(ref.getBase()));
result = result.add(mightThrow(ref.getIndex()));
}
@Override
public void caseStaticFieldRef(StaticFieldRef ref) {
result = result.add(mgr.INITIALIZATION_ERRORS);
}
@Override
public void caseInstanceFieldRef(InstanceFieldRef ref) {
result = result.add(mgr.RESOLVE_FIELD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
result = result.add(mightThrow(ref.getBase()));
}
@Override
public void caseParameterRef(ParameterRef v) {
}
@Override
public void caseCaughtExceptionRef(CaughtExceptionRef v) {
}
@Override
public void caseThisRef(ThisRef v) {
}
@Override
public void caseLocal(Local l) {
}
@Override
public void caseNewInvokeExpr(NewInvokeExpr e) {
caseStaticInvokeExpr(e);
}
@SuppressWarnings("rawtypes")
@Override
public void casePhiExpr(PhiExpr e) {
for (ValueBox box : e.getUseBoxes()) {
result = result.add(mightThrow(box.getValue()));
}
}
@Override
public void defaultCase(Object obj) {
}
// The remaining cases are not declared by GrimpValueSwitch,
// but are used to factor out code common to several cases.
private void caseBinopExpr(BinopExpr expr) {
result = result.add(mightThrow(expr.getOp1()));
result = result.add(mightThrow(expr.getOp2()));
}
private void caseBinopDivExpr(BinopExpr expr) {
// Factors out code common to caseDivExpr and caseRemExpr.
// The checks against constant divisors would perhaps be
// better performed in a later pass, post-constant-propagation.
Value divisor = expr.getOp2();
Type divisorType = divisor.getType();
if (divisorType instanceof UnknownType) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
} else if ((divisorType instanceof IntegerType)
&& ((!(divisor instanceof IntConstant)) || (((IntConstant) divisor).equals(INT_CONSTANT_ZERO)))) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
} else if ((divisorType == LongType.v())
&& ((!(divisor instanceof LongConstant)) || (((LongConstant) divisor).equals(LONG_CONSTANT_ZERO)))) {
result = result.add(mgr.ARITHMETIC_EXCEPTION);
}
caseBinopExpr(expr);
}
private void caseInstanceInvokeExpr(InstanceInvokeExpr expr) {
result = result.add(mgr.RESOLVE_METHOD_ERRORS);
result = result.add(mgr.NULL_POINTER_EXCEPTION);
for (int i = 0; i < expr.getArgCount(); i++) {
result = result.add(mightThrow(expr.getArg(i)));
}
result = result.add(mightThrow(expr.getBase()));
result = result.add(mightThrow(expr.getMethodRef()));
}
}
}
| 32,321
| 26.275949
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/ArrayRefBlockGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Set;
import soot.Body;
import soot.Trap;
import soot.Unit;
import soot.baf.Inst;
import soot.jimple.Stmt;
/**
* A CFG where the nodes are {@link Block} instances, and where {@link Unit}s which include array references start new
* blocks. Exceptional control flow is ignored, so the graph will be a forest where each exception handler constitutes a
* disjoint subgraph.
*/
public class ArrayRefBlockGraph extends BlockGraph {
/**
* <p>
* Constructs an {@link ArrayRefBlockGraph} from the given {@link Body}.
* </p>
*
* <p>
* Note that this constructor builds a {@link BriefUnitGraph} internally when splitting <tt>body</tt>'s {@link Unit}s into
* {@link Block}s. Callers who need both a {@link BriefUnitGraph} and an {@link ArrayRefBlockGraph} should use the
* constructor taking the <tt>BriefUnitGraph</tt> as a parameter, as a minor optimization.
* </p>
*
* @param body
* the Body instance from which the graph is built.
*/
public ArrayRefBlockGraph(Body body) {
this(new BriefUnitGraph(body));
}
/**
* Constructs an <tt>ArrayRefBlockGraph</tt> corresponding to the <tt>Unit</tt>-level control flow represented by the
* passed {@link BriefUnitGraph}.
*
* @param unitGraph
* The <tt>BriefUnitGraph</tt> for which to build an <tt>ArrayRefBlockGraph</tt>.
*/
public ArrayRefBlockGraph(BriefUnitGraph unitGraph) {
super(unitGraph);
soot.util.PhaseDumper.v().dumpGraph(this, mBody);
}
/**
* <p>
* Utility method for computing the basic block leaders for a {@link Body}, given its {@link UnitGraph} (i.e., the
* instructions which begin new basic blocks).
* </p>
*
* <p>
* This implementation chooses as block leaders all the <tt>Unit</tt>s that {@link BlockGraph.computerLeaders()}, and adds:
*
* <ul>
*
* <li>All <tt>Unit</tt>s which contain an array reference, as defined by {@link Stmt.containsArrayRef()} and
* {@link Inst.containsArrayRef()}.
*
* <li>The first <tt>Unit</tt> not covered by each {@link Trap} (i.e., the <tt>Unit</tt> returned by
* {@link Trap.getLastUnit()}.</li>
*
* </ul>
* </p>
*
* @param unitGraph
* is the <tt>Unit</tt>-level CFG which is to be split into basic blocks.
*
* @return the {@link Set} of {@link Unit}s in <tt>unitGraph</tt> which are block leaders.
*/
@Override
protected Set<Unit> computeLeaders(UnitGraph unitGraph) {
Body body = unitGraph.getBody();
if (body != mBody) {
throw new RuntimeException(
"ArrayRefBlockGraph.computeLeaders() called with a UnitGraph that doesn't match its mBody.");
}
Set<Unit> leaders = super.computeLeaders(unitGraph);
for (Unit unit : body.getUnits()) {
if (((unit instanceof Stmt) && ((Stmt) unit).containsArrayRef())
|| ((unit instanceof Inst) && ((Inst) unit).containsArrayRef())) {
leaders.add(unit);
}
}
return leaders;
}
}
| 3,836
| 32.955752
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/Block.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 - 2000 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.SootMethod;
import soot.Unit;
import soot.baf.BafBody;
import soot.util.Chain;
/**
* Represents BasicBlocks that partition a method body. It is implemented as view on an underlying Body instance; as a
* consequence, changes made on a Block will be automatically reflected in its enclosing method body. Blocks also exist in
* the context of a BlockGraph, a CFG for a method where Block instances are the nodes of the graph. Hence, a Block can be
* queried for its successors and predecessors Blocks, as found in this graph.
*/
public class Block implements Iterable<Unit> {
private static final Logger logger = LoggerFactory.getLogger(Block.class);
private Unit mHead, mTail;
private final Body mBody;
private List<Block> mPreds, mSuccessors;
private int mBlockLength = 0, mIndexInMethod = 0;
/**
* Constructs a Block in the context of a BlockGraph, and enclosing Body instances.
*
* @param aHead
* The first unit ir this Block.
* @param aTail
* The last unit in this Block.
* @param aBody
* The Block's enclosing Body instance.
* @param aIndexInMethod
* The index of this Block in the list of Blocks that partition it's enclosing Body instance.
* @param aBlockLength
* The number of units that makeup this block.
* @param aBlockGraph
* The Graph of Blocks in which this block lives.
*
* @see Body
* @see Chain
* @see BlockGraph
* @see Unit
* @see SootMethod
*/
public Block(Unit aHead, Unit aTail, Body aBody, int aIndexInMethod, int aBlockLength, BlockGraph aBlockGraph) {
mHead = aHead;
mTail = aTail;
mBody = aBody;
mIndexInMethod = aIndexInMethod;
mBlockLength = aBlockLength;
}
/**
* Returns the Block's enclosing Body instance.
*
* @return The block's chain of instructions.
* @see soot.jimple.JimpleBody
* @see BafBody
* @see Body
*/
public Body getBody() {
return mBody;
}
/**
* Returns an iterator for the linear chain of Units that make up the block.
*
* @return An iterator that iterates over the block's units.
* @see Chain
* @see Unit
*/
@Override
public Iterator<Unit> iterator() {
return mBody == null ? null : mBody.getUnits().iterator(mHead, mTail);
}
/**
* Inserts a Unit before some other Unit in this block.
*
*
* @param toInsert
* A Unit to be inserted.
* @param point
* A Unit in the Block's body before which we wish to insert the Unit.
* @see Unit
* @see Chain
*/
public void insertBefore(Unit toInsert, Unit point) {
if (point == mHead) {
mHead = toInsert;
}
mBody.getUnits().insertBefore(toInsert, point);
}
/**
* Inserts a Unit after some other Unit in the Block.
*
* @param toInsert
* A Unit to be inserted.
* @param point
* A Unit in the Block after which we wish to insert the Unit.
* @see Unit
*/
public void insertAfter(Unit toInsert, Unit point) {
if (point == mTail) {
mTail = toInsert;
}
mBody.getUnits().insertAfter(toInsert, point);
}
/**
* Removes a Unit occurring before some other Unit in the Block.
*
* @param item
* A Unit to be remove from the Block's Unit Chain.
* @return True if the item could be found and removed.
*
*/
public boolean remove(Unit item) {
Chain<Unit> methodBody = mBody.getUnits();
if (item == mHead) {
mHead = methodBody.getSuccOf(item);
} else if (item == mTail) {
mTail = methodBody.getPredOf(item);
}
return methodBody.remove(item);
}
/**
* Returns the Unit occurring immediately after some other Unit in the block.
*
* @param aItem
* The Unit from which we wish to get it's successor.
* @return The successor or null if <code>aItem</code> is the tail for this Block.
*
*/
public Unit getSuccOf(Unit aItem) {
return aItem == mTail ? null : mBody.getUnits().getSuccOf(aItem);
}
/**
* Returns the Unit occurring immediately before some other Unit in the block.
*
* @param aItem
* The Unit from which we wish to get it's predecessor.
* @return The predecessor or null if <code>aItem</code> is the head for this Block.
*/
public Unit getPredOf(Unit aItem) {
return aItem == mHead ? null : mBody.getUnits().getPredOf(aItem);
}
/**
* Set the index of this Block in the list of Blocks that partition its enclosing Body instance.
*
* @param aIndexInMethod
* The index of this Block in the list of Blocks that partition it's enclosing Body instance.
**/
public void setIndexInMethod(int aIndexInMethod) {
mIndexInMethod = aIndexInMethod;
}
/**
* Returns the index of this Block in the list of Blocks that partition it's enclosing Body instance.
*
* @return The index of the block in it's enclosing Body instance.
*/
public int getIndexInMethod() {
return mIndexInMethod;
}
/**
* Returns the first unit in this block.
*
* @return The first unit in this block.
*/
public Unit getHead() {
return mHead;
}
/**
* Returns the last unit in this block.
*
* @return The last unit in this block.
*/
public Unit getTail() {
return mTail;
}
/**
* Sets the list of Blocks that are predecessors of this block in it's enclosing BlockGraph instance.
*
* @param preds
* The a List of Blocks that precede this block.
*
* @see BlockGraph
*/
public void setPreds(List<Block> preds) {
mPreds = preds;
}
/**
* Returns the List of Block that are predecessors to this block,
*
* @return A list of predecessor blocks.
* @see BlockGraph
*/
public List<Block> getPreds() {
return mPreds;
}
/**
* Sets the list of Blocks that are successors of this block in it's enclosing BlockGraph instance.
*
* @param succs
* The a List of Blocks that succede this block.
*
* @see BlockGraph
*/
public void setSuccs(List<Block> succs) {
mSuccessors = succs;
}
/**
* Returns the List of Blocks that are successors to this block,
*
* @return A list of successorblocks.
* @see BlockGraph
*/
public List<Block> getSuccs() {
return mSuccessors;
}
public String toShortString() {
return "Block #" + mIndexInMethod;
}
@Override
public String toString() {
StringBuilder strBuf = new StringBuilder();
strBuf.append("Block ").append(mIndexInMethod).append(':').append(System.lineSeparator());
// print out predecessors and successors.
strBuf.append("[preds: ");
if (mPreds != null) {
for (Block b : mPreds) {
strBuf.append(b.getIndexInMethod()).append(' ');
}
}
strBuf.append("] [succs: ");
if (mSuccessors != null) {
for (Block b : mSuccessors) {
strBuf.append(b.getIndexInMethod()).append(' ');
}
}
strBuf.append(']').append(System.lineSeparator());
// print out Units in the Block
final Unit tail = mTail;
Iterator<Unit> basicBlockIt = mBody.getUnits().iterator(mHead, tail);
if (basicBlockIt.hasNext()) {
Unit someUnit = basicBlockIt.next();
strBuf.append(someUnit.toString()).append(';').append(System.lineSeparator());
while (basicBlockIt.hasNext()) {
someUnit = basicBlockIt.next();
if (someUnit == tail) {
break;
}
strBuf.append(someUnit.toString()).append(';').append(System.lineSeparator());
}
if (tail == null) {
strBuf.append("error: null tail found; block length: ").append(mBlockLength).append(System.lineSeparator());
} else if (tail != mHead) {
strBuf.append(tail.toString()).append(';').append(System.lineSeparator());
}
}
// Or, it could be an empty block (e.g. Start or Stop Block) --NU
// else
// logger.debug("No basic blocks found; must be interface class.");
return strBuf.toString();
}
}
| 9,001
| 27.852564
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/BlockGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Trap;
import soot.Unit;
import soot.jimple.NopStmt;
import soot.util.Chain;
/**
* <p>
* Represents the control flow graph of a {@link Body} at the basic block level. Each node of the graph is a {@link Block}
* while the edges represent the flow of control from one basic block to the next.
* </p>
*
* <p>
* This is an abstract base class for different variants of {@link BlockGraph}, where the variants differ in how they analyze
* the control flow between individual units (represented by passing different variants of {@link UnitGraph} to the
* <code>BlockGraph</code> constructor) and in how they identify block leaders (represented by overriding
* <code>BlockGraph</code>'s definition of {@link computeLeaders()}.
*/
public abstract class BlockGraph implements DirectedBodyGraph<Block> {
protected Body mBody;
protected Chain<Unit> mUnits;
protected List<Block> mBlocks;
protected List<Block> mHeads;
protected List<Block> mTails;
/**
* Create a <code>BlockGraph</code> representing at the basic block level the control flow specified, at the
* <code>Unit</code> level, by a given {@link UnitGraph}.
*
* @param unitGraph
* A representation of the control flow at the level of individual {@link Unit}s.
*/
protected BlockGraph(UnitGraph unitGraph) {
this.mBody = unitGraph.getBody();
this.mUnits = mBody.getUnits();
buildBlocks(computeLeaders(unitGraph), unitGraph);
}
/**
* <p>
* Utility method for computing the basic block leaders for a {@link Body}, given its {@link UnitGraph} (i.e., the
* instructions which begin new basic blocks).
* </p>
*
* <p>
* This implementation designates as basic block leaders :
*
* <ul>
*
* <li>Any <code>Unit</code> which has zero predecessors (e.g. the <code>Unit</code> following a return or unconditional
* branch) or more than one predecessor (e.g. a merge point).</li>
*
* <li><code>Unit</code>s which are the target of any branch (even if they have no other predecessors and the branch has no
* other successors, which is possible for the targets of unconditional branches or degenerate conditional branches which
* both branch and fall through to the same <code>Unit</code>).</li>
*
* <li>All successors of any <code>Unit</code> which has more than one successor (this includes the successors of
* <code>Unit</code>s which may throw an exception that gets caught within the <code>Body</code>, as well the successors of
* conditional branches).</li>
*
* <li>The first <code>Unit</code> in any <code>Trap</code> handler. (Strictly speaking, if <code>unitGraph</code> were a
* <code>ExceptionalUnitGraph</code> that included only a single unexceptional predecessor for some handler—because
* no trapped unit could possibly throw the exception that the handler catches, while the code preceding the handler fell
* through to the handler's code—then you could merge the handler into the predecessor's basic block; but such
* situations occur only in carefully contrived bytecode.)
*
* </ul>
* </p>
*
* @param unitGraph
* is the <code>Unit</code>-level CFG which is to be split into basic blocks.
*
* @return the {@link Set} of {@link Unit}s in <code>unitGraph</code> which are block leaders.
*/
protected Set<Unit> computeLeaders(UnitGraph unitGraph) {
Body body = unitGraph.getBody();
if (body != mBody) {
throw new RuntimeException("BlockGraph.computeLeaders() called with a UnitGraph that doesn't match its mBody.");
}
Set<Unit> leaders = new HashSet<Unit>();
// Trap handlers start new basic blocks, no matter how many predecessors they have.
for (Trap trap : body.getTraps()) {
leaders.add(trap.getHandlerUnit());
}
for (Unit u : body.getUnits()) {
// If predCount == 1 but the predecessor is a branch, u will get added
// by that branch's successor test.
if (unitGraph.getPredsOf(u).size() != 1) {
leaders.add(u);
}
List<Unit> successors = unitGraph.getSuccsOf(u);
if ((successors.size() > 1) || u.branches()) {
for (Unit next : successors) {
leaders.add(next);
}
}
}
return leaders;
}
/**
* <p>
* A utility method that does most of the work of constructing basic blocks, once the set of block leaders has been
* determined, and which designates the heads and tails of the graph.
* </p>
*
* <p>
* <code>BlockGraph</code> provides an implementation of <code>buildBlocks()</code> which splits the {@link Unit}s in
* <code>unitGraph</code> so that each <code>Unit</code> in the passed set of block leaders is the first unit in a block.
* It defines as heads the blocks which begin with <code>Unit</code>s which are heads in <code>unitGraph</code>, and
* defines as tails the blocks which end with <code>Unit</code>s which are tails in <code>unitGraph</code>. Subclasses
* might override this behavior.
*
* @param leaders
* Contains <code>Unit</code>s which are to be block leaders.
*
* @param unitGraph
* Provides information about the predecessors and successors of each <code>Unit</code> in the <code>Body</code>,
* for determining the predecessors and successors of each created {@link Block}.
*
* @return a {@link Map} from {@link Unit}s which begin or end a block to the block which contains them.
*/
protected Map<Unit, Block> buildBlocks(Set<Unit> leaders, UnitGraph unitGraph) {
final ArrayList<Block> blockList = new ArrayList<Block>(leaders.size());
final ArrayList<Block> headList = new ArrayList<Block>();
final ArrayList<Block> tailList = new ArrayList<Block>();
// Maps head and tail units to their blocks, for building predecessor and successor lists.
final Map<Unit, Block> unitToBlock = new HashMap<Unit, Block>();
{
Unit blockHead = null;
int blockLength = 0;
Iterator<Unit> unitIt = mUnits.iterator();
if (unitIt.hasNext()) {
blockHead = unitIt.next();
if (!leaders.contains(blockHead)) {
throw new RuntimeException("BlockGraph: first unit not a leader!");
}
blockLength++;
}
Unit blockTail = blockHead;
int indexInMethod = 0;
while (unitIt.hasNext()) {
Unit u = unitIt.next();
if (leaders.contains(u)) {
addBlock(blockHead, blockTail, indexInMethod, blockLength, blockList, unitToBlock);
indexInMethod++;
blockHead = u;
blockLength = 0;
}
blockTail = u;
blockLength++;
}
if (blockLength > 0) {
// Add final block.
addBlock(blockHead, blockTail, indexInMethod, blockLength, blockList, unitToBlock);
}
}
// The underlying UnitGraph defines heads and tails.
for (Unit headUnit : unitGraph.getHeads()) {
Block headBlock = unitToBlock.get(headUnit);
if (headBlock.getHead() == headUnit) {
headList.add(headBlock);
} else {
throw new RuntimeException("BlockGraph(): head Unit is not the first unit in the corresponding Block!");
}
}
for (Unit tailUnit : unitGraph.getTails()) {
Block tailBlock = unitToBlock.get(tailUnit);
if (tailBlock.getTail() == tailUnit) {
tailList.add(tailBlock);
} else {
throw new RuntimeException("BlockGraph(): tail Unit is not the last unit in the corresponding Block!");
}
}
for (Iterator<Block> blockIt = blockList.iterator(); blockIt.hasNext();) {
Block block = blockIt.next();
List<Unit> predUnits = unitGraph.getPredsOf(block.getHead());
if (predUnits.isEmpty()) {
block.setPreds(Collections.<Block>emptyList());
// If the UnreachableCodeEliminator is not eliminating unreachable handlers, then they will have no
// predecessors, yet not be heads.
/*
* if (! headList.contains(block)) { throw new RuntimeException("Block with no predecessors is not a head!" );
*
* // Note that a block can be a head even if it has // predecessors: a handler that might catch an exception //
* thrown by the first Unit in the method. }
*/
} else {
List<Block> predBlocks = new ArrayList<Block>(predUnits.size());
for (Unit predUnit : predUnits) {
assert (predUnit != null);
Block predBlock = unitToBlock.get(predUnit);
if (predBlock == null) {
throw new RuntimeException("BlockGraph(): block head predecessor (" + predUnit + ") mapped to null block!");
}
predBlocks.add(predBlock);
}
block.setPreds(Collections.unmodifiableList(predBlocks));
if (block.getHead() == mUnits.getFirst()) {
headList.add(block); // Make the first block a head even if the Body is one huge loop.
}
}
List<Unit> succUnits = unitGraph.getSuccsOf(block.getTail());
if (succUnits.isEmpty()) {
block.setSuccs(Collections.<Block>emptyList());
if (!tailList.contains(block)) {
// if this block is totally empty and unreachable, we remove it
if (block.getPreds().isEmpty() && block.getHead() == block.getTail() && block.getHead() instanceof NopStmt) {
blockIt.remove();
} else {
throw new RuntimeException("Block with no successors is not a tail!: " + block.toString());
// Note that a block can be a tail even if it has
// successors: a return that throws a caught exception.
}
}
} else {
List<Block> succBlocks = new ArrayList<Block>(succUnits.size());
for (Unit succUnit : succUnits) {
assert (succUnit != null);
Block succBlock = unitToBlock.get(succUnit);
if (succBlock == null) {
throw new RuntimeException("BlockGraph(): block tail successor (" + succUnit + ") mapped to null block!");
}
succBlocks.add(succBlock);
}
block.setSuccs(Collections.unmodifiableList(succBlocks));
}
}
blockList.trimToSize(); // potentially a long-lived object
this.mBlocks = Collections.unmodifiableList(blockList);
headList.trimToSize(); // potentially a long-lived object
this.mHeads = headList.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(headList);
tailList.trimToSize(); // potentially a long-lived object
this.mTails = tailList.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(tailList);
return unitToBlock;
}
/**
* A utility method which creates a new block and adds information about it to data structures used to build the graph.
*
* @param head
* The first unit in the block.
* @param tail
* The last unit in the block.
* @param index
* The index of this block this {@link Body}.
* @param length
* The number of units in this block.
* @param blockList
* The list of blocks for this method. <code>addBlock()</code> will add the newly created block to this list.
* @param unitToBlock
* A map from units to blocks. <code>addBlock()</code> will add mappings from <code>head</code> and
* <code>tail</code> to the new block
*/
private void addBlock(Unit head, Unit tail, int index, int length, List<Block> blockList, Map<Unit, Block> unitToBlock) {
Block block = new Block(head, tail, mBody, index, length, this);
blockList.add(block);
unitToBlock.put(tail, block);
unitToBlock.put(head, block);
}
/**
* Returns the {@link Body} this {@link BlockGraph} is derived from.
*
* @return The {@link Body} this {@link BlockGraph} is derived from.
*/
@Override
public Body getBody() {
return mBody;
}
/**
* Returns a list of the Blocks composing this graph.
*
* @return A list of the blocks composing this graph in the same order as they partition underlying Body instance's unit
* chain.
* @see Block
*/
public List<Block> getBlocks() {
return mBlocks;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
for (Block someBlock : mBlocks) {
buf.append(someBlock.toString()).append('\n');
}
return buf.toString();
}
/* DirectedGraph implementation */
@Override
public List<Block> getHeads() {
return mHeads;
}
@Override
public List<Block> getTails() {
return mTails;
}
@Override
public List<Block> getPredsOf(Block b) {
return b.getPreds();
}
@Override
public List<Block> getSuccsOf(Block b) {
return b.getSuccs();
}
@Override
public int size() {
return mBlocks.size();
}
@Override
public Iterator<Block> iterator() {
return mBlocks.iterator();
}
}
| 13,980
| 36.888889
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/BlockGraphConverter.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.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.Collections;
import java.util.Iterator;
import java.util.List;
import soot.Body;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
/**
* This utility class can convert any BlockGraph to a single-headed and single-tailed graph by inserting appropriate Start or
* Stop nodes. It can also fully reverse the graph, something that might be useful e.g. when computing control dependences
* with a dominators algorithm.
*
* <p>
* Note: This class may be retracted in a future release when a suitable replacement becomes available.
* </p>
*
* @author Navindra Umanee
**/
public class BlockGraphConverter {
/**
* Transforms a multi-headed and/or multi-tailed BlockGraph to a single-headed singled-tailed BlockGraph by inserting a
* dummy start and stop nodes.
**/
public static void addStartStopNodesTo(BlockGraph graph) {
ADDSTART: {
List<Block> heads = graph.getHeads();
int headCount = heads.size();
if (headCount == 0) {
break ADDSTART;
}
if ((headCount == 1) && (heads.get(0) instanceof DummyBlock)) {
break ADDSTART;
}
List<Block> blocks = graph.getBlocks();
DummyBlock head = new DummyBlock(graph.getBody(), 0);
head.makeHeadBlock(heads);
graph.mHeads = Collections.<Block>singletonList(head);
for (Block block : blocks) {
block.setIndexInMethod(block.getIndexInMethod() + 1);
}
List<Block> newBlocks = new ArrayList<Block>();
newBlocks.add(head);
newBlocks.addAll(blocks);
graph.mBlocks = newBlocks;
}
ADDSTOP: {
List<Block> tails = graph.getTails();
int tailCount = tails.size();
if (tailCount == 0) {
break ADDSTOP;
}
if ((tailCount == 1) && (tails.get(0) instanceof DummyBlock)) {
break ADDSTOP;
}
List<Block> blocks = graph.getBlocks();
DummyBlock tail = new DummyBlock(graph.getBody(), blocks.size());
tail.makeTailBlock(tails);
graph.mTails = Collections.<Block>singletonList(tail);
blocks.add(tail);
}
}
/**
* Reverses a BlockGraph by making the heads tails, the tails heads and reversing the edges. It does not change the
* ordering of Units in individual blocks, nor does it change the Block labels. This utility could be useful when
* calculating control dependences with a dominators algorithm.
**/
public static void reverse(BlockGraph graph) {
// Issue: Do we change indexInMethod? No...
// Issue: Do we reverse the Units list in the Block?
// Issue: Do we need to implement an equals method in Block?
// When are two Blocks from two different BlockGraphs
// equal?
for (Block block : graph.getBlocks()) {
List<Block> succs = block.getSuccs();
List<Block> preds = block.getPreds();
block.setSuccs(preds);
block.setPreds(succs);
}
List<Block> heads = graph.getHeads();
List<Block> tails = graph.getTails();
graph.mHeads = new ArrayList<Block>(tails);
graph.mTails = new ArrayList<Block>(heads);
}
public static void main(String[] args) {
// assumes 2 args: Class + Method
Scene.v().loadClassAndSupport(args[0]);
SootClass sc = Scene.v().getSootClass(args[0]);
SootMethod sm = sc.getMethod(args[1]);
Body b = sm.retrieveActiveBody();
CompleteBlockGraph cfg = new CompleteBlockGraph(b);
System.out.println(cfg);
BlockGraphConverter.addStartStopNodesTo(cfg);
System.out.println(cfg);
BlockGraphConverter.reverse(cfg);
System.out.println(cfg);
}
}
/**
* Represents Start or Stop node in the graph.
*
* @author Navindra Umanee
**/
class DummyBlock extends Block {
DummyBlock(Body body, int indexInMethod) {
super(null, null, body, indexInMethod, 0, null);
}
void makeHeadBlock(List<Block> oldHeads) {
setPreds(new ArrayList<Block>());
setSuccs(new ArrayList<Block>(oldHeads));
for (Block oldHead : oldHeads) {
List<Block> newPreds = new ArrayList<Block>();
newPreds.add(this);
List<Block> oldPreds = oldHead.getPreds();
if (oldPreds != null) {
newPreds.addAll(oldPreds);
}
oldHead.setPreds(newPreds);
}
}
void makeTailBlock(List<Block> oldTails) {
setSuccs(new ArrayList<Block>());
setPreds(new ArrayList<Block>(oldTails));
Iterator<Block> tailsIt = oldTails.iterator();
while (tailsIt.hasNext()) {
Block oldTail = tailsIt.next();
List<Block> newSuccs = new ArrayList<Block>();
newSuccs.add(this);
List<Block> oldSuccs = oldTail.getSuccs();
if (oldSuccs != null) {
newSuccs.addAll(oldSuccs);
}
oldTail.setSuccs(newSuccs);
}
}
@Override
public Iterator<Unit> iterator() {
return Collections.emptyIterator();
}
}
| 5,713
| 28.760417
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/BriefBlockGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Body;
import soot.Unit;
/**
* <p>
* Represents a CFG for a {@link Body} where the nodes are {@link Block}s and edges are derived from control flow. Control
* flow associated with exceptions is ignored, so the graph will be a forest where each exception handler constitutes a
* disjoint subgraph.
* </p>
*/
public class BriefBlockGraph extends BlockGraph {
/**
* Constructs a {@link BriefBlockGraph} from a given {@link Body}.
*
* <p>
* Note that this constructor builds a {@link BriefUnitGraph} internally when splitting <tt>body</tt>'s {@link Unit}s into
* {@link Block}s. Callers who already have a {@link BriefUnitGraph} to hand can use the constructor taking a
* <tt>CompleteUnitGraph</tt> as a parameter, as a minor optimization.
*
* @param body
* the {@link Body} for which to build a graph.
*/
public BriefBlockGraph(Body body) {
this(new BriefUnitGraph(body));
}
/**
* Constructs a {@link BriefBlockGraph} representing the <tt>Unit</tt>-level control flow represented by the passed
* {@link BriefUnitGraph}.
*
* @param unitGraph
* the {@link Body} for which to build a graph.
*/
public BriefBlockGraph(BriefUnitGraph unitGraph) {
super(unitGraph);
soot.util.PhaseDumper.v().dumpGraph(this, mBody);
}
}
| 2,171
| 32.9375
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/BriefUnitGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.List;
import soot.Body;
import soot.Timers;
import soot.Unit;
import soot.options.Options;
/**
* Represents a CFG where the nodes are Unit instances, and where no edges are included to account for control flow
* associated with exceptions.
*
* @see Unit
* @see UnitGraph
*/
public class BriefUnitGraph extends UnitGraph {
/**
* Constructs a BriefUnitGraph given a Body instance.
*
* @param body
* The underlying body we want to make a graph for.
*/
public BriefUnitGraph(Body body) {
super(body);
int size = unitChain.size();
if (Options.v().time()) {
Timers.v().graphTimer.start();
}
unitToSuccs = new HashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f);
unitToPreds = new HashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f);
buildUnexceptionalEdges(unitToSuccs, unitToPreds);
buildHeadsAndTails();
if (Options.v().time()) {
Timers.v().graphTimer.end();
}
soot.util.PhaseDumper.v().dumpGraph(this, body);
}
}
| 1,891
| 26.42029
| 115
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/ClassicCompleteBlockGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of 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.List;
import soot.Body;
import soot.Trap;
import soot.Unit;
/**
* <p>
* Represents a CFG where the nodes are {@link Block}s and the edges are derived from control flow. Control flow associated
* with exceptions is taken into account: when a <tt>Unit</tt> may throw an exception that is caught by a {@link Trap} within
* the <tt>Body</tt>, the excepting <tt>Unit</tt> starts a new basic block.
* </p>
*
* <p>
* <tt>ClassicCompleteBlockGraph</tt> approximates the results that would have been produced by Soot's
* {@link CompleteBlockGraph} in releases up to Soot 2.1.0. It is included solely for testing purposes, and should not be
* used in actual analyses. The approximation works not by duplicating the old {@link CompleteBlockGraph}'s logic, but by
* using {@link ClassicCompleteUnitGraph} as the basis for dividing {@link Unit}s into {@link Block}s.
* </p>
*/
public class ClassicCompleteBlockGraph extends BlockGraph {
/**
* <p>
* Constructs a <tt>ClassicCompleteBlockGraph</tt> for the blocks found by partitioning the the units of the provided
* {@link Body} instance into basic blocks.
* </p>
*
* <p>
* Note that this constructor builds a {@link ClassicCompleteUnitGraph} internally when splitting <tt>body</tt>'s
* {@link Unit}s into {@link Block}s. Callers who already have a {@link ClassicCompleteUnitGraph} to hand can use the
* constructor taking a <tt>ClassicCompleteUnitGraph</tt> as a parameter, as a minor optimization.
*
* @param body
* The underlying body we want to make a graph for.
*/
public ClassicCompleteBlockGraph(Body body) {
super(new ClassicCompleteUnitGraph(body));
}
/**
* Constructs a graph for the blocks found by partitioning the the units in a {@link ClassicCompleteUnitGraph}.
*
* @param unitGraph
* A {@link ClassicCompleteUnitGraph} built from <tt>body</tt>. The <tt>CompleteBlockGraph</tt> constructor uses
* the passed <tt>graph</tt> to split the body into blocks.
*/
public ClassicCompleteBlockGraph(ClassicCompleteUnitGraph unitGraph) {
super(unitGraph);
// Adjust the heads and tails to match the old CompleteBlockGraph.
Unit entryPoint = getBody().getUnits().getFirst();
List<Block> newHeads = new ArrayList<Block>(1);
for (Block b : getBlocks()) {
if (b.getHead() == entryPoint) {
newHeads.add(b);
break;
}
}
mHeads = Collections.unmodifiableList(newHeads);
mTails = Collections.emptyList();
soot.util.PhaseDumper.v().dumpGraph(this, mBody);
}
}
| 3,476
| 37.633333
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/ClassicCompleteUnitGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import soot.Body;
import soot.Trap;
import soot.Unit;
import soot.toolkits.exceptions.ThrowAnalysis;
/**
* <p>
* Represents a CFG for a Body instance where the nodes are {@link Unit} instances, and where edges are a conservative
* indication of unexceptional and exceptional control flow.
* </p>
*
* <p>
* <tt>ClassicCompleteUnitGraph</tt> attempts to duplicate the results that would have been produced by Soot's
* <code>CompleteUnitGraph</code> in releases up to Soot 2.1.0 (the one known discrepancy is that the 2.1.0
* <code>CompleteUnitGraph</code> would include two edges joining one node to another {@link Unit}s if the first node both
* branched to and fell through to the second). It is included solely for testing purposes, and should not be used in actual
* analyses.
* </p>
*
* <p>
* There are two distinctions between the graphs produced by the <tt>ClassicCompleteUnitGraph</tt> and
* <tt>ExceptionalUnitGraph</tt>:
* <ol>
*
* <li><tt>ExceptionalUnitGraph</tt> only creates edges to a <tt>Trap</tt> handler for trapped <tt>Unit</tt>s that have the
* potential to throw the particular exception type caught by the handler, according to the {@link ThrowAnalysis} used to
* estimate which exceptions each {@link Unit} may throw. <tt>ClassicCompleteUnitGraph</tt> creates edges for all trapped
* <tt>Unit</tt>s, regardless of the types of exceptions they may throw.</li>
*
* <li>When <tt>ExceptionalUnitGraph</tt> creates edges for a trapped <tt>Unit</tt> that may throw a caught exception, it
* adds edges from each predecessor of the excepting <tt>Unit</tt> to the handler. If the excepting <tt>Unit</tt> itself has
* no potential side effects, <tt>ExceptionalUnitGraph</tt> may omit an edge from it to the handler, depending on the
* parameters passed to the <tt>ExceptionalUnitGraph</tt> constructor. <tt>ClassicCompleteUnitGraph</tt>, on the other hand,
* always adds an edge from the excepting <tt>Unit</tt> itself to the handler, and adds edges from the predecessor only of
* the first <tt>Unit</tt> covered by a <tt>Trap</tt> (in this one aspect <tt>ClassicCompleteUnitGraph</tt> is less
* conservative than <tt>ExceptionalUnitGraph</tt>, since it ignores the possibility of a branch into the middle of a
* protected area).</li>
*
* </ol>
* </p>
*/
public class ClassicCompleteUnitGraph extends TrapUnitGraph {
/**
* Constructs the graph from a given Body instance.
*
* @param body
* the Body instance from which the graph is built.
*/
public ClassicCompleteUnitGraph(Body body) {
// The TrapUnitGraph constructor will use our buildExceptionalEdges:
super(body);
}
/**
* Method to compute the edges corresponding to exceptional control flow.
*
* @param unitToSuccs
* A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is * an ``out parameter'';
* <tt>buildExceptionalEdges</tt> will add a mapping for every <tt>Unit</tt> within the scope of one or more
* {@link Trap}s to a <tt>List</tt> of the handler units of those <tt>Trap</tt>s.
*
* @param unitToPreds
* A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is an ``out parameter'';
* <tt>buildExceptionalEdges</tt> will add a mapping for every {@link Trap} handler to all the <tt>Unit</tt>s
* within the scope of that <tt>Trap</tt>.
*/
@Override
protected void buildExceptionalEdges(Map<Unit, List<Unit>> unitToSuccs, Map<Unit, List<Unit>> unitToPreds) {
// First, add the same edges as TrapUnitGraph.
super.buildExceptionalEdges(unitToSuccs, unitToPreds);
// Then add edges from the predecessors of the first
// trapped Unit for each Trap.
for (Trap trap : body.getTraps()) {
Unit catcher = trap.getHandlerUnit();
// Make a copy of firstTrapped's predecessors to iterate over,
// just in case we're about to add new predecessors to this
// very list, though that can only happen if the handler traps
// itself. And to really allow for that
// possibility, we should iterate here until we reach a fixed
// point; but the old UnitGraph that we are attempting to
// duplicate did not do that, so we won't either.
for (Unit pred : new ArrayList<Unit>(getPredsOf(trap.getBeginUnit()))) {
addEdge(unitToSuccs, unitToPreds, pred, catcher);
}
}
}
}
| 5,324
| 44.905172
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/CompleteBlockGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Body;
import soot.Trap;
/**
* <p>
* Represents a CFG for a {@link Body} instance where the nodes are {@link Block} instances, and where control flow
* associated with exceptions is taken into account. When dividing the {@link Body} into basic blocks,
* <code>CompleteBlockGraph</code> assumes that every {@link Unit} covered by a {@link Trap} has the potential to throw an
* exception caught by the {@link Trap}. This generally has the effect of separating every covered {@link Unit} into a
* separate block.
*
* <p>
* This implementation of <code>CompleteBlockGraph</code> is included for backwards compatibility, but the graphs it produces
* are not necessarily identical to the graphs produced by the implementation of <code>CompleteBlockGraph</code> See the
* documentation for {@link CompleteUnitGraph} for details of the incompatibilities.
* </p>
*/
public class CompleteBlockGraph extends ExceptionalBlockGraph {
public CompleteBlockGraph(Body b) {
super(new CompleteUnitGraph(b));
}
}
| 1,877
| 38.957447
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/CompleteUnitGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Body;
import soot.toolkits.exceptions.PedanticThrowAnalysis;
/**
* <p>
* Represents a CFG for a {@link Body} instance where the nodes are {@link soot.Unit} instances, and where control flow
* associated with exceptions is taken into account. In a <code>CompleteUnitGraph</code>, every <code>Unit</code> covered by
* a {@link soot.Trap} is considered to have the potential to throw an exception caught by the <code>Trap</code>, so there
* are edges to the <code>Trap</code>'s handler from every trapped <code>Unit</code> , as well as from all the predecessors
* of the trapped <code>Unit</code>s.
*
* <p>
* This implementation of <code>CompleteUnitGraph</code> is included for backwards compatibility (new code should use
* {@link ExceptionalUnitGraph}), but the graphs it produces are not necessarily identical to the graphs produced by the
* implementation of <code>CompleteUnitGraph</code> provided by versions of Soot up to and including release 2.1.0. The known
* differences include:
*
* <ul>
*
* <li>If a <code>Body</code> includes <code>Unit</code>s which branch into the middle of the region protected by a
* <code>Trap</code> this implementation of <code>CompleteUnitGraph</code> will include edges from those branching
* <code>Unit</code>s to the <code>Trap</code>'s handler (since the branches are predecessors of an instruction which may
* throw an exception caught by the <code>Trap</code>). The 2.1.0 implementation of <code>CompleteUnitGraph</code> mistakenly
* omitted these edges.</li>
*
* <li>If the initial <code>Unit</code> in the <code>Body</code> might throw an exception caught by a <code>Trap</code>
* within the body, this implementation will include the initial handler <code>Unit</code> in the list returned by
* <code>getHeads()</code> (since the handler unit might be the first Unit in the method to execute to completion). The 2.1.0
* implementation of <code>CompleteUnitGraph</code> mistakenly omitted the handler from the set of heads.</li>
*
* </ul>
* </p>
*/
public class CompleteUnitGraph extends ExceptionalUnitGraph {
public CompleteUnitGraph(Body b) {
super(b, PedanticThrowAnalysis.v(), false);
}
}
| 3,038
| 47.238095
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/CytronDominanceFrontier.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* Class to compute the DominanceFrontier using Cytron's celebrated efficient algorithm.
*
* @author Navindra Umanee
* @see <a href="http://citeseer.nj.nec.com/cytron91efficiently.html">Efficiently Computing Static Single Assignment Form and
* the Control Dependence Graph</a>
*/
public class CytronDominanceFrontier<N> implements DominanceFrontier<N> {
protected DominatorTree<N> dt;
protected Map<DominatorNode<N>, List<DominatorNode<N>>> nodeToFrontier;
public CytronDominanceFrontier(DominatorTree<N> dt) {
this.dt = dt;
this.nodeToFrontier = new HashMap<DominatorNode<N>, List<DominatorNode<N>>>();
for (DominatorNode<N> head : dt.getHeads()) {
bottomUpDispatch(head);
}
for (N gode : dt.graph) {
DominatorNode<N> dode = dt.fetchDode(gode);
if (dode == null) {
throw new RuntimeException("dode == null");
} else if (!isFrontierKnown(dode)) {
throw new RuntimeException("Frontier not defined for node: " + dode);
}
}
}
@Override
public List<DominatorNode<N>> getDominanceFrontierOf(DominatorNode<N> node) {
List<DominatorNode<N>> frontier = nodeToFrontier.get(node);
if (frontier == null) {
throw new RuntimeException("Frontier not defined for node: " + node);
}
return Collections.unmodifiableList(frontier);
}
protected boolean isFrontierKnown(DominatorNode<N> node) {
return nodeToFrontier.containsKey(node);
}
/**
* Make sure we visit children first. This is reverse topological order.
*/
protected void bottomUpDispatch(DominatorNode<N> node) {
// *** FIXME: It's annoying that this algorithm is so
// *** inefficient in that in traverses the tree from the head
// *** to the tail before it does anything.
if (isFrontierKnown(node)) {
return;
}
for (DominatorNode<N> child : dt.getChildrenOf(node)) {
if (!isFrontierKnown(child)) {
bottomUpDispatch(child);
}
}
processNode(node);
}
/**
* Calculate dominance frontier for a set of basic blocks.
*
* <p>
* Uses the algorithm of Cytron et al., TOPLAS Oct. 91:
*
* <pre>
* <code>
* for each X in a bottom-up traversal of the dominator tree do
*
* DF(X) < - null
* for each Y in Succ(X) do
* if (idom(Y)!=X) then DF(X) <- DF(X) U Y
* end
* for each Z in {idom(z) = X} do
* for each Y in DF(Z) do
* if (idom(Y)!=X) then DF(X) <- DF(X) U Y
* end
* end
* </code>
* </pre>
*/
protected void processNode(DominatorNode<N> node) {
HashSet<DominatorNode<N>> dominanceFrontier = new HashSet<DominatorNode<N>>();
// local
for (DominatorNode<N> succ : dt.getSuccsOf(node)) {
if (!dt.isImmediateDominatorOf(node, succ)) {
dominanceFrontier.add(succ);
}
}
// up
for (DominatorNode<N> child : dt.getChildrenOf(node)) {
for (DominatorNode<N> childFront : getDominanceFrontierOf(child)) {
if (!dt.isImmediateDominatorOf(node, childFront)) {
dominanceFrontier.add(childFront);
}
}
}
nodeToFrontier.put(node, new ArrayList<>(dominanceFrontier));
}
}
| 4,224
| 29.615942
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/DirectedBodyGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Body;
/**
*
* @param <N>
*/
public interface DirectedBodyGraph<N> extends DirectedGraph<N> {
/**
* @return the {@link Body} from which this graph was built
*/
public Body getBody();
}
| 1,061
| 26.947368
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/DirectedGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.List;
/**
* Defines the notion of a directed graph.
*
* @param <N>
* node type
*/
public interface DirectedGraph<N> extends Iterable<N> {
/**
* Returns a list of entry points for this graph.
*/
public List<N> getHeads();
/** Returns a list of exit points for this graph. */
public List<N> getTails();
/**
* Returns a list of predecessors for the given node in the graph.
*/
public List<N> getPredsOf(N s);
/**
* Returns a list of successors for the given node in the graph.
*/
public List<N> getSuccsOf(N s);
/**
* Returns the node count for this graph.
*/
public int size();
/**
* Returns an iterator for the nodes in this graph. No specific ordering of the nodes is guaranteed.
*/
@Override
public Iterator<N> iterator();
}
| 1,697
| 25.53125
| 102
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/DominanceFrontier.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Navindra Umanee <navindra@cs.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.List;
/**
* Interface to compute and/or store the dominance frontiers of nodes in a dominator tree.
*
* @author Navindra Umanee
**/
public interface DominanceFrontier<N> {
public List<DominatorNode<N>> getDominanceFrontierOf(DominatorNode<N> node);
}
| 1,129
| 31.285714
| 90
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/DominatorAnalysis.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Unit;
import soot.jimple.Stmt;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
// STEP 1: What are we computing?
// SETS OF Units that are dominators => Use ArraySparseSet.
//
// STEP 2: Precisely define what we are computing.
// For each statement compute the set of stmts that dominate it
//
// STEP 3: Decide whether it is a backwards or forwards analysis.
// FORWARDS
//
//
/**
* @deprecated use {@link MHGDominatorsFinder} instead
*/
@Deprecated
public class DominatorAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<Unit>> {
private UnitGraph g;
private FlowSet<Unit> allNodes;
public DominatorAnalysis(UnitGraph g) {
super(g);
this.g = g;
initAllNodes();
doAnalysis();
}
private void initAllNodes() {
allNodes = new ArraySparseSet<Unit>();
for (Unit u : g) {
allNodes.add(u);
}
}
// STEP 4: Is the merge operator union or intersection?
// INTERSECTION
@Override
protected void merge(FlowSet<Unit> in1, FlowSet<Unit> in2, FlowSet<Unit> out) {
in1.intersection(in2, out);
}
@Override
protected void copy(FlowSet<Unit> source, FlowSet<Unit> dest) {
source.copy(dest);
}
// STEP 5: Define flow equations.
// dom(s) = s U ( ForAll Y in pred(s): Intersection (dom(y)))
// ie: dom(s) = s and whoever dominates all the predeccessors of s
//
@Override
protected void flowThrough(FlowSet<Unit> in, Unit s, FlowSet<Unit> out) {
if (isUnitStartNode(s)) {
// System.out.println("s: "+s+" is start node");
out.clear();
out.add(s);
// System.out.println("in: "+in+" out: "+out);
} else {
// System.out.println("s: "+s+" is not start node");
// FlowSet domsOfPreds = allNodes.clone();
// for each pred of s
for (Unit pred : g.getPredsOf(s)) {
// get the unitToBeforeFlow and find the intersection
// System.out.println("pred: "+pred);
FlowSet<Unit> next = getFlowAfter(pred);
// System.out.println("next: "+next);
// System.out.println("in before intersect: "+in);
in.intersection(next, in);
// System.out.println("in after intersect: "+in);
}
// intersected with in
// System.out.println("out init: "+out);
out.intersection(in, out);
out.add(s);
// System.out.println("out after: "+out);
}
}
private boolean isUnitStartNode(Unit s) {
// System.out.println("head: "+g.getHeads().get(0));
if (s.equals(g.getHeads().get(0))) {
return true;
}
return false;
}
// STEP 6: Determine value for start/end node, and
// initial approximation.
// dom(startNode) = startNode
// dom(node) = allNodes
//
@Override
protected FlowSet<Unit> entryInitialFlow() {
FlowSet<Unit> fs = new ArraySparseSet<Unit>();
List<Unit> heads = g.getHeads();
if (heads.size() != 1) {
throw new RuntimeException("Expect one start node only.");
}
fs.add(heads.get(0));
return fs;
}
@Override
protected FlowSet<Unit> newInitialFlow() {
return allNodes.clone();
}
/**
* Returns true if s post-dominates t.
*/
public boolean dominates(Stmt s, Stmt t) {
return getFlowBefore(t).contains(s);
}
}
| 4,156
| 25.477707
| 81
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/DominatorNode.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.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.List;
/**
* Represents a dominator node in DominatorTree. Usually you should use DominatorTree or DominanceFrontier to obtain
* information on how a node relates to other nodes instead of directly using any methods provided here.
*
* @author Navindra Umanee
**/
public class DominatorNode<N> {
protected N gode;
protected DominatorNode<N> parent;
protected List<DominatorNode<N>> children;
protected DominatorNode(N gode) {
this.gode = gode;
this.children = new ArrayList<DominatorNode<N>>();
}
/**
* Sets the parent of this node in the DominatorTree. Usually called internally.
**/
public void setParent(DominatorNode<N> parent) {
this.parent = parent;
}
/**
* Adds a child to the internal list of children of this node in tree. Usually called internally.
**/
public boolean addChild(DominatorNode<N> child) {
if (children.contains(child)) {
return false;
} else {
children.add(child);
return true;
}
}
/**
* Returns the node (from the original DirectedGraph) encapsulated by this DominatorNode.
**/
public N getGode() {
return gode;
}
/**
* Returns the parent of the node in the DominatorTree.
**/
public DominatorNode<N> getParent() {
return parent;
}
/**
* Returns a backed list of the children of this node in the DominatorTree.
**/
public List<DominatorNode<N>> getChildren() {
return children;
}
/**
* Returns true if this node is the head of its DominatorTree.
**/
public boolean isHead() {
return parent == null;
}
/**
* Returns true if this node is a tail of its DominatorTree.
**/
public boolean isTail() {
return children.isEmpty();
}
@Override
public String toString() {
// *** FIXME: Print info about parent and children
return gode.toString();
}
}
| 2,748
| 25.180952
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/DominatorTree.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.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.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Constructs a dominator tree structure from the given DominatorsFinder. The nodes in DominatorTree are of type
* DominatorNode.
*
* <p>
*
* Note: DominatorTree does not currently implement DirectedGraph since it provides 4 methods of navigating the nodes where
* the meaning of getPredsOf and getSuccsOf diverge from the usual meaning in a DirectedGraph implementation.
*
* <p>
*
* If you need a DirectedGraph implementation, see DominatorTreeAdapter.
*
* @author Navindra Umanee
*/
public class DominatorTree<N> implements Iterable<DominatorNode<N>> {
private static final Logger logger = LoggerFactory.getLogger(DominatorTree.class);
protected final DominatorsFinder<N> dominators;
protected final DirectedGraph<N> graph;
protected final List<DominatorNode<N>> heads;
protected final List<DominatorNode<N>> tails;
/**
* "gode" is a node in the original graph, "dode" is a node in the dominator tree.
*/
protected final Map<N, DominatorNode<N>> godeToDode;
public DominatorTree(DominatorsFinder<N> dominators) {
// if(Options.v().verbose())
// logger.debug("[" + graph.getBody().getMethod().getName() +
// "] Constructing DominatorTree...");
this.dominators = dominators;
this.graph = dominators.getGraph();
this.heads = new ArrayList<DominatorNode<N>>();
this.tails = new ArrayList<DominatorNode<N>>();
this.godeToDode = new HashMap<N, DominatorNode<N>>();
buildTree();
}
/**
* @return the original graph to which the DominatorTree pertains
*/
public DirectedGraph<N> getGraph() {
return dominators.getGraph();
}
/**
* @return the root of the dominator tree.
*/
public List<DominatorNode<N>> getHeads() {
return Collections.unmodifiableList(heads);
}
/**
* Gets the first head of the dominator tree. This function is implemented for single-headed trees and mainly for backwards
* compatibility.
*
* @return The first head of the dominator tree
*/
public DominatorNode<N> getHead() {
return heads.isEmpty() ? null : heads.get(0);
}
/**
* @return list of the tails of the dominator tree.
*/
public List<DominatorNode<N>> getTails() {
return Collections.unmodifiableList(tails);
}
/**
* @return the parent of {@code node} in the tree, null if the node is at the root.
*/
public DominatorNode<N> getParentOf(DominatorNode<N> node) {
return node.getParent();
}
/**
* @return the children of node in the tree.
*/
public List<DominatorNode<N>> getChildrenOf(DominatorNode<N> node) {
return Collections.unmodifiableList(node.getChildren());
}
/**
* @return list of the DominatorNodes corresponding to the predecessors of {@code node} in the original DirectedGraph
*/
public List<DominatorNode<N>> getPredsOf(DominatorNode<N> node) {
List<DominatorNode<N>> predNodes = new ArrayList<DominatorNode<N>>();
for (N pred : graph.getPredsOf(node.getGode())) {
predNodes.add(getDode(pred));
}
return predNodes;
}
/**
* @return list of the DominatorNodes corresponding to the successors of {@code node} in the original DirectedGraph
*/
public List<DominatorNode<N>> getSuccsOf(DominatorNode<N> node) {
List<DominatorNode<N>> succNodes = new ArrayList<DominatorNode<N>>();
for (N succ : graph.getSuccsOf(node.getGode())) {
succNodes.add(getDode(succ));
}
return succNodes;
}
/**
* @return true if idom immediately dominates node.
*/
public boolean isImmediateDominatorOf(DominatorNode<N> idom, DominatorNode<N> node) {
// node.getParent() could be null
return (node.getParent() == idom);
}
/**
* @return true if dom dominates node.
*/
public boolean isDominatorOf(DominatorNode<N> dom, DominatorNode<N> node) {
return dominators.isDominatedBy(node.getGode(), dom.getGode());
}
/**
* @return DominatorNode for a given node in the original DirectedGraph.
*/
public DominatorNode<N> getDode(N gode) {
DominatorNode<N> dode = godeToDode.get(gode);
if (dode == null) {
throw new RuntimeException(
"Assertion failed: Dominator tree does not have a corresponding dode for gode (" + gode + ")");
}
return dode;
}
/**
* @return iterator over the nodes in the tree. No ordering is implied.
*/
@Override
public Iterator<DominatorNode<N>> iterator() {
return godeToDode.values().iterator();
}
/**
* @return the number of nodes in the tree
*/
public int size() {
return godeToDode.size();
}
/**
* Add all the necessary links between nodes to form a meaningful tree structure.
*/
protected void buildTree() {
// hook up children with parents and vice-versa
for (N gode : graph) {
DominatorNode<N> dode = fetchDode(gode);
DominatorNode<N> parent = fetchParent(gode);
if (parent == null) {
heads.add(dode);
} else {
parent.addChild(dode);
dode.setParent(parent);
}
}
// identify the tail nodes
for (DominatorNode<N> dode : this) {
if (dode.isTail()) {
tails.add(dode);
}
}
if (heads instanceof ArrayList) {
((ArrayList<?>) heads).trimToSize(); // potentially a long-lived object
}
if (tails instanceof ArrayList) {
((ArrayList<?>) tails).trimToSize(); // potentially a long-lived object
}
}
/**
* Convenience method, ensures we don't create more than one DominatorNode for a given block.
*/
protected DominatorNode<N> fetchDode(N gode) {
DominatorNode<N> dode = godeToDode.get(gode);
if (dode == null) {
dode = new DominatorNode<N>(gode);
godeToDode.put(gode, dode);
}
return dode;
}
protected DominatorNode<N> fetchParent(N gode) {
N immediateDominator = dominators.getImmediateDominator(gode);
return (immediateDominator == null) ? null : fetchDode(immediateDominator);
}
}
| 6,994
| 28.639831
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/DominatorTreeAdapter.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Navindra Umanee <navindra@cs.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.Collections;
import java.util.Iterator;
import java.util.List;
/**
* This adapter provides a DirectedGraph interface to DominatorTree.
*
* <p>
*
* This might be useful if e.g. you want to apply a DirectedGraph analysis such as the PseudoTopologicalOrderer to a
* DominatorTree.
*
* @author Navindra Umanee
*
* @param <N>
**/
public class DominatorTreeAdapter<N> implements DirectedGraph<DominatorNode<N>> {
protected DominatorTree<N> dt;
public DominatorTreeAdapter(DominatorTree<N> dt) {
this.dt = dt;
}
@Override
public List<DominatorNode<N>> getHeads() {
return dt.getHeads();
}
@Override
public List<DominatorNode<N>> getTails() {
return dt.getTails();
}
@Override
public List<DominatorNode<N>> getPredsOf(DominatorNode<N> node) {
return Collections.singletonList(dt.getParentOf(node));
}
@Override
public List<DominatorNode<N>> getSuccsOf(DominatorNode<N> node) {
return dt.getChildrenOf(node);
}
@Override
public Iterator<DominatorNode<N>> iterator() {
return dt.iterator();
}
@Override
public int size() {
return dt.size();
}
}
| 1,996
| 24.602564
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/DominatorsFinder.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Navindra Umanee <navindra@cs.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.Collection;
import java.util.List;
/**
* General interface for a dominators analysis.
*
* @author Navindra Umanee
**/
public interface DominatorsFinder<N> {
/**
* Returns the graph to which the analysis pertains.
**/
public DirectedGraph<N> getGraph();
/**
* Returns a list of dominators for the given node in the graph.
**/
public List<N> getDominators(N node);
/**
* Returns the immediate dominator of node or null if the node has no immediate dominator.
**/
public N getImmediateDominator(N node);
/**
* True if "node" is dominated by "dominator" in the graph.
**/
public boolean isDominatedBy(N node, N dominator);
/**
* True if "node" is dominated by all nodes in "dominators" in the graph.
**/
public boolean isDominatedByAll(N node, Collection<N> dominators);
}
| 1,699
| 27.813559
| 92
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/EdgeLabelledDirectedGraph.java
|
package soot.toolkits.graph;
/*-
* #%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;
/**
* A {@link DirectedGraph} with labels on the edges.
*
* @param <N>
* type of the nodes
* @param <L>
* type of the labels
*/
public interface EdgeLabelledDirectedGraph<N, L> extends DirectedGraph<N> {
/**
* Returns a list of labels for which an edge exists between from and to
*
* @param from
* out node of the edges to get labels for
* @param to
* in node of the edges to get labels for
*
* @return
*/
public List<L> getLabelsForEdges(N from, N to);
/**
* Returns a DirectedGraph consisting of all edges with the given label and their nodes. Nodes without edges are not
* included in the new graph.
*
* @param label
* edge label to use as a filter in building the subgraph
*
* @return
*/
public DirectedGraph<N> getEdgesForLabel(L label);
/**
* @param from
* @param to
* @param label
*
* @return true if the graph contains an edge between the 2 nodes with the given label, false otherwise
*/
public boolean containsEdge(N from, N to, L label);
/**
* @param from
* out node for the edges
* @param to
* in node for the edges
*
* @return true if the graph contains any edges between the 2 nodes, false, otherwise
*/
public boolean containsAnyEdge(N from, N to);
/**
* @param label
* label for the edges
*
* @return true if the graph contains any edges with the given label, false otherwise
*/
public boolean containsAnyEdge(L label);
/**
* @param node
* node that we want to know if the graph contains
*
* @return true if the graph contains the node, false otherwise
*/
public boolean containsNode(N node);
}
| 2,620
| 26.589474
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/ExceptionalBlockGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Trap;
import soot.Unit;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.exceptions.ThrowableSet;
/**
* <p>
* Represents a CFG where the nodes are {@link Block}s and the edges are derived from control flow. Control flow associated
* with exceptions is taken into account: when a {@link Unit} may throw an exception that is caught by a {@link Trap} within
* the <code>Body</code>, the excepting <code>Unit</code> starts a new basic block (<code>Unit</code>s do not start a new
* block when all the exceptions they might throw would escape the method without being caught).
* </p>
*/
public class ExceptionalBlockGraph extends BlockGraph implements ExceptionalGraph<Block> {
// Maps for distinguishing exceptional and unexceptional control flow.
// We follow two conventions to save space (and runtime, if no client ever
// asks for the exceptional information): if the graph contains no
// exceptional edges (e.g. there are no traps in the method) we leave
// all these map references as NULL, while if an individual block has only
// unexceptional successors or predecessors, it is not added to the
// relevant map. When the access methods are asked about such blocks,
// they return empty lists for the exceptional predecessors and successors,
// and the complete list of predecessors or successors for
// the unexceptional predecessors and successors.
protected Map<Block, List<Block>> blockToExceptionalPreds;
protected Map<Block, List<Block>> blockToExceptionalSuccs;
protected Map<Block, List<Block>> blockToUnexceptionalPreds;
protected Map<Block, List<Block>> blockToUnexceptionalSuccs;
protected Map<Block, Collection<ExceptionDest>> blockToExceptionDests;
// When the graph has no traps (thus no exceptional CFG edges); we cache the
// throwAnalysis for generating ExceptionDests on demand. If there
// are traps, throwAnalysis remains null.
protected ThrowAnalysis throwAnalysis;
/**
* <p>
* Constructs an <code>ExceptionalBlockGraph</code> for the blocks found by partitioning the the units of the provided
* <code>Body</code> instance into basic blocks.
* </p>
*
* <p>
* Note that this constructor builds an {@link ExceptionalUnitGraph} internally when splitting <code>body</code>'s
* {@link Unit}s into {@link Block}s. Callers who already have an <code>ExceptionalUnitGraph</code> to hand can use the
* constructor taking an <code>ExceptionalUnitGraph</code> as a parameter, as a minor optimization.
*
* @param body
* The underlying body we want to make a graph for.
*/
public ExceptionalBlockGraph(Body body) {
this(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body));
}
/**
* Constructs a graph for the blocks found by partitioning the the {@link Unit}s in an {@link ExceptionalUnitGraph}.
*
* @param unitGraph
* The <code>ExceptionalUnitGraph</code> whose <code>Unit</code>s are to be split into blocks.
*/
public ExceptionalBlockGraph(ExceptionalUnitGraph unitGraph) {
super(unitGraph);
soot.util.PhaseDumper.v().dumpGraph(this);
}
/**
* {@inheritDoc}
*
* This implementation calls the inherited implementation to split units into blocks, before adding the distinctions
* between exceptional and unexceptional control flow.
*
* @param {@inheritDoc}
*
* @return {@inheritDoc}
*/
@Override
protected Map<Unit, Block> buildBlocks(Set<Unit> leaders, UnitGraph uncastUnitGraph) {
ExceptionalUnitGraph unitGraph = (ExceptionalUnitGraph) uncastUnitGraph;
Map<Unit, Block> unitToBlock = super.buildBlocks(leaders, unitGraph);
if (unitGraph.getBody().getTraps().isEmpty()) {
// All exceptions escape the method. Cache the ThrowAnalysis
// to respond to getExceptionDests() on demand.
throwAnalysis = unitGraph.getThrowAnalysis();
if (throwAnalysis == null) {
throw new IllegalStateException("ExceptionalUnitGraph lacked a cached ThrowAnalysis for a Body with no Traps.");
}
} else {
int initialMapSize = (mBlocks.size() * 2) / 3;
blockToUnexceptionalPreds = new HashMap<Block, List<Block>>(initialMapSize);
blockToUnexceptionalSuccs = new HashMap<Block, List<Block>>(initialMapSize);
blockToExceptionalPreds = new HashMap<Block, List<Block>>(initialMapSize);
blockToExceptionalSuccs = new HashMap<Block, List<Block>>(initialMapSize);
for (Block block : mBlocks) {
Unit blockHead = block.getHead();
List<Unit> exceptionalPredUnits = unitGraph.getExceptionalPredsOf(blockHead);
if (!exceptionalPredUnits.isEmpty()) {
List<Block> exceptionalPreds = Collections.unmodifiableList(mappedValues(exceptionalPredUnits, unitToBlock));
blockToExceptionalPreds.put(block, exceptionalPreds);
List<Unit> unexceptionalPredUnits = unitGraph.getUnexceptionalPredsOf(blockHead);
List<Block> unexceptionalPreds = unexceptionalPredUnits.isEmpty() ? Collections.emptyList()
: Collections.unmodifiableList(mappedValues(unexceptionalPredUnits, unitToBlock));
blockToUnexceptionalPreds.put(block, unexceptionalPreds);
}
Unit blockTail = block.getTail();
List<Unit> exceptionalSuccUnits = unitGraph.getExceptionalSuccsOf(blockTail);
if (!exceptionalSuccUnits.isEmpty()) {
List<Block> exceptionalSuccs = Collections.unmodifiableList(mappedValues(exceptionalSuccUnits, unitToBlock));
blockToExceptionalSuccs.put(block, exceptionalSuccs);
List<Unit> unexceptionalSuccUnits = unitGraph.getUnexceptionalSuccsOf(blockTail);
List<Block> unexceptionalSuccs = unexceptionalSuccUnits.isEmpty() ? Collections.emptyList()
: Collections.unmodifiableList(mappedValues(unexceptionalSuccUnits, unitToBlock));
blockToUnexceptionalSuccs.put(block, unexceptionalSuccs);
}
}
blockToExceptionDests = buildExceptionDests(unitGraph, unitToBlock);
}
return unitToBlock;
}
/**
* Utility method which, given a {@link List} of objects and a {@link Map} where those objects appear as keys, returns a
* <code>List</code> of the values to which the keys map, in the corresponding order.
*
* @param keys
* the keys to be looked up.
*
* @param keyToValue
* the map in which to look up the keys.
*
* @throws IllegalStateException
* if one of the elements in <code>keys</code> does not appear in <code>keyToValue</code>
*/
private static <K, V> List<V> mappedValues(List<K> keys, Map<K, V> keyToValue) {
ArrayList<V> result = new ArrayList<V>(keys.size());
for (K key : keys) {
V value = keyToValue.get(key);
if (value == null) {
throw new IllegalStateException("No value corresponding to key: " + key);
}
result.add(value);
}
result.trimToSize(); // potentially a long-lived object
return result;
}
private Map<Block, Collection<ExceptionDest>> buildExceptionDests(ExceptionalUnitGraph unitGraph,
Map<Unit, Block> unitToBlock) {
Map<Block, Collection<ExceptionDest>> result =
new HashMap<Block, Collection<ExceptionDest>>(mBlocks.size() * 2 + 1, 0.7f);
for (Block block : mBlocks) {
result.put(block, collectDests(block, unitGraph, unitToBlock));
}
return result;
}
/**
* Utility method which, given a {@link Block} and the {@link ExceptionalUnitGraph} from which it was constructed, returns
* the {@link ExceptionDest}s representing the exceptions which may be thrown by units in the block.
*
* @param block
* the {@link Block} whose exceptions are to be collected.
*
* @param unitGraph
* the {@link ExceptionalUnitGraph} from which this graph is constructed.
*
* @param unitToBlock
* a {@link Map} from the units which are block heads or tails to the blocks that they belong to.
*
* @return a {@link Collection} of {@link ExceptionDest}s representing the exceptions that may be thrown by this block,
* together with their catchers.
*/
private Collection<ExceptionDest> collectDests(Block block, ExceptionalUnitGraph unitGraph, Map<Unit, Block> unitToBlock) {
final Unit blockHead = block.getHead();
final Unit blockTail = block.getTail();
final ThrowableSet emptyThrowables = ThrowableSet.Manager.v().EMPTY;
ThrowableSet escapingThrowables = emptyThrowables;
ArrayList<ExceptionDest> blocksDests = null;
Map<Trap, ThrowableSet> trapToThrowables = null; // Don't allocate unless we need it.
int caughtCount = 0;
for (Unit unit : block) {
Collection<ExceptionalUnitGraph.ExceptionDest> unitDests = unitGraph.getExceptionDests(unit);
if (unitDests.size() != 1 && unit != blockHead && unit != blockTail) {
throw new IllegalStateException(
"Multiple ExceptionDests associated with a unit which does not begin or end its block.");
}
for (soot.toolkits.graph.ExceptionalUnitGraph.ExceptionDest unitDest : unitDests) {
if (unitDest.getTrap() == null) {
try {
escapingThrowables = escapingThrowables.add(unitDest.getThrowables());
} catch (ThrowableSet.AlreadyHasExclusionsException e) {
if (escapingThrowables != emptyThrowables) {
// Return multiple escaping ExceptionDests,
// since ThrowableSet's limitations do not permit us
// to add all the escaping type descriptions together.
if (blocksDests == null) {
blocksDests = new ArrayList<ExceptionDest>(10);
}
blocksDests.add(new ExceptionDest(null, escapingThrowables, null));
}
escapingThrowables = unitDest.getThrowables();
}
} else {
if (unit != blockHead && unit != blockTail) {
// Assertion failure.
throw new IllegalStateException("Unit " + unit.toString() + " is not a block head or tail, yet it throws "
+ unitDest.getThrowables() + " to " + unitDest.getTrap());
}
caughtCount++;
if (trapToThrowables == null) {
trapToThrowables = new HashMap<Trap, ThrowableSet>(unitDests.size() * 2);
}
Trap trap = unitDest.getTrap();
ThrowableSet throwables = trapToThrowables.get(trap);
if (throwables == null) {
throwables = unitDest.getThrowables();
} else {
throwables = throwables.add(unitDest.getThrowables());
}
trapToThrowables.put(trap, throwables);
}
}
}
if (blocksDests == null) {
blocksDests = new ArrayList<ExceptionDest>(caughtCount + 1);
} else {
blocksDests.ensureCapacity(blocksDests.size() + caughtCount);
}
if (escapingThrowables != emptyThrowables) {
blocksDests.add(new ExceptionDest(null, escapingThrowables, null));
}
if (trapToThrowables != null) {
for (Map.Entry<Trap, ThrowableSet> entry : trapToThrowables.entrySet()) {
Trap trap = entry.getKey();
Block trapBlock = unitToBlock.get(trap.getHandlerUnit());
if (trapBlock == null) {
throw new IllegalStateException("catching unit is not recorded as a block leader.");
}
blocksDests.add(new ExceptionDest(trap, entry.getValue(), trapBlock));
}
}
blocksDests.trimToSize(); // potentially a long-lived object
return blocksDests;
}
@Override
public List<Block> getUnexceptionalPredsOf(Block b) {
if (blockToUnexceptionalPreds == null || !blockToUnexceptionalPreds.containsKey(b)) {
return b.getPreds();
} else {
return blockToUnexceptionalPreds.get(b);
}
}
@Override
public List<Block> getUnexceptionalSuccsOf(Block b) {
if (blockToUnexceptionalSuccs == null || !blockToUnexceptionalSuccs.containsKey(b)) {
return b.getSuccs();
} else {
return blockToUnexceptionalSuccs.get(b);
}
}
@Override
public List<Block> getExceptionalPredsOf(Block b) {
if (blockToExceptionalPreds == null || !blockToExceptionalPreds.containsKey(b)) {
return Collections.emptyList();
} else {
return blockToExceptionalPreds.get(b);
}
}
@Override
public List<Block> getExceptionalSuccsOf(Block b) {
if (blockToExceptionalSuccs == null || !blockToExceptionalSuccs.containsKey(b)) {
return Collections.emptyList();
} else {
return blockToExceptionalSuccs.get(b);
}
}
@Override
public Collection<ExceptionDest> getExceptionDests(final Block b) {
if (blockToExceptionDests == null) {
ExceptionDest e = new ExceptionDest(null, null, null) {
@Override
public ThrowableSet getThrowables() {
if (null == throwables) {
throwables = ThrowableSet.Manager.v().EMPTY;
for (Unit unit : b) {
throwables = throwables.add(throwAnalysis.mightThrow(unit));
}
}
return throwables;
}
};
return Collections.singletonList(e);
}
return blockToExceptionDests.get(b);
}
public static class ExceptionDest implements ExceptionalGraph.ExceptionDest<Block> {
private final Trap trap;
private final Block handler;
protected ThrowableSet throwables;
protected ExceptionDest(Trap trap, ThrowableSet throwables, Block handler) {
this.trap = trap;
this.throwables = throwables;
this.handler = handler;
}
@Override
public Trap getTrap() {
return trap;
}
@Override
public ThrowableSet getThrowables() {
return throwables;
}
@Override
public Block getHandlerNode() {
return handler;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(getThrowables());
buf.append(" -> ");
if (trap == null) {
buf.append("(escapes)");
} else {
buf.append(trap.toString());
buf.append("handler: ");
buf.append(getHandlerNode().toString());
}
return buf.toString();
}
}
}
| 15,266
| 38.551813
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/ExceptionalGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of 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.List;
import soot.Body;
import soot.Trap;
import soot.toolkits.exceptions.ThrowableSet;
/**
* <p>
* Defines the interface for navigating a control flow graph which distinguishes exceptional control flow.
* </p>
*
* @param <N>
* node type
*/
public interface ExceptionalGraph<N> extends DirectedBodyGraph<N> {
/**
* <p>
* Data structure to represent the fact that a given {@link Trap} will catch some subset of the exceptions which may be
* thrown by a given graph node.
* </p>
*
* <p>
* Note that these ``destinations'' are different from the edges in the CFG proper which are returned by
* <code>getSuccsOf()</code> and <code>getPredsOf()</code>. An edge from <code>a</code> to <code>b</code> in the CFG
* represents the fact that after node <code>a</code> executes (perhaps only partially, if it throws an exception after
* producing a side effect), execution may proceed to node <code>b</code>. An ExceptionDest from <code>a</code> to
* <code>b</code>, on the other hand, says that when <code>a</code> fails to execute, execution may proceed to
* <code>b</code> instead.
* </p>
*
* @param <N>
*/
public interface ExceptionDest<N> {
/**
* Returns the trap corresponding to this destination.
*
* @return either a {@link Trap} representing the handler that catches the exceptions, if there is such a handler within
* the method, or <code>null</code> if there is no such handler and the exceptions cause the method to terminate
* abruptly.
*/
public Trap getTrap();
/**
* Returns the exceptions thrown to this destination.
*
* @return a {@link ThrowableSet} representing the exceptions which may be caught by this <code>ExceptionDest</code>'s
* trap.
*/
public ThrowableSet getThrowables();
/**
* Returns the CFG node corresponding to the beginning of the exception handler that catches the exceptions (that is, the
* node that includes {@link trap().getBeginUnit()}).
*
* @return the node in this graph which represents the beginning of the handler which catches these exceptions, or
* <code>null</code> if there is no such handler and the exceptions cause the method to terminate abruptly.
*/
// Maybe we should define an interface for Unit and Block to
// implement, and return an instance of that, rather than
// an Object. We chose Object because that's what DirectedGraph
// deals in.
public N getHandlerNode();
}
/**
* Returns the {@link Body} from which this graph was built.
*
* @return the <code>Body</code> from which this graph was built.
*/
@Override
public Body getBody();
/**
* Returns a list of nodes which are predecessors of a given node when only unexceptional control flow is considered.
*
* @param n
* The node whose predecessors are to be returned.
*
* @return a {@link List} of the nodes in this graph from which there is an unexceptional edge to <code>n</code>.
*/
public List<N> getUnexceptionalPredsOf(N n);
/**
* Returns a list of nodes which are successors of a given node when only unexceptional control flow is considered.
*
* @param n
* The node whose successors are to be returned.
*
* @return a {@link List} of nodes in this graph to which there is an unexceptional edge from <code>n</code>.
*/
public List<N> getUnexceptionalSuccsOf(N n);
/**
* Returns a list of nodes which are predecessors of a given node when only exceptional control flow is considered.
*
* @param n
* The node whose predecessors are to be returned.
*
* @return a {@link List} of nodes in this graph from which there is an exceptional edge to <code>n</code>.
*/
public List<N> getExceptionalPredsOf(N n);
/**
* Returns a list of nodes which are successors of a given node when only exceptional control flow is considered.
*
* @param n
* The node whose successors are to be returned.
*
* @return a {@link List} of nodes in this graph to which there is an exceptional edge from <code>n</code>.
*/
public List<N> getExceptionalSuccsOf(N n);
/**
* Returns a collection of {@link ExceptionalGraph.ExceptionDest ExceptionDest} objects which represent how exceptions
* thrown by a specified node will be handled.
*
* @param n
* The node for which to provide exception information.
*
* @return a collection of <code>ExceptionDest</code> objects describing the traps and handlers, if any, which catch the
* exceptions which may be thrown by <code>n</code>.
*/
public Collection<? extends ExceptionDest<N>> getExceptionDests(N n);
}
| 5,643
| 36.377483
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/ExceptionalUnitGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import soot.Body;
import soot.RefType;
import soot.Scene;
import soot.Timers;
import soot.Trap;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.baf.Inst;
import soot.baf.NewInst;
import soot.baf.StaticGetInst;
import soot.baf.StaticPutInst;
import soot.baf.ThrowInst;
import soot.jimple.InvokeExpr;
import soot.jimple.NewExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.options.Options;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.exceptions.ThrowableSet;
import soot.util.ArraySet;
import soot.util.Chain;
/**
* <p>
* Represents a control flow graph for a {@link Body} instance where the nodes are {@link Unit} instances, and where control
* flow associated with exceptions is taken into account.
* </p>
*
* <p>
* To describe precisely the circumstances under which exceptional edges are added to the graph, we need to distinguish the
* exceptions thrown explicitly by a <code>throw</code> instruction from the exceptions which are thrown implicitly by the VM
* to signal an error it encounters in the course of executing an instruction, which need not be a <code>throw</code>.
* </p>
*
* <p>
* For every {@link ThrowInst} or {@link ThrowStmt} <code>Unit</code> which may explicitly throw an exception that would be
* caught by a {@link Trap} in the <code>Body</code>, there will be an edge from the <code>throw</code> <code>Unit</code> to
* the <code>Trap</code> handler's first <code>Unit</code>.
* </p>
*
* <p>
* For every <code>Unit</code> which may implicitly throw an exception that could be caught by a <code>Trap</code> in the
* <code>Body</code>, there will be an edge from each of the excepting <code>Unit</code>'s predecessors to the
* <code>Trap</code> handler's first <code>Unit</code> (since any of those predecessors may have been the last
* <code>Unit</code> to complete execution before the handler starts execution). If the excepting <code>Unit</code> might
* have the side effect of changing some field, then there will definitely be an edge from the excepting <code>Unit</code>
* itself to its handlers, since the side effect might occur before the exception is raised. If the excepting
* <code>Unit</code> has no side effects, then parameters passed to the <code>ExceptionalUnitGraph</code> constructor
* determine whether or not there is an edge from the excepting <code>Unit</code> itself to the handler <code>Unit</code>.
* </p>
*/
public class ExceptionalUnitGraph extends UnitGraph implements ExceptionalGraph<Unit> {
// If there are no Traps within the method, these will be the same maps as unitToSuccs and unitToPreds.
protected Map<Unit, List<Unit>> unitToUnexceptionalSuccs;
protected Map<Unit, List<Unit>> unitToUnexceptionalPreds;
protected Map<Unit, List<Unit>> unitToExceptionalSuccs;
protected Map<Unit, List<Unit>> unitToExceptionalPreds;
protected Map<Unit, Collection<ExceptionDest>> unitToExceptionDests;
// Cached reference to the analysis used to generate this graph, for generating responses
// to getExceptionDests() on the fly for nodes from which all exceptions escape the method.
protected ThrowAnalysis throwAnalysis;
/**
* Constructs the graph for a given Body instance, using the <code>ThrowAnalysis</code> and
* <code>omitExceptingUnitEdges</code> value that are passed as parameters.
*
* @param body
* the <code>Body</code> from which to build a graph.
*
* @param throwAnalysis
* the source of information about the exceptions which each {@link Unit} may throw.
*
* @param omitExceptingUnitEdges
* indicates whether the CFG should omit edges to a handler from trapped <code>Unit</code>s which may implicitly
* throw an exception which the handler catches but which have no potential side effects. The CFG will contain
* edges to the handler from all predecessors of <code>Unit</code>s which may implicitly throw a caught exception
* regardless of the setting for this parameter. If this parameter is <code>false</code>, there will also be edges
* to the handler from all the potentially excepting <code>Unit</code>s themselves. If this parameter is
* <code>true</code>, there will be edges to the handler from the excepting <code>Unit</code>s themselves only if
* they have potential side effects (or if they are themselves the predecessors of other potentially excepting
* <code>Unit</code>s). A setting of <code>true</code> produces CFGs which allow for more precise analyses, since
* a <code>Unit</code> without side effects has no effect on the computational state when it throws an exception.
* Use settings of <code>false</code> for compatibility with more conservative analyses, or to cater to
* conservative bytecode verifiers.
*/
public ExceptionalUnitGraph(Body body, ThrowAnalysis throwAnalysis, boolean omitExceptingUnitEdges) {
super(body);
initialize(throwAnalysis, omitExceptingUnitEdges);
}
/**
* Constructs the graph from a given Body instance using the passed {@link ThrowAnalysis} and a default value, provided by
* the {@link Options} class, for the <code>omitExceptingUnitEdges</code> parameter.
*
* @param body
* the {@link Body} from which to build a graph.
*
* @param throwAnalysis
* the source of information about the exceptions which each {@link Unit} may throw.
*
*/
public ExceptionalUnitGraph(Body body, ThrowAnalysis throwAnalysis) {
this(body, throwAnalysis, Options.v().omit_excepting_unit_edges());
}
/**
* Constructs the graph from a given Body instance, using the {@link Scene} 's default {@link ThrowAnalysis} to estimate
* the set of exceptions that each {@link Unit} might throw and a default value, provided by the {@link Options} class, for
* the <code>omitExceptingUnitEdges</code> parameter.
*
* @param body
* the <code>Body</code> from which to build a graph.
*
*/
public ExceptionalUnitGraph(Body body) {
this(body, Scene.v().getDefaultThrowAnalysis(), Options.v().omit_excepting_unit_edges());
}
/**
* <p>
* Allocates an <code>ExceptionalUnitGraph</code> object without initializing it. This “partial constructor” is
* provided for the benefit of subclasses whose constructors need to perform some subclass-specific processing before
* actually creating the graph edges (because, for example, the subclass overrides a utility method like
* {@link #buildExceptionDests(ThrowAnalysis)} or {@link #buildExceptionalEdges(ThrowAnalysis, Map, Map, Map, boolean)}
* with a replacement method that depends on additional parameters passed to the subclass's constructor). The subclass
* constructor is responsible for calling {@link #initialize(ThrowAnalysis, boolean)}, or otherwise performing the
* initialization required to implement <code>ExceptionalUnitGraph</code>'s interface.
* </p>
*
* <p>
* Clients who opt to extend <code>ExceptionalUnitGraph</code> should be warned that the class has not been carefully
* designed for inheritance; code that uses the <code>protected</code> members of this class may need to be rewritten for
* each new Soot release.
* </p>
*
* @param body
* the <code>Body</code> from which to build a graph.
*
* @param ignoredBogusParameter
* a meaningless placeholder, which exists solely to distinguish this constructor from the public
* {@link #ExceptionalUnitGraph(Body)} constructor.
*/
protected ExceptionalUnitGraph(Body body, boolean ignoredBogusParameter) {
super(body);
}
/**
* Performs the real work of constructing an <code>ExceptionalUnitGraph</code>, factored out of the constructors so that
* subclasses have the option to delay creating the graph's edges until after they have performed some subclass-specific
* initialization.
*
* @param throwAnalysis
* the source of information about the exceptions which each {@link Unit} may throw.
*
* @param omitExceptingUnitEdges
* indicates whether the CFG should omit edges to a handler from trapped <code>Unit</code>s which may throw an
* exception which the handler catches but which have no potential side effects.
*/
protected void initialize(ThrowAnalysis throwAnalysis, boolean omitExceptingUnitEdges) {
int size = unitChain.size();
if (Options.v().time()) {
Timers.v().graphTimer.start();
}
unitToUnexceptionalSuccs = new LinkedHashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f);
unitToUnexceptionalPreds = new LinkedHashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f);
buildUnexceptionalEdges(unitToUnexceptionalSuccs, unitToUnexceptionalPreds);
this.throwAnalysis = throwAnalysis;
Set<Unit> trapUnitsThatAreHeads;
if (body.getTraps().isEmpty()) {
// No handlers, so all exceptional control flow exits the method.
unitToExceptionDests = Collections.emptyMap();
unitToExceptionalSuccs = Collections.emptyMap();
unitToExceptionalPreds = Collections.emptyMap();
trapUnitsThatAreHeads = Collections.emptySet();
unitToSuccs = unitToUnexceptionalSuccs;
unitToPreds = unitToUnexceptionalPreds;
} else {
unitToExceptionDests = buildExceptionDests(throwAnalysis);
unitToExceptionalSuccs = new LinkedHashMap<Unit, List<Unit>>(unitToExceptionDests.size() * 2 + 1, 0.7f);
unitToExceptionalPreds = new LinkedHashMap<Unit, List<Unit>>(body.getTraps().size() * 2 + 1, 0.7f);
trapUnitsThatAreHeads = buildExceptionalEdges(throwAnalysis, unitToExceptionDests, unitToExceptionalSuccs,
unitToExceptionalPreds, omitExceptingUnitEdges);
// We'll need separate maps for the combined
// exceptional and unexceptional edges:
unitToSuccs = combineMapValues(unitToUnexceptionalSuccs, unitToExceptionalSuccs);
unitToPreds = combineMapValues(unitToUnexceptionalPreds, unitToExceptionalPreds);
}
buildHeadsAndTails(trapUnitsThatAreHeads);
if (Options.v().time()) {
Timers.v().graphTimer.end();
}
soot.util.PhaseDumper.v().dumpGraph(this);
}
/**
* <p>
* Utility method used in the construction of {@link soot.toolkits.graph.UnitGraph UnitGraph} variants which include
* exceptional control flow. It determines which {@link Unit}s may throw exceptions that would be caught by {@link Trap}s
* within the method.
* </p>
*
* @param throwAnalysis
* The source of information about which exceptions each <code>Unit</code> may throw.
*
* @return <code>null</code> if no <code>Unit</code>s in the method throw any exceptions caught within the method.
* Otherwise, a {@link Map} from <code>Unit</code>s to {@link Collection}s of {@link ExceptionDest}s.
*
* <p>
* The returned map has an idiosyncracy which is hidden from most client code, but which is exposed to subclasses
* extending <code>ExceptionalUnitGraph</code>. If a <code>Unit</code> throws one or more exceptions which are
* caught within the method, it will be mapped to a <code>Collection</code> of <code>ExceptionDest</code>s
* describing the sets of exceptions that the <code>Unit</code> might throw to each {@link Trap}. But if all of a
* <code>Unit</code>'s exceptions escape the method, it will be mapped to <code>null</code, rather than to a
* <code>Collection</code> containing a single <code>ExceptionDest</code> with a <code>null</code> trap. (The
* special case for <code>Unit</code>s with no caught exceptions allows <code>buildExceptionDests()</code> to
* ignore completely <code>Unit</code>s which are outside the scope of all <code>Trap</code>s.)
* </p>
*/
protected Map<Unit, Collection<ExceptionDest>> buildExceptionDests(ThrowAnalysis throwAnalysis) {
Chain<Unit> units = body.getUnits();
Map<Unit, ThrowableSet> unitToUncaughtThrowables = new LinkedHashMap<Unit, ThrowableSet>(units.size());
Map<Unit, Collection<ExceptionDest>> result = null;
// Record the caught exceptions.
for (Trap trap : body.getTraps()) {
RefType catcher = trap.getException().getType();
for (Iterator<Unit> unitIt = units.iterator(trap.getBeginUnit(), units.getPredOf(trap.getEndUnit())); unitIt
.hasNext();) {
Unit unit = unitIt.next();
ThrowableSet thrownSet = unitToUncaughtThrowables.get(unit);
if (thrownSet == null) {
thrownSet = throwAnalysis.mightThrow(unit);
}
ThrowableSet.Pair catchableAs = thrownSet.whichCatchableAs(catcher);
if (!catchableAs.getCaught().equals(ThrowableSet.Manager.v().EMPTY)) {
result = addDestToMap(result, unit, trap, catchableAs.getCaught());
unitToUncaughtThrowables.put(unit, catchableAs.getUncaught());
} else {
assert thrownSet.equals(catchableAs.getUncaught()) : "ExceptionalUnitGraph.buildExceptionDests(): "
+ "catchableAs.caught == EMPTY, but catchableAs.uncaught != thrownSet" + System.getProperty("line.separator")
+ body.getMethod().getSubSignature() + " Unit: " + unit.toString() + System.getProperty("line.separator")
+ " catchableAs.getUncaught() == " + catchableAs.getUncaught().toString()
+ System.getProperty("line.separator") + " thrownSet == " + thrownSet.toString();
}
}
}
for (Map.Entry<Unit, ThrowableSet> entry : unitToUncaughtThrowables.entrySet()) {
Unit unit = entry.getKey();
ThrowableSet escaping = entry.getValue();
if (escaping != ThrowableSet.Manager.v().EMPTY) {
result = addDestToMap(result, unit, null, escaping);
}
}
return result == null ? Collections.emptyMap() : result;
}
/**
* A utility method for recording the exceptions that a <code>Unit</code> throws to a particular <code>Trap</code>. Note
* that this method relies on the fact that the call to add escaping exceptions for a <code>Unit</code> will always follow
* all calls for its caught exceptions.
*
* @param map
* A <code>Map</code> from <code>Unit</code>s to <code>Collection</code>s of <code>ExceptionDest</code>s.
* <code>null</code> if no exceptions have been recorded yet.
*
* @param u
* The <code>Unit</code> throwing the exceptions.
*
* @param t
* The <code>Trap</code> which catches the exceptions, or <code>null</code> if the exceptions escape the method.
*
* @param caught
* The set of exception types thrown by <code>u</code> which are caught by <code>t</code>.
*
* @return a <code>Map</code> which whose contents are equivalent to the input <code>map</code>, plus the information that
* <code>u</code> throws <code>caught</code> to <code>t</code>.
*/
private Map<Unit, Collection<ExceptionDest>> addDestToMap(Map<Unit, Collection<ExceptionDest>> map, Unit u, Trap t,
ThrowableSet caught) {
Collection<ExceptionDest> dests = (map == null ? null : map.get(u));
if (dests == null) {
if (t == null) {
// All exceptions from u escape, so don't record any.
return map;
} else {
if (map == null) {
map = new LinkedHashMap<Unit, Collection<ExceptionDest>>(unitChain.size() * 2 + 1);
}
dests = new ArrayList<ExceptionDest>(3);
map.put(u, dests);
}
}
dests.add(new ExceptionDest(t, caught));
return map;
}
/**
* Method to compute the edges corresponding to exceptional control flow.
*
* @param throwAnalysis
* the source of information about the exceptions which each {@link Unit} may throw.
*
* @param unitToExceptionDests
* A <code>Map</code> from {@link Unit}s to {@link Collection}s of {@link ExceptionalUnitGraph.ExceptionDest
* ExceptionDest}s which represent the handlers that might catch exceptions thrown by the <code>Unit</code>. This
* is an ``in parameter''.
*
* @param unitToSuccs
* A <code>Map</code> from <code>Unit</code>s to {@link List}s of <code>Unit</code>s. This is an ``out
* parameter''; <code>buildExceptionalEdges</code> will add a mapping from every <code>Unit</code> in the body
* that may throw an exception that could be caught by a {@link Trap} in the body to a list of its exceptional
* successors.
*
* @param unitToPreds
* A <code>Map</code> from <code>Unit</code>s to <code>List</code>s of <code>Unit</code>s. This is an ``out
* parameter''; <code>buildExceptionalEdges</code> will add a mapping from each handler unit that may catch an
* exception to the list of <code>Unit</code>s whose exceptions it may catch.
* @param omitExceptingUnitEdges
* Indicates whether to omit exceptional edges from excepting units which lack side effects
*
* @return a {@link Set} of trap <code>Unit</code>s that might catch exceptions thrown by the first <code>Unit</code> in
* the {@link Body} associated with the graph being constructed. Such trap <code>Unit</code>s may need to be added
* to the list of heads (depending on your definition of heads), since they can be the first <code>Unit</code> in
* the <code>Body</code> which actually completes execution.
*/
protected Set<Unit> buildExceptionalEdges(ThrowAnalysis throwAnalysis,
Map<Unit, Collection<ExceptionDest>> unitToExceptionDests, Map<Unit, List<Unit>> unitToSuccs,
Map<Unit, List<Unit>> unitToPreds, boolean omitExceptingUnitEdges) {
Set<Unit> trapsThatAreHeads = new ArraySet<Unit>();
Unit entryPoint = unitChain.getFirst();
for (Entry<Unit, Collection<ExceptionDest>> entry : unitToExceptionDests.entrySet()) {
Unit thrower = entry.getKey();
List<Unit> throwersPreds = getUnexceptionalPredsOf(thrower);
Collection<ExceptionDest> dests = entry.getValue();
// We need to recognize:
// - caught exceptions for which we must add edges from the
// thrower's predecessors to the catcher:
// - all exceptions of non-throw instructions;
// - implicit exceptions of throw instructions.
//
// - caught exceptions where we must add edges from the
// thrower itself to the catcher:
// - any exception of non-throw instructions if
// omitExceptingUnitEdges is not set.
// - any exception of non-throw instructions with side effects.
// - explicit exceptions of throw instructions
// - implicit exceptions of throw instructions if
// omitExceptingUnitEdges is not set.
// - implicit exceptions of throw instructions with possible
// side effects (this is only possible for the grimp
// IR, where the throw's argument may be an
// expression---probably a NewInvokeExpr---which
// might have executed partially before the
// exception arose).
//
// Note that a throw instruction may be capable of throwing a given
// Throwable type both implicitly and explicitly.
//
// We track these situations using predThrowables and
// selfThrowables. Essentially predThrowables is the set
// of Throwable types to whose catchers there should be
// edges from predecessors of the thrower, while
// selfThrowables is the set of Throwable types to whose
// catchers there should be edges from the thrower itself,
// but we we take some short cuts to avoid calling
// ThrowableSet.catchableAs() when we can avoid it.
boolean alwaysAddSelfEdges = ((!omitExceptingUnitEdges) || mightHaveSideEffects(thrower));
ThrowableSet predThrowables = null;
ThrowableSet selfThrowables = null;
if (thrower instanceof ThrowInst) {
ThrowInst throwInst = (ThrowInst) thrower;
predThrowables = throwAnalysis.mightThrowImplicitly(throwInst);
selfThrowables = throwAnalysis.mightThrowExplicitly(throwInst);
} else if (thrower instanceof ThrowStmt) {
ThrowStmt throwStmt = (ThrowStmt) thrower;
predThrowables = throwAnalysis.mightThrowImplicitly(throwStmt);
selfThrowables = throwAnalysis.mightThrowExplicitly(throwStmt);
}
for (ExceptionDest dest : dests) {
if (dest.getTrap() != null) {
Unit catcher = dest.getTrap().getHandlerUnit();
RefType trapsType = dest.getTrap().getException().getType();
if (predThrowables == null || predThrowables.catchableAs(trapsType)) {
// Add edges from the thrower's predecessors to the
// catcher.
if (thrower == entryPoint) {
trapsThatAreHeads.add(catcher);
}
for (Unit pred : throwersPreds) {
addEdge(unitToSuccs, unitToPreds, pred, catcher);
}
}
if (alwaysAddSelfEdges || (selfThrowables != null && selfThrowables.catchableAs(trapsType))) {
addEdge(unitToSuccs, unitToPreds, thrower, catcher);
}
}
}
}
// Now we have to worry about transitive exceptional
// edges, when a handler might itself throw an exception
// that is caught within the method. For that we need a
// worklist containing CFG edges that lead to such a handler.
class CFGEdge {
Unit head; // If null, represents an edge to the handler
// from the fictitious "predecessor" of the
// very first unit in the chain. I.e., tail
// is a handler which might be reached as a
// result of an exception thrown by the
// first Unit in the Body.
Unit tail;
CFGEdge(Unit head, Unit tail) {
if (tail == null) {
throw new RuntimeException("invalid CFGEdge(" + (head == null ? "null" : head.toString()) + ',' + "null" + ')');
}
this.head = head;
this.tail = tail;
}
@Override
public boolean equals(Object rhs) {
if (rhs == this) {
return true;
}
if (!(rhs instanceof CFGEdge)) {
return false;
}
CFGEdge rhsEdge = (CFGEdge) rhs;
return ((this.head == rhsEdge.head) && (this.tail == rhsEdge.tail));
}
@Override
public int hashCode() {
// Following Joshua Bloch's recipe in "Effective Java", Item 8:
int result = 17;
result = 37 * result + this.head.hashCode();
result = 37 * result + this.tail.hashCode();
return result;
}
}
LinkedList<CFGEdge> workList = new LinkedList<CFGEdge>();
for (Trap trap : body.getTraps()) {
Unit handlerStart = trap.getHandlerUnit();
if (mightThrowToIntraproceduralCatcher(handlerStart)) {
List<Unit> handlerPreds = getUnexceptionalPredsOf(handlerStart);
for (Unit pred : handlerPreds) {
workList.addLast(new CFGEdge(pred, handlerStart));
}
handlerPreds = getExceptionalPredsOf(handlerStart);
for (Unit pred : handlerPreds) {
workList.addLast(new CFGEdge(pred, handlerStart));
}
if (trapsThatAreHeads.contains(handlerStart)) {
workList.addLast(new CFGEdge(null, handlerStart));
}
}
}
// Now for every CFG edge that leads to a handler that may
// itself throw an exception catchable within the method, add
// edges from the head of that edge to the unit that catches
// the handler's exception.
while (workList.size() > 0) {
CFGEdge edgeToThrower = workList.removeFirst();
Unit pred = edgeToThrower.head;
Unit thrower = edgeToThrower.tail;
Collection<ExceptionDest> throwerDests = getExceptionDests(thrower);
for (ExceptionDest dest : throwerDests) {
if (dest.getTrap() != null) {
Unit handlerStart = dest.getTrap().getHandlerUnit();
boolean edgeAdded = false;
if (pred == null) {
if (!trapsThatAreHeads.contains(handlerStart)) {
trapsThatAreHeads.add(handlerStart);
edgeAdded = true;
}
} else {
if (!getExceptionalSuccsOf(pred).contains(handlerStart)) {
addEdge(unitToSuccs, unitToPreds, pred, handlerStart);
edgeAdded = true;
}
}
if (edgeAdded && mightThrowToIntraproceduralCatcher(handlerStart)) {
workList.addLast(new CFGEdge(pred, handlerStart));
}
}
}
}
return trapsThatAreHeads;
}
/**
* <p>
* Utility method for checking if a {@link Unit} might have side effects. It simply returns true for any unit which invokes
* a method directly or which might invoke static initializers indirectly (by creating a new object or by refering to a
* static field; see sections 2.17.4, 2.17.5, and 5.5 of the Java Virtual Machine Specification).
* </p>
*
* <code>mightHaveSideEffects()</code> is declared package-private so that it is available to unit tests that are part of
* this package.
*
* @param u
* The unit whose potential for side effects is to be checked.
*
* @return whether or not <code>u</code> has the potential for side effects.
*/
static boolean mightHaveSideEffects(Unit u) {
if (u instanceof Inst) {
Inst i = (Inst) u;
return (i.containsInvokeExpr() || (i instanceof StaticPutInst) || (i instanceof StaticGetInst)
|| (i instanceof NewInst));
} else if (u instanceof Stmt) {
for (ValueBox vb : u.getUseBoxes()) {
Value v = vb.getValue();
if ((v instanceof StaticFieldRef) || (v instanceof InvokeExpr) || (v instanceof NewExpr)) {
return true;
}
}
}
return false;
}
/**
* Utility method for checking if a Unit might throw an exception which may be caught by a {@link Trap} within this method.
*
* @param u
* The unit for whose exceptions are to be checked
*
* @return whether or not <code>u</code> may throw an exception which may be caught by a <code>Trap</code> in this method,
*/
private boolean mightThrowToIntraproceduralCatcher(Unit u) {
for (ExceptionDest dest : getExceptionDests(u)) {
if (dest.getTrap() != null) {
return true;
}
}
return false;
}
/**
* <p>
* A placeholder that overrides {@link UnitGraph#buildHeadsAndTails()} with a method which always throws an exception. The
* placeholder serves to indicate that <code>ExceptionalUnitGraph</code> does not use <code>buildHeadsAndTails()</code>,
* and to document the conditions under which <code>ExceptionalUnitGraph considers a node to be a head or
* tail.
* </p>
*
* <p>
* <code>ExceptionalUnitGraph</code> defines the graph's set of heads to include the first {@link Unit} in the graph's
* body, together with the first <code>Unit</code> in any exception handler which might catch an exception thrown by the
* first <code>Unit</code> in the body (because any of those <code>Unit</code>s might be the first to successfully complete
* execution). <code>ExceptionalUnitGraph</code> defines the graph's set of tails to include all <code>Unit</code>s which
* represent some variety of return bytecode or an <code>athrow</code> bytecode whose argument might escape the method.
* </p>
*/
@Override
protected void buildHeadsAndTails() throws IllegalStateException {
throw new IllegalStateException("ExceptionalUnitGraph uses buildHeadsAndTails(List) instead of buildHeadsAndTails()");
}
/**
* Utility method, to be called only after the unitToPreds and unitToSuccs maps have been built. It defines the graph's set
* of heads to include the first {@link Unit} in the graph's body, together with all the <code>Unit</code>s in
* <code>additionalHeads</code>. It defines the graph's set of tails to include all <code>Unit</code>s which represent some
* sort of return bytecode or an <code>athrow</code> bytecode which may escape the method.
*/
private void buildHeadsAndTails(Set<Unit> additionalHeads) {
heads = new ArrayList<Unit>(additionalHeads.size() + 1);
heads.addAll(additionalHeads);
if (unitChain.isEmpty()) {
throw new IllegalStateException("No body for method " + body.getMethod().getSignature());
}
Unit entryPoint = unitChain.getFirst();
if (!heads.contains(entryPoint)) {
heads.add(entryPoint);
}
tails = new ArrayList<Unit>();
for (Unit u : unitChain) {
if (u instanceof soot.jimple.ReturnStmt || u instanceof soot.jimple.ReturnVoidStmt || u instanceof soot.baf.ReturnInst
|| u instanceof soot.baf.ReturnVoidInst) {
tails.add(u);
} else if (u instanceof soot.jimple.ThrowStmt || u instanceof soot.baf.ThrowInst) {
int escapeMethodCount = 0;
for (ExceptionDest dest : getExceptionDests(u)) {
if (dest.getTrap() == null) {
escapeMethodCount++;
}
}
if (escapeMethodCount > 0) {
tails.add(u);
}
}
}
}
/**
* Returns a collection of {@link ExceptionalUnitGraph.ExceptionDest ExceptionDest} objects which represent how exceptions
* thrown by a specified unit will be handled.
*
* @param u
* The unit for which to provide exception information. ( <code>u</code> must be a <code>Unit</code>, though the
* parameter is declared as an <code>Object</code> to satisfy the interface of
* {@link soot.toolkits.graph.ExceptionalGraph ExceptionalGraph}.
*
* @return a collection of <code>ExceptionDest</code> objects describing the traps, if any, which catch the exceptions
* which may be thrown by <code>u</code>.
*/
@Override
public Collection<ExceptionDest> getExceptionDests(final Unit u) {
Collection<ExceptionDest> result = unitToExceptionDests.get(u);
if (result == null) {
ExceptionDest e = new ExceptionDest(null, null) {
private ThrowableSet throwables;
@Override
public ThrowableSet getThrowables() {
if (null == throwables) {
throwables = throwAnalysis.mightThrow(u);
}
return throwables;
}
};
return Collections.singletonList(e);
}
return result;
}
public static class ExceptionDest implements ExceptionalGraph.ExceptionDest<Unit> {
private Trap trap;
private ThrowableSet throwables;
protected ExceptionDest(Trap trap, ThrowableSet throwables) {
this.trap = trap;
this.throwables = throwables;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((throwables == null) ? 0 : throwables.hashCode());
result = prime * result + ((trap == null) ? 0 : trap.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ExceptionDest other = (ExceptionDest) obj;
if (throwables == null) {
if (other.throwables != null) {
return false;
}
} else if (!throwables.equals(other.throwables)) {
return false;
}
if (trap == null) {
if (other.trap != null) {
return false;
}
} else if (!trap.equals(other.trap)) {
return false;
}
return true;
}
@Override
public Trap getTrap() {
return trap;
}
@Override
public ThrowableSet getThrowables() {
return throwables;
}
@Override
public Unit getHandlerNode() {
if (trap == null) {
return null;
} else {
return trap.getHandlerUnit();
}
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(getThrowables());
buf.append(" -> ");
if (trap == null) {
buf.append("(escapes)");
} else {
buf.append(trap.toString());
}
return buf.toString();
}
}
@Override
public List<Unit> getUnexceptionalPredsOf(Unit u) {
List<Unit> preds = unitToUnexceptionalPreds.get(u);
return preds == null ? Collections.<Unit>emptyList() : preds;
}
@Override
public List<Unit> getUnexceptionalSuccsOf(Unit u) {
List<Unit> succs = unitToUnexceptionalSuccs.get(u);
return succs == null ? Collections.<Unit>emptyList() : succs;
}
@Override
public List<Unit> getExceptionalPredsOf(Unit u) {
List<Unit> preds = unitToExceptionalPreds.get(u);
return preds == null ? Collections.<Unit>emptyList() : preds;
}
@Override
public List<Unit> getExceptionalSuccsOf(Unit u) {
List<Unit> succs = unitToExceptionalSuccs.get(u);
return succs == null ? Collections.<Unit>emptyList() : succs;
}
/**
* <p>
* Return the {@link ThrowAnalysis} used to construct this graph, if the graph contains no {@link Trap}s, or
* <code>null</code> if the graph does contain <code>Trap</code>s. A reference to the <code>ThrowAnalysis</code> is kept
* when there are no <code>Trap</code>s so that the graph can generate responses to {@link #getExceptionDests(Object)} on
* the fly, rather than precomputing information that may never be needed.
* </p>
*
* <p>
* This method is package-private because it exposes a detail of the implementation of <code>ExceptionalUnitGraph</code> so
* that the {@link soot.toolkits.graph.ExceptionalBlockGraph ExceptionalBlockGraph} constructor can cache the same
* <code>ThrowAnalysis</code> for the same purpose.
*
* @return the {@link ThrowAnalysis} used to generate this graph if the graph contains no {@link Trap}s, or
* <code>null</code> if the graph contains one or more {@link Trap}s.
*/
public ThrowAnalysis getThrowAnalysis() {
return throwAnalysis;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
for (Unit u : unitChain) {
buf.append(" preds: ").append(getPredsOf(u)).append('\n');
buf.append(" unexceptional preds: ").append(getUnexceptionalPredsOf(u)).append('\n');
buf.append(" exceptional preds: ").append(getExceptionalPredsOf(u)).append('\n');
buf.append(u.toString()).append('\n');
buf.append(" exception destinations: ").append(getExceptionDests(u)).append('\n');
buf.append(" unexceptional succs: ").append(getUnexceptionalSuccsOf(u)).append('\n');
buf.append(" exceptional succs: ").append(getExceptionalSuccsOf(u)).append('\n');
buf.append(" succs ").append(getSuccsOf(u)).append("\n\n");
}
return buf.toString();
}
}
| 36,113
| 42.774545
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/ExceptionalUnitGraphFactory.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Body;
import soot.G;
import soot.Scene;
import soot.Singletons.Global;
import soot.options.Options;
import soot.toolkits.exceptions.ThrowAnalysis;
public class ExceptionalUnitGraphFactory {
public ExceptionalUnitGraphFactory(Global g) {
}
public static ExceptionalUnitGraphFactory v() {
return G.v().soot_toolkits_graph_ExceptionalUnitGraphFactory();
}
public static ExceptionalUnitGraph createExceptionalUnitGraph(Body body) {
return v().newExceptionalUnitGraph(body, Scene.v().getDefaultThrowAnalysis(), Options.v().omit_excepting_unit_edges());
}
public static ExceptionalUnitGraph createExceptionalUnitGraph(Body body, ThrowAnalysis throwAnalysis) {
return v().newExceptionalUnitGraph(body, throwAnalysis, Options.v().omit_excepting_unit_edges());
}
public static ExceptionalUnitGraph createExceptionalUnitGraph(Body body, ThrowAnalysis throwAnalysis,
boolean omitExceptingUnitEdges) {
return v().newExceptionalUnitGraph(body, throwAnalysis, omitExceptingUnitEdges);
}
protected ExceptionalUnitGraph newExceptionalUnitGraph(Body body, ThrowAnalysis throwAnalysis,
boolean omitExceptingUnitEdges) {
return new ExceptionalUnitGraph(body, throwAnalysis, omitExceptingUnitEdges);
}
}
| 2,109
| 34.762712
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/HashMutableDirectedGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai, Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HashMap based implementation of a MutableBlockGraph.
*
* @param <N>
*/
public class HashMutableDirectedGraph<N> implements MutableDirectedGraph<N> {
private static final Logger logger = LoggerFactory.getLogger(HashMutableDirectedGraph.class);
protected final Map<N, Set<N>> nodeToPreds;
protected final Map<N, Set<N>> nodeToSuccs;
protected final Set<N> heads;
protected final Set<N> tails;
private static <T> List<T> getCopy(Collection<? extends T> c) {
return Collections.unmodifiableList(new ArrayList<T>(c));
}
private static <A, B> Map<A, Set<B>> deepCopy(Map<A, Set<B>> in) {
HashMap<A, Set<B>> retVal = new HashMap<>(in);
for (Map.Entry<A, Set<B>> e : retVal.entrySet()) {
e.setValue(new LinkedHashSet<B>(e.getValue()));
}
return retVal;
}
public HashMutableDirectedGraph() {
this.nodeToPreds = new HashMap<N, Set<N>>();
this.nodeToSuccs = new HashMap<N, Set<N>>();
this.heads = new HashSet<N>();
this.tails = new HashSet<N>();
}
// copy constructor
public HashMutableDirectedGraph(HashMutableDirectedGraph<N> orig) {
this.nodeToPreds = deepCopy(orig.nodeToPreds);
this.nodeToSuccs = deepCopy(orig.nodeToSuccs);
this.heads = new HashSet<N>(orig.heads);
this.tails = new HashSet<N>(orig.tails);
}
@Override
public Object clone() {
return new HashMutableDirectedGraph<N>(this);
}
/** Removes all nodes and edges. */
public void clearAll() {
nodeToPreds.clear();
nodeToSuccs.clear();
heads.clear();
tails.clear();
}
/* Returns an unbacked list of heads for this graph. */
@Override
public List<N> getHeads() {
return getCopy(heads);
}
/* Returns an unbacked list of tails for this graph. */
@Override
public List<N> getTails() {
return getCopy(tails);
}
@Override
public List<N> getPredsOf(N s) {
Set<N> preds = nodeToPreds.get(s);
if (preds != null) {
return getCopy(preds);
}
throw new RuntimeException(s + " not in graph!");
}
/**
* Same as {@link #getPredsOf(Object)} but returns a set. This is faster than calling {@link #getPredsOf(Object)}. Also,
* certain operations like {@link Collection#contains(Object)} execute faster on the set than on the list. The returned set
* is unmodifiable.
*/
public Set<N> getPredsOfAsSet(N s) {
Set<N> preds = nodeToPreds.get(s);
if (preds != null) {
return Collections.unmodifiableSet(preds);
}
throw new RuntimeException(s + " not in graph!");
}
@Override
public List<N> getSuccsOf(N s) {
Set<N> succs = nodeToSuccs.get(s);
if (succs != null) {
return getCopy(succs);
}
throw new RuntimeException(s + " not in graph!");
}
/**
* Same as {@link #getSuccsOf(Object)} but returns a set. This is faster than calling {@link #getSuccsOf(Object)}. Also,
* certain operations like {@link Collection#contains(Object)} execute faster on the set than on the list. The returned set
* is unmodifiable.
*/
public Set<N> getSuccsOfAsSet(N s) {
Set<N> succs = nodeToSuccs.get(s);
if (succs != null) {
return Collections.unmodifiableSet(succs);
}
throw new RuntimeException(s + " not in graph!");
}
@Override
public int size() {
return nodeToPreds.keySet().size();
}
@Override
public Iterator<N> iterator() {
return nodeToPreds.keySet().iterator();
}
@Override
public void addEdge(N from, N to) {
if (from == null || to == null) {
throw new RuntimeException("edge with null endpoint");
}
if (containsEdge(from, to)) {
return;
}
Set<N> succsList = nodeToSuccs.get(from);
if (succsList == null) {
throw new RuntimeException(from + " not in graph!");
}
Set<N> predsList = nodeToPreds.get(to);
if (predsList == null) {
throw new RuntimeException(to + " not in graph!");
}
heads.remove(to);
tails.remove(from);
succsList.add(to);
predsList.add(from);
}
@Override
public void removeEdge(N from, N to) {
Set<N> succs = nodeToSuccs.get(from);
if (succs == null || !succs.contains(to)) {
// i.e. containsEdge(from, to)==false
return;
}
Set<N> preds = nodeToPreds.get(to);
if (preds == null) {
// i.e. inconsistent data structures
throw new RuntimeException(to + " not in graph!");
}
succs.remove(to);
preds.remove(from);
if (succs.isEmpty()) {
tails.add(from);
}
if (preds.isEmpty()) {
heads.add(to);
}
}
@Override
public boolean containsEdge(N from, N to) {
Set<N> succs = nodeToSuccs.get(from);
return succs != null && succs.contains(to);
}
@Override
public boolean containsNode(N node) {
return nodeToPreds.keySet().contains(node);
}
@Override
public List<N> getNodes() {
return getCopy(nodeToPreds.keySet());
}
@Override
public void addNode(N node) {
if (containsNode(node)) {
throw new RuntimeException("Node already in graph");
}
nodeToSuccs.put(node, new LinkedHashSet<N>());
nodeToPreds.put(node, new LinkedHashSet<N>());
heads.add(node);
tails.add(node);
}
@Override
public void removeNode(N node) {
for (N n : new ArrayList<N>(nodeToSuccs.get(node))) {
removeEdge(node, n);
}
nodeToSuccs.remove(node);
for (N n : new ArrayList<N>(nodeToPreds.get(node))) {
removeEdge(n, node);
}
nodeToPreds.remove(node);
heads.remove(node);
tails.remove(node);
}
public void printGraph() {
for (N node : this) {
logger.debug("Node = " + node);
logger.debug("Preds:");
for (N p : getPredsOf(node)) {
logger.debug(" ");
logger.debug("" + p);
}
logger.debug("Succs:");
for (N s : getSuccsOf(node)) {
logger.debug(" ");
logger.debug("" + s);
}
}
}
}
| 7,082
| 25.040441
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/HashMutableEdgeLabelledDirectedGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai, Patrick Lam
* Copyright (C) 2007 Richard L. Halpert
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of 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.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HashMap based implementation of a MutableEdgeLabelledDirectedGraph.
*
* @param <N>
* @param <L>
*/
public class HashMutableEdgeLabelledDirectedGraph<N, L> implements MutableEdgeLabelledDirectedGraph<N, L> {
private static final Logger logger = LoggerFactory.getLogger(HashMutableEdgeLabelledDirectedGraph.class);
protected static class DGEdge<N> {
final N from;
final N to;
public DGEdge(N from, N to) {
this.from = from;
this.to = to;
}
public N from() {
return from;
}
public N to() {
return to;
}
@Override
public boolean equals(Object o) {
if (o instanceof DGEdge) {
DGEdge<?> other = (DGEdge<?>) o;
return this.from.equals(other.from) && this.to.equals(other.to);
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(new Object[] { from, to });
}
}
private static <T> List<T> getCopy(Collection<? extends T> c) {
return Collections.unmodifiableList(new ArrayList<T>(c));
}
protected final Map<N, List<N>> nodeToPreds;
protected final Map<N, List<N>> nodeToSuccs;
protected final Map<DGEdge<N>, List<L>> edgeToLabels;
protected final Map<L, List<DGEdge<N>>> labelToEdges;
protected final Set<N> heads;
protected final Set<N> tails;
public HashMutableEdgeLabelledDirectedGraph() {
this.nodeToPreds = new HashMap<N, List<N>>();
this.nodeToSuccs = new HashMap<N, List<N>>();
this.edgeToLabels = new HashMap<DGEdge<N>, List<L>>();
this.labelToEdges = new HashMap<L, List<DGEdge<N>>>();
this.heads = new HashSet<N>();
this.tails = new HashSet<N>();
}
// copy constructor
public HashMutableEdgeLabelledDirectedGraph(HashMutableEdgeLabelledDirectedGraph<N, L> orig) {
this.nodeToPreds = deepCopy(orig.nodeToPreds);
this.nodeToSuccs = deepCopy(orig.nodeToSuccs);
this.edgeToLabels = deepCopy(orig.edgeToLabels);
this.labelToEdges = deepCopy(orig.labelToEdges);
this.heads = new HashSet<N>(orig.heads);
this.tails = new HashSet<N>(orig.tails);
}
private static <A, B> Map<A, List<B>> deepCopy(Map<A, List<B>> in) {
HashMap<A, List<B>> retVal = new HashMap<>(in);
for (Map.Entry<A, List<B>> e : retVal.entrySet()) {
e.setValue(new ArrayList<B>(e.getValue()));
}
return retVal;
}
@Override
public HashMutableEdgeLabelledDirectedGraph<N, L> clone() {
return new HashMutableEdgeLabelledDirectedGraph<>(this);
}
/**
* Removes all nodes and edges.
*/
public void clearAll() {
this.nodeToPreds.clear();
this.nodeToSuccs.clear();
this.edgeToLabels.clear();
this.labelToEdges.clear();
this.heads.clear();
this.tails.clear();
}
/* Returns an unbacked list of heads for this graph. */
@Override
public List<N> getHeads() {
return getCopy(heads);
}
/* Returns an unbacked list of tails for this graph. */
@Override
public List<N> getTails() {
return getCopy(tails);
}
@Override
public List<N> getPredsOf(N s) {
List<N> preds = nodeToPreds.get(s);
if (preds != null) {
return Collections.unmodifiableList(preds);
}
throw new RuntimeException(s + " not in graph!");
}
@Override
public List<N> getSuccsOf(N s) {
List<N> succs = nodeToSuccs.get(s);
if (succs != null) {
return Collections.unmodifiableList(succs);
}
throw new RuntimeException(s + " not in graph!");
}
@Override
public int size() {
return nodeToPreds.keySet().size();
}
@Override
public Iterator<N> iterator() {
return nodeToPreds.keySet().iterator();
}
@Override
public void addEdge(N from, N to, L label) {
if (from == null || to == null) {
throw new RuntimeException("edge with null endpoint");
}
if (label == null) {
throw new RuntimeException("edge with null label");
}
if (containsEdge(from, to, label)) {
return;
}
List<N> succsList = nodeToSuccs.get(from);
if (succsList == null) {
throw new RuntimeException(from + " not in graph!");
}
List<N> predsList = nodeToPreds.get(to);
if (predsList == null) {
throw new RuntimeException(to + " not in graph!");
}
heads.remove(to);
tails.remove(from);
if (!succsList.contains(to)) {
succsList.add(to);
}
if (!predsList.contains(from)) {
predsList.add(from);
}
DGEdge<N> edge = new DGEdge<N>(from, to);
List<L> labels = edgeToLabels.get(edge);
if (labels == null) {
edgeToLabels.put(edge, labels = new ArrayList<L>());
}
List<DGEdge<N>> edges = labelToEdges.get(label);
if (edges == null) {
labelToEdges.put(label, edges = new ArrayList<DGEdge<N>>());
}
// if(!labels.contains(label))
labels.add(label);
// if(!edges.contains(edge))
edges.add(edge);
}
@Override
public List<L> getLabelsForEdges(N from, N to) {
DGEdge<N> edge = new DGEdge<N>(from, to);
return edgeToLabels.get(edge);
}
@Override
public MutableDirectedGraph<N> getEdgesForLabel(L label) {
List<DGEdge<N>> edges = labelToEdges.get(label);
MutableDirectedGraph<N> ret = new HashMutableDirectedGraph<N>();
if (edges == null) {
return ret;
}
for (DGEdge<N> edge : edges) {
N from = edge.from();
if (!ret.containsNode(from)) {
ret.addNode(from);
}
N to = edge.to();
if (!ret.containsNode(to)) {
ret.addNode(to);
}
ret.addEdge(from, to);
}
return ret;
}
@Override
public void removeEdge(N from, N to, L label) {
DGEdge<N> edge = new DGEdge<N>(from, to);
List<L> labels = edgeToLabels.get(edge);
if (labels == null || !labels.contains(label)) {
// i.e. containsEdge(from, to, label)==false
return;
}
List<DGEdge<N>> edges = labelToEdges.get(label);
if (edges == null) {
// i.e. inconsistent data structures
throw new RuntimeException("label " + label + " not in graph!");
}
labels.remove(label);
edges.remove(edge);
// if this edge has no more labels, then it's gone!
if (labels.isEmpty()) {
edgeToLabels.remove(edge);
List<N> succsList = nodeToSuccs.get(from);
if (succsList == null) {
// i.e. inconsistent data structures
throw new RuntimeException(from + " not in graph!");
}
List<N> predsList = nodeToPreds.get(to);
if (predsList == null) {
// i.e. inconsistent data structures
throw new RuntimeException(to + " not in graph!");
}
succsList.remove(to);
predsList.remove(from);
if (succsList.isEmpty()) {
tails.add(from);
}
if (predsList.isEmpty()) {
heads.add(to);
}
}
// if this label has no more edges, then who cares?
if (edges.isEmpty()) {
labelToEdges.remove(label);
}
}
@Override
public void removeAllEdges(N from, N to) {
DGEdge<N> edge = new DGEdge<N>(from, to);
List<L> labels = edgeToLabels.get(edge);
if (labels == null || labels.isEmpty()) {
// i.e. containsAnyEdge(from, to)==false
return;
}
for (L label : getCopy(labels)) {
removeEdge(from, to, label);
}
}
@Override
public void removeAllEdges(L label) {
List<DGEdge<N>> edges = labelToEdges.get(label);
if (edges == null || edges.isEmpty()) {
// i.e. containsAnyEdge(label)==false
return;
}
for (DGEdge<N> edge : getCopy(edges)) {
removeEdge(edge.from(), edge.to(), label);
}
}
@Override
public boolean containsEdge(N from, N to, L label) {
List<L> labels = edgeToLabels.get(new DGEdge<>(from, to));
return labels != null && labels.contains(label);
}
@Override
public boolean containsAnyEdge(N from, N to) {
List<L> labels = edgeToLabels.get(new DGEdge<>(from, to));
return labels != null && !labels.isEmpty();
}
@Override
public boolean containsAnyEdge(L label) {
List<DGEdge<N>> edges = labelToEdges.get(label);
return edges != null && !edges.isEmpty();
}
@Override
public boolean containsNode(N node) {
return nodeToPreds.keySet().contains(node);
}
@Override
public void addNode(N node) {
if (containsNode(node)) {
throw new RuntimeException("Node already in graph");
}
nodeToSuccs.put(node, new ArrayList<N>());
nodeToPreds.put(node, new ArrayList<N>());
heads.add(node);
tails.add(node);
}
@Override
public void removeNode(N node) {
for (N n : new ArrayList<N>(nodeToSuccs.get(node))) {
removeAllEdges(node, n);
}
nodeToSuccs.remove(node);
for (N n : new ArrayList<N>(nodeToPreds.get(node))) {
removeAllEdges(n, node);
}
nodeToPreds.remove(node);
heads.remove(node);
tails.remove(node);
}
public void printGraph() {
for (N node : this) {
logger.debug("Node = " + node);
logger.debug("Preds:");
for (N pred : getPredsOf(node)) {
DGEdge<N> edge = new DGEdge<N>(pred, node);
List<L> labels = edgeToLabels.get(edge);
logger.debug(" " + pred + " [" + labels + "]");
}
logger.debug("Succs:");
for (N succ : getSuccsOf(node)) {
DGEdge<N> edge = new DGEdge<N>(node, succ);
List<L> labels = edgeToLabels.get(edge);
logger.debug(" " + succ + " [" + labels + "]");
}
}
}
}
| 10,630
| 25.120393
| 107
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/HashReversibleGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Navindra Umanee <navindra@cs.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.List;
/**
* A reversible version of HashMutableDirectedGraph
*
* @author Navindra Umanee
*
* @param <N>
*/
public class HashReversibleGraph<N> extends HashMutableDirectedGraph<N> implements ReversibleGraph<N> {
protected boolean reversed;
public HashReversibleGraph(DirectedGraph<N> dg) {
this();
for (N s : dg) {
addNode(s);
}
for (N s : dg) {
for (N t : dg.getSuccsOf(s)) {
addEdge(s, t);
}
}
/* use the same heads and tails as the original graph */
heads.clear();
heads.addAll(dg.getHeads());
tails.clear();
tails.addAll(dg.getTails());
}
public HashReversibleGraph() {
super();
reversed = false;
}
@Override
public boolean isReversed() {
return reversed;
}
@Override
public ReversibleGraph<N> reverse() {
reversed = !reversed;
return this;
}
@Override
public void addEdge(N from, N to) {
if (reversed) {
super.addEdge(to, from);
} else {
super.addEdge(from, to);
}
}
@Override
public void removeEdge(N from, N to) {
if (reversed) {
super.removeEdge(to, from);
} else {
super.removeEdge(from, to);
}
}
@Override
public boolean containsEdge(N from, N to) {
return reversed ? super.containsEdge(to, from) : super.containsEdge(from, to);
}
@Override
public List<N> getHeads() {
return reversed ? super.getTails() : super.getHeads();
}
@Override
public List<N> getTails() {
return reversed ? super.getHeads() : super.getTails();
}
@Override
public List<N> getPredsOf(N s) {
return reversed ? super.getSuccsOf(s) : super.getPredsOf(s);
}
@Override
public List<N> getSuccsOf(N s) {
return reversed ? super.getPredsOf(s) : super.getSuccsOf(s);
}
}
| 2,654
| 21.887931
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/InverseGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.List;
/**
* An inverted graph of a directed graph.
*
* @author Eric Bodden
*
* @param <N>
*/
public class InverseGraph<N> implements DirectedGraph<N> {
protected final DirectedGraph<N> g;
public InverseGraph(DirectedGraph<N> g) {
this.g = g;
}
/**
* {@inheritDoc}
*/
@Override
public List<N> getHeads() {
return g.getTails();
}
/**
* {@inheritDoc}
*/
@Override
public List<N> getPredsOf(N s) {
return g.getSuccsOf(s);
}
/**
* {@inheritDoc}
*/
@Override
public List<N> getSuccsOf(N s) {
return g.getPredsOf(s);
}
/**
* {@inheritDoc}
*/
@Override
public List<N> getTails() {
return g.getHeads();
}
/**
* {@inheritDoc}
*/
@Override
public Iterator<N> iterator() {
return g.iterator();
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return g.size();
}
}
| 1,762
| 18.373626
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/LoopNestTree.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.Comparator;
import java.util.TreeSet;
import soot.Body;
import soot.jimple.Stmt;
import soot.jimple.toolkits.annotation.logic.Loop;
import soot.jimple.toolkits.annotation.logic.LoopFinder;
/**
* A loop nesting tree, implemented as a tree-map. Loops are represented by pairs of head-statements and the respective loop.
* The iterator over this collection returns the loop in such an order that a loop l will always returned before a loop m if
* l is an inner loop of m.
*
* @author Eric Bodden
*/
public class LoopNestTree extends TreeSet<Loop> {
/**
* Comparator, stating that a loop l1 is smaller than a loop l2 if l2 contains all statements of l1.
*
* @author Eric Bodden
*/
private static class LoopNestTreeComparator implements Comparator<Loop> {
@Override
public int compare(Loop loop1, Loop loop2) {
Collection<Stmt> stmts1 = loop1.getLoopStatements();
Collection<Stmt> stmts2 = loop2.getLoopStatements();
if (stmts1.equals(stmts2)) {
assert loop1.getHead().equals(loop2.getHead()); // should really have the same head then
// equal (same) loops
return 0;
} else if (stmts1.containsAll(stmts2)) {
// 1 superset of 2
return 1;
} else if (stmts2.containsAll(stmts1)) {
// 1 subset of 2
return -1;
}
// overlap (?) or disjoint: order does not matter;
// however we must *not* return 0 as this would only keep one of the two loops;
// hence, return 1
return 1;
}
}
/**
* Builds a loop nest tree from a method body using {@link LoopFinder}.
*/
public LoopNestTree(Body b) {
this(computeLoops(b));
}
/**
* Builds a loop nest tree from a mapping from loop headers to statements in the loop.
*/
public LoopNestTree(Collection<Loop> loops) {
super(new LoopNestTreeComparator());
addAll(loops);
}
private static Collection<Loop> computeLoops(Body b) {
return new LoopFinder().getLoops(b);
}
public boolean hasNestedLoops() {
// TODO could be speeded up by just comparing two consecutive
// loops returned by the iterator
LoopNestTreeComparator comp = new LoopNestTreeComparator();
for (Loop loop1 : this) {
for (Loop loop2 : this) {
if (comp.compare(loop1, loop2) != 0) {
return true;
}
}
}
return false;
}
}
| 3,247
| 29.933333
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/MHGDominatorsFinder.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Navindra Umanee <navindra@cs.mcgill.ca>
* Copyright (C) 2007 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Calculate dominators for basic blocks.
* <p>
* Uses the algorithm contained in Dragon book, pg. 670-1.
*
* <pre>
* D(n0) := { n0 }
* for n in N - { n0 } do D(n) := N;
* while changes to any D(n) occur do
* for n in N - {n0} do
* D(n) := {n} U (intersect of D(p) over all predecessors p of n)
* </pre>
*
* 2007/07/03 - updated to use {@link BitSet}s instead of {@link HashSet}s, as the most expensive operation in this algorithm
* used to be cloning of the fullSet, which is very cheap for {@link BitSet}s.
*
* @author Navindra Umanee
* @author Eric Bodden
**/
public class MHGDominatorsFinder<N> implements DominatorsFinder<N> {
protected final DirectedGraph<N> graph;
protected final Set<N> heads;
protected final Map<N, BitSet> nodeToFlowSet;
protected final Map<N, Integer> nodeToIndex;
protected final Map<Integer, N> indexToNode;
protected int lastIndex = 0;
public MHGDominatorsFinder(DirectedGraph<N> graph) {
this.graph = graph;
this.heads = new HashSet<>(graph.getHeads());
int size = graph.size() * 2 + 1;
this.nodeToFlowSet = new HashMap<N, BitSet>(size, 0.7f);
this.nodeToIndex = new HashMap<N, Integer>(size, 0.7f);
this.indexToNode = new HashMap<Integer, N>(size, 0.7f);
doAnalysis();
}
protected void doAnalysis() {
final DirectedGraph<N> graph = this.graph;
// build full set
BitSet fullSet = new BitSet(graph.size());
fullSet.flip(0, graph.size());// set all to true
// set up domain for intersection: head nodes are only dominated by themselves,
// other nodes are dominated by everything else
for (N o : graph) {
if (heads.contains(o)) {
BitSet self = new BitSet();
self.set(indexOf(o));
nodeToFlowSet.put(o, self);
} else {
nodeToFlowSet.put(o, fullSet);
}
}
boolean changed;
do {
changed = false;
for (N o : graph) {
if (heads.contains(o)) {
continue;
}
// initialize to the "neutral element" for the intersection
// this clone() is fast on BitSets (opposed to on HashSets)
BitSet predsIntersect = (BitSet) fullSet.clone();
// intersect over all predecessors
for (N next : graph.getPredsOf(o)) {
predsIntersect.and(getDominatorsBitSet(next));
}
BitSet oldSet = getDominatorsBitSet(o);
// each node dominates itself
predsIntersect.set(indexOf(o));
if (!predsIntersect.equals(oldSet)) {
nodeToFlowSet.put(o, predsIntersect);
changed = true;
}
}
} while (changed);
}
protected BitSet getDominatorsBitSet(N node) {
BitSet bitSet = nodeToFlowSet.get(node);
assert (bitSet != null) : "Node " + node + " is not in the graph!";
return bitSet;
}
protected int indexOfAssert(N o) {
Integer index = nodeToIndex.get(o);
assert (index != null) : "Node " + o + " is not in the graph!";
return index;
}
protected int indexOf(N o) {
Integer index = nodeToIndex.get(o);
if (index == null) {
index = lastIndex;
nodeToIndex.put(o, index);
indexToNode.put(index, o);
lastIndex++;
}
return index;
}
@Override
public DirectedGraph<N> getGraph() {
return graph;
}
@Override
public List<N> getDominators(N node) {
// reconstruct list of dominators from bitset
List<N> result = new ArrayList<N>();
BitSet bitSet = getDominatorsBitSet(node);
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
result.add(indexToNode.get(i));
if (i == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
}
return result;
}
@Override
public N getImmediateDominator(N node) {
// root node
if (heads.contains(node)) {
return null;
}
BitSet doms = (BitSet) getDominatorsBitSet(node).clone();
doms.clear(indexOfAssert(node));
for (int i = doms.nextSetBit(0); i >= 0; i = doms.nextSetBit(i + 1)) {
N dominator = indexToNode.get(i);
if (isDominatedByAll(dominator, doms)) {
if (dominator != null) {
return dominator;
}
}
if (i == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
}
return null;
}
private boolean isDominatedByAll(N node, BitSet doms) {
BitSet s1 = getDominatorsBitSet(node);
for (int i = doms.nextSetBit(0); i >= 0; i = doms.nextSetBit(i + 1)) {
if (!s1.get(i)) {
return false;
}
if (i == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
}
return true;
}
@Override
public boolean isDominatedBy(N node, N dominator) {
return getDominatorsBitSet(node).get(indexOfAssert(dominator));
}
@Override
public boolean isDominatedByAll(N node, Collection<N> dominators) {
BitSet s1 = getDominatorsBitSet(node);
for (N n : dominators) {
if (!s1.get(indexOfAssert(n))) {
return false;
}
}
return true;
}
}
| 6,162
| 27.665116
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/MHGPostDominatorsFinder.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Post-dominators finder for multi-headed graph. The dominators returned by this finder are postdominators, so e.g.
* {@link #getDominators(Object)} returns all post-dominators.
*
* @author Eric Bodden
**/
public class MHGPostDominatorsFinder<N> extends MHGDominatorsFinder<N> {
public MHGPostDominatorsFinder(DirectedGraph<N> graph) {
super(new InverseGraph<N>(graph));
}
}
| 1,220
| 31.131579
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/MemoryEfficientGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2001 Felix Kwok
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of 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;
/**
* A memory efficient version of HashMutableDirectedGraph, in the sense that throw-away objects passed as arguments will not
* be kept in the process of adding edges.
*
* @param <N>
*/
public class MemoryEfficientGraph<N> extends HashMutableDirectedGraph<N> {
HashMap<N, N> self = new HashMap<N, N>();
@Override
public void addNode(N o) {
super.addNode(o);
self.put(o, o);
}
@Override
public void removeNode(N o) {
super.removeNode(o);
self.remove(o);
}
@Override
public void addEdge(N from, N to) {
if (containsNode(from) && containsNode(to)) {
super.addEdge(self.get(from), self.get(to));
} else if (!containsNode(from)) {
throw new RuntimeException(from.toString() + " not in graph!");
} else {
throw new RuntimeException(to.toString() + " not in graph!");
}
}
@Override
public void removeEdge(N from, N to) {
if (containsNode(from) && containsNode(to)) {
super.removeEdge(self.get(from), self.get(to));
} else if (!containsNode(from)) {
throw new RuntimeException(from.toString() + " not in graph!");
} else {
throw new RuntimeException(to.toString() + " not in graph!");
}
}
}
| 2,058
| 28
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/toolkits/graph/MutableDirectedGraph.java
|
package soot.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai, Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
/**
* Defines a DirectedGraph which is modifiable. Provides an interface to add/delete nodes and edges.
*
* @param <N>
*/
public interface MutableDirectedGraph<N> extends DirectedGraph<N> {
/**
* Adds an edge to the graph between 2 nodes. If the edge is already present no change is made.
*
* @param from
* out node for the edge.
* @param to
* in node for the edge.
*/
public void addEdge(N from, N to);
/**
* Removes an edge between 2 nodes in the graph. If the edge is not present no change is made.
*
* @param from
* out node for the edge to remove.
* @param to
* in node for the edge to remove.
*/
public void removeEdge(N from, N to);
/**
* @return true if the graph contains an edge the 2 nodes false otherwise.
*/
public boolean containsEdge(N from, N to);
/** @return a list of the nodes that compose the graph. No ordering is implied. */
public List<N> getNodes();
/**
* Adds a node to the graph. Initially the added node has no successors or predecessors. ; as a consequence it is
* considered both a head and tail for the graph.
*
* @param node
* a node to add to the graph.
* @see #getHeads
* @see #getTails
*/
public void addNode(N node);
/**
* Removes a node from the graph. If the node is not found in the graph, no change is made.
*
* @param node
* the node to be removed.
*/
public void removeNode(N node);
/**
* @param node
* node that we want to know if the graph constains.
* @return true if the graph contains the node. false otherwise.
*/
public boolean containsNode(N node);
}
| 2,588
| 28.758621
| 115
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.