repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/MoveInlineVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/MoveInlineVisitor.java | package jadx.core.dex.visitors;
import java.util.ArrayList;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.RegDebugInfoAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.dex.visitors.ssa.SSATransform;
import jadx.core.utils.InsnRemover;
@JadxVisitor(
name = "MoveInlineVisitor",
desc = "Inline redundant move instructions",
runAfter = SSATransform.class,
runBefore = CodeShrinkVisitor.class
)
public class MoveInlineVisitor extends AbstractVisitor {
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode()) {
return;
}
moveInline(mth);
}
public static void moveInline(MethodNode mth) {
InsnRemover remover = new InsnRemover(mth);
for (BlockNode block : mth.getBasicBlocks()) {
remover.setBlock(block);
for (InsnNode insn : block.getInstructions()) {
if (insn.getType() != InsnType.MOVE) {
continue;
}
if (processMove(mth, insn)) {
remover.addAndUnbind(insn);
}
}
remover.perform();
}
}
private static boolean processMove(MethodNode mth, InsnNode move) {
RegisterArg resultArg = move.getResult();
InsnArg moveArg = move.getArg(0);
if (resultArg.sameRegAndSVar(moveArg)) {
return true;
}
if (moveArg.isRegister()) {
RegisterArg moveReg = (RegisterArg) moveArg;
if (moveReg.getSVar().isAssignInPhi()) {
// don't mix already merged variables
return false;
}
}
SSAVar ssaVar = resultArg.getSVar();
if (ssaVar.getUseList().isEmpty()) {
// unused result
return true;
}
if (ssaVar.isUsedInPhi()) {
return false;
// TODO: review conditions of 'up' move inline (test TestMoveInline)
// return deleteMove(mth, move);
}
RegDebugInfoAttr debugInfo = moveArg.get(AType.REG_DEBUG_INFO);
for (RegisterArg useArg : ssaVar.getUseList()) {
InsnNode useInsn = useArg.getParentInsn();
if (useInsn == null) {
return false;
}
if (debugInfo == null) {
RegDebugInfoAttr debugInfoAttr = useArg.get(AType.REG_DEBUG_INFO);
if (debugInfoAttr != null) {
debugInfo = debugInfoAttr;
}
}
}
// all checks passed, execute inline
for (RegisterArg useArg : new ArrayList<>(ssaVar.getUseList())) {
InsnNode useInsn = useArg.getParentInsn();
if (useInsn == null) {
continue;
}
InsnArg replaceArg;
if (moveArg.isRegister()) {
replaceArg = ((RegisterArg) moveArg).duplicate(useArg.getInitType());
} else {
replaceArg = moveArg.duplicate();
}
useInsn.inheritMetadata(move);
replaceArg.copyAttributesFrom(useArg);
if (debugInfo != null) {
replaceArg.addAttr(debugInfo);
}
if (!useInsn.replaceArg(useArg, replaceArg)) {
mth.addWarnComment("Failed to replace arg in insn: " + useInsn);
}
}
return true;
}
private static boolean deleteMove(MethodNode mth, InsnNode move) {
InsnArg moveArg = move.getArg(0);
if (!moveArg.isRegister()) {
return false;
}
RegisterArg moveReg = (RegisterArg) moveArg;
SSAVar ssaVar = moveReg.getSVar();
if (ssaVar.getUseCount() != 1 || ssaVar.isUsedInPhi()) {
return false;
}
RegisterArg assignArg = ssaVar.getAssign();
InsnNode parentInsn = assignArg.getParentInsn();
if (parentInsn == null) {
return false;
}
if (parentInsn.getSourceLine() != move.getSourceLine()
|| moveArg.contains(AType.REG_DEBUG_INFO)) {
// preserve debug info
return false;
}
// set move result into parent insn result
InsnRemover.unbindAllArgs(mth, move);
InsnRemover.unbindResult(mth, parentInsn);
RegisterArg resArg = parentInsn.getResult();
RegisterArg newResArg = move.getResult().duplicate(resArg.getInitType());
newResArg.copyAttributesFrom(resArg);
parentInsn.setResult(newResArg);
return true;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/ConstructorVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/ConstructorVisitor.java | package jadx.core.dex.visitors;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import jadx.core.codegen.TypeGen;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.ssa.SSATransform;
import jadx.core.dex.visitors.typeinference.TypeInferenceVisitor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.exceptions.JadxRuntimeException;
@JadxVisitor(
name = "ConstructorVisitor",
desc = "Replace invoke with constructor call",
runAfter = { SSATransform.class, MoveInlineVisitor.class },
runBefore = TypeInferenceVisitor.class
)
public class ConstructorVisitor extends AbstractVisitor {
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode()) {
return;
}
if (replaceInvoke(mth)) {
MoveInlineVisitor.moveInline(mth);
}
}
private static boolean replaceInvoke(MethodNode mth) {
boolean replaced = false;
InsnRemover remover = new InsnRemover(mth);
for (BlockNode block : mth.getBasicBlocks()) {
remover.setBlock(block);
int size = block.getInstructions().size();
for (int i = 0; i < size; i++) {
InsnNode insn = block.getInstructions().get(i);
if (insn.getType() == InsnType.INVOKE) {
replaced |= processInvoke(mth, block, i, remover);
}
}
remover.perform();
}
return replaced;
}
private static boolean processInvoke(MethodNode mth, BlockNode block, int indexInBlock, InsnRemover remover) {
InvokeNode inv = (InvokeNode) block.getInstructions().get(indexInBlock);
MethodInfo callMth = inv.getCallMth();
if (!callMth.isConstructor()) {
return false;
}
ArgType instType = searchInstanceType(inv);
if (instType != null && !instType.equals(callMth.getDeclClass().getType())) {
ClassInfo instCls = ClassInfo.fromType(mth.root(), instType);
callMth = MethodInfo.fromDetails(mth.root(), instCls, callMth.getName(),
callMth.getArgumentsTypes(), callMth.getReturnType());
}
ConstructorInsn co = new ConstructorInsn(mth, inv, callMth);
if (canRemoveConstructor(mth, co)) {
remover.addAndUnbind(inv);
return false;
}
co.inheritMetadata(inv);
RegisterArg instanceArg = (RegisterArg) inv.getArg(0);
instanceArg.getSVar().removeUse(instanceArg);
if (co.isNewInstance()) {
InsnNode assignInsn = instanceArg.getAssignInsn();
if (assignInsn != null) {
if (assignInsn.getType() == InsnType.CONSTRUCTOR) {
// arg already used in another constructor instruction
// insert new PHI insn to merge these branched constructors results
instanceArg = insertPhiInsn(mth, block, instanceArg, ((ConstructorInsn) assignInsn));
} else {
InsnNode newInstInsn = removeAssignChain(mth, assignInsn, remover, InsnType.NEW_INSTANCE);
if (newInstInsn != null) {
co.inheritMetadata(newInstInsn);
newInstInsn.add(AFlag.REMOVE);
remover.addWithoutUnbind(newInstInsn);
}
}
}
// convert instance arg from 'use' to 'assign'
co.setResult(instanceArg.duplicate());
}
co.rebindArgs();
ConstructorInsn replace = processConstructor(mth, co);
if (replace != null) {
remover.addAndUnbind(co);
BlockUtils.replaceInsn(mth, block, indexInBlock, replace);
} else {
BlockUtils.replaceInsn(mth, block, indexInBlock, co);
}
return true;
}
private static @Nullable ArgType searchInstanceType(InvokeNode inv) {
InsnArg instanceArg = inv.getInstanceArg();
if (instanceArg == null || !instanceArg.isRegister()) {
return null;
}
InsnNode assignInsn = ((RegisterArg) instanceArg).getSVar().getAssignInsn();
if (assignInsn == null || assignInsn.getType() != InsnType.NEW_INSTANCE) {
return null;
}
return ((IndexInsnNode) assignInsn).getIndexAsType();
}
private static RegisterArg insertPhiInsn(MethodNode mth, BlockNode curBlock,
RegisterArg instArg, ConstructorInsn otherCtr) {
BlockNode otherBlock = BlockUtils.getBlockByInsn(mth, otherCtr);
if (otherBlock == null) {
throw new JadxRuntimeException("Block not found by insn: " + otherCtr);
}
BlockNode crossBlock = BlockUtils.getPathCross(mth, curBlock, otherBlock);
if (crossBlock == null) {
// no path cross => PHI insn not needed
// use new SSA var on usage from current path
RegisterArg newResArg = instArg.duplicateWithNewSSAVar(mth);
List<BlockNode> pathBlocks = BlockUtils.collectAllSuccessors(mth, curBlock, true);
for (RegisterArg useReg : instArg.getSVar().getUseList()) {
InsnNode parentInsn = useReg.getParentInsn();
if (parentInsn != null) {
BlockNode useBlock = BlockUtils.getBlockByInsn(mth, parentInsn, pathBlocks);
if (useBlock != null) {
parentInsn.replaceArg(useReg, newResArg.duplicate());
}
}
}
return newResArg;
}
RegisterArg newResArg = instArg.duplicateWithNewSSAVar(mth);
RegisterArg useArg = otherCtr.getResult();
RegisterArg otherResArg = useArg.duplicateWithNewSSAVar(mth);
PhiInsn phiInsn = SSATransform.addPhi(mth, crossBlock, useArg.getRegNum());
phiInsn.setResult(useArg.duplicate());
phiInsn.bindArg(newResArg.duplicate(), BlockUtils.getPrevBlockOnPath(mth, crossBlock, curBlock));
phiInsn.bindArg(otherResArg.duplicate(), BlockUtils.getPrevBlockOnPath(mth, crossBlock, otherBlock));
phiInsn.rebindArgs();
otherCtr.setResult(otherResArg.duplicate());
otherCtr.rebindArgs();
return newResArg;
}
private static boolean canRemoveConstructor(MethodNode mth, ConstructorInsn co) {
ClassNode parentClass = mth.getParentClass();
if (co.isSuper() && (co.getArgsCount() == 0 || parentClass.isEnum())) {
return true;
}
if (co.isThis() && co.getArgsCount() == 0) {
MethodNode defCo = parentClass.searchMethodByShortId(co.getCallMth().getShortId());
if (defCo == null || defCo.isNoCode()) {
// default constructor not implemented
return true;
}
}
// remove super() call in instance initializer
return parentClass.isAnonymous() && mth.isDefaultConstructor() && co.isSuper();
}
/**
* Replace call of synthetic constructor with all 'null' args
* to a non-synthetic or default constructor if possible.
*
* @return insn for replacement or null if replace not needed or not possible.
*/
@Nullable
private static ConstructorInsn processConstructor(MethodNode mth, ConstructorInsn co) {
MethodNode callMth = mth.root().resolveMethod(co.getCallMth());
if (callMth == null
|| !callMth.getAccessFlags().isSynthetic()
|| !allArgsNull(co)) {
return null;
}
ClassNode classNode = mth.root().resolveClass(callMth.getParentClass().getClassInfo());
if (classNode == null) {
return null;
}
RegisterArg instanceArg = co.getResult();
if (instanceArg == null) {
return null;
}
boolean passThis = instanceArg.isThis();
String ctrId = "<init>(" + (passThis ? TypeGen.signature(instanceArg.getInitType()) : "") + ")V";
MethodNode defCtr = classNode.searchMethodByShortId(ctrId);
if (defCtr == null || defCtr.equals(callMth) || defCtr.getAccessFlags().isSynthetic()) {
return null;
}
ConstructorInsn newInsn = new ConstructorInsn(defCtr.getMethodInfo(), co.getCallType());
newInsn.setResult(co.getResult().duplicate());
newInsn.inheritMetadata(co);
return newInsn;
}
private static boolean allArgsNull(ConstructorInsn insn) {
for (InsnArg insnArg : insn.getArguments()) {
if (insnArg.isLiteral()) {
LiteralArg lit = (LiteralArg) insnArg;
if (lit.getLiteral() != 0) {
return false;
}
} else {
return false;
}
}
return true;
}
/**
* Remove instructions on 'move' chain until instruction with type 'insnType'
*/
private static InsnNode removeAssignChain(MethodNode mth, InsnNode insn, InsnRemover remover, InsnType insnType) {
if (insn == null) {
return null;
}
InsnType type = insn.getType();
if (type == insnType) {
return insn;
}
if (insn.isAttrStorageEmpty()) {
remover.addWithoutUnbind(insn);
} else {
BlockUtils.replaceInsn(mth, insn, new InsnNode(InsnType.NOP, 0));
}
if (type == InsnType.MOVE) {
RegisterArg arg = (RegisterArg) insn.getArg(0);
return removeAssignChain(mth, arg.getAssignInsn(), remover, insnType);
}
return null;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/ClassModifier.java | jadx-core/src/main/java/jadx/core/dex/visitors/ClassModifier.java | package jadx.core.dex.visitors;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.core.Consts;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.FieldReplaceAttr;
import jadx.core.dex.attributes.nodes.MethodReplaceAttr;
import jadx.core.dex.attributes.nodes.RenameReasonAttr;
import jadx.core.dex.attributes.nodes.SkipMethodArgsAttr;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.InvokeType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.fixaccessmodifiers.FixAccessModifiers;
import jadx.core.dex.visitors.usage.UsageInfoVisitor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "ClassModifier",
desc = "Remove synthetic classes, methods and fields",
runAfter = {
ModVisitor.class,
FixAccessModifiers.class,
ProcessAnonymous.class
}
)
public class ClassModifier extends AbstractVisitor {
@Override
public boolean visit(ClassNode cls) throws JadxException {
if (cls.contains(AFlag.PACKAGE_INFO)) {
return false;
}
for (ClassNode inner : cls.getInnerClasses()) {
visit(inner);
}
if (isEmptySyntheticClass(cls)) {
cls.add(AFlag.DONT_GENERATE);
return false;
}
removeSyntheticFields(cls);
cls.getMethods().forEach(ClassModifier::removeSyntheticMethods);
cls.getMethods().forEach(ClassModifier::removeEmptyMethods);
return false;
}
private static boolean isEmptySyntheticClass(ClassNode cls) {
return cls.getAccessFlags().isSynthetic()
&& cls.getFields().isEmpty()
&& cls.getMethods().isEmpty()
&& cls.getInnerClasses().isEmpty();
}
/**
* Remove synthetic fields if type is outer class or class will be inlined (anonymous)
*/
private static void removeSyntheticFields(ClassNode cls) {
boolean inline = cls.isAnonymous();
if (inline || cls.getClassInfo().isInner()) {
for (FieldNode field : cls.getFields()) {
ArgType fldType = field.getType();
if (field.getAccessFlags().isSynthetic() && fldType.isObject() && !fldType.isGenericType()) {
ClassInfo clsInfo = ClassInfo.fromType(cls.root(), fldType);
ClassNode fieldsCls = cls.root().resolveClass(clsInfo);
ClassInfo parentClass = cls.getClassInfo().getParentClass();
if (fieldsCls == null) {
continue;
}
boolean isParentInst = Objects.equals(parentClass, fieldsCls.getClassInfo());
if (inline || isParentInst) {
int found = 0;
for (MethodNode mth : cls.getMethods()) {
if (removeFieldUsageFromConstructor(mth, field, fieldsCls)) {
found++;
}
}
if (found != 0) {
if (isParentInst) {
field.addAttr(new FieldReplaceAttr(fieldsCls.getClassInfo()));
}
field.add(AFlag.DONT_GENERATE);
}
}
}
}
}
}
private static boolean removeFieldUsageFromConstructor(MethodNode mth, FieldNode field, ClassNode fieldsCls) {
if (mth.isNoCode() || !mth.getAccessFlags().isConstructor()) {
return false;
}
List<RegisterArg> args = mth.getArgRegs();
if (args.isEmpty() || mth.contains(AFlag.SKIP_FIRST_ARG)) {
return false;
}
RegisterArg arg = args.get(0);
if (!arg.getType().equals(fieldsCls.getClassInfo().getType())) {
return false;
}
BlockNode block = mth.getEnterBlock().getCleanSuccessors().get(0);
List<InsnNode> instructions = block.getInstructions();
if (instructions.isEmpty()) {
return false;
}
InsnNode insn = instructions.get(0);
if (insn.getType() != InsnType.IPUT) {
return false;
}
IndexInsnNode putInsn = (IndexInsnNode) insn;
FieldInfo fieldInfo = (FieldInfo) putInsn.getIndex();
if (!fieldInfo.equals(field.getFieldInfo()) || !putInsn.getArg(0).equals(arg)) {
return false;
}
mth.skipFirstArgument();
InsnRemover.remove(mth, block, insn);
// other arg usage -> wrap with IGET insn
if (arg.getSVar().getUseCount() != 0) {
InsnNode iget = new IndexInsnNode(InsnType.IGET, fieldInfo, 1);
iget.addArg(insn.getArg(1));
for (InsnArg insnArg : new ArrayList<>(arg.getSVar().getUseList())) {
insnArg.wrapInstruction(mth, iget);
}
}
return true;
}
private static void removeSyntheticMethods(MethodNode mth) {
if (mth.isNoCode() || mth.contains(AFlag.DONT_GENERATE)) {
return;
}
AccessInfo af = mth.getAccessFlags();
if (!af.isSynthetic()) {
return;
}
ClassNode cls = mth.getParentClass();
if (removeBridgeMethod(cls, mth)) {
if (Consts.DEBUG) {
mth.addDebugComment("Removed as synthetic bridge method");
} else {
mth.add(AFlag.DONT_GENERATE);
}
return;
}
// remove synthetic constructor for inner classes
if (mth.isConstructor()
&& (mth.contains(AFlag.METHOD_CANDIDATE_FOR_INLINE) || mth.contains(AFlag.ANONYMOUS_CONSTRUCTOR))) {
InsnNode insn = BlockUtils.getOnlyOneInsnFromMth(mth);
if (insn != null) {
List<RegisterArg> args = mth.getArgRegs();
if (isRemovedClassInArgs(cls, args)) {
modifySyntheticMethod(cls, mth, insn, args);
}
}
}
}
private static boolean isRemovedClassInArgs(ClassNode cls, List<RegisterArg> mthArgs) {
boolean removedFound = false;
for (RegisterArg arg : mthArgs) {
ArgType argType = arg.getType();
if (!argType.isObject()) {
continue;
}
boolean remove = false;
ClassNode argCls = cls.root().resolveClass(argType);
if (argCls == null) {
// check if missing class from current top class
ClassInfo argClsInfo = ClassInfo.fromType(cls.root(), argType);
if (argClsInfo.getParentClass() != null
&& cls.getFullName().startsWith(argClsInfo.getParentClass().getFullName())) {
remove = true;
}
} else {
if (argCls.contains(AFlag.DONT_GENERATE) || isEmptySyntheticClass(argCls)) {
remove = true;
}
}
if (remove) {
arg.add(AFlag.REMOVE);
removedFound = true;
}
}
return removedFound;
}
/**
* Remove synthetic constructor and redirect calls to existing constructor
*/
private static void modifySyntheticMethod(ClassNode cls, MethodNode mth, InsnNode insn, List<RegisterArg> args) {
if (insn.getType() == InsnType.CONSTRUCTOR) {
ConstructorInsn constr = (ConstructorInsn) insn;
if (constr.isThis() && !args.isEmpty()) {
// remove first arg for non-static class (references to outer class)
RegisterArg firstArg = args.get(0);
if (firstArg.getType().equals(cls.getParentClass().getClassInfo().getType())) {
SkipMethodArgsAttr.skipArg(mth, 0);
}
// remove unused args
int argsCount = args.size();
for (int i = 0; i < argsCount; i++) {
RegisterArg arg = args.get(i);
SSAVar sVar = arg.getSVar();
if (sVar != null && sVar.getUseCount() == 0) {
SkipMethodArgsAttr.skipArg(mth, i);
}
}
MethodInfo callMth = constr.getCallMth();
MethodNode callMthNode = cls.root().resolveMethod(callMth);
if (callMthNode != null) {
mth.addAttr(new MethodReplaceAttr(callMthNode));
mth.add(AFlag.DONT_GENERATE);
// code generation order should be already fixed for marked methods
UsageInfoVisitor.replaceMethodUsage(callMthNode, mth);
}
}
}
}
private static boolean removeBridgeMethod(ClassNode cls, MethodNode mth) {
if (cls.root().getArgs().isInlineMethods()) { // simple wrapper remove is same as inline
List<InsnNode> allInsns = BlockUtils.collectAllInsns(mth.getBasicBlocks());
if (allInsns.size() == 1) {
InsnNode wrappedInsn = allInsns.get(0);
if (wrappedInsn.getType() == InsnType.RETURN) {
InsnArg arg = wrappedInsn.getArg(0);
if (arg.isInsnWrap()) {
wrappedInsn = ((InsnWrapArg) arg).getWrapInsn();
}
}
return checkSyntheticWrapper(mth, wrappedInsn);
}
}
return false;
}
private static boolean checkSyntheticWrapper(MethodNode mth, InsnNode insn) {
InsnType insnType = insn.getType();
if (insnType != InsnType.INVOKE) {
return false;
}
InvokeNode invokeInsn = (InvokeNode) insn;
if (invokeInsn.getInvokeType() == InvokeType.SUPER) {
return false;
}
MethodInfo callMth = invokeInsn.getCallMth();
MethodNode wrappedMth = mth.root().resolveMethod(callMth);
if (wrappedMth == null) {
return false;
}
AccessInfo wrappedAccFlags = wrappedMth.getAccessFlags();
if (wrappedAccFlags.isStatic()) {
return false;
}
if (callMth.getArgsCount() != mth.getMethodInfo().getArgsCount()) {
return false;
}
// rename method only from current class
if (!mth.getParentClass().equals(wrappedMth.getParentClass())) {
return false;
}
// all args must be registers passed from method args (allow only casts insns)
for (InsnArg arg : insn.getArguments()) {
if (!registersAndCastsOnly(arg)) {
return false;
}
}
// remove confirmed, change visibility and name if needed
if (!wrappedAccFlags.isPublic() && !mth.root().getArgs().isRespectBytecodeAccModifiers()) {
// must be public
FixAccessModifiers.changeVisibility(wrappedMth, AccessFlags.PUBLIC);
}
String alias = mth.getAlias();
if (!Objects.equals(wrappedMth.getAlias(), alias)) {
wrappedMth.rename(alias);
RenameReasonAttr.forNode(wrappedMth).append("merged with bridge method [inline-methods]");
}
wrappedMth.addAttr(new MethodReplaceAttr(mth));
wrappedMth.copyAttributeFrom(mth, AType.METHOD_OVERRIDE);
wrappedMth.addDebugComment("Method merged with bridge method: " + mth.getMethodInfo().getShortId());
return true;
}
private static boolean registersAndCastsOnly(InsnArg arg) {
if (arg.isRegister()) {
return true;
}
if (arg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
if (wrapInsn.getType() == InsnType.CHECK_CAST) {
return registersAndCastsOnly(wrapInsn.getArg(0));
}
}
return false;
}
/**
* Remove public empty constructors (static or default)
*/
private static void removeEmptyMethods(MethodNode mth) {
if (!mth.getArgRegs().isEmpty()) {
return;
}
AccessInfo af = mth.getAccessFlags();
boolean publicConstructor = mth.isConstructor() && af.isPublic();
boolean clsInit = mth.getMethodInfo().isClassInit() && af.isStatic();
if (publicConstructor || clsInit) {
if (!BlockUtils.isAllBlocksEmpty(mth.getBasicBlocks())) {
return;
}
if (clsInit) {
mth.add(AFlag.DONT_GENERATE);
} else {
// don't remove default constructor if other constructors exists or constructor has annotations
if (mth.isDefaultConstructor()
&& !isNonDefaultConstructorExists(mth)
&& !mth.contains(JadxAttrType.ANNOTATION_LIST)) {
mth.add(AFlag.DONT_GENERATE);
}
}
}
}
private static boolean isNonDefaultConstructorExists(MethodNode defCtor) {
ClassNode parentClass = defCtor.getParentClass();
for (MethodNode mth : parentClass.getMethods()) {
if (mth != defCtor
&& mth.isConstructor()
&& !mth.isDefaultConstructor()) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/OverrideMethodVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/OverrideMethodVisitor.java | package jadx.core.dex.visitors;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import jadx.core.clsp.ClspClass;
import jadx.core.clsp.ClspMethod;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.MethodBridgeAttr;
import jadx.core.dex.attributes.nodes.MethodOverrideAttr;
import jadx.core.dex.attributes.nodes.RenameReasonAttr;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.IMethodDetails;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.rename.RenameVisitor;
import jadx.core.dex.visitors.typeinference.TypeCompare;
import jadx.core.dex.visitors.typeinference.TypeCompareEnum;
import jadx.core.dex.visitors.typeinference.TypeInferenceVisitor;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxException;
import jadx.core.utils.exceptions.JadxRuntimeException;
@JadxVisitor(
name = "OverrideMethodVisitor",
desc = "Mark override methods and revert type erasure",
runBefore = {
TypeInferenceVisitor.class,
RenameVisitor.class
}
)
public class OverrideMethodVisitor extends AbstractVisitor {
@Override
public boolean visit(ClassNode cls) throws JadxException {
SuperTypesData superData = collectSuperTypes(cls);
if (superData != null) {
for (MethodNode mth : cls.getMethods()) {
processMth(mth, superData);
}
}
return true;
}
private void processMth(MethodNode mth, SuperTypesData superData) {
if (mth.isConstructor() || mth.getAccessFlags().isStatic() || mth.getAccessFlags().isPrivate()) {
return;
}
MethodOverrideAttr attr = processOverrideMethods(mth, superData);
if (attr != null) {
if (attr.getBaseMethods().isEmpty()) {
throw new JadxRuntimeException("No base methods for override attribute: " + attr.getOverrideList());
}
mth.addAttr(attr);
IMethodDetails baseMth = Utils.getOne(attr.getBaseMethods());
if (baseMth != null) {
boolean updated = fixMethodReturnType(mth, baseMth, superData);
updated |= fixMethodArgTypes(mth, baseMth, superData);
if (updated) {
// check if new signature cause method collisions
checkMethodSignatureCollisions(mth, mth.root().getArgs().isRenameValid());
}
}
}
}
private MethodOverrideAttr processOverrideMethods(MethodNode mth, SuperTypesData superData) {
MethodOverrideAttr result = mth.get(AType.METHOD_OVERRIDE);
if (result != null) {
return result;
}
ClassNode cls = mth.getParentClass();
String signature = mth.getMethodInfo().makeSignature(false);
List<IMethodDetails> overrideList = new ArrayList<>();
Set<IMethodDetails> baseMethods = new HashSet<>();
for (ArgType superType : superData.getSuperTypes()) {
ClassNode classNode = mth.root().resolveClass(superType);
if (classNode != null) {
MethodNode ovrdMth = searchOverriddenMethod(classNode, mth, signature);
if (ovrdMth != null) {
if (isMethodVisibleInCls(ovrdMth, cls)) {
overrideList.add(ovrdMth);
MethodOverrideAttr attr = ovrdMth.get(AType.METHOD_OVERRIDE);
if (attr != null) {
addBaseMethod(superData, overrideList, baseMethods, superType);
return buildOverrideAttr(mth, overrideList, baseMethods, attr);
}
}
}
} else {
ClspClass clsDetails = mth.root().getClsp().getClsDetails(superType);
if (clsDetails != null) {
Map<String, ClspMethod> methodsMap = clsDetails.getMethodsMap();
for (Map.Entry<String, ClspMethod> entry : methodsMap.entrySet()) {
String mthShortId = entry.getKey();
// do not check full signature, classpath methods can be trusted
// i.e. doesn't contain methods with same signature in one class
if (mthShortId.startsWith(signature)) {
overrideList.add(entry.getValue());
break;
}
}
}
}
addBaseMethod(superData, overrideList, baseMethods, superType);
}
return buildOverrideAttr(mth, overrideList, baseMethods, null);
}
private void addBaseMethod(SuperTypesData superData, List<IMethodDetails> overrideList, Set<IMethodDetails> baseMethods,
ArgType superType) {
if (superData.getEndTypes().contains(superType.getObject())) {
IMethodDetails last = Utils.last(overrideList);
if (last != null) {
baseMethods.add(last);
}
}
}
@Nullable
private MethodNode searchOverriddenMethod(ClassNode cls, MethodNode mth, String signature) {
// search by exact full signature (with return value) to fight obfuscation (see test
// 'TestOverrideWithSameName')
String shortId = mth.getMethodInfo().getShortId();
for (MethodNode supMth : cls.getMethods()) {
if (supMth.getMethodInfo().getShortId().equals(shortId) && !supMth.getAccessFlags().isStatic()) {
return supMth;
}
}
// search by signature without return value and check if return value is wider type
for (MethodNode supMth : cls.getMethods()) {
if (supMth.getMethodInfo().getShortId().startsWith(signature) && !supMth.getAccessFlags().isStatic()) {
TypeCompare typeCompare = cls.root().getTypeCompare();
ArgType supRetType = supMth.getMethodInfo().getReturnType();
ArgType mthRetType = mth.getMethodInfo().getReturnType();
TypeCompareEnum res = typeCompare.compareTypes(supRetType, mthRetType);
if (res.isWider()) {
return supMth;
}
if (res == TypeCompareEnum.UNKNOWN || res == TypeCompareEnum.CONFLICT) {
mth.addDebugComment("Possible override for method " + supMth.getMethodInfo().getFullId());
}
}
}
return null;
}
@Nullable
private MethodOverrideAttr buildOverrideAttr(MethodNode mth, List<IMethodDetails> overrideList,
Set<IMethodDetails> baseMethods, @Nullable MethodOverrideAttr attr) {
if (overrideList.isEmpty() && attr == null) {
return null;
}
if (attr == null) {
// traced to base method
List<IMethodDetails> cleanOverrideList = overrideList.stream().distinct().collect(Collectors.toList());
return applyOverrideAttr(mth, cleanOverrideList, baseMethods, false);
}
// trace stopped at already processed method -> start merging
List<IMethodDetails> mergedOverrideList = Utils.mergeLists(overrideList, attr.getOverrideList());
List<IMethodDetails> cleanOverrideList = mergedOverrideList.stream().distinct().collect(Collectors.toList());
Set<IMethodDetails> mergedBaseMethods = Utils.mergeSets(baseMethods, attr.getBaseMethods());
return applyOverrideAttr(mth, cleanOverrideList, mergedBaseMethods, true);
}
private MethodOverrideAttr applyOverrideAttr(MethodNode mth, List<IMethodDetails> overrideList,
Set<IMethodDetails> baseMethods, boolean update) {
// don't rename method if override list contains not resolved method
boolean dontRename = overrideList.stream().anyMatch(m -> !(m instanceof MethodNode));
SortedSet<MethodNode> relatedMethods = null;
List<MethodNode> mthNodes = getMethodNodes(mth, overrideList);
if (update) {
// merge related methods from all override attributes
for (MethodNode mthNode : mthNodes) {
MethodOverrideAttr ovrdAttr = mthNode.get(AType.METHOD_OVERRIDE);
if (ovrdAttr != null) {
// use one of already allocated sets
relatedMethods = ovrdAttr.getRelatedMthNodes();
break;
}
}
if (relatedMethods != null) {
relatedMethods.addAll(mthNodes);
} else {
relatedMethods = new TreeSet<>(mthNodes);
}
for (MethodNode mthNode : mthNodes) {
MethodOverrideAttr ovrdAttr = mthNode.get(AType.METHOD_OVERRIDE);
if (ovrdAttr != null) {
SortedSet<MethodNode> set = ovrdAttr.getRelatedMthNodes();
if (relatedMethods != set) {
relatedMethods.addAll(set);
}
}
}
} else {
relatedMethods = new TreeSet<>(mthNodes);
}
int depth = 0;
for (MethodNode mthNode : mthNodes) {
if (dontRename) {
mthNode.add(AFlag.DONT_RENAME);
}
if (depth == 0) {
// skip current (first) method
depth = 1;
continue;
}
if (update) {
MethodOverrideAttr ovrdAttr = mthNode.get(AType.METHOD_OVERRIDE);
if (ovrdAttr != null) {
ovrdAttr.setRelatedMthNodes(relatedMethods);
continue;
}
}
mthNode.addAttr(new MethodOverrideAttr(Utils.listTail(overrideList, depth), relatedMethods, baseMethods));
depth++;
}
return new MethodOverrideAttr(overrideList, relatedMethods, baseMethods);
}
@NotNull
private List<MethodNode> getMethodNodes(MethodNode mth, List<IMethodDetails> overrideList) {
List<MethodNode> list = new ArrayList<>(1 + overrideList.size());
list.add(mth);
for (IMethodDetails md : overrideList) {
if (md instanceof MethodNode) {
list.add((MethodNode) md);
}
}
return list;
}
/**
* NOTE: Simplified version of method from ModVisitor.isFieldVisibleInMethod
*/
private boolean isMethodVisibleInCls(MethodNode superMth, ClassNode cls) {
AccessInfo accessFlags = superMth.getAccessFlags();
if (accessFlags.isPrivate()) {
return false;
}
if (accessFlags.isPublic() || accessFlags.isProtected()) {
return true;
}
// package-private
return Objects.equals(superMth.getParentClass().getPackage(), cls.getPackage());
}
private static final class SuperTypesData {
private final List<ArgType> superTypes;
private final Set<String> endTypes;
private SuperTypesData(List<ArgType> superTypes, Set<String> endTypes) {
this.superTypes = superTypes;
this.endTypes = endTypes;
}
public List<ArgType> getSuperTypes() {
return superTypes;
}
public Set<String> getEndTypes() {
return endTypes;
}
}
@Nullable
private SuperTypesData collectSuperTypes(ClassNode cls) {
Set<ArgType> superTypes = new LinkedHashSet<>();
Set<String> endTypes = new HashSet<>();
collectSuperTypes(cls, superTypes, endTypes);
if (superTypes.isEmpty()) {
return null;
}
if (endTypes.isEmpty()) {
throw new JadxRuntimeException("No end types in class hierarchy: " + cls);
}
return new SuperTypesData(new ArrayList<>(superTypes), endTypes);
}
private void collectSuperTypes(ClassNode cls, Set<ArgType> superTypes, Set<String> endTypes) {
RootNode root = cls.root();
int k = 0;
ArgType superClass = cls.getSuperClass();
if (superClass != null) {
k += addSuperType(root, superTypes, endTypes, superClass);
}
for (ArgType iface : cls.getInterfaces()) {
k += addSuperType(root, superTypes, endTypes, iface);
}
if (k == 0) {
endTypes.add(cls.getType().getObject());
}
}
private int addSuperType(RootNode root, Set<ArgType> superTypes, Set<String> endTypes, ArgType superType) {
if (Objects.equals(superType, ArgType.OBJECT)) {
return 0;
}
if (!superTypes.add(superType)) {
// found 'super' loop, stop processing
return 0;
}
ClassNode classNode = root.resolveClass(superType);
if (classNode != null) {
collectSuperTypes(classNode, superTypes, endTypes);
return 1;
}
ClspClass clsDetails = root.getClsp().getClsDetails(superType);
if (clsDetails != null) {
int k = 0;
for (ArgType parentType : clsDetails.getParents()) {
k += addSuperType(root, superTypes, endTypes, parentType);
}
if (k == 0) {
endTypes.add(superType.getObject());
}
return 1;
}
// no info found => treat as hierarchy end
endTypes.add(superType.getObject());
return 1;
}
private boolean fixMethodReturnType(MethodNode mth, IMethodDetails baseMth, SuperTypesData superData) {
ArgType returnType = mth.getReturnType();
if (returnType == ArgType.VOID) {
return false;
}
boolean updated = updateReturnType(mth, baseMth, superData);
if (updated) {
mth.addDebugComment("Return type fixed from '" + returnType + "' to match base method");
}
return updated;
}
private boolean updateReturnType(MethodNode mth, IMethodDetails baseMth, SuperTypesData superData) {
ArgType baseReturnType = baseMth.getReturnType();
if (mth.getReturnType().equals(baseReturnType)) {
return false;
}
if (!baseReturnType.containsTypeVariable()) {
return false;
}
TypeCompare typeCompare = mth.root().getTypeUpdate().getTypeCompare();
ArgType baseCls = baseMth.getMethodInfo().getDeclClass().getType();
for (ArgType superType : superData.getSuperTypes()) {
TypeCompareEnum compareResult = typeCompare.compareTypes(superType, baseCls);
if (compareResult == TypeCompareEnum.NARROW_BY_GENERIC) {
ArgType targetRetType = mth.root().getTypeUtils().replaceClassGenerics(superType, baseReturnType);
if (targetRetType != null
&& !targetRetType.containsTypeVariable()
&& !targetRetType.equals(mth.getReturnType())) {
mth.updateReturnType(targetRetType);
return true;
}
}
}
return false;
}
private boolean fixMethodArgTypes(MethodNode mth, IMethodDetails baseMth, SuperTypesData superData) {
List<ArgType> mthArgTypes = mth.getArgTypes();
List<ArgType> baseArgTypes = baseMth.getArgTypes();
if (mthArgTypes.equals(baseArgTypes)) {
return false;
}
int argCount = mthArgTypes.size();
if (argCount != baseArgTypes.size()) {
return false;
}
boolean changed = false;
List<ArgType> newArgTypes = new ArrayList<>(argCount);
for (int argNum = 0; argNum < argCount; argNum++) {
ArgType newType = updateArgType(mth, baseMth, superData, argNum);
if (newType != null) {
changed = true;
newArgTypes.add(newType);
} else {
newArgTypes.add(mthArgTypes.get(argNum));
}
}
if (changed) {
mth.updateArgTypes(newArgTypes, "Method arguments types fixed to match base method");
}
return changed;
}
private ArgType updateArgType(MethodNode mth, IMethodDetails baseMth, SuperTypesData superData, int argNum) {
ArgType arg = mth.getArgTypes().get(argNum);
ArgType baseArg = baseMth.getArgTypes().get(argNum);
if (arg.equals(baseArg)) {
return null;
}
if (!baseArg.containsTypeVariable()) {
return null;
}
TypeCompare typeCompare = mth.root().getTypeUpdate().getTypeCompare();
ArgType baseCls = baseMth.getMethodInfo().getDeclClass().getType();
for (ArgType superType : superData.getSuperTypes()) {
TypeCompareEnum compareResult = typeCompare.compareTypes(superType, baseCls);
if (compareResult == TypeCompareEnum.NARROW_BY_GENERIC) {
ArgType targetArgType = mth.root().getTypeUtils().replaceClassGenerics(superType, baseArg);
if (targetArgType != null
&& !targetArgType.containsTypeVariable()
&& !targetArgType.equals(arg)) {
return targetArgType;
}
}
}
return null;
}
private void checkMethodSignatureCollisions(MethodNode mth, boolean rename) {
String mthName = mth.getMethodInfo().getAlias();
String newSignature = MethodInfo.makeShortId(mthName, mth.getArgTypes(), null);
for (MethodNode otherMth : mth.getParentClass().getMethods()) {
String otherMthName = otherMth.getAlias();
if (otherMthName.equals(mthName) && otherMth != mth) {
String otherSignature = otherMth.getMethodInfo().makeSignature(true, false);
if (otherSignature.equals(newSignature)) {
if (rename) {
if (otherMth.contains(AFlag.DONT_RENAME) || otherMth.contains(AType.METHOD_OVERRIDE)) {
otherMth.addWarnComment("Can't rename method to resolve collision");
} else {
otherMth.getMethodInfo().setAlias(makeNewAlias(otherMth));
otherMth.addAttr(new RenameReasonAttr("avoid collision after fix types in other method"));
}
}
otherMth.addAttr(new MethodBridgeAttr(mth));
return;
}
}
}
}
// TODO: at this point deobfuscator is not available and map file already saved
private static String makeNewAlias(MethodNode mth) {
ClassNode cls = mth.getParentClass();
String baseName = mth.getAlias();
int k = 2;
while (true) {
String alias = baseName + k;
MethodNode methodNode = cls.searchMethodByShortName(alias);
if (methodNode == null) {
return alias;
}
k++;
}
}
@Override
public String getName() {
return "OverrideMethodVisitor";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/ExtractFieldInit.java | jadx-core/src/main/java/jadx/core/dex/visitors/ExtractFieldInit.java | package jadx.core.dex.visitors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.FieldInitInsnAttr;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.ListUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "ExtractFieldInit",
desc = "Move duplicated field initialization from constructors",
runAfter = ModVisitor.class,
runBefore = ClassModifier.class
)
public class ExtractFieldInit extends AbstractVisitor {
@Override
public boolean visit(ClassNode cls) throws JadxException {
for (ClassNode inner : cls.getInnerClasses()) {
visit(inner);
}
if (!cls.getFields().isEmpty()) {
moveStaticFieldsInit(cls);
moveCommonFieldsInit(cls);
}
return false;
}
private static final class FieldInitInfo {
final FieldNode fieldNode;
final IndexInsnNode putInsn;
final boolean canMove;
public FieldInitInfo(FieldNode fieldNode, IndexInsnNode putInsn, boolean canMove) {
this.fieldNode = fieldNode;
this.putInsn = putInsn;
this.canMove = canMove;
}
}
private static final class ConstructorInitInfo {
final MethodNode constructorMth;
final List<FieldInitInfo> fieldInits;
private ConstructorInitInfo(MethodNode constructorMth, List<FieldInitInfo> fieldInits) {
this.constructorMth = constructorMth;
this.fieldInits = fieldInits;
}
}
private static void moveStaticFieldsInit(ClassNode cls) {
MethodNode classInitMth = cls.getClassInitMth();
if (classInitMth == null
|| !classInitMth.getAccessFlags().isStatic()
|| classInitMth.isNoCode()
|| classInitMth.getBasicBlocks() == null) {
return;
}
if (ListUtils.noneMatch(cls.getFields(), FieldNode::isStatic)) {
return;
}
while (processStaticFields(cls, classInitMth)) {
// sometimes instructions moved to field init prevent from vars inline -> inline and try again
CodeShrinkVisitor.shrinkMethod(classInitMth);
}
}
private static boolean processStaticFields(ClassNode cls, MethodNode classInitMth) {
List<FieldInitInfo> inits = collectFieldsInit(cls, classInitMth, InsnType.SPUT);
if (inits.isEmpty()) {
return false;
}
// ignore field init constant if field initialized in class init method
for (FieldInitInfo fieldInit : inits) {
FieldNode field = fieldInit.fieldNode;
if (field.getAccessFlags().isFinal()) {
field.remove(JadxAttrType.CONSTANT_VALUE);
}
}
filterFieldsInit(inits);
if (inits.isEmpty()) {
return false;
}
for (FieldInitInfo fieldInit : inits) {
IndexInsnNode insn = fieldInit.putInsn;
InsnArg arg = insn.getArg(0);
if (arg instanceof InsnWrapArg) {
((InsnWrapArg) arg).getWrapInsn().add(AFlag.DECLARE_VAR);
}
InsnRemover.remove(classInitMth, insn);
addFieldInitAttr(classInitMth, fieldInit.fieldNode, insn);
}
fixFieldsOrder(cls, inits);
return true;
}
private static void moveCommonFieldsInit(ClassNode cls) {
if (ListUtils.noneMatch(cls.getFields(), FieldNode::isInstance)) {
return;
}
List<MethodNode> constructors = getConstructorsList(cls);
if (constructors.isEmpty()) {
return;
}
List<ConstructorInitInfo> infoList = new ArrayList<>(constructors.size());
for (MethodNode constructorMth : constructors) {
List<FieldInitInfo> inits = collectFieldsInit(cls, constructorMth, InsnType.IPUT);
filterFieldsInit(inits);
if (inits.isEmpty()) {
return;
}
infoList.add(new ConstructorInitInfo(constructorMth, inits));
}
// compare collected instructions
ConstructorInitInfo common = null;
for (ConstructorInitInfo info : infoList) {
if (common == null) {
common = info;
continue;
}
if (!compareFieldInits(common.fieldInits, info.fieldInits)) {
return;
}
}
if (common == null) {
return;
}
// all checks passed
for (ConstructorInitInfo info : infoList) {
for (FieldInitInfo fieldInit : info.fieldInits) {
IndexInsnNode putInsn = fieldInit.putInsn;
InsnArg arg = putInsn.getArg(0);
if (arg instanceof InsnWrapArg) {
((InsnWrapArg) arg).getWrapInsn().add(AFlag.DECLARE_VAR);
}
InsnRemover.remove(info.constructorMth, putInsn);
}
}
for (FieldInitInfo fieldInit : common.fieldInits) {
addFieldInitAttr(common.constructorMth, fieldInit.fieldNode, fieldInit.putInsn);
}
fixFieldsOrder(cls, common.fieldInits);
}
private static List<FieldInitInfo> collectFieldsInit(ClassNode cls, MethodNode mth, InsnType putType) {
List<FieldInitInfo> fieldsInit = new ArrayList<>();
Set<BlockNode> singlePathBlocks = new HashSet<>();
BlockUtils.visitSinglePath(mth.getEnterBlock(), singlePathBlocks::add);
boolean canReorder = true;
for (BlockNode block : mth.getBasicBlocks()) {
for (InsnNode insn : block.getInstructions()) {
boolean fieldInsn = false;
if (insn.getType() == putType) {
IndexInsnNode putInsn = (IndexInsnNode) insn;
FieldInfo field = (FieldInfo) putInsn.getIndex();
if (field.getDeclClass().equals(cls.getClassInfo())) {
FieldNode fn = cls.searchField(field);
if (fn != null) {
boolean canMove = canReorder && singlePathBlocks.contains(block);
fieldsInit.add(new FieldInitInfo(fn, putInsn, canMove));
fieldInsn = true;
}
}
}
if (!fieldInsn && canReorder && !insn.canReorder()) {
canReorder = false;
}
}
}
return fieldsInit;
}
private static void filterFieldsInit(List<FieldInitInfo> inits) {
// exclude fields initialized several times
Set<FieldInfo> excludedFields = inits
.stream()
.collect(Collectors.toMap(fi -> fi.fieldNode, fi -> 1, Integer::sum))
.entrySet()
.stream()
.filter(v -> v.getValue() > 1)
.map(v -> v.getKey().getFieldInfo())
.collect(Collectors.toSet());
for (FieldInitInfo initInfo : inits) {
if (!checkInsn(initInfo)) {
excludedFields.add(initInfo.fieldNode.getFieldInfo());
}
}
if (!excludedFields.isEmpty()) {
boolean changed;
do {
changed = false;
for (FieldInitInfo initInfo : inits) {
FieldInfo fieldInfo = initInfo.fieldNode.getFieldInfo();
if (excludedFields.contains(fieldInfo)) {
continue;
}
if (insnUseExcludedField(initInfo, excludedFields)) {
excludedFields.add(fieldInfo);
changed = true;
}
}
} while (changed);
}
// apply
if (!excludedFields.isEmpty()) {
inits.removeIf(fi -> excludedFields.contains(fi.fieldNode.getFieldInfo()));
}
}
private static boolean checkInsn(FieldInitInfo initInfo) {
if (!initInfo.canMove) {
return false;
}
IndexInsnNode insn = initInfo.putInsn;
InsnArg arg = insn.getArg(0);
if (arg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
if (!wrapInsn.canReorder() && insn.contains(AType.EXC_CATCH)) {
return false;
}
} else {
return arg.isLiteral() || arg.isThis();
}
Set<RegisterArg> regs = new HashSet<>();
insn.getRegisterArgs(regs);
if (!regs.isEmpty()) {
for (RegisterArg reg : regs) {
if (!reg.isThis()) {
return false;
}
}
}
return true;
}
private static boolean insnUseExcludedField(FieldInitInfo initInfo, Set<FieldInfo> excludedFields) {
if (excludedFields.isEmpty()) {
return false;
}
IndexInsnNode insn = initInfo.putInsn;
boolean staticField = insn.getType() == InsnType.SPUT;
InsnType useType = staticField ? InsnType.SGET : InsnType.IGET;
// exclude if init code use any excluded field
Boolean exclude = insn.visitInsns(innerInsn -> {
if (innerInsn.getType() == useType) {
FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) innerInsn).getIndex();
if (excludedFields.contains(fieldInfo)) {
return true;
}
}
return null;
});
return Objects.equals(exclude, Boolean.TRUE);
}
private static void fixFieldsOrder(ClassNode cls, List<FieldInitInfo> inits) {
List<FieldNode> orderedFields = processFieldsDependencies(cls, inits);
applyFieldsOrder(cls, orderedFields);
}
private static List<FieldNode> processFieldsDependencies(ClassNode cls, List<FieldInitInfo> inits) {
List<FieldNode> orderedFields = Utils.collectionMap(inits, v -> v.fieldNode);
// collect dependant fields
Map<FieldNode, List<FieldNode>> deps = new HashMap<>(inits.size());
for (FieldInitInfo initInfo : inits) {
IndexInsnNode insn = initInfo.putInsn;
boolean staticField = insn.getType() == InsnType.SPUT;
InsnType useType = staticField ? InsnType.SGET : InsnType.IGET;
insn.visitInsns(subInsn -> {
if (subInsn.getType() == useType) {
FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) subInsn).getIndex();
if (fieldInfo.getDeclClass().equals(cls.getClassInfo())) {
FieldNode depField = cls.searchField(fieldInfo);
if (depField != null) {
deps.computeIfAbsent(initInfo.fieldNode, k -> new ArrayList<>())
.add(depField);
}
}
}
});
}
if (deps.isEmpty()) {
return orderedFields;
}
// build new list with deps fields before usage field
List<FieldNode> result = new ArrayList<>();
for (FieldNode field : orderedFields) {
int idx = result.indexOf(field);
List<FieldNode> fieldDeps = deps.get(field);
if (fieldDeps == null) {
if (idx == -1) {
result.add(field);
}
continue;
}
if (idx == -1) {
for (FieldNode depField : fieldDeps) {
if (!result.contains(depField)) {
result.add(depField);
}
}
result.add(field);
continue;
}
for (FieldNode depField : fieldDeps) {
int depIdx = result.indexOf(depField);
if (depIdx == -1) {
result.add(idx, depField);
} else if (depIdx > idx) {
result.remove(depIdx);
result.add(idx, depField);
}
}
}
return result;
}
private static void applyFieldsOrder(ClassNode cls, List<FieldNode> orderedFields) {
List<FieldNode> clsFields = cls.getFields();
// check if already ordered
boolean ordered = Collections.indexOfSubList(clsFields, orderedFields) != -1;
if (!ordered) {
clsFields.removeAll(orderedFields);
clsFields.addAll(orderedFields);
}
}
private static boolean compareFieldInits(List<FieldInitInfo> base, List<FieldInitInfo> other) {
if (base.size() != other.size()) {
return false;
}
int count = base.size();
for (int i = 0; i < count; i++) {
InsnNode baseInsn = base.get(i).putInsn;
InsnNode otherInsn = other.get(i).putInsn;
if (!baseInsn.isSame(otherInsn)) {
return false;
}
}
return true;
}
private static List<MethodNode> getConstructorsList(ClassNode cls) {
List<MethodNode> list = new ArrayList<>();
for (MethodNode mth : cls.getMethods()) {
AccessInfo accFlags = mth.getAccessFlags();
if (!accFlags.isStatic() && accFlags.isConstructor()) {
list.add(mth);
if (mth.isNoCode() || BlockUtils.isAllBlocksEmpty(mth.getBasicBlocks())) {
return Collections.emptyList();
}
}
}
return list;
}
private static void addFieldInitAttr(MethodNode mth, FieldNode field, IndexInsnNode putInsn) {
InsnNode assignInsn;
InsnArg fldArg = putInsn.getArg(0);
if (fldArg.isInsnWrap()) {
assignInsn = ((InsnWrapArg) fldArg).getWrapInsn();
} else {
assignInsn = InsnNode.wrapArg(fldArg);
}
field.addAttr(new FieldInitInsnAttr(mth, assignInsn));
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/ShadowFieldVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/ShadowFieldVisitor.java | package jadx.core.dex.visitors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.dex.visitors.typeinference.TypeInferenceVisitor;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "ShadowFieldVisitor",
desc = "Fix shadowed field access",
runAfter = TypeInferenceVisitor.class,
runBefore = CodeShrinkVisitor.class
)
public class ShadowFieldVisitor extends AbstractVisitor {
private Map<String, FieldFixInfo> fixInfoMap;
@Override
public void init(RootNode root) {
Map<String, FieldFixInfo> map = new HashMap<>();
for (ClassNode cls : root.getClasses(true)) {
Map<FieldInfo, FieldFixType> fieldFixMap = searchShadowedFields(cls);
if (!fieldFixMap.isEmpty()) {
FieldFixInfo fixInfo = new FieldFixInfo();
fixInfo.fieldFixMap = fieldFixMap;
map.put(cls.getRawName(), fixInfo);
}
}
this.fixInfoMap = map;
}
@Override
public void visit(MethodNode mth) throws JadxException {
if (mth.isNoCode()) {
return;
}
fixShadowFieldAccess(mth, fixInfoMap);
}
private static class FieldFixInfo {
Map<FieldInfo, FieldFixType> fieldFixMap;
}
private enum FieldFixType {
SUPER,
CAST
}
private static Map<FieldInfo, FieldFixType> searchShadowedFields(ClassNode thisCls) {
List<FieldNode> allFields = collectAllInstanceFields(thisCls);
if (allFields.isEmpty()) {
return Collections.emptyMap();
}
Map<String, List<FieldNode>> mapByName = groupByName(allFields);
mapByName.entrySet().removeIf(entry -> entry.getValue().size() == 1);
if (mapByName.isEmpty()) {
return Collections.emptyMap();
}
Map<FieldInfo, FieldFixType> fixMap = new HashMap<>();
for (List<FieldNode> fields : mapByName.values()) {
boolean fromThisCls = fields.get(0).getParentClass() == thisCls;
if (fromThisCls && fields.size() == 2) {
// only one super class contains same field => can use super
FieldNode otherField = fields.get(1);
if (otherField.getParentClass() != thisCls) {
fixMap.put(otherField.getFieldInfo(), FieldFixType.SUPER);
}
} else {
// several super classes contains same field => can't use super, need cast to exact class
for (FieldNode field : fields) {
if (field.getParentClass() != thisCls) {
fixMap.put(field.getFieldInfo(), FieldFixType.CAST);
}
}
}
}
return fixMap;
}
private static Map<String, List<FieldNode>> groupByName(List<FieldNode> allFields) {
Map<String, List<FieldNode>> groupByName = new HashMap<>(allFields.size());
for (FieldNode field : allFields) {
groupByName
.computeIfAbsent(field.getName(), k -> new ArrayList<>())
.add(field);
}
return groupByName;
}
private static List<FieldNode> collectAllInstanceFields(ClassNode cls) {
List<FieldNode> fieldsList = new ArrayList<>();
Set<ClassNode> visited = new HashSet<>();
ClassNode currentClass = cls;
while (currentClass != null) {
if (!visited.add(currentClass)) {
String msg = "Found 'super' loop in classes: " + visited;
visited.forEach(c -> c.addWarnComment(msg));
return fieldsList;
}
for (FieldNode field : currentClass.getFields()) {
if (!field.getAccessFlags().isStatic()) {
fieldsList.add(field);
}
}
ArgType superClass = currentClass.getSuperClass();
if (superClass == null) {
break;
}
currentClass = cls.root().resolveClass(superClass);
}
return fieldsList;
}
private static void fixShadowFieldAccess(MethodNode mth, Map<String, FieldFixInfo> fixInfoMap) {
for (BlockNode block : mth.getBasicBlocks()) {
for (InsnNode insn : block.getInstructions()) {
processInsn(mth, insn, fixInfoMap);
}
}
}
private static void processInsn(MethodNode mth, InsnNode insn, Map<String, FieldFixInfo> fixInfoMap) {
FieldInfo fieldInfo = getFieldInfo(insn);
if (fieldInfo == null) {
return;
}
InsnArg arg = insn.getArg(insn.getArgsCount() - 1);
ArgType type = arg.getType();
if (!type.isTypeKnown() || !type.isObject()) {
return;
}
FieldFixInfo fieldFixInfo = fixInfoMap.get(type.getObject());
if (fieldFixInfo == null) {
return;
}
FieldFixType fieldFixType = fieldFixInfo.fieldFixMap.get(fieldInfo);
if (fieldFixType == null) {
return;
}
fixFieldAccess(mth, fieldInfo, fieldFixType, arg);
}
@Nullable
private static FieldInfo getFieldInfo(InsnNode insn) {
switch (insn.getType()) {
case IPUT:
case IGET:
return (FieldInfo) ((IndexInsnNode) insn).getIndex();
default:
return null;
}
}
private static void fixFieldAccess(MethodNode mth, FieldInfo fieldInfo, FieldFixType fieldFixType, InsnArg arg) {
if (fieldFixType == FieldFixType.SUPER) {
if (arg.isThis()) {
// convert 'this' to 'super'
arg.add(AFlag.SUPER);
return;
}
}
// apply cast
InsnNode castInsn = new IndexInsnNode(InsnType.CAST, fieldInfo.getDeclClass().getType(), 1);
castInsn.addArg(arg.duplicate());
castInsn.add(AFlag.SYNTHETIC);
castInsn.add(AFlag.EXPLICIT_CAST);
arg.wrapInstruction(mth, castInsn, false);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/ProcessAnonymous.java | jadx-core/src/main/java/jadx/core/dex/visitors/ProcessAnonymous.java | package jadx.core.dex.visitors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.AnonymousClassAttr;
import jadx.core.dex.attributes.nodes.AnonymousClassAttr.InlineType;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.usage.UsageInfoVisitor;
import jadx.core.utils.ListUtils;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "ProcessAnonymous",
desc = "Mark anonymous and lambda classes (for future inline)",
runAfter = {
UsageInfoVisitor.class
}
)
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public class ProcessAnonymous extends AbstractVisitor {
private boolean inlineAnonymousClasses;
@Override
public void init(RootNode root) {
inlineAnonymousClasses = root.getArgs().isInlineAnonymousClasses();
if (!inlineAnonymousClasses) {
return;
}
root.getClasses().forEach(ProcessAnonymous::processClass);
mergeAnonymousDeps(root);
}
@Override
public boolean visit(ClassNode cls) throws JadxException {
if (inlineAnonymousClasses && cls.contains(AFlag.CLASS_UNLOADED)) {
// enter only on class reload
visitClassAndInners(cls);
}
return false;
}
private void visitClassAndInners(ClassNode cls) {
processClass(cls);
cls.getInnerClasses().forEach(this::visitClassAndInners);
}
private static void processClass(ClassNode cls) {
try {
markAnonymousClass(cls);
} catch (StackOverflowError | Exception e) {
cls.addError("Anonymous visitor error", e);
}
}
private static void markAnonymousClass(ClassNode cls) {
if (!canBeAnonymous(cls)) {
return;
}
MethodNode anonymousConstructor = ListUtils.filterOnlyOne(cls.getMethods(), MethodNode::isConstructor);
if (anonymousConstructor == null) {
return;
}
InlineType inlineType = checkUsage(cls, anonymousConstructor);
if (inlineType == null) {
return;
}
ArgType baseType = getBaseType(cls);
if (baseType == null) {
return;
}
ClassNode outerCls;
if (inlineType == InlineType.INSTANCE_FIELD) {
outerCls = cls.getUseInMth().get(0).getParentClass();
} else {
outerCls = anonymousConstructor.getUseIn().get(0).getParentClass();
}
outerCls.addInlinedClass(cls);
cls.addAttr(new AnonymousClassAttr(outerCls, baseType, inlineType));
cls.add(AFlag.DONT_GENERATE);
anonymousConstructor.add(AFlag.ANONYMOUS_CONSTRUCTOR);
// force anonymous class to be processed before outer class,
// actual usage of outer class will be removed at anonymous class process,
// see ModVisitor.processAnonymousConstructor method
ClassNode topOuterCls = outerCls.getTopParentClass();
cls.removeDependency(topOuterCls);
ListUtils.safeRemove(outerCls.getUseIn(), cls);
// move dependency to codegen stage
if (cls.isTopClass()) {
topOuterCls.removeDependency(cls);
topOuterCls.addCodegenDep(cls);
}
}
private static void undoAnonymousMark(ClassNode cls) {
AnonymousClassAttr attr = cls.get(AType.ANONYMOUS_CLASS);
ClassNode outerCls = attr.getOuterCls();
cls.setDependencies(ListUtils.safeAdd(cls.getDependencies(), outerCls.getTopParentClass()));
outerCls.setUseIn(ListUtils.safeAdd(outerCls.getUseIn(), cls));
cls.remove(AType.ANONYMOUS_CLASS);
cls.remove(AFlag.DONT_GENERATE);
for (MethodNode mth : cls.getMethods()) {
if (mth.isConstructor()) {
mth.remove(AFlag.ANONYMOUS_CONSTRUCTOR);
}
}
cls.addDebugComment("Anonymous mark cleared");
}
private void mergeAnonymousDeps(RootNode root) {
// Collect edges to build bidirectional tree:
// inline edge: anonymous -> outer (one-to-one)
// use edges: outer -> *anonymous (one-to-many)
Map<ClassNode, ClassNode> inlineMap = new HashMap<>();
Map<ClassNode, List<ClassNode>> useMap = new HashMap<>();
for (ClassNode anonymousCls : root.getClasses()) {
AnonymousClassAttr attr = anonymousCls.get(AType.ANONYMOUS_CLASS);
if (attr != null) {
ClassNode outerCls = attr.getOuterCls();
List<ClassNode> list = useMap.get(outerCls);
if (list == null || list.isEmpty()) {
list = new ArrayList<>(2);
useMap.put(outerCls, list);
}
list.add(anonymousCls);
useMap.putIfAbsent(anonymousCls, Collections.emptyList()); // put leaf explicitly
inlineMap.put(anonymousCls, outerCls);
}
}
if (inlineMap.isEmpty()) {
return;
}
// starting from leaf process deps in nodes up to root
Set<ClassNode> added = new HashSet<>();
useMap.forEach((key, list) -> {
if (list.isEmpty()) {
added.clear();
updateDeps(key, inlineMap, added);
}
});
for (ClassNode cls : root.getClasses()) {
List<ClassNode> deps = cls.getCodegenDeps();
if (deps.size() > 1) {
// distinct sorted dep, reusing collections to reduce memory allocations :)
added.clear();
added.addAll(deps);
deps.clear();
deps.addAll(added);
Collections.sort(deps);
}
}
}
private void updateDeps(ClassNode leafCls, Map<ClassNode, ClassNode> inlineMap, Set<ClassNode> added) {
ClassNode topNode;
ClassNode current = leafCls;
while (true) {
if (!added.add(current)) {
current.addWarnComment("Loop in anonymous inline: " + current + ", path: " + added);
added.forEach(ProcessAnonymous::undoAnonymousMark);
return;
}
ClassNode next = inlineMap.get(current);
if (next == null) {
topNode = current.getTopParentClass();
break;
}
current = next;
}
if (added.size() <= 2) {
// first level deps already processed
return;
}
List<ClassNode> deps = topNode.getCodegenDeps();
if (deps.isEmpty()) {
deps = new ArrayList<>(added.size());
topNode.setCodegenDeps(deps);
}
for (ClassNode add : added) {
deps.add(add.getTopParentClass());
}
}
private static boolean canBeAnonymous(ClassNode cls) {
if (cls.getAccessFlags().isSynthetic()) {
return true;
}
String shortName = cls.getClassInfo().getShortName();
if (shortName.contains("$") || Character.isDigit(shortName.charAt(0))) {
return true;
}
if (cls.getUseIn().size() == 1 && cls.getUseInMth().size() == 1) {
MethodNode useMth = cls.getUseInMth().get(0);
// allow use in enum class init
return useMth.getMethodInfo().isClassInit() && useMth.getParentClass().isEnum();
}
return false;
}
/**
* Checks:
* - class have only one constructor which used only once (allow common code for field init)
* - methods or fields not used outside (allow only nested inner classes with synthetic usage)
* - if constructor used only in class init check if possible inline by instance field
*
* @return decided inline type
*/
private static InlineType checkUsage(ClassNode cls, MethodNode ctr) {
if (ctr.getUseIn().size() != 1) {
// check if used in common field init in all constructors
if (!checkForCommonFieldInit(ctr)) {
return null;
}
}
MethodNode ctrUseMth = ctr.getUseIn().get(0);
ClassNode ctrUseCls = ctrUseMth.getParentClass();
if (ctrUseCls.equals(cls)) {
if (checkForInstanceFieldUsage(cls, ctr)) {
return InlineType.INSTANCE_FIELD;
}
// exclude self usage
return null;
}
if (ctrUseCls.getTopParentClass().equals(cls)) {
// exclude usage inside inner classes
return null;
}
if (!checkMethodsUsage(cls, ctr, ctrUseMth)) {
return null;
}
for (FieldNode field : cls.getFields()) {
for (MethodNode useMth : field.getUseIn()) {
if (badMethodUsage(cls, useMth, field.getAccessFlags())) {
return null;
}
}
}
return InlineType.CONSTRUCTOR;
}
private static boolean checkMethodsUsage(ClassNode cls, MethodNode ctr, MethodNode ctrUseMth) {
for (MethodNode mth : cls.getMethods()) {
if (mth == ctr) {
continue;
}
for (MethodNode useMth : mth.getUseIn()) {
if (useMth.equals(ctrUseMth)) {
continue;
}
if (badMethodUsage(cls, useMth, mth.getAccessFlags())) {
return false;
}
}
}
return true;
}
private static boolean checkForInstanceFieldUsage(ClassNode cls, MethodNode ctr) {
MethodNode ctrUseMth = ctr.getUseIn().get(0);
if (!ctrUseMth.getMethodInfo().isClassInit()) {
return false;
}
if (cls.getUseInMth().isEmpty()) {
// no outside usage, inline not needed
return false;
}
FieldNode instFld = ListUtils.filterOnlyOne(cls.getFields(),
f -> f.getAccessFlags().containsFlags(AccessFlags.PUBLIC, AccessFlags.STATIC, AccessFlags.FINAL)
&& f.getFieldInfo().getType().equals(cls.getClassInfo().getType()));
if (instFld == null) {
return false;
}
List<MethodNode> instFldUseIn = instFld.getUseIn();
if (instFldUseIn.size() != 2
|| !instFldUseIn.contains(ctrUseMth) // initialized in class init
|| !instFldUseIn.containsAll(cls.getUseInMth()) // class used only with this field
) {
return false;
}
if (!checkMethodsUsage(cls, ctr, ctrUseMth)) {
return false;
}
for (FieldNode field : cls.getFields()) {
if (field == instFld) {
continue;
}
for (MethodNode useMth : field.getUseIn()) {
if (badMethodUsage(cls, useMth, field.getAccessFlags())) {
return false;
}
}
}
instFld.add(AFlag.INLINE_INSTANCE_FIELD);
return true;
}
private static boolean badMethodUsage(ClassNode cls, MethodNode useMth, AccessInfo accessFlags) {
ClassNode useCls = useMth.getParentClass();
if (useCls.equals(cls)) {
return false;
}
if (accessFlags.isSynthetic()) {
// allow synthetic usage in inner class
return !useCls.getParentClass().equals(cls);
}
return true;
}
/**
* Checks:
* + all in constructors
* + all usage in one class
* - same field put (ignored: methods not loaded yet)
*/
private static boolean checkForCommonFieldInit(MethodNode ctrMth) {
List<MethodNode> ctrUse = ctrMth.getUseIn();
if (ctrUse.isEmpty()) {
return false;
}
ClassNode firstUseCls = ctrUse.get(0).getParentClass();
return ListUtils.allMatch(ctrUse, m -> m.isConstructor() && m.getParentClass().equals(firstUseCls));
}
@Nullable
private static ArgType getBaseType(ClassNode cls) {
int interfacesCount = cls.getInterfaces().size();
if (interfacesCount > 1) {
return null;
}
ArgType superCls = cls.getSuperClass();
if (superCls == null || superCls.equals(ArgType.OBJECT)) {
if (interfacesCount == 1) {
return cls.getInterfaces().get(0);
}
return ArgType.OBJECT;
}
if (interfacesCount == 0) {
return superCls;
}
// check if super class already implement that interface (weird case)
ArgType interfaceType = cls.getInterfaces().get(0);
if (cls.root().getClsp().isImplements(superCls.getObject(), interfaceType.getObject())) {
return superCls;
}
if (cls.root().getArgs().isAllowInlineKotlinLambda()) {
if (superCls.getObject().equals("kotlin.jvm.internal.Lambda")) {
// Inline such class with have different semantic: missing 'arity' property.
// For now, it is unclear how it may affect code execution.
return interfaceType;
}
}
return null;
}
@Override
public String getName() {
return "ProcessAnonymous";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/SaveCode.java | jadx-core/src/main/java/jadx/core/dex/visitors/SaveCode.java | package jadx.core.dex.visitors;
import java.io.File;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeInfo;
import jadx.api.JadxArgs;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.utils.files.FileUtils;
public class SaveCode {
private static final Logger LOG = LoggerFactory.getLogger(SaveCode.class);
private SaveCode() {
}
public static void save(File dir, ClassNode cls, ICodeInfo code) {
if (cls.contains(AFlag.DONT_GENERATE)) {
return;
}
if (code == null) {
throw new JadxRuntimeException("Code not generated for class " + cls.getFullName());
}
if (code == ICodeInfo.EMPTY) {
return;
}
String codeStr = code.getCodeStr();
if (codeStr.isEmpty()) {
return;
}
JadxArgs args = cls.root().getArgs();
if (args.isSkipFilesSave()) {
return;
}
String fileName = cls.getClassInfo().getAliasFullPath() + getFileExtension(cls.root());
if (!args.getSecurity().isValidEntryName(fileName)) {
return;
}
save(codeStr, new File(dir, fileName));
}
public static void save(ICodeInfo codeInfo, File file) {
save(codeInfo.getCodeStr(), file);
}
public static void save(String code, File file) {
File outFile = FileUtils.prepareFile(file);
try (PrintWriter out = new PrintWriter(outFile, StandardCharsets.UTF_8)) {
out.println(code);
} catch (Exception e) {
LOG.error("Save file error", e);
}
}
public static String getFileExtension(RootNode root) {
JadxArgs.OutputFormatEnum outputFormat = root.getArgs().getOutputFormat();
switch (outputFormat) {
case JAVA:
return ".java";
case JSON:
return ".json";
default:
throw new JadxRuntimeException("Unknown output format: " + outputFormat);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/GenericTypesVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/GenericTypesVisitor.java | package jadx.core.dex.visitors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.dex.attributes.nodes.GenericInfoAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.dex.visitors.typeinference.TypeInferenceVisitor;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "GenericTypesVisitor",
desc = "Fix and apply generic type info",
runAfter = TypeInferenceVisitor.class,
runBefore = { CodeShrinkVisitor.class, MethodInvokeVisitor.class }
)
public class GenericTypesVisitor extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(GenericTypesVisitor.class);
@Override
public void visit(MethodNode mth) throws JadxException {
if (mth.isNoCode()) {
return;
}
for (BlockNode block : mth.getBasicBlocks()) {
for (InsnNode insn : block.getInstructions()) {
if (insn.getType() == InsnType.CONSTRUCTOR) {
attachGenericTypesInfo(mth, (ConstructorInsn) insn);
}
}
}
}
private void attachGenericTypesInfo(MethodNode mth, ConstructorInsn insn) {
try {
RegisterArg resultArg = insn.getResult();
if (resultArg == null) {
return;
}
ArgType argType = resultArg.getSVar().getCodeVar().getType();
if (argType == null || argType.getGenericTypes() == null) {
return;
}
ClassNode cls = mth.root().resolveClass(insn.getClassType());
if (cls != null && cls.getGenericTypeParameters().isEmpty()) {
return;
}
insn.addAttr(new GenericInfoAttr(argType.getGenericTypes()));
} catch (Exception e) {
LOG.error("Failed to attach constructor generic info", e);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/InitCodeVariables.java | jadx-core/src/main/java/jadx/core/dex/visitors/InitCodeVariables.java | package jadx.core.dex.visitors;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.CodeVar;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.ssa.SSATransform;
import jadx.core.utils.exceptions.JadxException;
import jadx.core.utils.exceptions.JadxRuntimeException;
@JadxVisitor(
name = "InitCodeVariables",
desc = "Initialize code variables",
runAfter = SSATransform.class
)
public class InitCodeVariables extends AbstractVisitor {
@Override
public void visit(MethodNode mth) throws JadxException {
initCodeVars(mth);
}
public static void rerun(MethodNode mth) {
for (SSAVar sVar : mth.getSVars()) {
sVar.resetTypeAndCodeVar();
}
initCodeVars(mth);
}
private static void initCodeVars(MethodNode mth) {
RegisterArg thisArg = mth.getThisArg();
if (thisArg != null) {
initCodeVar(mth, thisArg);
}
for (RegisterArg mthArg : mth.getArgRegs()) {
initCodeVar(mth, mthArg);
}
for (SSAVar ssaVar : mth.getSVars()) {
initCodeVar(ssaVar);
}
}
public static void initCodeVar(MethodNode mth, RegisterArg regArg) {
SSAVar ssaVar = regArg.getSVar();
if (ssaVar == null) {
ssaVar = mth.makeNewSVar(regArg);
}
initCodeVar(ssaVar);
}
public static void initCodeVar(SSAVar ssaVar) {
if (ssaVar.isCodeVarSet()) {
return;
}
CodeVar codeVar = new CodeVar();
RegisterArg assignArg = ssaVar.getAssign();
if (assignArg.contains(AFlag.THIS)) {
codeVar.setName(RegisterArg.THIS_ARG_NAME);
codeVar.setThis(true);
}
if (assignArg.contains(AFlag.METHOD_ARGUMENT) || assignArg.contains(AFlag.CUSTOM_DECLARE)) {
codeVar.setDeclared(true);
}
setCodeVar(ssaVar, codeVar);
}
private static void setCodeVar(SSAVar ssaVar, CodeVar codeVar) {
List<PhiInsn> phiList = ssaVar.getPhiList();
if (!phiList.isEmpty()) {
Set<SSAVar> vars = new LinkedHashSet<>();
vars.add(ssaVar);
collectConnectedVars(phiList, vars);
setCodeVarType(codeVar, vars);
vars.forEach(var -> {
if (var.isCodeVarSet()) {
codeVar.mergeFlagsFrom(var.getCodeVar());
}
var.setCodeVar(codeVar);
});
} else {
ssaVar.setCodeVar(codeVar);
}
}
private static void setCodeVarType(CodeVar codeVar, Set<SSAVar> vars) {
if (vars.size() > 1) {
List<ArgType> imTypes = vars.stream()
.map(SSAVar::getImmutableType)
.filter(Objects::nonNull)
.filter(ArgType::isTypeKnown)
.distinct()
.collect(Collectors.toList());
int imCount = imTypes.size();
if (imCount == 1) {
codeVar.setType(imTypes.get(0));
} else if (imCount > 1) {
throw new JadxRuntimeException("Several immutable types in one variable: " + imTypes + ", vars: " + vars);
}
}
}
private static void collectConnectedVars(List<PhiInsn> phiInsnList, Set<SSAVar> vars) {
if (phiInsnList.isEmpty()) {
return;
}
for (PhiInsn phiInsn : phiInsnList) {
SSAVar resultVar = phiInsn.getResult().getSVar();
if (vars.add(resultVar)) {
collectConnectedVars(resultVar.getPhiList(), vars);
}
phiInsn.getArguments().forEach(arg -> {
SSAVar sVar = ((RegisterArg) arg).getSVar();
if (vars.add(sVar)) {
collectConnectedVars(sVar.getPhiList(), vars);
}
});
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/AbstractTypeConstraint.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/AbstractTypeConstraint.java | package jadx.core.dex.visitors.typeinference;
import java.util.ArrayList;
import java.util.List;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.utils.Utils;
public abstract class AbstractTypeConstraint implements ITypeConstraint {
protected final InsnNode insn;
protected final List<SSAVar> relatedVars;
public AbstractTypeConstraint(InsnNode insn, InsnArg arg) {
this.insn = insn;
this.relatedVars = collectRelatedVars(insn, arg);
}
private List<SSAVar> collectRelatedVars(InsnNode insn, InsnArg arg) {
List<SSAVar> list = new ArrayList<>(insn.getArgsCount());
if (insn.getResult() == arg) {
for (InsnArg insnArg : insn.getArguments()) {
if (insnArg.isRegister()) {
list.add(((RegisterArg) insnArg).getSVar());
}
}
} else {
list.add(insn.getResult().getSVar());
for (InsnArg insnArg : insn.getArguments()) {
if (insnArg != arg && insnArg.isRegister()) {
list.add(((RegisterArg) insnArg).getSVar());
}
}
}
return list;
}
@Override
public List<SSAVar> getRelatedVars() {
return relatedVars;
}
@Override
public String toString() {
return "(" + insn.getType() + ':' + Utils.listToString(relatedVars, SSAVar::toShortString) + ')';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeSearchVarInfo.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeSearchVarInfo.java | package jadx.core.dex.visitors.typeinference;
import java.util.Collections;
import java.util.List;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.SSAVar;
public class TypeSearchVarInfo {
private final SSAVar var;
private boolean typeResolved;
private ArgType currentType;
private List<ArgType> candidateTypes;
private int currentIndex = -1;
private List<ITypeConstraint> constraints;
public TypeSearchVarInfo(SSAVar var) {
this.var = var;
}
public void markResolved(ArgType type) {
this.currentType = type;
this.typeResolved = true;
this.candidateTypes = Collections.emptyList();
}
public void reset() {
if (typeResolved) {
return;
}
currentIndex = 0;
currentType = candidateTypes.get(0);
}
/**
* Switch {@code currentType} to next candidate
*
* @return true - if this is the first candidate
*/
public boolean nextType() {
if (typeResolved) {
return false;
}
int len = candidateTypes.size();
currentIndex = (currentIndex + 1) % len;
currentType = candidateTypes.get(currentIndex);
return currentIndex == 0;
}
public SSAVar getVar() {
return var;
}
public boolean isTypeResolved() {
return typeResolved;
}
public void setTypeResolved(boolean typeResolved) {
this.typeResolved = typeResolved;
}
public ArgType getCurrentType() {
return currentType;
}
public void setCurrentType(ArgType currentType) {
this.currentType = currentType;
}
public List<ArgType> getCandidateTypes() {
return candidateTypes;
}
public void setCandidateTypes(List<ArgType> candidateTypes) {
this.candidateTypes = candidateTypes;
}
public List<ITypeConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<ITypeConstraint> constraints) {
this.constraints = constraints;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(var.toShortString());
if (typeResolved) {
sb.append(", resolved type: ").append(currentType);
} else {
sb.append(", currentType=").append(currentType);
sb.append(", candidateTypes=").append(candidateTypes);
sb.append(", constraints=").append(constraints);
}
return sb.toString();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/ITypeConstraint.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/ITypeConstraint.java | package jadx.core.dex.visitors.typeinference;
import java.util.List;
import jadx.core.dex.instructions.args.SSAVar;
public interface ITypeConstraint {
List<SSAVar> getRelatedVars();
boolean check(TypeSearchState state);
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeCompareEnum.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeCompareEnum.java | package jadx.core.dex.visitors.typeinference;
public enum TypeCompareEnum {
EQUAL,
NARROW,
NARROW_BY_GENERIC, // same basic type with generic
WIDER,
WIDER_BY_GENERIC, // same basic type without generic
CONFLICT,
CONFLICT_BY_GENERIC, // same basic type, conflict in generics
UNKNOWN;
public TypeCompareEnum invert() {
switch (this) {
case NARROW:
return WIDER;
case NARROW_BY_GENERIC:
return WIDER_BY_GENERIC;
case WIDER:
return NARROW;
case WIDER_BY_GENERIC:
return NARROW_BY_GENERIC;
case CONFLICT:
case CONFLICT_BY_GENERIC:
case EQUAL:
case UNKNOWN:
default:
return this;
}
}
public boolean isEqual() {
return this == EQUAL;
}
public boolean isWider() {
return this == WIDER || this == WIDER_BY_GENERIC;
}
public boolean isWiderOrEqual() {
return isEqual() || isWider();
}
public boolean isNarrow() {
return this == NARROW || this == NARROW_BY_GENERIC;
}
public boolean isNarrowOrEqual() {
return isEqual() || isNarrow();
}
public boolean isConflict() {
return this == CONFLICT || this == CONFLICT_BY_GENERIC;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdate.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdate.java | package jadx.core.dex.visitors.typeinference;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.JadxArgs;
import jadx.core.Consts;
import jadx.core.clsp.ClspClass;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.ArithNode;
import jadx.core.dex.instructions.BaseInvokeNode;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.IMethodDetails;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.nodes.utils.TypeUtils;
import jadx.core.utils.exceptions.JadxOverflowException;
import jadx.core.utils.exceptions.JadxRuntimeException;
import static jadx.core.dex.visitors.typeinference.TypeUpdateResult.CHANGED;
import static jadx.core.dex.visitors.typeinference.TypeUpdateResult.REJECT;
import static jadx.core.dex.visitors.typeinference.TypeUpdateResult.SAME;
public final class TypeUpdate {
private static final Logger LOG = LoggerFactory.getLogger(TypeUpdate.class);
private final RootNode root;
private final Map<InsnType, ITypeListener> listenerRegistry;
private final TypeCompare comparator;
private final JadxArgs args;
public TypeUpdate(RootNode root) {
this.root = root;
this.args = root.getArgs();
this.listenerRegistry = initListenerRegistry();
this.comparator = new TypeCompare(root);
}
/**
* Perform recursive type checking and type propagation for all related variables
*/
public TypeUpdateResult apply(MethodNode mth, SSAVar ssaVar, ArgType candidateType) {
return apply(mth, ssaVar, candidateType, TypeUpdateFlags.FLAGS_EMPTY);
}
/**
* Allow wider types for apply from debug info and some special cases
*/
public TypeUpdateResult applyWithWiderAllow(MethodNode mth, SSAVar ssaVar, ArgType candidateType) {
return apply(mth, ssaVar, candidateType, TypeUpdateFlags.FLAGS_WIDER);
}
/**
* Force type setting
*/
public TypeUpdateResult applyWithWiderIgnSame(MethodNode mth, SSAVar ssaVar, ArgType candidateType) {
return apply(mth, ssaVar, candidateType, TypeUpdateFlags.FLAGS_WIDER_IGNORE_SAME);
}
public TypeUpdateResult applyDebugInfo(MethodNode mth, SSAVar ssaVar, ArgType candidateType) {
return apply(mth, ssaVar, candidateType, TypeUpdateFlags.FLAGS_APPLY_DEBUG);
}
private TypeUpdateResult apply(MethodNode mth, SSAVar ssaVar, ArgType candidateType, TypeUpdateFlags flags) {
try {
if (candidateType == null || !candidateType.isTypeKnown()) {
return REJECT;
}
TypeUpdateInfo updateInfo = new TypeUpdateInfo(mth, flags, args);
TypeUpdateResult result = updateTypeChecked(updateInfo, ssaVar.getAssign(), candidateType);
if (result == REJECT) {
return result;
}
if (updateInfo.isEmpty()) {
return SAME;
}
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Applying type {} to {}:", candidateType, ssaVar.toShortString());
updateInfo.getSortedUpdates().forEach(upd -> LOG.debug(" {} -> {} in {}",
upd.getType(), upd.getArg().toShortString(), upd.getArg().getParentInsn()));
}
updateInfo.applyUpdates();
return CHANGED;
} catch (Exception e) {
mth.addWarnComment("Type update failed for variable: " + ssaVar + ", new type: " + candidateType, e);
return REJECT;
}
}
private TypeUpdateResult updateTypeChecked(TypeUpdateInfo updateInfo, InsnArg arg, ArgType candidateType) {
if (candidateType == null) {
throw new JadxRuntimeException("Null type update for arg: " + arg);
}
if (updateInfo.isProcessed(arg)) {
return CHANGED;
}
TypeUpdateResult res = verifyType(updateInfo, arg, candidateType);
if (res != null) {
return res;
}
if (arg instanceof RegisterArg) {
RegisterArg reg = (RegisterArg) arg;
return updateTypeForSsaVar(updateInfo, reg.getSVar(), candidateType);
}
return requestUpdate(updateInfo, arg, candidateType);
}
private @Nullable TypeUpdateResult verifyType(TypeUpdateInfo updateInfo, InsnArg arg, ArgType candidateType) {
ArgType currentType = arg.getType();
TypeUpdateFlags typeUpdateFlags = updateInfo.getFlags();
if (Objects.equals(currentType, candidateType)) {
if (!typeUpdateFlags.isIgnoreSame()) {
return SAME;
}
} else {
if (candidateType.isWildcard()) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Wildcard type rejected for {}: candidate={}, current={}", arg, candidateType, currentType);
}
return REJECT;
}
TypeCompareEnum compareResult = comparator.compareTypes(candidateType, currentType);
if (compareResult.isConflict()) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Type rejected for {}: candidate={} in conflict with current={}", arg, candidateType, currentType);
}
return REJECT;
}
if (compareResult == TypeCompareEnum.UNKNOWN && typeUpdateFlags.isIgnoreUnknown()) {
return REJECT;
}
if (arg.isTypeImmutable() && currentType != ArgType.UNKNOWN) {
// don't changed type
if (compareResult == TypeCompareEnum.EQUAL) {
return SAME;
}
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Type rejected for {} due to conflict: candidate={}, current={}", arg, candidateType, currentType);
}
return REJECT;
}
if (compareResult == TypeCompareEnum.WIDER_BY_GENERIC && typeUpdateFlags.isKeepGenerics()) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Type rejected for {}: candidate={} is removing generic from current={}", arg, candidateType, currentType);
}
return REJECT;
}
if (compareResult.isWider() && !typeUpdateFlags.isAllowWider()) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Type rejected for {}: candidate={} is wider than current={}", arg, candidateType, currentType);
}
return REJECT;
}
if (candidateType.containsTypeVariable()) {
// reject unknown type vars
ArgType unknownTypeVar = root.getTypeUtils().checkForUnknownTypeVars(updateInfo.getMth(), candidateType);
if (unknownTypeVar != null) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Type rejected for {}: candidate: '{}' has unknown type var: '{}'", arg, candidateType, unknownTypeVar);
}
return REJECT;
}
}
}
return null;
}
private TypeUpdateResult updateTypeForSsaVar(TypeUpdateInfo updateInfo, SSAVar ssaVar, ArgType candidateType) {
TypeInfo typeInfo = ssaVar.getTypeInfo();
ArgType immutableType = ssaVar.getImmutableType();
if (immutableType != null && !Objects.equals(immutableType, candidateType)) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.info("Reject change immutable type {} to {} for {}", immutableType, candidateType, ssaVar);
}
return REJECT;
}
if (!inBounds(updateInfo, ssaVar, typeInfo.getBounds(), candidateType)) {
return REJECT;
}
TypeUpdateResult result = requestUpdate(updateInfo, ssaVar.getAssign(), candidateType);
boolean allSame = result == SAME;
if (result != REJECT) {
List<RegisterArg> useList = ssaVar.getUseList();
for (RegisterArg arg : useList) {
result = requestUpdate(updateInfo, arg, candidateType);
if (result == REJECT) {
break;
}
if (result != SAME) {
allSame = false;
}
}
}
if (result == REJECT) {
// rollback update for all registers in current SSA var
updateInfo.rollbackUpdate(ssaVar.getAssign());
ssaVar.getUseList().forEach(updateInfo::rollbackUpdate);
return REJECT;
}
return allSame ? SAME : CHANGED;
}
private TypeUpdateResult requestUpdate(TypeUpdateInfo updateInfo, InsnArg arg, ArgType candidateType) {
if (updateInfo.isProcessed(arg)) {
return CHANGED;
}
updateInfo.requestUpdate(arg, candidateType);
try {
TypeUpdateResult result = runListeners(updateInfo, arg, candidateType);
if (result == REJECT) {
updateInfo.rollbackUpdate(arg);
}
return result;
} catch (StackOverflowError | BootstrapMethodError error) {
throw new JadxOverflowException("Type update terminated with stack overflow, arg: " + arg
+ ", method size: " + updateInfo.getMth().getInsnsCount());
}
}
private TypeUpdateResult runListeners(TypeUpdateInfo updateInfo, InsnArg arg, ArgType candidateType) {
InsnNode insn = arg.getParentInsn();
if (insn == null) {
return SAME;
}
ITypeListener listener = listenerRegistry.get(insn.getType());
if (listener == null) {
return CHANGED;
}
return listener.update(updateInfo, insn, arg, candidateType);
}
boolean inBounds(Set<ITypeBound> bounds, ArgType candidateType) {
for (ITypeBound bound : bounds) {
ArgType boundType = bound.getType();
if (boundType != null && !checkBound(candidateType, bound, boundType)) {
return false;
}
}
return true;
}
private boolean inBounds(TypeUpdateInfo updateInfo, SSAVar ssaVar, Set<ITypeBound> bounds, ArgType candidateType) {
for (ITypeBound bound : bounds) {
ArgType boundType;
if (updateInfo != null && bound instanceof ITypeBoundDynamic) {
boundType = ((ITypeBoundDynamic) bound).getType(updateInfo);
} else {
boundType = bound.getType();
}
if (boundType != null && !checkBound(candidateType, bound, boundType)) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Reject type '{}' for {} by bound: {} from {}", candidateType, ssaVar, boundType, bound);
}
return false;
}
}
return true;
}
private boolean checkBound(ArgType candidateType, ITypeBound bound, ArgType boundType) {
TypeCompareEnum compareResult = comparator.compareTypes(candidateType, boundType);
switch (compareResult) {
case EQUAL:
return true;
case WIDER:
return bound.getBound() != BoundEnum.USE;
case NARROW:
if (bound.getBound() == BoundEnum.ASSIGN) {
return !boundType.isTypeKnown() && checkAssignForUnknown(boundType, candidateType);
}
return true;
case WIDER_BY_GENERIC:
case NARROW_BY_GENERIC:
// allow replace object to same object with known generic type
// due to incomplete information about external methods and fields
return true;
case CONFLICT:
case CONFLICT_BY_GENERIC:
return false;
case UNKNOWN:
LOG.warn("Can't compare types, unknown hierarchy: {} and {}", candidateType, boundType);
comparator.compareTypes(candidateType, boundType);
return true;
default:
throw new JadxRuntimeException("Not processed type compare enum: " + compareResult);
}
}
private boolean checkAssignForUnknown(ArgType boundType, ArgType candidateType) {
if (boundType == ArgType.UNKNOWN) {
return true;
}
boolean candidateArray = candidateType.isArray();
if (boundType.isArray() && candidateArray) {
return checkAssignForUnknown(boundType.getArrayElement(), candidateType.getArrayElement());
}
if (candidateArray && boundType.contains(PrimitiveType.ARRAY)) {
return true;
}
if (candidateType.isObject() && boundType.contains(PrimitiveType.OBJECT)) {
return true;
}
if (candidateType.isPrimitive() && boundType.contains(candidateType.getPrimitiveType())) {
return true;
}
return false;
}
private Map<InsnType, ITypeListener> initListenerRegistry() {
Map<InsnType, ITypeListener> registry = new EnumMap<>(InsnType.class);
registry.put(InsnType.CONST, this::sameFirstArgListener);
registry.put(InsnType.MOVE, this::moveListener);
registry.put(InsnType.PHI, this::allSameListener);
registry.put(InsnType.AGET, this::arrayGetListener);
registry.put(InsnType.APUT, this::arrayPutListener);
registry.put(InsnType.IF, this::ifListener);
registry.put(InsnType.ARITH, this::arithListener);
registry.put(InsnType.NEG, this::suggestAllSameListener);
registry.put(InsnType.NOT, this::suggestAllSameListener);
registry.put(InsnType.CHECK_CAST, this::checkCastListener);
registry.put(InsnType.INVOKE, this::invokeListener);
registry.put(InsnType.CONSTRUCTOR, this::invokeListener);
return registry;
}
private TypeUpdateResult invokeListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
BaseInvokeNode invoke = (BaseInvokeNode) insn;
if (isAssign(invoke, arg)) {
// TODO: implement backward type propagation (from result to instance)
return SAME;
}
if (invoke.getInstanceArg() == arg) {
IMethodDetails methodDetails = root.getMethodUtils().getMethodDetails(invoke);
if (methodDetails == null) {
return SAME;
}
TypeUtils typeUtils = root.getTypeUtils();
Set<ArgType> knownTypeVars = typeUtils.getKnownTypeVarsAtMethod(updateInfo.getMth());
Map<ArgType, ArgType> typeVarsMap = typeUtils.getTypeVariablesMapping(candidateType);
ArgType returnType = methodDetails.getReturnType();
List<ArgType> argTypes = methodDetails.getArgTypes();
int argsCount = argTypes.size();
if (typeVarsMap.isEmpty()) {
// generics can't be resolved => use as is
return applyInvokeTypes(updateInfo, invoke, argsCount, knownTypeVars, () -> returnType, argTypes::get);
}
// resolve types before apply
return applyInvokeTypes(updateInfo, invoke, argsCount, knownTypeVars,
() -> typeUtils.replaceTypeVariablesUsingMap(returnType, typeVarsMap),
argNum -> typeUtils.replaceClassGenerics(candidateType, argTypes.get(argNum)));
}
return SAME;
}
private TypeUpdateResult applyInvokeTypes(TypeUpdateInfo updateInfo, BaseInvokeNode invoke, int argsCount,
Set<ArgType> knownTypeVars, Supplier<ArgType> getReturnType, Function<Integer, ArgType> getArgType) {
boolean allSame = true;
RegisterArg resultArg = invoke.getResult();
if (resultArg != null && !resultArg.isTypeImmutable()) {
ArgType returnType = checkType(knownTypeVars, getReturnType.get());
if (returnType != null) {
TypeUpdateResult result = updateTypeChecked(updateInfo, resultArg, returnType);
if (result == REJECT) {
TypeCompareEnum compare = comparator.compareTypes(returnType, resultArg.getType());
if (compare.isWider()) {
return REJECT;
}
}
if (result == CHANGED) {
allSame = false;
}
}
}
int argOffset = invoke.getFirstArgOffset();
for (int i = 0; i < argsCount; i++) {
InsnArg invokeArg = invoke.getArg(argOffset + i);
if (!invokeArg.isTypeImmutable()) {
ArgType argType = checkType(knownTypeVars, getArgType.apply(i));
if (argType != null) {
TypeUpdateResult result = updateTypeChecked(updateInfo, invokeArg, argType);
if (result == REJECT) {
TypeCompareEnum compare = comparator.compareTypes(argType, invokeArg.getType());
if (compare.isNarrow()) {
return REJECT;
}
}
if (result == CHANGED) {
allSame = false;
}
}
}
}
return allSame ? SAME : CHANGED;
}
@Nullable
private ArgType checkType(Set<ArgType> knownTypeVars, @Nullable ArgType type) {
if (type == null) {
return null;
}
if (type.isWildcard()) {
return null;
}
if (type.containsTypeVariable()) {
if (knownTypeVars.isEmpty()) {
return null;
}
Boolean hasUnknown = type.visitTypes(t -> t.isGenericType() && !knownTypeVars.contains(t) ? Boolean.TRUE : null);
if (hasUnknown != null) {
return null;
}
}
return type;
}
private TypeUpdateResult sameFirstArgListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
InsnArg changeArg = isAssign(insn, arg) ? insn.getArg(0) : insn.getResult();
if (updateInfo.hasUpdateWithType(changeArg, candidateType)) {
return CHANGED;
}
return updateTypeChecked(updateInfo, changeArg, candidateType);
}
private TypeUpdateResult moveListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
if (insn.getResult() == null) {
return CHANGED;
}
boolean assignChanged = isAssign(insn, arg);
InsnArg changeArg = assignChanged ? insn.getArg(0) : insn.getResult();
boolean correctType;
if (changeArg.getType().isTypeKnown()) {
// allow result to be wider
TypeCompareEnum cmp = comparator.compareTypes(candidateType, changeArg.getType());
correctType = cmp.isEqual() || (assignChanged ? cmp.isWider() : cmp.isNarrow());
} else {
correctType = true;
}
TypeUpdateResult result = updateTypeChecked(updateInfo, changeArg, candidateType);
if (result == SAME && !correctType) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Move insn types mismatch: {} -> {}, change arg: {}, insn: {}",
candidateType, changeArg.getType(), changeArg, insn);
}
return REJECT;
}
if (result == REJECT && correctType) {
return CHANGED;
}
return result;
}
/**
* All args must have same types
*/
private TypeUpdateResult allSameListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
if (!isAssign(insn, arg)) {
return updateTypeChecked(updateInfo, insn.getResult(), candidateType);
}
boolean allSame = true;
for (InsnArg insnArg : insn.getArguments()) {
if (insnArg == arg) {
continue;
}
TypeUpdateResult result = updateTypeChecked(updateInfo, insnArg, candidateType);
if (result == REJECT) {
return result;
}
if (result != SAME) {
allSame = false;
}
}
return allSame ? SAME : CHANGED;
}
private TypeUpdateResult arithListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
ArithNode arithInsn = (ArithNode) insn;
if (candidateType == ArgType.BOOLEAN && arithInsn.getOp().isBitOp()) {
// force all args to boolean
return allSameListener(updateInfo, insn, arg, candidateType);
}
return suggestAllSameListener(updateInfo, insn, arg, candidateType);
}
/**
* Try to set candidate type to all args, don't fail on reject
*/
private TypeUpdateResult suggestAllSameListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
if (!isAssign(insn, arg)) {
RegisterArg resultArg = insn.getResult();
if (resultArg != null) {
updateTypeChecked(updateInfo, resultArg, candidateType);
}
}
boolean allSame = true;
for (InsnArg insnArg : insn.getArguments()) {
if (insnArg != arg) {
TypeUpdateResult result = updateTypeChecked(updateInfo, insnArg, candidateType);
if (result == REJECT) {
// ignore
} else if (result != SAME) {
allSame = false;
}
}
}
return allSame ? SAME : CHANGED;
}
private TypeUpdateResult checkCastListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
IndexInsnNode checkCast = (IndexInsnNode) insn;
if (isAssign(insn, arg)) {
InsnArg insnArg = insn.getArg(0);
TypeUpdateResult result = updateTypeChecked(updateInfo, insnArg, candidateType);
return result == REJECT ? SAME : result;
}
ArgType castType = (ArgType) checkCast.getIndex();
TypeCompareEnum res = comparator.compareTypes(candidateType, castType);
if (res == TypeCompareEnum.CONFLICT) {
// allow casting one interface to another
if (!isInterfaces(candidateType, castType)) {
return REJECT;
}
}
if (res == TypeCompareEnum.CONFLICT_BY_GENERIC) {
if (!insn.contains(AFlag.SOFT_CAST)) {
return REJECT;
}
}
if (res == TypeCompareEnum.NARROW_BY_GENERIC && candidateType.containsGeneric()) {
// propagate generic type to result
return updateTypeChecked(updateInfo, checkCast.getResult(), candidateType);
}
ArgType currentType = checkCast.getArg(0).getType();
return candidateType.equals(currentType) ? SAME : CHANGED;
}
private boolean isInterfaces(ArgType firstType, ArgType secondType) {
if (!firstType.isObject() || !secondType.isObject()) {
return false;
}
ClspClass firstCls = root.getClsp().getClsDetails(firstType);
ClspClass secondCls = root.getClsp().getClsDetails(secondType);
if (firstCls != null && !firstCls.isInterface()) {
return false;
}
if (secondCls != null && !secondCls.isInterface()) {
return false;
}
if (firstCls == null || secondCls == null) {
return true;
}
return secondCls.isInterface() && firstCls.isInterface();
}
private TypeUpdateResult arrayGetListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
if (isAssign(insn, arg)) {
TypeUpdateResult result = updateTypeChecked(updateInfo, insn.getArg(0), ArgType.array(candidateType));
if (result == REJECT) {
ArgType arrType = insn.getArg(0).getType();
if (arrType.isTypeKnown() && arrType.isArray() && arrType.getArrayElement().isPrimitive()) {
TypeCompareEnum compResult = comparator.compareTypes(candidateType, arrType.getArrayElement());
if (compResult == TypeCompareEnum.WIDER) {
// allow implicit upcast for primitive types (int a = byteArr[n])
return CHANGED;
}
}
}
return result;
}
InsnArg arrArg = insn.getArg(0);
if (arrArg == arg) {
ArgType arrayElement = candidateType.getArrayElement();
if (arrayElement == null) {
return REJECT;
}
TypeUpdateResult result = updateTypeChecked(updateInfo, insn.getResult(), arrayElement);
if (result == REJECT) {
ArgType resType = insn.getResult().getType();
if (resType.isTypeKnown() && resType.isPrimitive()) {
TypeCompareEnum compResult = comparator.compareTypes(resType, arrayElement);
if (compResult == TypeCompareEnum.WIDER) {
// allow implicit upcast for primitive types (int a = byteArr[n])
return CHANGED;
}
}
}
return result;
}
// index argument
return SAME;
}
private TypeUpdateResult arrayPutListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
InsnArg arrArg = insn.getArg(0);
InsnArg putArg = insn.getArg(2);
if (arrArg == arg) {
ArgType arrayElement = candidateType.getArrayElement();
if (arrayElement == null) {
return REJECT;
}
TypeUpdateResult result = updateTypeChecked(updateInfo, putArg, arrayElement);
if (result == REJECT) {
ArgType putType = putArg.getType();
if (putType.isTypeKnown()) {
TypeCompareEnum compResult = comparator.compareTypes(arrayElement, putType);
if (compResult == TypeCompareEnum.WIDER || compResult == TypeCompareEnum.WIDER_BY_GENERIC) {
// allow wider result (i.e. allow put any objects in Object[] or byte in int[])
return CHANGED;
}
}
}
return result;
}
if (arrArg == putArg) {
return updateTypeChecked(updateInfo, arrArg, ArgType.array(candidateType));
}
// index
return SAME;
}
private TypeUpdateResult ifListener(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, ArgType candidateType) {
InsnArg firstArg = insn.getArg(0);
InsnArg secondArg = insn.getArg(1);
InsnArg updateArg = firstArg == arg ? secondArg : firstArg;
TypeUpdateResult result = updateTypeChecked(updateInfo, updateArg, candidateType);
if (result == REJECT) {
// soft checks for objects and array - exact type not compared
ArgType updateArgType = updateArg.getType();
if (candidateType.isObject() && updateArgType.canBeObject()) {
return SAME;
}
if (candidateType.isArray() && updateArgType.canBeArray()) {
return SAME;
}
if (candidateType.isPrimitive()) {
if (updateArgType.canBePrimitive(candidateType.getPrimitiveType())) {
return SAME;
}
if (updateArgType.isTypeKnown() && candidateType.getRegCount() == updateArgType.getRegCount()) {
return SAME;
}
}
}
return result;
}
private static boolean isAssign(InsnNode insn, InsnArg arg) {
return insn.getResult() == arg;
}
public TypeCompare getTypeCompare() {
return comparator;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeInferenceVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeInferenceVisitor.java | package jadx.core.dex.visitors.typeinference;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.Consts;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.AnonymousClassAttr;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.instructions.BaseInvokeNode;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.InvokeType;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.IMethodDetails;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.nodes.utils.MethodUtils;
import jadx.core.dex.trycatch.ExcHandlerAttr;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.AttachMethodDetails;
import jadx.core.dex.visitors.ConstInlineVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.ssa.SSATransform;
import jadx.core.utils.exceptions.JadxOverflowException;
@JadxVisitor(
name = "Type Inference",
desc = "Calculate best types for SSA variables",
runAfter = {
SSATransform.class,
ConstInlineVisitor.class,
AttachMethodDetails.class
}
)
public final class TypeInferenceVisitor extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(TypeInferenceVisitor.class);
private RootNode root;
private TypeUpdate typeUpdate;
@Override
public void init(RootNode root) {
this.root = root;
this.typeUpdate = root.getTypeUpdate();
}
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode()) {
return;
}
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.info("Start type inference in method: {}", mth);
}
try {
assignImmutableTypes(mth);
initTypeBounds(mth);
runTypePropagation(mth);
} catch (Exception e) {
mth.addError("Type inference failed", e);
}
}
/**
* Collect initial type bounds from assign and usages
*/
void initTypeBounds(MethodNode mth) {
List<SSAVar> ssaVars = mth.getSVars();
ssaVars.forEach(this::attachBounds);
ssaVars.forEach(this::mergePhiBounds);
if (Consts.DEBUG_TYPE_INFERENCE) {
ssaVars.stream().sorted()
.forEach(ssaVar -> LOG.debug("Type bounds for {}: {}", ssaVar.toShortString(), ssaVar.getTypeInfo().getBounds()));
}
}
/**
* Guess type from usage and try to set it to current variable
* and all connected instructions with {@link TypeUpdate#apply(MethodNode, SSAVar, ArgType)}
*/
boolean runTypePropagation(MethodNode mth) {
List<SSAVar> ssaVars = mth.getSVars();
ssaVars.forEach(var -> setImmutableType(mth, var));
ssaVars.forEach(var -> setBestType(mth, var));
return true;
}
private void setImmutableType(MethodNode mth, SSAVar ssaVar) {
try {
ArgType immutableType = ssaVar.getImmutableType();
if (immutableType != null) {
TypeUpdateResult result = typeUpdate.applyWithWiderIgnSame(mth, ssaVar, immutableType);
if (Consts.DEBUG_TYPE_INFERENCE && result == TypeUpdateResult.REJECT) {
LOG.info("Reject initial immutable type {} for {}", immutableType, ssaVar);
}
}
} catch (JadxOverflowException e) {
throw e;
} catch (Exception e) {
mth.addWarnComment("Failed to set immutable type for var: " + ssaVar, e);
}
}
private void setBestType(MethodNode mth, SSAVar ssaVar) {
try {
calculateFromBounds(mth, ssaVar);
} catch (JadxOverflowException e) {
throw e;
} catch (Exception e) {
mth.addWarnComment("Failed to calculate best type for var: " + ssaVar, e);
}
}
private void calculateFromBounds(MethodNode mth, SSAVar ssaVar) {
TypeInfo typeInfo = ssaVar.getTypeInfo();
Set<ITypeBound> bounds = typeInfo.getBounds();
Optional<ArgType> bestTypeOpt = selectBestTypeFromBounds(bounds);
if (bestTypeOpt.isEmpty()) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.warn("Failed to select best type from bounds, count={} : ", bounds.size());
for (ITypeBound bound : bounds) {
LOG.warn(" {}", bound);
}
}
return;
}
ArgType candidateType = bestTypeOpt.get();
TypeUpdateResult result = typeUpdate.apply(mth, ssaVar, candidateType);
if (Consts.DEBUG_TYPE_INFERENCE && result == TypeUpdateResult.REJECT) {
if (ssaVar.getTypeInfo().getType().equals(candidateType)) {
LOG.info("Same type rejected: {} -> {}, bounds: {}", ssaVar, candidateType, bounds);
} else if (candidateType.isTypeKnown()) {
LOG.debug("Type rejected: {} -> {}, bounds: {}", ssaVar, candidateType, bounds);
}
}
}
private Optional<ArgType> selectBestTypeFromBounds(Set<ITypeBound> bounds) {
return bounds.stream()
.map(ITypeBound::getType)
.filter(Objects::nonNull)
.max(typeUpdate.getTypeCompare().getComparator());
}
private void attachBounds(SSAVar var) {
TypeInfo typeInfo = var.getTypeInfo();
typeInfo.getBounds().clear();
RegisterArg assign = var.getAssign();
addAssignBound(typeInfo, assign);
for (RegisterArg regArg : var.getUseList()) {
addBound(typeInfo, makeUseBound(regArg));
}
}
private void mergePhiBounds(SSAVar ssaVar) {
for (PhiInsn usedInPhi : ssaVar.getUsedInPhi()) {
Set<ITypeBound> bounds = ssaVar.getTypeInfo().getBounds();
bounds.addAll(usedInPhi.getResult().getSVar().getTypeInfo().getBounds());
for (InsnArg arg : usedInPhi.getArguments()) {
bounds.addAll(((RegisterArg) arg).getSVar().getTypeInfo().getBounds());
}
}
}
private void addBound(TypeInfo typeInfo, ITypeBound bound) {
if (bound == null) {
return;
}
if (bound instanceof ITypeBoundDynamic
|| bound.getType() != ArgType.UNKNOWN) {
typeInfo.getBounds().add(bound);
}
}
private void addAssignBound(TypeInfo typeInfo, RegisterArg assign) {
ArgType immutableType = assign.getImmutableType();
if (immutableType != null) {
addBound(typeInfo, new TypeBoundConst(BoundEnum.ASSIGN, immutableType));
return;
}
InsnNode insn = assign.getParentInsn();
if (insn == null || insn.getResult() == null) {
addBound(typeInfo, new TypeBoundConst(BoundEnum.ASSIGN, assign.getInitType()));
return;
}
switch (insn.getType()) {
case NEW_INSTANCE:
ArgType clsType = (ArgType) ((IndexInsnNode) insn).getIndex();
addBound(typeInfo, new TypeBoundConst(BoundEnum.ASSIGN, clsType));
break;
case CONSTRUCTOR:
ArgType ctrClsType = replaceAnonymousType((ConstructorInsn) insn);
addBound(typeInfo, new TypeBoundConst(BoundEnum.ASSIGN, ctrClsType));
break;
case CONST:
LiteralArg constLit = (LiteralArg) insn.getArg(0);
addBound(typeInfo, new TypeBoundConst(BoundEnum.ASSIGN, constLit.getType()));
break;
case MOVE_EXCEPTION:
ExcHandlerAttr excHandlerAttr = insn.get(AType.EXC_HANDLER);
if (excHandlerAttr != null) {
for (ClassInfo catchType : excHandlerAttr.getHandler().getCatchTypes()) {
addBound(typeInfo, new TypeBoundConst(BoundEnum.ASSIGN, catchType.getType()));
}
} else {
addBound(typeInfo, new TypeBoundConst(BoundEnum.ASSIGN, insn.getResult().getInitType()));
}
break;
case INVOKE:
addBound(typeInfo, makeAssignInvokeBound((InvokeNode) insn));
break;
case IGET:
addBound(typeInfo, makeAssignFieldGetBound((IndexInsnNode) insn));
break;
case CHECK_CAST:
if (insn.contains(AFlag.SOFT_CAST)) {
// ignore bound, will run checks on update
} else {
addBound(typeInfo, new TypeBoundCheckCastAssign(root, (IndexInsnNode) insn));
}
break;
default:
ArgType type = insn.getResult().getInitType();
addBound(typeInfo, new TypeBoundConst(BoundEnum.ASSIGN, type));
break;
}
}
private ArgType replaceAnonymousType(ConstructorInsn ctr) {
if (ctr.isNewInstance()) {
ClassNode ctrCls = root.resolveClass(ctr.getClassType());
if (ctrCls != null && ctrCls.contains(AFlag.DONT_GENERATE)) {
AnonymousClassAttr baseTypeAttr = ctrCls.get(AType.ANONYMOUS_CLASS);
if (baseTypeAttr != null && baseTypeAttr.getInlineType() == AnonymousClassAttr.InlineType.CONSTRUCTOR) {
return baseTypeAttr.getBaseType();
}
}
}
return ctr.getClassType().getType();
}
private ITypeBound makeAssignFieldGetBound(IndexInsnNode insn) {
ArgType initType = insn.getResult().getInitType();
if (initType.containsTypeVariable()) {
return new TypeBoundFieldGetAssign(root, insn, initType);
}
return new TypeBoundConst(BoundEnum.ASSIGN, initType);
}
private ITypeBound makeAssignInvokeBound(InvokeNode invokeNode) {
ArgType boundType = invokeNode.getCallMth().getReturnType();
ArgType genericReturnType = root.getMethodUtils().getMethodGenericReturnType(invokeNode);
if (genericReturnType != null) {
if (genericReturnType.containsTypeVariable()) {
InvokeType invokeType = invokeNode.getInvokeType();
if (invokeNode.getArgsCount() != 0
&& invokeType != InvokeType.STATIC && invokeType != InvokeType.SUPER) {
return new TypeBoundInvokeAssign(root, invokeNode, genericReturnType);
}
} else {
boundType = genericReturnType;
}
}
return new TypeBoundConst(BoundEnum.ASSIGN, boundType);
}
@Nullable
private ITypeBound makeUseBound(RegisterArg regArg) {
InsnNode insn = regArg.getParentInsn();
if (insn == null) {
return null;
}
if (insn instanceof BaseInvokeNode) {
ITypeBound invokeUseBound = makeInvokeUseBound(regArg, (BaseInvokeNode) insn);
if (invokeUseBound != null) {
return invokeUseBound;
}
}
if (insn.getType() == InsnType.CHECK_CAST && insn.contains(AFlag.SOFT_CAST)) {
// ignore
return null;
}
return new TypeBoundConst(BoundEnum.USE, regArg.getInitType(), regArg);
}
private ITypeBound makeInvokeUseBound(RegisterArg regArg, BaseInvokeNode invoke) {
InsnArg instanceArg = invoke.getInstanceArg();
if (instanceArg == null) {
return null;
}
MethodUtils methodUtils = root.getMethodUtils();
IMethodDetails methodDetails = methodUtils.getMethodDetails(invoke);
if (methodDetails == null) {
return null;
}
if (instanceArg != regArg) {
int argIndex = invoke.getArgIndex(regArg) - invoke.getFirstArgOffset();
ArgType argType = methodDetails.getArgTypes().get(argIndex);
if (!argType.containsTypeVariable()) {
return null;
}
return new TypeBoundInvokeUse(root, invoke, regArg, argType);
}
// for override methods use origin declared class as a type
if (methodDetails instanceof MethodNode) {
MethodNode callMth = (MethodNode) methodDetails;
ClassInfo declCls = methodUtils.getMethodOriginDeclClass(callMth);
return new TypeBoundConst(BoundEnum.USE, declCls.getType(), regArg);
}
return null;
}
private void assignImmutableTypes(MethodNode mth) {
for (SSAVar ssaVar : mth.getSVars()) {
ArgType immutableType = getSsaImmutableType(ssaVar);
if (immutableType != null) {
ssaVar.markAsImmutable(immutableType);
}
}
}
@Nullable
private static ArgType getSsaImmutableType(SSAVar ssaVar) {
if (ssaVar.getAssign().contains(AFlag.IMMUTABLE_TYPE)) {
return ssaVar.getAssign().getInitType();
}
for (RegisterArg reg : ssaVar.getUseList()) {
if (reg.contains(AFlag.IMMUTABLE_TYPE)) {
return reg.getInitType();
}
}
return null;
}
@Override
public String getName() {
return "TypeInferenceVisitor";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/FixTypesVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/FixTypesVisitor.java | package jadx.core.dex.visitors.typeinference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.Consts;
import jadx.core.clsp.ClspGraph;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.PhiListAttr;
import jadx.core.dex.instructions.ArithNode;
import jadx.core.dex.instructions.ArithOp;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.instructions.mods.TernaryInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.InitCodeVariables;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.ModVisitor;
import jadx.core.dex.visitors.blocks.BlockSplitter;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnList;
import jadx.core.utils.InsnUtils;
import jadx.core.utils.ListUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxOverflowException;
@JadxVisitor(
name = "Fix Types Visitor",
desc = "Try various methods to fix unresolved types",
runAfter = {
TypeInferenceVisitor.class
},
runBefore = {
FinishTypeInference.class
}
)
public final class FixTypesVisitor extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(FixTypesVisitor.class);
private final TypeInferenceVisitor typeInference = new TypeInferenceVisitor();
private TypeUpdate typeUpdate;
private List<Function<MethodNode, Boolean>> resolvers;
@Override
public void init(RootNode root) {
this.typeUpdate = root.getTypeUpdate();
this.typeInference.init(root);
this.resolvers = Arrays.asList(
this::tryRestoreTypeVarCasts,
this::tryInsertCasts,
this::tryDeduceTypes,
this::trySplitConstInsns,
this::tryToFixIncompatiblePrimitives,
this::tryToForceImmutableTypes,
this::tryInsertAdditionalMove,
this::runMultiVariableSearch,
this::tryRemoveGenerics);
}
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode() || checkTypes(mth)) {
return;
}
try {
for (Function<MethodNode, Boolean> resolver : resolvers) {
if (resolver.apply(mth) && checkTypes(mth)) {
break;
}
}
} catch (Exception e) {
mth.addError("Types fix failed", e);
}
}
/**
* Check if all types resolved
*/
private static boolean checkTypes(MethodNode mth) {
for (SSAVar var : mth.getSVars()) {
ArgType type = var.getTypeInfo().getType();
if (!type.isTypeKnown()) {
return false;
}
}
return true;
}
private boolean runMultiVariableSearch(MethodNode mth) {
try {
TypeSearch typeSearch = new TypeSearch(mth);
if (!typeSearch.run()) {
mth.addWarnComment("Multi-variable type inference failed");
}
for (SSAVar var : mth.getSVars()) {
if (!var.getTypeInfo().getType().isTypeKnown()) {
return false;
}
}
return true;
} catch (Exception e) {
mth.addWarnComment("Multi-variable type inference failed. Error: " + Utils.getStackTrace(e));
return false;
}
}
private boolean setBestType(MethodNode mth, SSAVar ssaVar) {
try {
return calculateFromBounds(mth, ssaVar);
} catch (JadxOverflowException e) {
throw e;
} catch (Exception e) {
mth.addWarnComment("Failed to calculate best type for var: " + ssaVar, e);
return false;
}
}
private boolean calculateFromBounds(MethodNode mth, SSAVar ssaVar) {
TypeInfo typeInfo = ssaVar.getTypeInfo();
Set<ITypeBound> bounds = typeInfo.getBounds();
Optional<ArgType> bestTypeOpt = selectBestTypeFromBounds(bounds);
if (bestTypeOpt.isEmpty()) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.warn("Failed to select best type from bounds, count={} : ", bounds.size());
for (ITypeBound bound : bounds) {
LOG.warn(" {}", bound);
}
}
return false;
}
ArgType candidateType = bestTypeOpt.get();
TypeUpdateResult result = typeUpdate.apply(mth, ssaVar, candidateType);
if (result == TypeUpdateResult.REJECT) {
if (Consts.DEBUG_TYPE_INFERENCE) {
if (ssaVar.getTypeInfo().getType().equals(candidateType)) {
LOG.info("Same type rejected: {} -> {}, bounds: {}", ssaVar, candidateType, bounds);
} else if (candidateType.isTypeKnown()) {
LOG.debug("Type rejected: {} -> {}, bounds: {}", ssaVar, candidateType, bounds);
}
}
return false;
}
return result == TypeUpdateResult.CHANGED;
}
private Optional<ArgType> selectBestTypeFromBounds(Set<ITypeBound> bounds) {
return bounds.stream()
.map(ITypeBound::getType)
.filter(Objects::nonNull)
.max(typeUpdate.getTypeCompare().getComparator());
}
private boolean tryPossibleTypes(MethodNode mth, SSAVar var, ArgType type) {
List<ArgType> types = makePossibleTypesList(type, var);
if (types.isEmpty()) {
return false;
}
for (ArgType candidateType : types) {
TypeUpdateResult result = typeUpdate.apply(mth, var, candidateType);
if (result == TypeUpdateResult.CHANGED) {
return true;
}
}
return false;
}
private List<ArgType> makePossibleTypesList(ArgType type, @Nullable SSAVar var) {
if (type.isArray()) {
List<ArgType> list = new ArrayList<>();
for (ArgType arrElemType : makePossibleTypesList(type.getArrayElement(), null)) {
list.add(ArgType.array(arrElemType));
}
return list;
}
if (var != null) {
for (ITypeBound b : var.getTypeInfo().getBounds()) {
ArgType boundType = b.getType();
if (boundType.isObject() || boundType.isArray()) {
// don't add primitive types
return Collections.emptyList();
}
}
}
List<ArgType> list = new ArrayList<>();
for (PrimitiveType possibleType : type.getPossibleTypes()) {
if (possibleType == PrimitiveType.VOID) {
continue;
}
list.add(ArgType.convertFromPrimitiveType(possibleType));
}
return list;
}
private boolean tryDeduceTypes(MethodNode mth) {
boolean fixed = false;
for (SSAVar ssaVar : mth.getSVars()) {
if (deduceType(mth, ssaVar)) {
fixed = true;
}
}
return fixed;
}
@SuppressWarnings("RedundantIfStatement")
private boolean deduceType(MethodNode mth, SSAVar var) {
if (var.isTypeImmutable()) {
return false;
}
ArgType type = var.getTypeInfo().getType();
if (type.isTypeKnown()) {
return false;
}
// try best type from bounds again
if (setBestType(mth, var)) {
return true;
}
// try all possible types (useful for primitives)
if (tryPossibleTypes(mth, var, type)) {
return true;
}
// for objects try super types
if (tryWiderObjects(mth, var)) {
return true;
}
return false;
}
private boolean tryRemoveGenerics(MethodNode mth) {
boolean resolved = true;
for (SSAVar var : mth.getSVars()) {
ArgType type = var.getTypeInfo().getType();
if (!type.isTypeKnown()
&& !var.isTypeImmutable()
&& !tryRawType(mth, var)) {
resolved = false;
}
}
return resolved;
}
private boolean tryRawType(MethodNode mth, SSAVar var) {
Set<ArgType> objTypes = new LinkedHashSet<>();
for (ITypeBound bound : var.getTypeInfo().getBounds()) {
ArgType boundType = bound.getType();
if (boundType.isTypeKnown() && boundType.isObject()) {
objTypes.add(boundType);
}
}
if (objTypes.isEmpty()) {
return false;
}
for (ArgType objType : objTypes) {
if (checkRawType(mth, var, objType)) {
mth.addDebugComment("Type inference failed for " + var.toShortString() + "."
+ " Raw type applied. Possible types: " + Utils.listToString(objTypes));
return true;
}
}
return false;
}
private boolean checkRawType(MethodNode mth, SSAVar var, ArgType objType) {
if (objType.isObject() && objType.containsGeneric()) {
ArgType rawType = objType.isGenericType() ? ArgType.OBJECT : ArgType.object(objType.getObject());
TypeUpdateResult result = typeUpdate.applyWithWiderAllow(mth, var, rawType);
return result == TypeUpdateResult.CHANGED;
}
return false;
}
/**
* Fix check casts to type var extend type:
* <br>
* {@code <T extends Comparable> T var = (Comparable) obj; => T var = (T) obj; }
*/
private boolean tryRestoreTypeVarCasts(MethodNode mth) {
int changed = 0;
List<SSAVar> mthSVars = mth.getSVars();
for (SSAVar var : mthSVars) {
changed += restoreTypeVarCasts(var);
}
if (changed == 0) {
return false;
}
if (Consts.DEBUG_TYPE_INFERENCE) {
mth.addDebugComment("Restore " + changed + " type vars casts");
}
typeInference.initTypeBounds(mth);
return typeInference.runTypePropagation(mth);
}
private int restoreTypeVarCasts(SSAVar var) {
TypeInfo typeInfo = var.getTypeInfo();
Set<ITypeBound> bounds = typeInfo.getBounds();
if (!ListUtils.anyMatch(bounds, t -> t.getType().isGenericType())) {
return 0;
}
List<ITypeBound> casts = ListUtils.filter(bounds, TypeBoundCheckCastAssign.class::isInstance);
if (casts.isEmpty()) {
return 0;
}
ArgType bestType = selectBestTypeFromBounds(bounds).orElse(ArgType.UNKNOWN);
if (!bestType.isGenericType()) {
return 0;
}
List<ArgType> extendTypes = bestType.getExtendTypes();
if (extendTypes.size() != 1) {
return 0;
}
int fixed = 0;
ArgType extendType = extendTypes.get(0);
for (ITypeBound bound : casts) {
TypeBoundCheckCastAssign cast = (TypeBoundCheckCastAssign) bound;
ArgType castType = cast.getType();
TypeCompareEnum result = typeUpdate.getTypeCompare().compareTypes(extendType, castType);
if (result.isEqual() || result == TypeCompareEnum.NARROW_BY_GENERIC) {
cast.getInsn().updateIndex(bestType);
fixed++;
}
}
return fixed;
}
@SuppressWarnings({ "ForLoopReplaceableByWhile", "ForLoopReplaceableByForEach" })
private boolean tryInsertCasts(MethodNode mth) {
int added = 0;
List<SSAVar> mthSVars = mth.getSVars();
int varsCount = mthSVars.size();
for (int i = 0; i < varsCount; i++) {
SSAVar var = mthSVars.get(i);
ArgType type = var.getTypeInfo().getType();
if (!type.isTypeKnown() && !var.isTypeImmutable()) {
added += tryInsertVarCast(mth, var);
}
}
if (added != 0) {
InitCodeVariables.rerun(mth);
typeInference.initTypeBounds(mth);
return typeInference.runTypePropagation(mth);
}
return false;
}
private int tryInsertVarCast(MethodNode mth, SSAVar var) {
for (ITypeBound bound : var.getTypeInfo().getBounds()) {
ArgType boundType = bound.getType();
if (boundType.isTypeKnown()
&& !boundType.equals(var.getTypeInfo().getType())
&& boundType.containsTypeVariable()
&& !mth.root().getTypeUtils().containsUnknownTypeVar(mth, boundType)) {
if (insertAssignCast(mth, var, boundType)) {
return 1;
}
return insertUseCasts(mth, var);
}
}
return 0;
}
private int insertUseCasts(MethodNode mth, SSAVar var) {
List<RegisterArg> useList = var.getUseList();
if (useList.isEmpty()) {
return 0;
}
int useCasts = 0;
for (RegisterArg useReg : new ArrayList<>(useList)) {
if (insertSoftUseCast(mth, useReg)) {
useCasts++;
}
}
return useCasts;
}
private boolean insertAssignCast(MethodNode mth, SSAVar var, ArgType castType) {
RegisterArg assignArg = var.getAssign();
InsnNode assignInsn = assignArg.getParentInsn();
if (assignInsn == null || assignInsn.getType() == InsnType.PHI) {
return false;
}
BlockNode assignBlock = BlockUtils.getBlockByInsn(mth, assignInsn);
if (assignBlock == null) {
return false;
}
assignInsn.setResult(assignArg.duplicateWithNewSSAVar(mth));
IndexInsnNode castInsn = makeSoftCastInsn(assignArg.duplicate(), assignInsn.getResult().duplicate(), castType);
return BlockUtils.insertAfterInsn(assignBlock, assignInsn, castInsn);
}
private boolean insertSoftUseCast(MethodNode mth, RegisterArg useArg) {
InsnNode useInsn = useArg.getParentInsn();
if (useInsn == null || useInsn.getType() == InsnType.PHI) {
return false;
}
if (useInsn.getType() == InsnType.IF && useInsn.getArg(1).isZeroConst()) {
// cast isn't needed if compare with null
return false;
}
BlockNode useBlock = BlockUtils.getBlockByInsn(mth, useInsn);
if (useBlock == null) {
return false;
}
IndexInsnNode castInsn = makeSoftCastInsn(
useArg.duplicateWithNewSSAVar(mth),
useArg.duplicate(),
useArg.getInitType());
useInsn.replaceArg(useArg, castInsn.getResult().duplicate());
boolean success = BlockUtils.insertBeforeInsn(useBlock, useInsn, castInsn);
if (Consts.DEBUG_TYPE_INFERENCE && success) {
LOG.info("Insert soft cast for {} before {} in {}", useArg, useInsn, useBlock);
}
return success;
}
private IndexInsnNode makeSoftCastInsn(RegisterArg result, RegisterArg arg, ArgType castType) {
IndexInsnNode castInsn = new IndexInsnNode(InsnType.CHECK_CAST, castType, 1);
castInsn.setResult(result);
castInsn.addArg(arg);
castInsn.add(AFlag.SOFT_CAST);
castInsn.add(AFlag.SYNTHETIC);
return castInsn;
}
private boolean trySplitConstInsns(MethodNode mth) {
boolean constSplit = false;
for (SSAVar var : new ArrayList<>(mth.getSVars())) {
if (checkAndSplitConstInsn(mth, var)) {
constSplit = true;
}
}
if (!constSplit) {
return false;
}
InitCodeVariables.rerun(mth);
typeInference.initTypeBounds(mth);
return typeInference.runTypePropagation(mth);
}
private boolean checkAndSplitConstInsn(MethodNode mth, SSAVar var) {
ArgType type = var.getTypeInfo().getType();
if (type.isTypeKnown() || var.isTypeImmutable()) {
return false;
}
return splitByPhi(mth, var) || dupConst(mth, var);
}
private boolean dupConst(MethodNode mth, SSAVar var) {
InsnNode assignInsn = var.getAssign().getAssignInsn();
if (!InsnUtils.isInsnType(assignInsn, InsnType.CONST)) {
return false;
}
if (var.getUseList().size() < 2) {
return false;
}
BlockNode assignBlock = BlockUtils.getBlockByInsn(mth, assignInsn);
if (assignBlock == null) {
return false;
}
assignInsn.remove(AFlag.DONT_INLINE);
int insertIndex = 1 + BlockUtils.getInsnIndexInBlock(assignBlock, assignInsn);
List<RegisterArg> useList = new ArrayList<>(var.getUseList());
for (int i = 0, useCount = useList.size(); i < useCount; i++) {
RegisterArg useArg = useList.get(i);
useArg.remove(AFlag.DONT_INLINE_CONST);
if (i == 0) {
continue;
}
InsnNode useInsn = useArg.getParentInsn();
if (useInsn == null) {
continue;
}
InsnNode newInsn = assignInsn.copyWithNewSsaVar(mth);
assignBlock.getInstructions().add(insertIndex, newInsn);
useInsn.replaceArg(useArg, newInsn.getResult().duplicate());
}
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Duplicate const insn {} times: {} in {}", useList.size(), assignInsn, assignBlock);
}
return true;
}
/**
* For every PHI make separate CONST insn
*/
private static boolean splitByPhi(MethodNode mth, SSAVar var) {
if (var.getUsedInPhi().size() < 2) {
return false;
}
InsnNode assignInsn = var.getAssign().getAssignInsn();
InsnNode constInsn = InsnUtils.checkInsnType(assignInsn, InsnType.CONST);
if (constInsn == null) {
return false;
}
BlockNode blockNode = BlockUtils.getBlockByInsn(mth, constInsn);
if (blockNode == null) {
return false;
}
boolean first = true;
for (PhiInsn phiInsn : var.getUsedInPhi()) {
if (first) {
first = false;
continue;
}
InsnNode copyInsn = constInsn.copyWithNewSsaVar(mth);
copyInsn.add(AFlag.SYNTHETIC);
BlockUtils.insertAfterInsn(blockNode, constInsn, copyInsn);
RegisterArg phiArg = phiInsn.getArgBySsaVar(var);
phiInsn.replaceArg(phiArg, copyInsn.getResult().duplicate());
}
return true;
}
private boolean tryInsertAdditionalMove(MethodNode mth) {
int insnsAdded = 0;
for (BlockNode block : mth.getBasicBlocks()) {
PhiListAttr phiListAttr = block.get(AType.PHI_LIST);
if (phiListAttr != null) {
for (PhiInsn phiInsn : phiListAttr.getList()) {
insnsAdded += tryInsertAdditionalInsn(mth, phiInsn);
}
}
}
if (insnsAdded == 0) {
return false;
}
if (Consts.DEBUG_TYPE_INFERENCE) {
mth.addDebugComment("Additional " + insnsAdded + " move instructions added to help type inference");
}
InitCodeVariables.rerun(mth);
typeInference.initTypeBounds(mth);
if (typeInference.runTypePropagation(mth) && checkTypes(mth)) {
return true;
}
return tryDeduceTypes(mth);
}
/**
* Add MOVE instruction before PHI in bound blocks to make 'soft' type link.
* This allows using different types in blocks merged by PHI.
*/
private int tryInsertAdditionalInsn(MethodNode mth, PhiInsn phiInsn) {
ArgType phiType = getCommonTypeForPhiArgs(phiInsn);
if (phiType != null && phiType.isTypeKnown()) {
// all args have the same known type => nothing to do here
return 0;
}
// check if instructions can be inserted
if (insertMovesForPhi(mth, phiInsn, false) == 0) {
return 0;
}
// check passed => apply
return insertMovesForPhi(mth, phiInsn, true);
}
@Nullable
private ArgType getCommonTypeForPhiArgs(PhiInsn phiInsn) {
ArgType phiArgType = null;
for (InsnArg arg : phiInsn.getArguments()) {
ArgType type = arg.getType();
if (phiArgType == null) {
phiArgType = type;
} else if (!phiArgType.equals(type)) {
return null;
}
}
return phiArgType;
}
private int insertMovesForPhi(MethodNode mth, PhiInsn phiInsn, boolean apply) {
int argsCount = phiInsn.getArgsCount();
int count = 0;
for (int argIndex = 0; argIndex < argsCount; argIndex++) {
RegisterArg reg = phiInsn.getArg(argIndex);
BlockNode startBlock = phiInsn.getBlockByArgIndex(argIndex);
BlockNode blockNode = checkBlockForInsnInsert(startBlock);
if (blockNode == null) {
mth.addDebugComment("Failed to insert an additional move for type inference into block " + startBlock);
return 0;
}
boolean add = true;
SSAVar var = reg.getSVar();
InsnNode assignInsn = var.getAssign().getAssignInsn();
if (assignInsn != null) {
InsnType assignType = assignInsn.getType();
if (assignType == InsnType.CONST
|| (assignType == InsnType.MOVE && var.getUseCount() == 1)) {
add = false;
}
}
if (add) {
count++;
if (apply) {
insertMove(mth, blockNode, phiInsn, reg);
}
}
}
return count;
}
private void insertMove(MethodNode mth, BlockNode blockNode, PhiInsn phiInsn, RegisterArg reg) {
SSAVar var = reg.getSVar();
int regNum = reg.getRegNum();
RegisterArg resultArg = reg.duplicate(regNum, null);
SSAVar newSsaVar = mth.makeNewSVar(resultArg);
RegisterArg arg = reg.duplicate(regNum, var);
InsnNode moveInsn = new InsnNode(InsnType.MOVE, 1);
moveInsn.setResult(resultArg);
moveInsn.addArg(arg);
moveInsn.add(AFlag.SYNTHETIC);
blockNode.getInstructions().add(moveInsn);
phiInsn.replaceArg(reg, reg.duplicate(regNum, newSsaVar));
}
@Nullable
private BlockNode checkBlockForInsnInsert(BlockNode blockNode) {
if (blockNode.isSynthetic()) {
return null;
}
InsnNode lastInsn = BlockUtils.getLastInsn(blockNode);
if (lastInsn != null && BlockSplitter.isSeparate(lastInsn.getType())) {
// can't insert move in a block with 'separate' instruction => try previous block by simple path
List<BlockNode> preds = blockNode.getPredecessors();
if (preds.size() == 1) {
return checkBlockForInsnInsert(preds.get(0));
}
return null;
}
return blockNode;
}
private boolean tryWiderObjects(MethodNode mth, SSAVar var) {
Set<ArgType> objTypes = new LinkedHashSet<>();
for (ITypeBound bound : var.getTypeInfo().getBounds()) {
ArgType boundType = bound.getType();
if (boundType.isTypeKnown() && boundType.isObject()) {
objTypes.add(boundType);
}
}
if (objTypes.isEmpty()) {
return false;
}
ClspGraph clsp = mth.root().getClsp();
for (ArgType objType : objTypes) {
for (String ancestor : clsp.getSuperTypes(objType.getObject())) {
ArgType ancestorType = ArgType.object(ancestor);
TypeUpdateResult result = typeUpdate.applyWithWiderAllow(mth, var, ancestorType);
if (result == TypeUpdateResult.CHANGED) {
return true;
}
}
}
return false;
}
@SuppressWarnings("ForLoopReplaceableByForEach")
private boolean tryToFixIncompatiblePrimitives(MethodNode mth) {
boolean fixed = false;
List<SSAVar> ssaVars = mth.getSVars();
int ssaVarsCount = ssaVars.size();
// new vars will be added at a list end if fix is applied (can't use for-each loop here)
for (int i = 0; i < ssaVarsCount; i++) {
if (processIncompatiblePrimitives(mth, ssaVars.get(i))) {
fixed = true;
}
}
if (!fixed) {
return false;
}
InitCodeVariables.rerun(mth);
typeInference.initTypeBounds(mth);
return typeInference.runTypePropagation(mth);
}
private boolean processIncompatiblePrimitives(MethodNode mth, SSAVar var) {
TypeInfo typeInfo = var.getTypeInfo();
if (typeInfo.getType().isTypeKnown()) {
return false;
}
boolean assigned = false;
for (ITypeBound bound : typeInfo.getBounds()) {
ArgType boundType = bound.getType();
switch (bound.getBound()) {
case ASSIGN:
if (!boundType.contains(PrimitiveType.BOOLEAN)) {
return false;
}
assigned = true;
break;
case USE:
if (!boundType.canBeAnyNumber()) {
return false;
}
break;
}
}
if (!assigned) {
return false;
}
boolean fixed = false;
for (RegisterArg arg : new ArrayList<>(var.getUseList())) {
if (fixBooleanUsage(mth, arg)) {
fixed = true;
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.info("Fixed boolean usage for arg {} from {}", arg, arg.getParentInsn());
}
}
}
return fixed;
}
private boolean fixBooleanUsage(MethodNode mth, RegisterArg boundArg) {
ArgType boundType = boundArg.getInitType();
if (boundType == ArgType.BOOLEAN
|| (boundType.isTypeKnown() && !boundType.isPrimitive())) {
return false;
}
InsnNode insn = boundArg.getParentInsn();
if (insn == null || insn.getType() == InsnType.IF) {
return false;
}
BlockNode blockNode = BlockUtils.getBlockByInsn(mth, insn);
if (blockNode == null) {
return false;
}
List<InsnNode> insnList = blockNode.getInstructions();
int insnIndex = InsnList.getIndex(insnList, insn);
if (insnIndex == -1) {
return false;
}
InsnType insnType = insn.getType();
if (insnType == InsnType.CAST) {
// replace cast
ArgType type = (ArgType) ((IndexInsnNode) insn).getIndex();
TernaryInsn convertInsn = prepareBooleanConvertInsn(insn.getResult(), boundArg, type);
BlockUtils.replaceInsn(mth, blockNode, insnIndex, convertInsn);
return true;
}
if (insnType == InsnType.ARITH) {
ArithNode arithInsn = (ArithNode) insn;
if (arithInsn.getOp() == ArithOp.XOR && arithInsn.getArgsCount() == 2) {
// replace (boolean ^ 1) with (!boolean)
InsnArg secondArg = arithInsn.getArg(1);
if (secondArg.isLiteral() && ((LiteralArg) secondArg).getLiteral() == 1) {
InsnNode convertInsn = notBooleanToInt(arithInsn, boundArg);
BlockUtils.replaceInsn(mth, blockNode, insnIndex, convertInsn);
return true;
}
}
}
// insert before insn
RegisterArg resultArg = boundArg.duplicateWithNewSSAVar(mth);
TernaryInsn convertInsn = prepareBooleanConvertInsn(resultArg, boundArg, boundType);
insnList.add(insnIndex, convertInsn);
insn.replaceArg(boundArg, convertInsn.getResult().duplicate());
return true;
}
private InsnNode notBooleanToInt(ArithNode insn, RegisterArg boundArg) {
InsnNode notInsn = new InsnNode(InsnType.NOT, 1);
notInsn.addArg(boundArg.duplicate());
notInsn.add(AFlag.SYNTHETIC);
ArgType resType = insn.getResult().getType();
if (resType.canBePrimitive(PrimitiveType.BOOLEAN)) {
notInsn.setResult(insn.getResult());
return notInsn;
}
InsnArg notArg = InsnArg.wrapArg(notInsn);
notArg.setType(ArgType.BOOLEAN);
TernaryInsn convertInsn = ModVisitor.makeBooleanConvertInsn(insn.getResult(), notArg, ArgType.INT);
convertInsn.add(AFlag.SYNTHETIC);
return convertInsn;
}
private TernaryInsn prepareBooleanConvertInsn(RegisterArg resultArg, RegisterArg boundArg, ArgType useType) {
RegisterArg useArg = boundArg.getSVar().getAssign().duplicate();
TernaryInsn convertInsn = ModVisitor.makeBooleanConvertInsn(resultArg, useArg, useType);
convertInsn.add(AFlag.SYNTHETIC);
return convertInsn;
}
private boolean tryToForceImmutableTypes(MethodNode mth) {
boolean fixed = false;
for (SSAVar ssaVar : mth.getSVars()) {
ArgType type = ssaVar.getTypeInfo().getType();
if (!type.isTypeKnown() && ssaVar.isTypeImmutable()) {
if (forceImmutableType(ssaVar)) {
fixed = true;
}
}
}
if (!fixed) {
return false;
}
return typeInference.runTypePropagation(mth);
}
private boolean forceImmutableType(SSAVar ssaVar) {
for (RegisterArg useArg : ssaVar.getUseList()) {
InsnNode parentInsn = useArg.getParentInsn();
if (parentInsn != null) {
InsnType insnType = parentInsn.getType();
if (insnType == InsnType.AGET || insnType == InsnType.APUT) {
ssaVar.setType(ssaVar.getImmutableType());
return true;
}
}
}
return false;
}
@Override
public String getName() {
return "FixTypesVisitor";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateResult.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateResult.java | package jadx.core.dex.visitors.typeinference;
public enum TypeUpdateResult {
REJECT,
SAME,
CHANGED
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundCheckCastAssign.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundCheckCastAssign.java | package jadx.core.dex.visitors.typeinference;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.RootNode;
/**
* Allow ignoring down casts (return arg type instead cast type)
* Such casts will be removed later.
*/
public final class TypeBoundCheckCastAssign implements ITypeBoundDynamic {
private final RootNode root;
private final IndexInsnNode insn;
public TypeBoundCheckCastAssign(RootNode root, IndexInsnNode insn) {
this.root = root;
this.insn = insn;
}
@Override
public BoundEnum getBound() {
return BoundEnum.ASSIGN;
}
@Override
public ArgType getType(TypeUpdateInfo updateInfo) {
return getReturnType(updateInfo.getType(insn.getArg(0)));
}
@Override
public ArgType getType() {
return getReturnType(insn.getArg(0).getType());
}
private ArgType getReturnType(ArgType argType) {
ArgType castType = insn.getIndexAsType();
TypeCompareEnum result = root.getTypeCompare().compareTypes(argType, castType);
return result.isNarrow() ? argType : castType;
}
@Override
public @Nullable RegisterArg getArg() {
return insn.getResult();
}
public IndexInsnNode getInsn() {
return insn;
}
@Override
public String toString() {
return "CHECK_CAST_ASSIGN{(" + insn.getIndex() + ") " + insn.getArg(0).getType() + "}";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateInfo.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateInfo.java | package jadx.core.dex.visitors.typeinference;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import jadx.api.JadxArgs;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.exceptions.JadxOverflowException;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class TypeUpdateInfo {
private final MethodNode mth;
private final TypeUpdateFlags flags;
private final Map<InsnArg, TypeUpdateEntry> updateMap = new IdentityHashMap<>();
private final int updatesLimitCount;
private int updateSeq = 0;
public TypeUpdateInfo(MethodNode mth, TypeUpdateFlags flags, JadxArgs args) {
this.mth = mth;
this.flags = flags;
this.updatesLimitCount = mth.getInsnsCount() * args.getTypeUpdatesLimitCount();
}
public void requestUpdate(InsnArg arg, ArgType changeType) {
TypeUpdateEntry prev = updateMap.put(arg, new TypeUpdateEntry(updateSeq++, arg, changeType));
if (prev != null) {
throw new JadxRuntimeException("Unexpected type update override for arg: " + arg
+ " types: prev=" + prev.getType() + ", new=" + changeType
+ ", insn: " + arg.getParentInsn());
}
if (updateSeq > updatesLimitCount) {
throw new JadxOverflowException("Type inference error: updates count limit reached"
+ " with updateSeq = " + updateSeq + ". Try increasing the type limit count on preferences.");
}
}
public void rollbackUpdate(InsnArg arg) {
TypeUpdateEntry removed = updateMap.remove(arg);
if (removed != null) {
int seq = removed.getSeq();
updateMap.values().removeIf(upd -> upd.getSeq() > seq);
}
}
public void applyUpdates() {
updateMap.values().stream().sorted()
.forEach(upd -> upd.getArg().setType(upd.getType()));
}
public boolean isProcessed(InsnArg arg) {
return updateMap.containsKey(arg);
}
public boolean hasUpdateWithType(InsnArg arg, ArgType type) {
TypeUpdateEntry updateEntry = updateMap.get(arg);
if (updateEntry != null) {
return updateEntry.getType().equals(type);
}
return false;
}
public ArgType getType(InsnArg arg) {
TypeUpdateEntry updateEntry = updateMap.get(arg);
if (updateEntry != null) {
return updateEntry.getType();
}
return arg.getType();
}
public MethodNode getMth() {
return mth;
}
public boolean isEmpty() {
return updateMap.isEmpty();
}
public List<TypeUpdateEntry> getSortedUpdates() {
return updateMap.values().stream().sorted().collect(Collectors.toList());
}
public TypeUpdateFlags getFlags() {
return flags;
}
@Override
public String toString() {
return "TypeUpdateInfo{" + flags + ' ' + getSortedUpdates() + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/BoundEnum.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/BoundEnum.java | package jadx.core.dex.visitors.typeinference;
public enum BoundEnum {
ASSIGN,
USE
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundInvokeAssign.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundInvokeAssign.java | package jadx.core.dex.visitors.typeinference;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.IMethodDetails;
import jadx.core.dex.nodes.RootNode;
/**
* Special dynamic bound for invoke with generics.
* Bound type calculated using instance generic type.
* TODO: also can depends on argument types
*/
public final class TypeBoundInvokeAssign implements ITypeBoundDynamic {
private final RootNode root;
private final InvokeNode invokeNode;
private final ArgType genericReturnType;
public TypeBoundInvokeAssign(RootNode root, InvokeNode invokeNode, ArgType genericReturnType) {
this.root = root;
this.invokeNode = invokeNode;
this.genericReturnType = genericReturnType;
}
@Override
public BoundEnum getBound() {
return BoundEnum.ASSIGN;
}
@Override
public ArgType getType(TypeUpdateInfo updateInfo) {
return getReturnType(updateInfo.getType(getInstanceArg()));
}
@Override
public ArgType getType() {
return getReturnType(getInstanceArg().getType());
}
private ArgType getReturnType(ArgType instanceType) {
ArgType mthDeclType;
IMethodDetails methodDetails = root.getMethodUtils().getMethodDetails(invokeNode);
if (methodDetails != null) {
// use methods detail to resolve declaration class for virtual invokes
mthDeclType = methodDetails.getMethodInfo().getDeclClass().getType();
} else {
mthDeclType = instanceType;
}
ArgType resultGeneric = root.getTypeUtils().replaceClassGenerics(instanceType, mthDeclType, genericReturnType);
ArgType result = processResultType(resultGeneric);
if (result != null) {
return result;
}
return invokeNode.getCallMth().getReturnType();
}
@Nullable
private ArgType processResultType(@Nullable ArgType resultGeneric) {
if (resultGeneric == null) {
return null;
}
if (!resultGeneric.isWildcard()) {
return resultGeneric;
}
return resultGeneric.getWildcardType();
}
private InsnArg getInstanceArg() {
return invokeNode.getArg(0);
}
@Override
public RegisterArg getArg() {
return invokeNode.getResult();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TypeBoundInvokeAssign that = (TypeBoundInvokeAssign) o;
return invokeNode.equals(that.invokeNode);
}
@Override
public int hashCode() {
return invokeNode.hashCode();
}
@Override
public String toString() {
return "InvokeAssign{" + invokeNode.getCallMth().getShortId()
+ ", returnType=" + genericReturnType
+ ", currentType=" + getType()
+ ", instanceArg=" + getInstanceArg()
+ '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/FinishTypeInference.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/FinishTypeInference.java | package jadx.core.dex.visitors.typeinference;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
@JadxVisitor(
name = "Finish Type Inference",
desc = "Check used types",
runAfter = {
TypeInferenceVisitor.class
}
)
public final class FinishTypeInference extends AbstractVisitor {
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode() || mth.getSVars().isEmpty()) {
return;
}
mth.getSVars().forEach(var -> {
ArgType type = var.getTypeInfo().getType();
if (!type.isTypeKnown()) {
mth.addWarnComment("Type inference failed for: " + var.getDetailedVarInfo(mth));
}
ArgType codeVarType = var.getCodeVar().getType();
if (codeVarType == null) {
var.getCodeVar().setType(ArgType.UNKNOWN);
}
});
}
@Override
public String getName() {
return "FinishTypeInference";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeSearchState.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeSearchState.java | package jadx.core.dex.visitors.typeinference;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class TypeSearchState {
private final Map<SSAVar, TypeSearchVarInfo> varInfoMap;
public TypeSearchState(MethodNode mth) {
List<SSAVar> vars = mth.getSVars();
this.varInfoMap = new LinkedHashMap<>(vars.size());
for (SSAVar var : vars) {
varInfoMap.put(var, new TypeSearchVarInfo(var));
}
}
@NotNull
public TypeSearchVarInfo getVarInfo(SSAVar var) {
TypeSearchVarInfo varInfo = this.varInfoMap.get(var);
if (varInfo == null) {
throw new JadxRuntimeException("TypeSearchVarInfo not found in map for var: " + var);
}
return varInfo;
}
public ArgType getArgType(InsnArg arg) {
if (arg.isRegister()) {
RegisterArg reg = (RegisterArg) arg;
return getVarInfo(reg.getSVar()).getCurrentType();
}
return arg.getType();
}
public List<TypeSearchVarInfo> getAllVars() {
return new ArrayList<>(varInfoMap.values());
}
public List<TypeSearchVarInfo> getUnresolvedVars() {
return varInfoMap.values().stream()
.filter(varInfo -> !varInfo.isTypeResolved())
.collect(Collectors.toList());
}
public List<TypeSearchVarInfo> getResolvedVars() {
return varInfoMap.values().stream()
.filter(TypeSearchVarInfo::isTypeResolved)
.collect(Collectors.toList());
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeCompare.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeCompare.java | package jadx.core.dex.visitors.typeinference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.ArgType.WildcardBound;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.CONFLICT;
import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.CONFLICT_BY_GENERIC;
import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.EQUAL;
import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.NARROW;
import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.NARROW_BY_GENERIC;
import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.UNKNOWN;
import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.WIDER;
import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.WIDER_BY_GENERIC;
import static jadx.core.utils.Utils.isEmpty;
public class TypeCompare {
private static final Logger LOG = LoggerFactory.getLogger(TypeCompare.class);
private final RootNode root;
private final Comparator<ArgType> comparator;
private final Comparator<ArgType> reversedComparator;
public TypeCompare(RootNode root) {
this.root = root;
this.comparator = new ArgTypeComparator();
this.reversedComparator = comparator.reversed();
}
public TypeCompareEnum compareTypes(ClassNode first, ClassNode second) {
return compareObjects(first.getType(), second.getType());
}
public TypeCompareEnum compareTypes(ClassInfo first, ClassInfo second) {
return compareObjects(first.getType(), second.getType());
}
public TypeCompareEnum compareObjects(ArgType first, ArgType second) {
if (first == second || Objects.equals(first, second)) {
return TypeCompareEnum.EQUAL;
}
return compareObjectsNoPreCheck(first, second);
}
/**
* Compare two type and return result for first argument (narrow, wider or conflict)
*/
public TypeCompareEnum compareTypes(ArgType first, ArgType second) {
if (first == second || Objects.equals(first, second)) {
return TypeCompareEnum.EQUAL;
}
boolean firstKnown = first.isTypeKnown();
boolean secondKnown = second.isTypeKnown();
if (firstKnown != secondKnown) {
if (firstKnown) {
return compareWithUnknown(first, second);
} else {
return compareWithUnknown(second, first).invert();
}
}
boolean firstArray = first.isArray();
boolean secondArray = second.isArray();
if (firstArray != secondArray) {
if (firstArray) {
return compareArrayWithOtherType(first, second);
} else {
return compareArrayWithOtherType(second, first).invert();
}
}
if (firstArray /* && secondArray */) {
// both arrays
return compareTypes(first.getArrayElement(), second.getArrayElement());
}
if (!firstKnown /* && !secondKnown */) {
int variantLen = Integer.compare(first.getPossibleTypes().length, second.getPossibleTypes().length);
return variantLen > 0 ? WIDER : NARROW;
}
boolean firstPrimitive = first.isPrimitive();
boolean secondPrimitive = second.isPrimitive();
boolean firstObj = first.isObject();
boolean secondObj = second.isObject();
if (firstObj && secondObj) {
return compareObjectsNoPreCheck(first, second);
} else {
// primitive types conflicts with objects
if (firstObj && secondPrimitive) {
return CONFLICT;
}
if (firstPrimitive && secondObj) {
return CONFLICT;
}
}
if (firstPrimitive && secondPrimitive) {
return comparePrimitives(first.getPrimitiveType(), second.getPrimitiveType());
}
LOG.warn("Type compare function not complete, can't compare {} and {}", first, second);
return TypeCompareEnum.CONFLICT;
}
private TypeCompareEnum compareArrayWithOtherType(ArgType array, ArgType other) {
if (!other.isTypeKnown()) {
if (other.contains(PrimitiveType.ARRAY)) {
return NARROW;
}
return CONFLICT;
}
if (other.isObject()) {
if (other.equals(ArgType.OBJECT)) {
return NARROW;
}
return CONFLICT;
}
if (other.isPrimitive()) {
return CONFLICT;
}
throw new JadxRuntimeException("Unprocessed type: " + other + " in array compare");
}
private TypeCompareEnum compareWithUnknown(ArgType known, ArgType unknown) {
if (unknown == ArgType.UNKNOWN) {
return NARROW;
}
if (unknown == ArgType.UNKNOWN_OBJECT && (known.isObject() || known.isArray())) {
return NARROW;
}
if (known.equals(ArgType.OBJECT) && unknown.isArray()) {
return WIDER;
}
PrimitiveType knownPrimitive;
if (known.isPrimitive()) {
knownPrimitive = known.getPrimitiveType();
} else if (known.isArray()) {
knownPrimitive = PrimitiveType.ARRAY;
} else {
knownPrimitive = PrimitiveType.OBJECT;
}
PrimitiveType[] possibleTypes = unknown.getPossibleTypes();
for (PrimitiveType possibleType : possibleTypes) {
if (possibleType == knownPrimitive) {
return NARROW;
}
}
return CONFLICT;
}
private TypeCompareEnum compareObjectsNoPreCheck(ArgType first, ArgType second) {
boolean objectsEquals = first.getObject().equals(second.getObject());
boolean firstGenericType = first.isGenericType();
boolean secondGenericType = second.isGenericType();
if (firstGenericType && secondGenericType && !objectsEquals) {
return CONFLICT;
}
boolean firstGeneric = first.isGeneric();
boolean secondGeneric = second.isGeneric();
if (firstGenericType || secondGenericType) {
ArgType firstWildcardType = first.getWildcardType();
ArgType secondWildcardType = second.getWildcardType();
if (firstWildcardType != null || secondWildcardType != null) {
if (firstWildcardType != null && secondGenericType && first.getWildcardBound() == WildcardBound.UNBOUND) {
return CONFLICT;
}
if (firstGenericType && secondWildcardType != null && second.getWildcardBound() == WildcardBound.UNBOUND) {
return CONFLICT;
}
}
if (firstGenericType) {
return compareGenericTypeWithObject(first, second);
} else {
return compareGenericTypeWithObject(second, first).invert();
}
}
if (objectsEquals) {
if (firstGeneric != secondGeneric) {
return firstGeneric ? NARROW_BY_GENERIC : WIDER_BY_GENERIC;
}
// both generics on same object
if (first.getWildcardBound() != null && second.getWildcardBound() != null) {
// both wildcards
return compareWildcardTypes(first, second);
}
List<ArgType> firstGenericTypes = first.getGenericTypes();
List<ArgType> secondGenericTypes = second.getGenericTypes();
if (isEmpty(firstGenericTypes) || isEmpty(secondGenericTypes)) {
// check outer types
ArgType firstOuterType = first.getOuterType();
ArgType secondOuterType = second.getOuterType();
if (firstOuterType != null && secondOuterType != null) {
return compareTypes(firstOuterType, secondOuterType);
}
} else {
// compare generics arrays
int len = firstGenericTypes.size();
if (len == secondGenericTypes.size()) {
for (int i = 0; i < len; i++) {
TypeCompareEnum res = compareTypes(firstGenericTypes.get(i), secondGenericTypes.get(i));
if (res != EQUAL) {
return res;
}
}
}
}
}
boolean firstIsObjCls = first.equals(ArgType.OBJECT);
if (firstIsObjCls || second.equals(ArgType.OBJECT)) {
return firstIsObjCls ? WIDER : NARROW;
}
if (ArgType.isInstanceOf(root, first, second)) {
return NARROW;
}
if (ArgType.isInstanceOf(root, second, first)) {
return WIDER;
}
if (!ArgType.isClsKnown(root, first) || !ArgType.isClsKnown(root, second)) {
return UNKNOWN;
}
return TypeCompareEnum.CONFLICT;
}
private TypeCompareEnum compareWildcardTypes(ArgType first, ArgType second) {
WildcardBound firstWildcardBound = first.getWildcardBound();
WildcardBound secondWildcardBound = second.getWildcardBound();
if (firstWildcardBound == WildcardBound.UNBOUND) {
return WIDER;
}
if (secondWildcardBound == WildcardBound.UNBOUND) {
return NARROW;
}
TypeCompareEnum wildcardCompare = compareTypes(first.getWildcardType(), second.getWildcardType());
if (firstWildcardBound == secondWildcardBound) {
return wildcardCompare;
}
return CONFLICT;
}
private TypeCompareEnum compareGenericTypeWithObject(ArgType genericType, ArgType objType) {
if (objType.isGenericType()) {
return compareTypeVariables(genericType, objType);
}
if (objType.isWildcard()) {
return CONFLICT_BY_GENERIC;
}
boolean rootObject = objType.equals(ArgType.OBJECT);
List<ArgType> extendTypes = genericType.getExtendTypes();
if (extendTypes.isEmpty()) {
return rootObject ? NARROW : CONFLICT;
}
if (extendTypes.contains(objType) || rootObject) {
return NARROW;
}
for (ArgType extendType : extendTypes) {
TypeCompareEnum res = compareObjectsNoPreCheck(extendType, objType);
if (!res.isNarrow()) {
return res;
}
}
return NARROW;
}
private TypeCompareEnum compareTypeVariables(ArgType first, ArgType second) {
if (first.getObject().equals(second.getObject())) {
List<ArgType> firstExtendTypes = removeObject(first.getExtendTypes());
List<ArgType> secondExtendTypes = removeObject(second.getExtendTypes());
if (firstExtendTypes.equals(secondExtendTypes)) {
return EQUAL;
}
int firstExtSize = firstExtendTypes.size();
int secondExtSize = secondExtendTypes.size();
if (firstExtSize == 0) {
return WIDER;
}
if (secondExtSize == 0) {
return NARROW;
}
if (firstExtSize == 1 && secondExtSize == 1) {
return compareTypes(firstExtendTypes.get(0), secondExtendTypes.get(0));
}
}
return CONFLICT;
}
private List<ArgType> removeObject(List<ArgType> extendTypes) {
if (extendTypes.contains(ArgType.OBJECT)) {
if (extendTypes.size() == 1) {
return Collections.emptyList();
}
List<ArgType> result = new ArrayList<>(extendTypes);
result.remove(ArgType.OBJECT);
return result;
}
return extendTypes;
}
private TypeCompareEnum comparePrimitives(PrimitiveType type1, PrimitiveType type2) {
if (type1 == PrimitiveType.BOOLEAN || type2 == PrimitiveType.BOOLEAN) {
return type1 == type2 ? EQUAL : CONFLICT;
}
if (type1 == PrimitiveType.VOID || type2 == PrimitiveType.VOID) {
return type1 == type2 ? EQUAL : CONFLICT;
}
if (type1 == PrimitiveType.BYTE && type2 == PrimitiveType.CHAR) {
return WIDER;
}
if (type1 == PrimitiveType.SHORT && type2 == PrimitiveType.CHAR) {
return WIDER;
}
final int type1Width = getTypeWidth(type1);
final int type2Width = getTypeWidth(type2);
if (type1Width > type2Width) {
return WIDER;
} else if (type1Width < type2Width) {
return NARROW;
} else {
return EQUAL;
}
}
private byte getTypeWidth(PrimitiveType type) {
switch (type) {
case BYTE:
return 0;
case SHORT:
return 1;
case CHAR:
return 2;
case INT:
return 3;
case LONG:
return 4;
case FLOAT:
return 5;
case DOUBLE:
return 6;
case BOOLEAN:
case OBJECT:
case ARRAY:
case VOID:
throw new JadxRuntimeException("Type " + type + " should not be here");
}
throw new JadxRuntimeException("Unhandled type: " + type);
}
public Comparator<ArgType> getComparator() {
return comparator;
}
public Comparator<ArgType> getReversedComparator() {
return reversedComparator;
}
private final class ArgTypeComparator implements Comparator<ArgType> {
@Override
public int compare(ArgType a, ArgType b) {
TypeCompareEnum result = compareTypes(a, b);
switch (result) {
case CONFLICT:
return -2;
case WIDER:
case WIDER_BY_GENERIC:
return -1;
case NARROW:
case NARROW_BY_GENERIC:
return 1;
case EQUAL:
default:
return 0;
}
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeInfo.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeInfo.java | package jadx.core.dex.visitors.typeinference;
import java.util.LinkedHashSet;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import jadx.core.dex.instructions.args.ArgType;
public class TypeInfo {
private ArgType type = ArgType.UNKNOWN;
private final Set<ITypeBound> bounds = new LinkedHashSet<>();
@NotNull
public ArgType getType() {
return type;
}
public void setType(ArgType type) {
this.type = type;
}
public Set<ITypeBound> getBounds() {
return bounds;
}
@Override
public String toString() {
return "TypeInfo{type=" + type + ", bounds=" + bounds + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundConst.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundConst.java | package jadx.core.dex.visitors.typeinference;
import java.util.Objects;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.RegisterArg;
public final class TypeBoundConst implements ITypeBound {
private final BoundEnum bound;
private final ArgType type;
private final RegisterArg arg;
public TypeBoundConst(BoundEnum bound, ArgType type) {
this(bound, type, null);
}
public TypeBoundConst(BoundEnum bound, ArgType type, RegisterArg arg) {
this.bound = bound;
this.type = type;
this.arg = arg;
}
@Override
public BoundEnum getBound() {
return bound;
}
@Override
public ArgType getType() {
return type;
}
@Override
public RegisterArg getArg() {
return arg;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TypeBoundConst that = (TypeBoundConst) o;
return bound == that.bound && Objects.equals(type, that.type);
}
@Override
public int hashCode() {
return Objects.hash(bound, type);
}
@Override
public String toString() {
return "{" + bound + ": " + type + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateEntry.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateEntry.java | package jadx.core.dex.visitors.typeinference;
import org.jetbrains.annotations.NotNull;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
public final class TypeUpdateEntry implements Comparable<TypeUpdateEntry> {
private final int seq;
private final InsnArg arg;
private final ArgType type;
public TypeUpdateEntry(int seq, InsnArg arg, ArgType type) {
this.seq = seq;
this.arg = arg;
this.type = type;
}
public int getSeq() {
return seq;
}
public InsnArg getArg() {
return arg;
}
public ArgType getType() {
return type;
}
@Override
public int compareTo(@NotNull TypeUpdateEntry other) {
return Integer.compare(this.seq, other.seq);
}
@Override
public String toString() {
return type + " -> " + arg.toShortString() + " in " + arg.getParentInsn();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/ITypeBound.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/ITypeBound.java | package jadx.core.dex.visitors.typeinference;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.RegisterArg;
/**
* Information to restrict types by applying constraints (or boundaries)
*/
public interface ITypeBound {
BoundEnum getBound();
ArgType getType();
@Nullable
RegisterArg getArg();
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundInvokeUse.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundInvokeUse.java | package jadx.core.dex.visitors.typeinference;
import jadx.core.dex.instructions.BaseInvokeNode;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.RootNode;
/**
* Special dynamic bound for invoke with generics.
* Arguments bound type calculated using instance generic type.
*/
public final class TypeBoundInvokeUse implements ITypeBoundDynamic {
private final RootNode root;
private final BaseInvokeNode invokeNode;
private final RegisterArg arg;
private final ArgType genericArgType;
public TypeBoundInvokeUse(RootNode root, BaseInvokeNode invokeNode, RegisterArg arg, ArgType genericArgType) {
this.root = root;
this.invokeNode = invokeNode;
this.arg = arg;
this.genericArgType = genericArgType;
}
@Override
public BoundEnum getBound() {
return BoundEnum.USE;
}
@Override
public ArgType getType(TypeUpdateInfo updateInfo) {
return getArgType(updateInfo.getType(invokeNode.getInstanceArg()), updateInfo.getType(arg));
}
@Override
public ArgType getType() {
return getArgType(invokeNode.getInstanceArg().getType(), arg.getType());
}
private ArgType getArgType(ArgType instanceType, ArgType argType) {
ArgType resultGeneric = root.getTypeUtils().replaceClassGenerics(instanceType, genericArgType);
if (resultGeneric != null) {
return resultGeneric;
}
return argType;
}
@Override
public RegisterArg getArg() {
return arg;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TypeBoundInvokeUse that = (TypeBoundInvokeUse) o;
return invokeNode.equals(that.invokeNode);
}
@Override
public int hashCode() {
return invokeNode.hashCode();
}
@Override
public String toString() {
return "InvokeAssign{" + invokeNode.getCallMth().getShortId()
+ ", argType=" + genericArgType
+ ", currentType=" + getType()
+ ", instanceArg=" + invokeNode.getInstanceArg()
+ '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/ITypeListener.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/ITypeListener.java | package jadx.core.dex.visitors.typeinference;
import org.jetbrains.annotations.NotNull;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.nodes.InsnNode;
@FunctionalInterface
public interface ITypeListener {
/**
* Listener function - triggered on type update
*
* @param updateInfo store all allowed type updates
* @param arg apply suggested type for this arg
* @param candidateType suggest new type
*/
TypeUpdateResult update(TypeUpdateInfo updateInfo, InsnNode insn, InsnArg arg, @NotNull ArgType candidateType);
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/ITypeBoundDynamic.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/ITypeBoundDynamic.java | package jadx.core.dex.visitors.typeinference;
import jadx.core.dex.instructions.args.ArgType;
/**
* 'Dynamic' type bound allows to use requested and not yet applied types
* from {@link TypeUpdateInfo} for more precise restrictions
*/
public interface ITypeBoundDynamic extends ITypeBound {
/**
* This method will be executed instead of {@link ITypeBound#getType()}
* if {@link TypeUpdateInfo} is available.
*/
ArgType getType(TypeUpdateInfo updateInfo);
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateRegistry.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateRegistry.java | package jadx.core.dex.visitors.typeinference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import jadx.core.dex.instructions.InsnType;
public class TypeUpdateRegistry {
private final Map<InsnType, List<ITypeListener>> listenersMap = new EnumMap<>(InsnType.class);
public void add(InsnType insnType, ITypeListener listener) {
listenersMap.computeIfAbsent(insnType, k -> new ArrayList<>(3)).add(listener);
}
@NotNull
public List<ITypeListener> getListenersForInsn(InsnType insnType) {
List<ITypeListener> list = listenersMap.get(insnType);
if (list == null) {
return Collections.emptyList();
}
return list;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundFieldGetAssign.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeBoundFieldGetAssign.java | package jadx.core.dex.visitors.typeinference;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.RootNode;
/**
* Dynamic bound for instance field get of generic type.
* Bound type calculated using instance generic type.
*/
public final class TypeBoundFieldGetAssign implements ITypeBoundDynamic {
private final RootNode root;
private final IndexInsnNode getNode;
private final FieldInfo fieldInfo;
private final ArgType initType;
public TypeBoundFieldGetAssign(RootNode root, IndexInsnNode getNode, ArgType initType) {
this.root = root;
this.getNode = getNode;
this.fieldInfo = (FieldInfo) getNode.getIndex();
this.initType = initType;
}
@Override
public BoundEnum getBound() {
return BoundEnum.ASSIGN;
}
@Override
public ArgType getType(TypeUpdateInfo updateInfo) {
return getResultType(updateInfo.getType(getInstanceArg()));
}
@Override
public ArgType getType() {
return getResultType(getInstanceArg().getType());
}
private ArgType getResultType(ArgType instanceType) {
ArgType resultGeneric = root.getTypeUtils().replaceClassGenerics(instanceType, initType);
if (resultGeneric != null && !resultGeneric.isWildcard()) {
return resultGeneric;
}
return initType; // TODO: check if this type is allowed in current scope
}
private InsnArg getInstanceArg() {
return getNode.getArg(0);
}
@Override
public RegisterArg getArg() {
return getNode.getResult();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TypeBoundFieldGetAssign that = (TypeBoundFieldGetAssign) o;
return getNode.equals(that.getNode);
}
@Override
public int hashCode() {
return getNode.hashCode();
}
@Override
public String toString() {
return "FieldGetAssign{" + fieldInfo
+ ", type=" + getType()
+ ", instanceArg=" + getInstanceArg()
+ '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateFlags.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeUpdateFlags.java | package jadx.core.dex.visitors.typeinference;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static jadx.core.dex.visitors.typeinference.TypeUpdateFlags.FlagsEnum.ALLOW_WIDER;
import static jadx.core.dex.visitors.typeinference.TypeUpdateFlags.FlagsEnum.IGNORE_SAME;
import static jadx.core.dex.visitors.typeinference.TypeUpdateFlags.FlagsEnum.IGNORE_UNKNOWN;
import static jadx.core.dex.visitors.typeinference.TypeUpdateFlags.FlagsEnum.KEEP_GENERICS;
public class TypeUpdateFlags {
enum FlagsEnum {
ALLOW_WIDER,
IGNORE_SAME,
IGNORE_UNKNOWN,
KEEP_GENERICS,
}
static final TypeUpdateFlags FLAGS_EMPTY = build();
static final TypeUpdateFlags FLAGS_WIDER = build(ALLOW_WIDER);
static final TypeUpdateFlags FLAGS_WIDER_IGNORE_SAME = build(ALLOW_WIDER, IGNORE_SAME);
static final TypeUpdateFlags FLAGS_APPLY_DEBUG = build(ALLOW_WIDER, KEEP_GENERICS, IGNORE_UNKNOWN);
private final Set<FlagsEnum> flags;
private static TypeUpdateFlags build(FlagsEnum... flags) {
EnumSet<FlagsEnum> set;
if (flags.length == 0) {
set = EnumSet.noneOf(FlagsEnum.class);
} else {
set = EnumSet.copyOf(List.of(flags));
}
return new TypeUpdateFlags(set);
}
private TypeUpdateFlags(Set<FlagsEnum> flags) {
this.flags = flags;
}
public boolean isAllowWider() {
return flags.contains(ALLOW_WIDER);
}
public boolean isIgnoreSame() {
return flags.contains(IGNORE_SAME);
}
public boolean isIgnoreUnknown() {
return flags.contains(IGNORE_UNKNOWN);
}
public boolean isKeepGenerics() {
return flags.contains(KEEP_GENERICS);
}
@Override
public String toString() {
return flags.toString();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeSearch.java | jadx-core/src/main/java/jadx/core/dex/visitors/typeinference/TypeSearch.java | package jadx.core.dex.visitors.typeinference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.Consts;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
/**
* Slow and memory consuming multi-variable type search algorithm.
* Used only if fast type propagation is failed for some variables.
* <p>
* Stages description:
* - find all possible candidate types within bounds
* - build dynamic constraint list for every variable
* - run search by checking all candidates
*/
public class TypeSearch {
private static final Logger LOG = LoggerFactory.getLogger(TypeSearch.class);
private static final int VARS_PROCESS_LIMIT = 5_000;
private static final int CANDIDATES_COUNT_LIMIT = 10;
private static final int SEARCH_ITERATION_LIMIT = 1_000_000;
private final MethodNode mth;
private final TypeSearchState state;
private final TypeCompare typeCompare;
private final TypeUpdate typeUpdate;
public TypeSearch(MethodNode mth) {
this.mth = mth;
this.state = new TypeSearchState(mth);
this.typeUpdate = mth.root().getTypeUpdate();
this.typeCompare = typeUpdate.getTypeCompare();
}
public boolean run() {
if (mth.getSVars().size() > VARS_PROCESS_LIMIT) {
mth.addWarnComment("Multi-variable search skipped. Vars limit reached: " + mth.getSVars().size()
+ " (expected less than " + VARS_PROCESS_LIMIT + ")");
return false;
}
mth.getSVars().forEach(this::fillTypeCandidates);
mth.getSVars().forEach(this::collectConstraints);
// quick search for variables without dependencies
state.getUnresolvedVars().forEach(this::resolveIndependentVariables);
boolean searchSuccess;
List<TypeSearchVarInfo> vars = state.getUnresolvedVars();
if (vars.isEmpty()) {
searchSuccess = true;
} else {
searchSuccess = search(vars) && fullCheck(vars);
if (Consts.DEBUG_TYPE_INFERENCE && !searchSuccess) {
LOG.debug("Multi-variable search failed");
}
}
if (searchSuccess) {
return applyResolvedVars();
}
return false;
}
private boolean applyResolvedVars() {
List<TypeSearchVarInfo> resolvedVars = state.getResolvedVars();
List<TypeSearchVarInfo> updatedVars = new ArrayList<>();
for (TypeSearchVarInfo var : resolvedVars) {
SSAVar ssaVar = var.getVar();
ArgType resolvedType = var.getCurrentType();
if (!resolvedType.isTypeKnown()) {
// ignore unknown variables
continue;
}
if (resolvedType.equals(ssaVar.getTypeInfo().getType())) {
// type already set
continue;
}
ssaVar.setType(resolvedType);
updatedVars.add(var);
}
boolean applySuccess = true;
for (TypeSearchVarInfo var : updatedVars) {
TypeUpdateResult res = typeUpdate.applyWithWiderIgnSame(mth, var.getVar(), var.getCurrentType());
if (res == TypeUpdateResult.REJECT) {
mth.addDebugComment("Multi-variable search result rejected for " + var);
applySuccess = false;
}
}
return applySuccess;
}
private boolean search(List<TypeSearchVarInfo> vars) {
int len = vars.size();
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Run multi-variable search for {} vars: ", len);
StringBuilder sb = new StringBuilder();
long count = 1;
for (TypeSearchVarInfo var : vars) {
LOG.debug(" {}", var);
int size = var.getCandidateTypes().size();
sb.append(" * ").append(size);
count *= size;
}
sb.append(" = ").append(count);
LOG.debug(" max iterations count = {}", sb);
}
// prepare vars
for (TypeSearchVarInfo var : vars) {
var.reset();
}
// check all types combinations
int n = 0;
int i = 0;
while (!fullCheck(vars)) {
TypeSearchVarInfo first = vars.get(i);
if (first.nextType()) {
int k = i + 1;
if (k >= len) {
return false;
}
TypeSearchVarInfo next = vars.get(k);
while (true) {
if (next.nextType()) {
k++;
if (k >= len) {
return false;
}
next = vars.get(k);
} else {
break;
}
}
}
n++;
if (n > SEARCH_ITERATION_LIMIT) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug(" > iterations limit reached: {}", SEARCH_ITERATION_LIMIT);
}
return false;
}
}
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug(" > done after {} iterations", n);
}
// mark all vars as resolved
for (TypeSearchVarInfo var : vars) {
var.setTypeResolved(true);
}
return true;
}
private boolean resolveIndependentVariables(TypeSearchVarInfo varInfo) {
boolean allRelatedVarsResolved = varInfo.getConstraints().stream()
.flatMap(c -> c.getRelatedVars().stream())
.allMatch(v -> state.getVarInfo(v).isTypeResolved());
if (!allRelatedVarsResolved) {
return false;
}
// variable is independent, run single search
varInfo.reset();
do {
if (singleCheck(varInfo)) {
varInfo.setTypeResolved(true);
return true;
}
} while (!varInfo.nextType());
return false;
}
private boolean fullCheck(List<TypeSearchVarInfo> vars) {
for (TypeSearchVarInfo var : vars) {
if (!singleCheck(var)) {
return false;
}
}
return true;
}
private boolean singleCheck(TypeSearchVarInfo var) {
if (var.isTypeResolved()) {
return true;
}
for (ITypeConstraint constraint : var.getConstraints()) {
if (!constraint.check(state)) {
return false;
}
}
return true;
}
private void fillTypeCandidates(SSAVar ssaVar) {
TypeSearchVarInfo varInfo = state.getVarInfo(ssaVar);
ArgType immutableType = ssaVar.getImmutableType();
if (immutableType != null) {
varInfo.markResolved(immutableType);
return;
}
ArgType currentType = ssaVar.getTypeInfo().getType();
if (currentType.isTypeKnown()) {
varInfo.markResolved(currentType);
return;
}
Set<ArgType> assigns = new LinkedHashSet<>();
Set<ArgType> uses = new LinkedHashSet<>();
Set<ITypeBound> bounds = ssaVar.getTypeInfo().getBounds();
for (ITypeBound bound : bounds) {
if (bound.getBound() == BoundEnum.ASSIGN) {
assigns.add(bound.getType());
} else {
uses.add(bound.getType());
}
}
Set<ArgType> candidateTypes = new LinkedHashSet<>();
addCandidateTypes(bounds, candidateTypes, assigns);
addCandidateTypes(bounds, candidateTypes, uses);
for (ArgType assignType : assigns) {
addCandidateTypes(bounds, candidateTypes, getWiderTypes(assignType));
}
for (ArgType useType : uses) {
addCandidateTypes(bounds, candidateTypes, getNarrowTypes(useType));
}
addUsageTypeCandidates(ssaVar, bounds, candidateTypes);
int size = candidateTypes.size();
if (size == 0) {
varInfo.setTypeResolved(true);
varInfo.setCurrentType(ArgType.UNKNOWN);
varInfo.setCandidateTypes(Collections.emptyList());
} else if (size == 1) {
varInfo.setTypeResolved(true);
varInfo.setCurrentType(candidateTypes.iterator().next());
varInfo.setCandidateTypes(Collections.emptyList());
} else {
varInfo.setTypeResolved(false);
varInfo.setCurrentType(ArgType.UNKNOWN);
List<ArgType> types = new ArrayList<>(candidateTypes);
types.sort(typeCompare.getReversedComparator());
varInfo.setCandidateTypes(Collections.unmodifiableList(types));
}
}
private void addUsageTypeCandidates(SSAVar ssaVar, Set<ITypeBound> bounds, Set<ArgType> candidateTypes) {
for (RegisterArg useArg : ssaVar.getUseList()) {
InsnNode parentInsn = useArg.getParentInsn();
if (parentInsn != null) {
InsnType insnType = parentInsn.getType();
if (insnType == InsnType.APUT) {
ArgType aputType = parentInsn.getArg(2).getType();
if (aputType.isTypeKnown()) {
addCandidateType(bounds, candidateTypes, ArgType.array(aputType));
}
}
}
}
}
private void addCandidateTypes(Set<ITypeBound> bounds, Set<ArgType> collectedTypes, Collection<ArgType> candidateTypes) {
for (ArgType candidateType : candidateTypes) {
if (addCandidateType(bounds, collectedTypes, candidateType)) {
return;
}
}
}
private boolean addCandidateType(Set<ITypeBound> bounds, Set<ArgType> collectedTypes, ArgType candidateType) {
if (candidateType.isTypeKnown() && typeUpdate.inBounds(bounds, candidateType)) {
collectedTypes.add(candidateType);
if (collectedTypes.size() > CANDIDATES_COUNT_LIMIT) {
return true;
}
}
return false;
}
private List<ArgType> getWiderTypes(ArgType type) {
if (type.isTypeKnown()) {
if (type.isObject()) {
Set<String> ancestors = mth.root().getClsp().getSuperTypes(type.getObject());
return ancestors.stream().map(ArgType::object).collect(Collectors.toList());
}
} else {
return expandUnknownType(type);
}
return Collections.emptyList();
}
private List<ArgType> getNarrowTypes(ArgType type) {
if (type.isTypeKnown()) {
if (type.isObject()) {
if (type.equals(ArgType.OBJECT)) {
// a lot of objects to return
return Collections.singletonList(ArgType.OBJECT);
}
List<String> impList = mth.root().getClsp().getImplementations(type.getObject());
return impList.stream().map(ArgType::object).collect(Collectors.toList());
}
} else {
return expandUnknownType(type);
}
return Collections.emptyList();
}
private List<ArgType> expandUnknownType(ArgType type) {
List<ArgType> list = new ArrayList<>();
for (PrimitiveType possibleType : type.getPossibleTypes()) {
list.add(ArgType.convertFromPrimitiveType(possibleType));
}
return list;
}
private void collectConstraints(SSAVar var) {
TypeSearchVarInfo varInfo = state.getVarInfo(var);
if (varInfo.isTypeResolved()) {
varInfo.setConstraints(Collections.emptyList());
return;
}
varInfo.setConstraints(new ArrayList<>());
addConstraint(varInfo, makeConstraint(var.getAssign()));
for (RegisterArg regArg : var.getUseList()) {
addConstraint(varInfo, makeConstraint(regArg));
}
}
private void addConstraint(TypeSearchVarInfo varInfo, ITypeConstraint constraint) {
if (constraint != null) {
varInfo.getConstraints().add(constraint);
}
}
@Nullable
private ITypeConstraint makeConstraint(RegisterArg arg) {
InsnNode insn = arg.getParentInsn();
if (insn == null || arg.isTypeImmutable()) {
return null;
}
switch (insn.getType()) {
case MOVE:
return makeMoveConstraint(insn, arg);
case PHI:
return makePhiConstraint(insn, arg);
default:
return null;
}
}
@Nullable
private ITypeConstraint makeMoveConstraint(InsnNode insn, RegisterArg arg) {
if (!insn.getArg(0).isRegister()) {
return null;
}
return new AbstractTypeConstraint(insn, arg) {
@Override
public boolean check(TypeSearchState state) {
ArgType resType = state.getArgType(insn.getResult());
ArgType argType = state.getArgType(insn.getArg(0));
TypeCompareEnum res = typeCompare.compareTypes(resType, argType);
return res.isEqual() || res.isWider();
}
};
}
private ITypeConstraint makePhiConstraint(InsnNode insn, RegisterArg arg) {
return new AbstractTypeConstraint(insn, arg) {
@Override
public boolean check(TypeSearchState state) {
ArgType resType = state.getArgType(insn.getResult());
for (InsnArg insnArg : insn.getArguments()) {
ArgType argType = state.getArgType(insnArg);
if (!argType.equals(resType)) {
return false;
}
}
return true;
}
};
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/ssa/RenameState.java | jadx-core/src/main/java/jadx/core/dex/visitors/ssa/RenameState.java | package jadx.core.dex.visitors.ssa;
import java.util.Arrays;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.MethodNode;
final class RenameState {
private final MethodNode mth;
private final BlockNode block;
private final SSAVar[] vars;
private final int[] versions;
public static RenameState init(MethodNode mth) {
int regsCount = mth.getRegsCount();
RenameState state = new RenameState(
mth,
mth.getEnterBlock(),
new SSAVar[regsCount],
new int[regsCount]);
RegisterArg thisArg = mth.getThisArg();
if (thisArg != null) {
state.startVar(thisArg);
}
for (RegisterArg arg : mth.getArgRegs()) {
state.startVar(arg);
}
return state;
}
public static RenameState copyFrom(RenameState state, BlockNode block) {
return new RenameState(
state.mth,
block,
Arrays.copyOf(state.vars, state.vars.length),
state.versions);
}
private RenameState(MethodNode mth, BlockNode block, SSAVar[] vars, int[] versions) {
this.mth = mth;
this.block = block;
this.vars = vars;
this.versions = versions;
}
public BlockNode getBlock() {
return block;
}
public SSAVar getVar(int regNum) {
return vars[regNum];
}
public SSAVar startVar(RegisterArg regArg) {
int regNum = regArg.getRegNum();
int version = versions[regNum]++;
SSAVar ssaVar = mth.makeNewSVar(regNum, version, regArg);
vars[regNum] = ssaVar;
return ssaVar;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/ssa/SSATransform.java | jadx-core/src/main/java/jadx/core/dex/visitors/ssa/SSATransform.java | package jadx.core.dex.visitors.ssa;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.PhiListAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.trycatch.CatchAttr;
import jadx.core.dex.trycatch.ExcHandlerAttr;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.blocks.BlockProcessor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnList;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.exceptions.JadxException;
import jadx.core.utils.exceptions.JadxRuntimeException;
@JadxVisitor(
name = "SSATransform",
desc = "Calculate Single Side Assign (SSA) variables",
runAfter = BlockProcessor.class
)
public class SSATransform extends AbstractVisitor {
@Override
public void visit(MethodNode mth) throws JadxException {
if (mth.isNoCode()) {
return;
}
process(mth);
}
private static void process(MethodNode mth) {
if (!mth.getSVars().isEmpty()) {
return;
}
LiveVarAnalysis la = new LiveVarAnalysis(mth);
la.runAnalysis();
int regsCount = mth.getRegsCount();
for (int i = 0; i < regsCount; i++) {
placePhi(mth, i, la);
}
renameVariables(mth);
fixLastAssignInTry(mth);
removeBlockerInsns(mth);
markThisArgs(mth.getThisArg());
tryToFixUselessPhi(mth);
hidePhiInsns(mth);
removeUnusedInvokeResults(mth);
}
private static void placePhi(MethodNode mth, int regNum, LiveVarAnalysis la) {
List<BlockNode> blocks = mth.getBasicBlocks();
int blocksCount = blocks.size();
BitSet hasPhi = new BitSet(blocksCount);
BitSet processed = new BitSet(blocksCount);
Deque<BlockNode> workList = new ArrayDeque<>();
BitSet assignBlocks = la.getAssignBlocks(regNum);
for (int id = assignBlocks.nextSetBit(0); id >= 0; id = assignBlocks.nextSetBit(id + 1)) {
processed.set(id);
workList.add(blocks.get(id));
}
while (!workList.isEmpty()) {
BlockNode block = workList.pop();
BitSet domFrontier = block.getDomFrontier();
for (int id = domFrontier.nextSetBit(0); id >= 0; id = domFrontier.nextSetBit(id + 1)) {
if (!hasPhi.get(id) && la.isLive(id, regNum)) {
BlockNode df = blocks.get(id);
PhiInsn phiInsn = addPhi(mth, df, regNum);
df.getInstructions().add(0, phiInsn);
hasPhi.set(id);
if (!processed.get(id)) {
processed.set(id);
workList.add(df);
}
}
}
}
}
public static PhiInsn addPhi(MethodNode mth, BlockNode block, int regNum) {
PhiListAttr phiList = block.get(AType.PHI_LIST);
if (phiList == null) {
phiList = new PhiListAttr();
block.addAttr(phiList);
}
int size = block.getPredecessors().size();
if (mth.getEnterBlock() == block) {
RegisterArg thisArg = mth.getThisArg();
if (thisArg != null && thisArg.getRegNum() == regNum) {
size++;
} else {
for (RegisterArg arg : mth.getArgRegs()) {
if (arg.getRegNum() == regNum) {
size++;
break;
}
}
}
}
PhiInsn phiInsn = new PhiInsn(regNum, size);
phiList.getList().add(phiInsn);
phiInsn.setOffset(block.getStartOffset());
return phiInsn;
}
private static void renameVariables(MethodNode mth) {
RenameState initState = RenameState.init(mth);
initPhiInEnterBlock(initState);
Deque<RenameState> stack = new ArrayDeque<>();
stack.push(initState);
while (!stack.isEmpty()) {
RenameState state = stack.pop();
renameVarsInBlock(mth, state);
for (BlockNode dominated : state.getBlock().getDominatesOn()) {
stack.push(RenameState.copyFrom(state, dominated));
}
}
}
private static void initPhiInEnterBlock(RenameState initState) {
PhiListAttr phiList = initState.getBlock().get(AType.PHI_LIST);
if (phiList != null) {
for (PhiInsn phiInsn : phiList.getList()) {
bindPhiArg(initState, phiInsn);
}
}
}
private static void renameVarsInBlock(MethodNode mth, RenameState state) {
BlockNode block = state.getBlock();
for (InsnNode insn : block.getInstructions()) {
if (insn.getType() != InsnType.PHI) {
for (InsnArg arg : insn.getArguments()) {
if (!arg.isRegister()) {
continue;
}
RegisterArg reg = (RegisterArg) arg;
int regNum = reg.getRegNum();
SSAVar var = state.getVar(regNum);
if (var == null) {
// TODO: in most cases issue in incorrectly attached exception handlers
mth.addWarnComment("Not initialized variable reg: " + regNum + ", insn: " + insn + ", block:" + block);
var = state.startVar(reg);
}
var.use(reg);
}
}
RegisterArg result = insn.getResult();
if (result != null) {
state.startVar(result);
}
}
for (BlockNode s : block.getSuccessors()) {
PhiListAttr phiList = s.get(AType.PHI_LIST);
if (phiList == null) {
continue;
}
for (PhiInsn phiInsn : phiList.getList()) {
bindPhiArg(state, phiInsn);
}
}
}
private static void bindPhiArg(RenameState state, PhiInsn phiInsn) {
int regNum = phiInsn.getResult().getRegNum();
SSAVar var = state.getVar(regNum);
if (var == null) {
return;
}
RegisterArg arg = phiInsn.bindArg(state.getBlock());
var.use(arg);
var.addUsedInPhi(phiInsn);
}
/**
* Fix last try/catch assign instruction
*/
private static void fixLastAssignInTry(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
PhiListAttr phiList = block.get(AType.PHI_LIST);
if (phiList != null) {
ExcHandlerAttr handlerAttr = block.get(AType.EXC_HANDLER);
if (handlerAttr != null) {
for (PhiInsn phi : phiList.getList()) {
fixPhiInTryCatch(mth, phi, handlerAttr);
}
}
}
}
}
private static void fixPhiInTryCatch(MethodNode mth, PhiInsn phi, ExcHandlerAttr handlerAttr) {
int argsCount = phi.getArgsCount();
int k = 0;
while (k < argsCount) {
RegisterArg arg = phi.getArg(k);
if (shouldSkipInsnResult(mth, arg.getAssignInsn(), handlerAttr)) {
phi.removeArg(arg);
argsCount--;
} else {
k++;
}
}
if (phi.getArgsCount() == 0) {
throw new JadxRuntimeException("PHI empty after try-catch fix!");
}
}
private static boolean shouldSkipInsnResult(MethodNode mth, InsnNode insn, ExcHandlerAttr handlerAttr) {
if (insn != null
&& insn.getResult() != null
&& insn.contains(AFlag.TRY_LEAVE)) {
CatchAttr catchAttr = BlockUtils.getCatchAttrForInsn(mth, insn);
return catchAttr != null && catchAttr.getHandlers().contains(handlerAttr.getHandler());
}
return false;
}
private static boolean removeBlockerInsns(MethodNode mth) {
boolean removed = false;
for (BlockNode block : mth.getBasicBlocks()) {
PhiListAttr phiList = block.get(AType.PHI_LIST);
if (phiList == null) {
continue;
}
// check if args must be removed
for (PhiInsn phi : phiList.getList()) {
for (int i = 0; i < phi.getArgsCount(); i++) {
RegisterArg arg = phi.getArg(i);
InsnNode parentInsn = arg.getAssignInsn();
if (parentInsn != null && parentInsn.contains(AFlag.REMOVE)) {
phi.removeArg(arg);
InsnRemover.remove(mth, block, parentInsn);
removed = true;
}
}
}
}
return removed;
}
private static void tryToFixUselessPhi(MethodNode mth) {
int k = 0;
int maxTries = mth.getSVars().size() * 2;
while (fixUselessPhi(mth)) {
if (k++ > maxTries) {
throw new JadxRuntimeException("Phi nodes fix limit reached!");
}
}
}
private static boolean fixUselessPhi(MethodNode mth) {
boolean changed = false;
List<PhiInsn> insnToRemove = new ArrayList<>();
for (SSAVar var : mth.getSVars()) {
// phi result not used
if (var.getUseCount() == 0) {
InsnNode assignInsn = var.getAssign().getParentInsn();
if (assignInsn != null && assignInsn.getType() == InsnType.PHI) {
insnToRemove.add((PhiInsn) assignInsn);
changed = true;
}
}
}
for (BlockNode block : mth.getBasicBlocks()) {
PhiListAttr phiList = block.get(AType.PHI_LIST);
if (phiList == null) {
continue;
}
Iterator<PhiInsn> it = phiList.getList().iterator();
while (it.hasNext()) {
PhiInsn phi = it.next();
if (fixPhiWithSameArgs(mth, block, phi)) {
it.remove();
changed = true;
}
}
}
removePhiList(mth, insnToRemove);
return changed;
}
private static boolean fixPhiWithSameArgs(MethodNode mth, BlockNode block, PhiInsn phi) {
if (phi.getArgsCount() == 0) {
for (RegisterArg useArg : phi.getResult().getSVar().getUseList()) {
InsnNode useInsn = useArg.getParentInsn();
if (useInsn != null && useInsn.getType() == InsnType.PHI) {
phi.removeArg(useArg);
}
}
InsnRemover.remove(mth, block, phi);
return true;
}
boolean allSame = phi.getArgsCount() == 1 || isSameArgs(phi);
if (allSame) {
return replacePhiWithMove(mth, block, phi, phi.getArg(0));
}
return false;
}
private static boolean isSameArgs(PhiInsn phi) {
boolean allSame = true;
SSAVar var = null;
for (int i = 0; i < phi.getArgsCount(); i++) {
RegisterArg arg = phi.getArg(i);
if (var == null) {
var = arg.getSVar();
} else if (var != arg.getSVar()) {
allSame = false;
break;
}
}
return allSame;
}
private static boolean removePhiList(MethodNode mth, List<PhiInsn> insnToRemove) {
for (BlockNode block : mth.getBasicBlocks()) {
PhiListAttr phiList = block.get(AType.PHI_LIST);
if (phiList == null) {
continue;
}
List<PhiInsn> list = phiList.getList();
for (PhiInsn phiInsn : insnToRemove) {
if (list.remove(phiInsn)) {
for (InsnArg arg : phiInsn.getArguments()) {
if (arg == null) {
continue;
}
SSAVar sVar = ((RegisterArg) arg).getSVar();
if (sVar != null) {
sVar.removeUsedInPhi(phiInsn);
}
}
InsnRemover.remove(mth, block, phiInsn);
}
}
if (list.isEmpty()) {
block.remove(AType.PHI_LIST);
}
}
insnToRemove.clear();
return true;
}
private static boolean replacePhiWithMove(MethodNode mth, BlockNode block, PhiInsn phi, RegisterArg arg) {
List<InsnNode> insns = block.getInstructions();
int phiIndex = InsnList.getIndex(insns, phi);
if (phiIndex == -1) {
return false;
}
SSAVar assign = phi.getResult().getSVar();
SSAVar argVar = arg.getSVar();
if (argVar != null) {
argVar.removeUse(arg);
argVar.removeUsedInPhi(phi);
}
// try inline
if (inlinePhiInsn(mth, block, phi)) {
insns.remove(phiIndex);
} else {
assign.removeUsedInPhi(phi);
InsnNode m = new InsnNode(InsnType.MOVE, 1);
m.add(AFlag.SYNTHETIC);
m.setResult(phi.getResult());
m.addArg(arg);
arg.getSVar().use(arg);
insns.set(phiIndex, m);
}
return true;
}
private static boolean inlinePhiInsn(MethodNode mth, BlockNode block, PhiInsn phi) {
SSAVar resVar = phi.getResult().getSVar();
if (resVar == null) {
return false;
}
RegisterArg arg = phi.getArg(0);
if (arg.getSVar() == null) {
return false;
}
List<RegisterArg> useList = resVar.getUseList();
for (RegisterArg useArg : new ArrayList<>(useList)) {
InsnNode useInsn = useArg.getParentInsn();
if (useInsn == null || useInsn == phi || useArg.getRegNum() != arg.getRegNum()) {
return false;
}
// replace SSAVar in 'useArg' to SSAVar from 'arg'
// no need to replace whole RegisterArg
useArg.getSVar().removeUse(useArg);
arg.getSVar().use(useArg);
}
if (block.contains(AType.EXC_HANDLER)) {
// don't inline into exception handler
InsnNode assignInsn = arg.getAssignInsn();
if (assignInsn != null && !assignInsn.isConstInsn()) {
assignInsn.add(AFlag.DONT_INLINE);
}
}
InsnRemover.unbindInsn(mth, phi);
return true;
}
private static void markThisArgs(RegisterArg thisArg) {
if (thisArg != null) {
markOneArgAsThis(thisArg);
thisArg.getSVar().getUseList().forEach(SSATransform::markOneArgAsThis);
}
}
private static void markOneArgAsThis(RegisterArg arg) {
if (arg == null) {
return;
}
arg.add(AFlag.THIS);
arg.add(AFlag.IMMUTABLE_TYPE);
// mark all moved 'this'
InsnNode parentInsn = arg.getParentInsn();
if (parentInsn != null
&& parentInsn.getType() == InsnType.MOVE
&& parentInsn.getArg(0) == arg) {
RegisterArg resArg = parentInsn.getResult();
if (resArg.getRegNum() != arg.getRegNum()
&& !resArg.getSVar().isUsedInPhi()) {
markThisArgs(resArg);
parentInsn.add(AFlag.DONT_GENERATE);
}
}
}
private static void hidePhiInsns(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
block.getInstructions().removeIf(insn -> insn.getType() == InsnType.PHI);
}
}
private static void removeUnusedInvokeResults(MethodNode mth) {
Iterator<SSAVar> it = mth.getSVars().iterator();
while (it.hasNext()) {
SSAVar ssaVar = it.next();
if (ssaVar.getUseCount() == 0) {
InsnNode parentInsn = ssaVar.getAssign().getParentInsn();
if (parentInsn != null && parentInsn.getType() == InsnType.INVOKE) {
parentInsn.setResult(null);
it.remove();
}
}
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/ssa/LiveVarAnalysis.java | jadx-core/src/main/java/jadx/core/dex/visitors/ssa/LiveVarAnalysis.java | package jadx.core.dex.visitors.ssa;
import java.util.BitSet;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class LiveVarAnalysis {
private static final Logger LOG = LoggerFactory.getLogger(LiveVarAnalysis.class);
private final MethodNode mth;
private BitSet[] uses;
private BitSet[] defs;
private BitSet[] liveIn;
private BitSet[] assignBlocks;
public LiveVarAnalysis(MethodNode mth) {
this.mth = mth;
}
public void runAnalysis() {
int bbCount = mth.getBasicBlocks().size();
int regsCount = mth.getRegsCount();
this.uses = initBitSetArray(bbCount, regsCount);
this.defs = initBitSetArray(bbCount, regsCount);
this.assignBlocks = initBitSetArray(regsCount, bbCount);
fillBasicBlockInfo();
processLiveInfo();
}
public BitSet getAssignBlocks(int regNum) {
return assignBlocks[regNum];
}
public boolean isLive(int blockId, int regNum) {
if (blockId >= liveIn.length) {
LOG.warn("LiveVarAnalysis: out of bounds block: {}, max: {}", blockId, liveIn.length);
return false;
}
return liveIn[blockId].get(regNum);
}
public boolean isLive(BlockNode block, int regNum) {
return isLive(block.getId(), regNum);
}
private void fillBasicBlockInfo() {
for (BlockNode block : mth.getBasicBlocks()) {
int blockId = block.getId();
BitSet gen = uses[blockId];
BitSet kill = defs[blockId];
for (InsnNode insn : block.getInstructions()) {
for (InsnArg arg : insn.getArguments()) {
if (arg.isRegister()) {
int regNum = ((RegisterArg) arg).getRegNum();
if (!kill.get(regNum)) {
gen.set(regNum);
}
}
}
RegisterArg result = insn.getResult();
if (result != null) {
int regNum = result.getRegNum();
kill.set(regNum);
assignBlocks[regNum].set(blockId);
}
}
}
}
private void processLiveInfo() {
int bbCount = mth.getBasicBlocks().size();
int regsCount = mth.getRegsCount();
BitSet[] liveInBlocks = initBitSetArray(bbCount, regsCount);
List<BlockNode> blocks = mth.getBasicBlocks();
int blocksCount = blocks.size();
int iterationsLimit = blocksCount * 10;
boolean changed;
int k = 0;
do {
changed = false;
for (BlockNode block : blocks) {
int blockId = block.getId();
BitSet prevIn = liveInBlocks[blockId];
BitSet newIn = new BitSet(regsCount);
for (BlockNode successor : block.getSuccessors()) {
newIn.or(liveInBlocks[successor.getId()]);
}
newIn.andNot(defs[blockId]);
newIn.or(uses[blockId]);
if (!prevIn.equals(newIn)) {
changed = true;
liveInBlocks[blockId] = newIn;
}
}
if (k++ > iterationsLimit) {
throw new JadxRuntimeException("Live variable analysis reach iterations limit, blocks count: " + blocksCount);
}
} while (changed);
this.liveIn = liveInBlocks;
}
private static BitSet[] initBitSetArray(int length, int bitsCount) {
BitSet[] array = new BitSet[length];
for (int i = 0; i < length; i++) {
array[i] = new BitSet(bitsCount);
}
return array;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/methods/MutableMethodDetails.java | jadx-core/src/main/java/jadx/core/dex/visitors/methods/MutableMethodDetails.java | package jadx.core.dex.visitors.methods;
import java.util.Collections;
import java.util.List;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.IMethodDetails;
public class MutableMethodDetails implements IMethodDetails {
private final MethodInfo mthInfo;
private ArgType retType;
private List<ArgType> argTypes;
private List<ArgType> typeParams;
private List<ArgType> throwTypes;
private boolean varArg;
private int accFlags;
public MutableMethodDetails(IMethodDetails base) {
this.mthInfo = base.getMethodInfo();
this.retType = base.getReturnType();
this.argTypes = Collections.unmodifiableList(base.getArgTypes());
this.typeParams = Collections.unmodifiableList(base.getTypeParameters());
this.throwTypes = Collections.unmodifiableList(base.getThrows());
this.varArg = base.isVarArg();
this.accFlags = base.getRawAccessFlags();
}
@Override
public MethodInfo getMethodInfo() {
return mthInfo;
}
@Override
public ArgType getReturnType() {
return retType;
}
@Override
public List<ArgType> getArgTypes() {
return argTypes;
}
@Override
public List<ArgType> getTypeParameters() {
return typeParams;
}
@Override
public List<ArgType> getThrows() {
return throwTypes;
}
@Override
public boolean isVarArg() {
return varArg;
}
public void setRetType(ArgType retType) {
this.retType = retType;
}
public void setArgTypes(List<ArgType> argTypes) {
this.argTypes = argTypes;
}
public void setTypeParams(List<ArgType> typeParams) {
this.typeParams = typeParams;
}
public void setThrowTypes(List<ArgType> throwTypes) {
this.throwTypes = throwTypes;
}
public void setVarArg(boolean varArg) {
this.varArg = varArg;
}
@Override
public int getRawAccessFlags() {
return accFlags;
}
public void setRawAccessFlags(int accFlags) {
this.accFlags = accFlags;
}
@Override
public String toAttrString() {
return IMethodDetails.super.toAttrString() + " (mut)";
}
@Override
public String toString() {
return "Mutable" + toAttrString();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/rename/UserRenames.java | jadx-core/src/main/java/jadx/core/dex/visitors/rename/UserRenames.java | package jadx.core.dex.visitors.rename;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.data.ICodeData;
import jadx.api.data.ICodeRename;
import jadx.api.data.IJavaCodeRef;
import jadx.api.data.IJavaNodeRef;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.InfoStorage;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.PackageNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.StringUtils;
public class UserRenames {
private static final Logger LOG = LoggerFactory.getLogger(UserRenames.class);
public static void apply(RootNode root) {
ICodeData codeData = root.getArgs().getCodeData();
if (codeData == null || codeData.getRenames().isEmpty()) {
return;
}
InfoStorage infoStorage = root.getInfoStorage();
codeData.getRenames().stream()
.filter(r -> r.getCodeRef() == null && r.getNodeRef().getType() != IJavaNodeRef.RefType.PKG)
.collect(Collectors.groupingBy(r -> r.getNodeRef().getDeclaringClass()))
.forEach((clsRawName, renames) -> {
ClassInfo clsInfo = infoStorage.getCls(ArgType.object(clsRawName));
if (clsInfo != null) {
ClassNode cls = root.resolveClass(clsInfo);
if (cls != null) {
for (ICodeRename rename : renames) {
applyRename(cls, rename);
}
return;
}
}
LOG.warn("Class info with reference '{}' not found", clsRawName);
});
applyPkgRenames(root, codeData.getRenames());
}
private static void applyRename(ClassNode cls, ICodeRename rename) {
IJavaNodeRef nodeRef = rename.getNodeRef();
switch (nodeRef.getType()) {
case CLASS:
cls.rename(rename.getNewName());
break;
case FIELD:
FieldNode fieldNode = cls.searchFieldByShortId(nodeRef.getShortId());
if (fieldNode == null) {
String fieldName = StringUtils.getPrefix(nodeRef.getShortId(), ":");
String fieldSign = cls.getFields().stream()
.filter(f -> f.getFieldInfo().getName().equals(fieldName))
.map(f -> f.getFieldInfo().getShortId())
.collect(Collectors.joining());
LOG.warn("Field reference not found: {}. Fields with same name: {}", nodeRef, fieldSign);
} else {
fieldNode.rename(rename.getNewName());
}
break;
case METHOD:
MethodNode mth = cls.searchMethodByShortId(nodeRef.getShortId());
if (mth == null) {
LOG.warn("Method reference not found: {}", nodeRef);
} else {
IJavaCodeRef codeRef = rename.getCodeRef();
if (codeRef == null) {
mth.rename(rename.getNewName());
}
}
break;
}
}
private static void applyPkgRenames(RootNode root, List<ICodeRename> renames) {
renames.stream()
.filter(r -> r.getNodeRef().getType() == IJavaNodeRef.RefType.PKG)
.forEach(pkgRename -> {
String pkgFullName = pkgRename.getNodeRef().getDeclaringClass();
PackageNode pkgNode = root.resolvePackage(pkgFullName);
if (pkgNode == null) {
LOG.warn("Package for rename not found: {}", pkgFullName);
} else {
pkgNode.rename(pkgRename.getNewName());
}
});
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/rename/RenameVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/rename/RenameVisitor.java | package jadx.core.dex.visitors.rename;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.jetbrains.annotations.Nullable;
import jadx.api.JadxArgs;
import jadx.api.deobf.IAliasProvider;
import jadx.core.Consts;
import jadx.core.deobf.NameMapper;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.MethodOverrideAttr;
import jadx.core.dex.attributes.nodes.RenameReasonAttr;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.PackageNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.utils.StringUtils;
public class RenameVisitor extends AbstractVisitor {
private static final Pattern ANONYMOUS_CLASS_PATTERN = Pattern.compile("^\\d+$");
@Override
public void init(RootNode root) {
List<File> inputFiles = root.getArgs().getInputFiles();
if (inputFiles.isEmpty()) {
return;
}
process(root);
root.registerCodeDataUpdateListener(codeData -> process(root));
}
private void process(RootNode root) {
UserRenames.apply(root);
checkNames(root);
}
private static void checkNames(RootNode root) {
JadxArgs args = root.getArgs();
if (args.getRenameFlags().isEmpty()) {
return;
}
IAliasProvider aliasProvider = args.getAliasProvider();
List<ClassNode> classes = root.getClasses(true);
for (ClassNode cls : classes) {
checkClassName(aliasProvider, cls, args);
checkFields(aliasProvider, cls, args);
checkMethods(aliasProvider, cls, args);
}
if (!args.isFsCaseSensitive() && args.isRenameCaseSensitive()) {
Set<String> clsFullPaths = new HashSet<>(classes.size());
for (ClassNode cls : classes) {
ClassInfo clsInfo = cls.getClassInfo();
if (!clsFullPaths.add(clsInfo.getAliasFullPath().toLowerCase())) {
clsInfo.changeShortName(aliasProvider.forClass(cls));
cls.addAttr(new RenameReasonAttr(cls).append("case insensitive filesystem"));
clsFullPaths.add(clsInfo.getAliasFullPath().toLowerCase());
}
}
}
boolean pkgUpdated = false;
for (PackageNode pkg : root.getPackages()) {
pkgUpdated |= checkPackage(args, aliasProvider, pkg);
}
if (pkgUpdated) {
root.runPackagesUpdate();
}
processRootPackages(aliasProvider, root, classes);
}
private static void checkClassName(IAliasProvider aliasProvider, ClassNode cls, JadxArgs args) {
if (cls.contains(AFlag.DONT_RENAME)) {
return;
}
ClassInfo classInfo = cls.getClassInfo();
String clsName = classInfo.getAliasShortName();
String newShortName = fixClsShortName(args, clsName);
if (newShortName == null) {
// rename failed, use deobfuscator
cls.rename(aliasProvider.forClass(cls));
cls.addAttr(new RenameReasonAttr(cls).notPrintable());
return;
}
if (!newShortName.equals(clsName)) {
classInfo.changeShortName(newShortName);
cls.addAttr(new RenameReasonAttr(cls).append("invalid class name"));
}
if (classInfo.isInner() && args.isRenameValid()) {
// check inner classes names
ClassInfo parentClass = classInfo.getParentClass();
while (parentClass != null) {
if (parentClass.getAliasShortName().equals(newShortName)) {
cls.rename(aliasProvider.forClass(cls));
cls.addAttr(new RenameReasonAttr(cls).append("collision with other inner class name"));
break;
}
parentClass = parentClass.getParentClass();
}
}
}
private static boolean checkPackage(JadxArgs args, IAliasProvider aliasProvider, PackageNode pkg) {
if (args.isRenameValid() && pkg.getAliasPkgInfo().isDefaultPkg()) {
pkg.setFullAlias(Consts.DEFAULT_PACKAGE_NAME, false);
return true;
}
String pkgName = pkg.getAliasPkgInfo().getName();
boolean notValid = args.isRenameValid() && !NameMapper.isValidIdentifier(pkgName);
boolean notPrintable = args.isRenamePrintable() && !NameMapper.isAllCharsPrintable(pkgName);
if (notValid || notPrintable) {
pkg.setLeafAlias(aliasProvider.forPackage(pkg), false);
return true;
}
return false;
}
@Nullable
private static String fixClsShortName(JadxArgs args, String clsName) {
if (StringUtils.isEmpty(clsName)) {
return null;
}
boolean renameValid = args.isRenameValid();
if (renameValid) {
if (ANONYMOUS_CLASS_PATTERN.matcher(clsName).matches()) {
return Consts.ANONYMOUS_CLASS_PREFIX + NameMapper.removeInvalidCharsMiddle(clsName);
}
char firstChar = clsName.charAt(0);
if (firstChar == '$' || Character.isDigit(firstChar)) {
return 'C' + NameMapper.removeInvalidCharsMiddle(clsName);
}
}
String cleanClsName = args.isRenamePrintable()
? NameMapper.removeNonPrintableCharacters(clsName)
: clsName;
if (cleanClsName.isEmpty()) {
return null;
}
if (renameValid) {
cleanClsName = NameMapper.removeInvalidChars(clsName, "C");
if (!NameMapper.isValidIdentifier(cleanClsName)) {
return 'C' + cleanClsName;
}
}
return cleanClsName;
}
private static void checkFields(IAliasProvider aliasProvider, ClassNode cls, JadxArgs args) {
Set<String> names = new HashSet<>();
for (FieldNode field : cls.getFields()) {
FieldInfo fieldInfo = field.getFieldInfo();
String fieldName = fieldInfo.getAlias();
boolean notUnique = !names.add(fieldName);
boolean notValid = args.isRenameValid() && !NameMapper.isValidIdentifier(fieldName);
boolean notPrintable = args.isRenamePrintable() && !NameMapper.isAllCharsPrintable(fieldName);
if (notUnique || notValid || notPrintable) {
field.rename(aliasProvider.forField(field));
field.addAttr(new RenameReasonAttr(field, notValid, notPrintable));
if (notUnique) {
field.addAttr(new RenameReasonAttr(field).append("collision with other field name"));
}
}
}
}
private static void checkMethods(IAliasProvider aliasProvider, ClassNode cls, JadxArgs args) {
List<MethodNode> methods = new ArrayList<>(cls.getMethods().size());
for (MethodNode method : cls.getMethods()) {
if (!method.getAccessFlags().isConstructor()) {
methods.add(method);
}
}
for (MethodNode mth : methods) {
String alias = mth.getAlias();
boolean notValid = args.isRenameValid() && !NameMapper.isValidIdentifier(alias);
boolean notPrintable = args.isRenamePrintable() && !NameMapper.isAllCharsPrintable(alias);
if (notValid || notPrintable) {
mth.rename(aliasProvider.forMethod(mth));
mth.addAttr(new RenameReasonAttr(mth, notValid, notPrintable));
}
}
// Rename methods with same signature
if (args.isRenameValid()) {
Set<String> names = new HashSet<>(methods.size());
for (MethodNode mth : methods) {
String signature = mth.getMethodInfo().makeSignature(true, false);
if (!names.add(signature) && canRename(mth)) {
mth.rename(aliasProvider.forMethod(mth));
mth.addAttr(new RenameReasonAttr("collision with other method in class"));
}
}
}
}
private static boolean canRename(MethodNode mth) {
if (mth.contains(AFlag.DONT_RENAME)) {
return false;
}
MethodOverrideAttr overrideAttr = mth.get(AType.METHOD_OVERRIDE);
if (overrideAttr != null) {
for (MethodNode relatedMth : overrideAttr.getRelatedMthNodes()) {
if (relatedMth != mth && mth.getParentClass().equals(relatedMth.getParentClass())) {
// ignore rename if exists related method from same class (bridge method in most cases)
// such rename will also rename current method and will not help to resolve name collision
return false;
}
}
}
return true;
}
private static void processRootPackages(IAliasProvider aliasProvider, RootNode root, List<ClassNode> classes) {
Set<String> rootPkgs = collectRootPkgs(root);
root.getCacheStorage().setRootPkgs(rootPkgs);
if (root.getArgs().isRenameValid()) {
// rename field if collide with any root package
for (ClassNode cls : classes) {
for (FieldNode field : cls.getFields()) {
if (rootPkgs.contains(field.getAlias())) {
field.rename(aliasProvider.forField(field));
field.addAttr(new RenameReasonAttr("collision with root package name"));
}
}
}
}
}
private static Set<String> collectRootPkgs(RootNode root) {
Set<String> rootPkgs = new HashSet<>();
for (PackageNode pkg : root.getPackages()) {
if (pkg.isRoot()) {
rootPkgs.add(pkg.getPkgInfo().getName());
}
}
return rootPkgs;
}
@Override
public String getName() {
return "RenameVisitor";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/rename/CodeRenameVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/rename/CodeRenameVisitor.java | package jadx.core.dex.visitors.rename;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.data.ICodeData;
import jadx.api.data.ICodeRename;
import jadx.api.data.IJavaCodeRef;
import jadx.api.data.IJavaNodeRef;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.InitCodeVariables;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.debuginfo.DebugInfoApplyVisitor;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "ApplyCodeRename",
desc = "Rename variables and other entities in methods",
runAfter = {
InitCodeVariables.class,
DebugInfoApplyVisitor.class
}
)
public class CodeRenameVisitor extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(CodeRenameVisitor.class);
private Map<String, List<ICodeRename>> clsRenamesMap;
@Override
public void init(RootNode root) throws JadxException {
updateRenamesMap(root.getArgs().getCodeData());
root.registerCodeDataUpdateListener(this::updateRenamesMap);
}
@Override
public boolean visit(ClassNode cls) {
List<ICodeRename> renames = getRenames(cls);
if (!renames.isEmpty()) {
applyRenames(cls, renames);
}
cls.getInnerClasses().forEach(this::visit);
return false;
}
private static void applyRenames(ClassNode cls, List<ICodeRename> renames) {
for (ICodeRename rename : renames) {
IJavaNodeRef nodeRef = rename.getNodeRef();
if (nodeRef.getType() == IJavaNodeRef.RefType.METHOD) {
MethodNode methodNode = cls.searchMethodByShortId(nodeRef.getShortId());
if (methodNode == null) {
LOG.warn("Method reference not found: {}", nodeRef);
} else {
IJavaCodeRef codeRef = rename.getCodeRef();
if (codeRef != null) {
processRename(methodNode, codeRef, rename);
}
}
}
}
}
private static void processRename(MethodNode mth, IJavaCodeRef codeRef, ICodeRename rename) {
switch (codeRef.getAttachType()) {
case MTH_ARG: {
List<RegisterArg> argRegs = mth.getArgRegs();
int argNum = codeRef.getIndex();
if (argNum < argRegs.size()) {
argRegs.get(argNum).getSVar().getCodeVar().setName(rename.getNewName());
} else {
LOG.warn("Incorrect method arg ref {}, should be less than {}", argNum, argRegs.size());
}
break;
}
case VAR: {
int regNum = codeRef.getIndex() >> 16;
int ssaVer = codeRef.getIndex() & 0xFFFF;
for (SSAVar ssaVar : mth.getSVars()) {
if (ssaVar.getRegNum() == regNum && ssaVar.getVersion() == ssaVer) {
ssaVar.getCodeVar().setName(rename.getNewName());
return;
}
}
LOG.warn("Can't find variable ref by {}_{}", regNum, ssaVer);
break;
}
default:
LOG.warn("Rename code ref type {} not yet supported", codeRef.getAttachType());
break;
}
}
private List<ICodeRename> getRenames(ClassNode cls) {
if (clsRenamesMap == null) {
return Collections.emptyList();
}
List<ICodeRename> clsComments = clsRenamesMap.get(cls.getClassInfo().getRawName());
if (clsComments == null) {
return Collections.emptyList();
}
return clsComments;
}
private void updateRenamesMap(@Nullable ICodeData data) {
if (data == null) {
this.clsRenamesMap = Collections.emptyMap();
} else {
this.clsRenamesMap = data.getRenames().stream()
.filter(r -> r.getCodeRef() != null)
.collect(Collectors.groupingBy(r -> r.getNodeRef().getDeclaringClass()));
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/rename/SourceFileRename.java | jadx-core/src/main/java/jadx/core/dex/visitors/rename/SourceFileRename.java | package jadx.core.dex.visitors.rename;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.Nullable;
import jadx.api.args.UseSourceNameAsClassNameAlias;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.api.plugins.input.data.attributes.types.SourceFileAttr;
import jadx.core.deobf.NameMapper;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.nodes.RenameReasonAttr;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.utils.BetterName;
import jadx.core.utils.StringUtils;
import jadx.core.utils.exceptions.JadxException;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class SourceFileRename extends AbstractVisitor {
@Override
public String getName() {
return "SourceFileRename";
}
@Override
public void init(RootNode root) throws JadxException {
final var useSourceName = root.getArgs().getUseSourceNameAsClassNameAlias();
if (useSourceName == UseSourceNameAsClassNameAlias.NEVER) {
return;
}
int repeatLimit = root.getArgs().getSourceNameRepeatLimit();
if (repeatLimit <= 1) {
return;
}
List<ClassNode> classes = root.getClasses();
Map<String, Integer> aliasUseCount = new HashMap<>();
for (ClassNode cls : classes) {
aliasUseCount.put(cls.getClassInfo().getShortName(), 1);
}
List<ClsRename> renames = new ArrayList<>();
for (ClassNode cls : classes) {
if (cls.contains(AFlag.DONT_RENAME)) {
continue;
}
String alias = getAliasFromSourceFile(cls);
if (alias != null) {
int count = aliasUseCount.merge(alias, 1, Integer::sum);
if (count < repeatLimit) {
renames.add(new ClsRename(cls, alias, count));
}
}
}
for (ClsRename clsRename : renames) {
String alias = clsRename.getAlias();
Integer count = aliasUseCount.get(alias);
if (count < repeatLimit) {
applyRename(clsRename.getCls(), clsRename.buildAlias(), useSourceName);
}
}
}
private static void applyRename(ClassNode cls, String alias, UseSourceNameAsClassNameAlias useSourceName) {
if (cls.getClassInfo().hasAlias()) {
String currentAlias = cls.getAlias();
String betterName = getBetterName(currentAlias, alias, useSourceName);
if (betterName.equals(currentAlias)) {
return;
}
}
cls.getClassInfo().changeShortName(alias);
cls.addAttr(new RenameReasonAttr(cls).append("use source file name"));
}
private static String getBetterName(String currentName, String sourceName, UseSourceNameAsClassNameAlias useSourceName) {
switch (useSourceName) {
case ALWAYS:
return sourceName;
case IF_BETTER:
return BetterName.getBetterClassName(sourceName, currentName);
case NEVER:
return currentName;
default:
throw new JadxRuntimeException("Unhandled strategy: " + useSourceName);
}
}
private static @Nullable String getAliasFromSourceFile(ClassNode cls) {
SourceFileAttr sourceFileAttr = cls.get(JadxAttrType.SOURCE_FILE);
if (sourceFileAttr == null) {
return null;
}
if (cls.getClassInfo().isInner()) {
return null;
}
String name = sourceFileAttr.getFileName();
name = StringUtils.removeSuffix(name, ".java");
name = StringUtils.removeSuffix(name, ".kt");
if (!NameMapper.isValidAndPrintable(name)) {
return null;
}
if (name.equals(cls.getName())) {
return null;
}
return name;
}
private static final class ClsRename {
private final ClassNode cls;
private final String alias;
private final int suffix;
private ClsRename(ClassNode cls, String alias, int suffix) {
this.cls = cls;
this.alias = alias;
this.suffix = suffix;
}
public ClassNode getCls() {
return cls;
}
public String getAlias() {
return alias;
}
public int getSuffix() {
return suffix;
}
public String buildAlias() {
return suffix < 2 ? alias : alias + suffix;
}
@Override
public String toString() {
return "ClsRename{" + cls + " -> '" + alias + suffix + "'}";
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/fixaccessmodifiers/VisibilityUtils.java | jadx-core/src/main/java/jadx/core/dex/visitors/fixaccessmodifiers/VisibilityUtils.java | package jadx.core.dex.visitors.fixaccessmodifiers;
import java.util.function.Consumer;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.ICodeNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
class VisibilityUtils {
private final RootNode root;
VisibilityUtils(RootNode rootNode) {
this.root = rootNode;
}
void checkVisibility(ICodeNode targetNode, ICodeNode callerNode, OnBadVisibilityCallback callback) {
ClassNode targetCls = targetNode instanceof ClassNode
? (ClassNode) targetNode
: targetNode.getDeclaringClass();
ClassNode callerCls = callerNode instanceof ClassNode
? (ClassNode) callerNode
: callerNode.getDeclaringClass();
if (targetCls.equals(callerCls) || inSameTopClass(targetCls, callerCls)) {
return;
}
if (inSamePkg(targetCls, callerCls)) {
visitDeclaringNodes(targetNode, node -> {
if (node.getAccessFlags().isPrivate()) {
callback.onBadVisibility(node, 0); // PACKAGE_PRIVATE
}
});
} else {
visitDeclaringNodes(targetNode, node -> {
AccessInfo nodeVisFlags = node.getAccessFlags().getVisibility();
if (nodeVisFlags.isPublic()) {
return;
}
if (nodeVisFlags.isPrivate() || nodeVisFlags.isPackagePrivate()) {
ClassNode nodeDeclaringCls = node.getDeclaringClass();
int expectedVisFlag = nodeDeclaringCls != null && isSuperType(callerCls, nodeDeclaringCls)
? AccessFlags.PROTECTED
: AccessFlags.PUBLIC;
callback.onBadVisibility(node, expectedVisFlag);
} else if (nodeVisFlags.isProtected()) {
ClassNode nodeDeclaringCls = node.getDeclaringClass();
if (nodeDeclaringCls == null || !isSuperType(callerCls, nodeDeclaringCls)) {
callback.onBadVisibility(node, AccessFlags.PUBLIC);
}
} else {
throw new JadxRuntimeException(nodeVisFlags + " is not supported");
}
});
}
}
private static void visitDeclaringNodes(ICodeNode targetNode, Consumer<ICodeNode> action) {
ICodeNode currentNode = targetNode;
do {
action.accept(currentNode);
currentNode = currentNode.getDeclaringClass();
} while (currentNode != null);
}
private static boolean inSamePkg(ClassNode cls1, ClassNode cls2) {
return cls1.getPackageNode().equals(cls2.getPackageNode());
}
private static boolean inSameTopClass(ClassNode cls1, ClassNode cls2) {
return cls1.getTopParentClass().equals(cls2.getTopParentClass());
}
private boolean isSuperType(ClassNode cls, ClassNode superCls) {
return root.getClsp().getSuperTypes(cls.getRawName()).stream()
.anyMatch(x -> x.equals(superCls.getRawName()));
}
interface OnBadVisibilityCallback {
void onBadVisibility(ICodeNode node, int expectedVisFlag);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/fixaccessmodifiers/FixAccessModifiers.java | jadx-core/src/main/java/jadx/core/dex/visitors/fixaccessmodifiers/FixAccessModifiers.java | package jadx.core.dex.visitors.fixaccessmodifiers;
import java.util.Set;
import java.util.stream.Collectors;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.MethodInlineAttr;
import jadx.core.dex.attributes.nodes.MethodOverrideAttr;
import jadx.core.dex.attributes.nodes.NotificationAttrNode;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.IMethodDetails;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.ModVisitor;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "FixAccessModifiers",
desc = "Change class and method access modifiers if needed",
runAfter = ModVisitor.class
)
public class FixAccessModifiers extends AbstractVisitor {
private VisibilityUtils visibilityUtils;
private boolean respectAccessModifiers;
@Override
public void init(RootNode root) {
this.visibilityUtils = new VisibilityUtils(root);
this.respectAccessModifiers = root.getArgs().isRespectBytecodeAccModifiers();
}
@Override
public boolean visit(ClassNode cls) throws JadxException {
if (respectAccessModifiers) {
return true;
}
fixClassVisibility(cls);
return true;
}
@Override
public void visit(MethodNode mth) {
if (respectAccessModifiers || mth.contains(AFlag.DONT_GENERATE)) {
return;
}
fixMethodVisibility(mth);
}
private void fixClassVisibility(ClassNode cls) {
AccessInfo accessFlags = cls.getAccessFlags();
if (cls.isTopClass() && accessFlags.isPublic()) {
return;
}
if (cls.isTopClass() && (accessFlags.isPrivate() || accessFlags.isProtected())) {
changeVisibility(cls, AccessFlags.PUBLIC);
return;
}
for (ClassNode useCls : cls.getUseIn()) {
visibilityUtils.checkVisibility(cls, useCls, (node, visFlag) -> {
changeVisibility((NotificationAttrNode) node, visFlag);
});
}
for (MethodNode useMth : cls.getUseInMth()) {
MethodInlineAttr inlineAttr = useMth.get(AType.METHOD_INLINE);
boolean isInline = inlineAttr != null && !inlineAttr.notNeeded();
boolean isCandidateForInline = useMth.contains(AFlag.METHOD_CANDIDATE_FOR_INLINE);
if (isInline || isCandidateForInline) {
Set<ClassNode> usedInClss = useMth.getUseIn().stream()
.map(MethodNode::getParentClass)
.collect(Collectors.toSet());
for (ClassNode useCls : usedInClss) {
visibilityUtils.checkVisibility(cls, useCls, (node, visFlag) -> {
changeVisibility((NotificationAttrNode) node, visFlag);
});
}
}
}
}
private void fixMethodVisibility(MethodNode mth) {
AccessInfo accessFlags = mth.getAccessFlags();
MethodOverrideAttr overrideAttr = mth.get(AType.METHOD_OVERRIDE);
if (overrideAttr != null && !overrideAttr.getOverrideList().isEmpty()) {
// visibility can't be weaker
IMethodDetails parentMD = overrideAttr.getOverrideList().get(0);
AccessInfo parentAccInfo = new AccessInfo(parentMD.getRawAccessFlags(), AccessInfo.AFType.METHOD);
if (accessFlags.isVisibilityWeakerThan(parentAccInfo)) {
changeVisibility(mth, parentAccInfo.getVisibility().rawValue());
}
}
for (MethodNode useMth : mth.getUseIn()) {
visibilityUtils.checkVisibility(mth, useMth, (node, visFlag) -> {
changeVisibility((NotificationAttrNode) node, visFlag);
});
}
}
public static void changeVisibility(NotificationAttrNode node, int newVisFlag) {
AccessInfo accessFlags = node.getAccessFlags();
AccessInfo newAccFlags = accessFlags.changeVisibility(newVisFlag);
if (newAccFlags != accessFlags) {
node.setAccessFlags(newAccFlags);
node.addInfoComment("Access modifiers changed from: " + accessFlags.visibilityName());
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/IRegionVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/IRegionVisitor.java | package jadx.core.dex.visitors.regions;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
public interface IRegionVisitor {
void processBlock(MethodNode mth, IBlock container);
/**
* @return true for traverse sub-blocks, false otherwise.
*/
boolean enterRegion(MethodNode mth, IRegion region);
void leaveRegion(MethodNode mth, IRegion region);
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/DepthRegionTraversal.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/DepthRegionTraversal.java | package jadx.core.dex.visitors.regions;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.utils.exceptions.JadxOverflowException;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class DepthRegionTraversal {
private static final int ITERATIVE_LIMIT_MULTIPLIER = 5;
private DepthRegionTraversal() {
}
public static void traverse(MethodNode mth, IRegionVisitor visitor) {
traverseInternal(mth, visitor, mth.getRegion());
}
public static void traverse(MethodNode mth, IContainer container, IRegionVisitor visitor) {
traverseInternal(mth, visitor, container);
}
public static void traverseIterative(MethodNode mth, IRegionIterativeVisitor visitor) {
boolean repeat;
int k = 0;
int limit = ITERATIVE_LIMIT_MULTIPLIER * mth.getBasicBlocks().size();
do {
repeat = traverseIterativeStepInternal(mth, visitor, mth.getRegion());
if (k++ > limit) {
throw new JadxRuntimeException("Iterative traversal limit reached: "
+ "limit: " + limit + ", visitor: " + visitor.getClass().getName()
+ ", blocks count: " + mth.getBasicBlocks().size());
}
} while (repeat);
}
public static void traverseIncludingExcHandlers(MethodNode mth, IRegionIterativeVisitor visitor) {
boolean repeat;
int k = 0;
int limit = ITERATIVE_LIMIT_MULTIPLIER * mth.getBasicBlocks().size();
do {
repeat = traverseIterativeStepInternal(mth, visitor, mth.getRegion());
if (!repeat) {
for (ExceptionHandler h : mth.getExceptionHandlers()) {
repeat = traverseIterativeStepInternal(mth, visitor, h.getHandlerRegion());
if (repeat) {
break;
}
}
}
if (k++ > limit) {
throw new JadxRuntimeException("Iterative traversal limit reached: "
+ "limit: " + limit + ", visitor: " + visitor.getClass().getName()
+ ", blocks count: " + mth.getBasicBlocks().size());
}
} while (repeat);
}
private static void traverseInternal(MethodNode mth, IRegionVisitor visitor, IContainer container) {
if (container instanceof IBlock) {
visitor.processBlock(mth, (IBlock) container);
} else if (container instanceof IRegion) {
IRegion region = (IRegion) container;
if (visitor.enterRegion(mth, region)) {
region.getSubBlocks().forEach(subCont -> traverseInternal(mth, visitor, subCont));
}
visitor.leaveRegion(mth, region);
}
}
private static boolean traverseIterativeStepInternal(MethodNode mth, IRegionIterativeVisitor visitor, IContainer container) {
if (container instanceof IRegion) {
IRegion region = (IRegion) container;
if (visitor.visitRegion(mth, region)) {
return true;
}
for (IContainer subCont : region.getSubBlocks()) {
try {
if (traverseIterativeStepInternal(mth, visitor, subCont)) {
return true;
}
} catch (StackOverflowError overflow) {
throw new JadxOverflowException("Region traversal failed: Recursive call in traverseIterativeStepInternal method");
}
}
}
return false;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/PostProcessRegions.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/PostProcessRegions.java | package jadx.core.dex.visitors.regions;
import java.util.Collections;
import java.util.List;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.EdgeInsnAttr;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnContainer;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.SwitchRegion;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.visitors.regions.maker.SwitchRegionMaker;
public final class PostProcessRegions extends AbstractRegionVisitor {
private static final IRegionVisitor INSTANCE = new PostProcessRegions();
static void process(MethodNode mth) {
DepthRegionTraversal.traverse(mth, INSTANCE);
}
@Override
public void leaveRegion(MethodNode mth, IRegion region) {
if (region instanceof LoopRegion) {
// merge conditions in loops
LoopRegion loop = (LoopRegion) region;
loop.mergePreCondition();
} else if (region instanceof SwitchRegion) {
SwitchRegionMaker.insertBreaks(mth, (SwitchRegion) region);
} else if (region instanceof Region) {
insertEdgeInsn((Region) region);
}
}
/**
* Insert insn block from edge insn attribute.
*/
private static void insertEdgeInsn(Region region) {
List<IContainer> subBlocks = region.getSubBlocks();
if (subBlocks.isEmpty()) {
return;
}
IContainer last = subBlocks.get(subBlocks.size() - 1);
List<EdgeInsnAttr> edgeInsnAttrs = last.getAll(AType.EDGE_INSN);
if (edgeInsnAttrs.isEmpty()) {
return;
}
EdgeInsnAttr insnAttr = edgeInsnAttrs.get(0);
if (!insnAttr.getStart().equals(last)) {
return;
}
if (last instanceof BlockNode) {
BlockNode block = (BlockNode) last;
if (block.getInstructions().isEmpty()) {
block.getInstructions().add(insnAttr.getInsn());
return;
}
}
List<InsnNode> insns = Collections.singletonList(insnAttr.getInsn());
region.add(new InsnContainer(insns));
}
private PostProcessRegions() {
// singleton
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/IfRegionVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/IfRegionVisitor.java | package jadx.core.dex.visitors.regions;
import java.util.List;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.conditions.IfCondition;
import jadx.core.dex.regions.conditions.IfCondition.Mode;
import jadx.core.dex.regions.conditions.IfRegion;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.utils.InsnUtils;
import jadx.core.utils.RegionUtils;
import static jadx.core.utils.RegionUtils.insnsCount;
public class IfRegionVisitor extends AbstractVisitor {
private static final ProcessIfRegionVisitor PROCESS_IF_REGION_VISITOR = new ProcessIfRegionVisitor();
private static final RemoveRedundantElseVisitor REMOVE_REDUNDANT_ELSE_VISITOR = new RemoveRedundantElseVisitor();
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode()) {
return;
}
process(mth);
}
public static void processIfRequested(MethodNode mth) {
if (mth.contains(AFlag.REQUEST_IF_REGION_OPTIMIZE)) {
try {
process(mth);
} finally {
mth.remove(AFlag.REQUEST_IF_REGION_OPTIMIZE);
}
}
}
private static void process(MethodNode mth) {
TernaryMod.process(mth);
DepthRegionTraversal.traverse(mth, PROCESS_IF_REGION_VISITOR);
DepthRegionTraversal.traverseIterative(mth, REMOVE_REDUNDANT_ELSE_VISITOR);
}
private static class ProcessIfRegionVisitor extends AbstractRegionVisitor {
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
if (region instanceof IfRegion) {
IfRegion ifRegion = (IfRegion) region;
orderBranches(mth, ifRegion);
markElseIfChains(mth, ifRegion);
}
return true;
}
}
@SuppressWarnings({ "UnnecessaryReturnStatement" })
private static void orderBranches(MethodNode mth, IfRegion ifRegion) {
if (RegionUtils.isEmpty(ifRegion.getElseRegion())) {
return;
}
if (RegionUtils.isEmpty(ifRegion.getThenRegion())) {
invertIfRegion(ifRegion);
return;
}
if (mth.contains(AFlag.USE_LINES_HINTS)) {
int thenLine = RegionUtils.getFirstSourceLine(ifRegion.getThenRegion());
int elseLine = RegionUtils.getFirstSourceLine(ifRegion.getElseRegion());
if (thenLine != 0 && elseLine != 0) {
if (thenLine > elseLine) {
invertIfRegion(ifRegion);
}
return;
}
}
if (ifRegion.simplifyCondition()) {
IfCondition condition = ifRegion.getCondition();
if (condition != null && condition.getMode() == Mode.NOT) {
invertIfRegion(ifRegion);
}
}
int thenSize = insnsCount(ifRegion.getThenRegion());
int elseSize = insnsCount(ifRegion.getElseRegion());
if (isSimpleExitBlock(mth, ifRegion.getElseRegion())) {
if (isSimpleExitBlock(mth, ifRegion.getThenRegion())) {
if (elseSize < thenSize) {
invertIfRegion(ifRegion);
return;
}
}
if (elseSize == 1) {
boolean lastRegion = RegionUtils.hasExitEdge(ifRegion);
if (lastRegion && mth.isVoidReturn()) {
InsnNode lastElseInsn = RegionUtils.getLastInsn(ifRegion.getElseRegion());
if (InsnUtils.isInsnType(lastElseInsn, InsnType.THROW)) {
// move `throw` into `then` block
invertIfRegion(ifRegion);
} else {
// single return at method end will be removed later
}
return;
}
if (thenSize > 2 && !(lastRegion && thenSize < 4 /* keep small code block inside else */)) {
invertIfRegion(ifRegion);
return;
}
}
}
boolean thenExit = RegionUtils.hasExitBlock(ifRegion.getThenRegion());
boolean elseExit = RegionUtils.hasExitBlock(ifRegion.getElseRegion());
if (elseExit && (!thenExit || elseSize < thenSize)) {
invertIfRegion(ifRegion);
return;
}
// move 'if' from 'then' branch to make 'else if' chain
if (isIfRegion(ifRegion.getThenRegion())
&& !isIfRegion(ifRegion.getElseRegion())
&& !thenExit) {
invertIfRegion(ifRegion);
return;
}
// move 'break' into 'then' branch
if (RegionUtils.hasBreakInsn(ifRegion.getElseRegion())) {
invertIfRegion(ifRegion);
return;
}
}
private static boolean isIfRegion(IContainer container) {
if (container instanceof IfRegion) {
return true;
}
if (container instanceof IRegion) {
List<IContainer> subBlocks = ((IRegion) container).getSubBlocks();
return subBlocks.size() == 1 && subBlocks.get(0) instanceof IfRegion;
}
return false;
}
/**
* Mark if-else-if chains
*/
private static void markElseIfChains(MethodNode mth, IfRegion ifRegion) {
if (isSimpleExitBlock(mth, ifRegion.getThenRegion())) {
return;
}
IContainer elsRegion = ifRegion.getElseRegion();
if (elsRegion instanceof Region) {
List<IContainer> subBlocks = ((Region) elsRegion).getSubBlocks();
if (subBlocks.size() == 1 && subBlocks.get(0) instanceof IfRegion) {
subBlocks.get(0).add(AFlag.ELSE_IF_CHAIN);
elsRegion.add(AFlag.ELSE_IF_CHAIN);
}
}
}
private static class RemoveRedundantElseVisitor implements IRegionIterativeVisitor {
@Override
public boolean visitRegion(MethodNode mth, IRegion region) {
if (region instanceof IfRegion) {
return removeRedundantElseBlock(mth, (IfRegion) region);
}
return false;
}
}
@SuppressWarnings("UnnecessaryParentheses")
private static boolean removeRedundantElseBlock(MethodNode mth, IfRegion ifRegion) {
if (ifRegion.getElseRegion() == null) {
return false;
}
if (!RegionUtils.hasExitBlock(ifRegion.getThenRegion())) {
return false;
}
InsnNode lastThanInsn = RegionUtils.getLastInsn(ifRegion.getThenRegion());
if (InsnUtils.isInsnType(lastThanInsn, InsnType.THROW)) {
// always omit else after 'throw'
} else {
// code style check:
// will remove 'return;' from 'then' and 'else' with one instruction
// see #jadx.tests.integration.conditions.TestConditions9
if (mth.isVoidReturn()) {
int thenSize = insnsCount(ifRegion.getThenRegion());
// keep small blocks with same or 'similar' size unchanged
if (thenSize < 5) {
int elseSize = insnsCount(ifRegion.getElseRegion());
int range = ifRegion.getElseRegion().contains(AFlag.ELSE_IF_CHAIN) ? 4 : 2;
if (thenSize == elseSize || (thenSize * range > elseSize && thenSize < elseSize * range)) {
return false;
}
}
}
}
IRegion parent = ifRegion.getParent();
Region newRegion = new Region(parent);
if (parent.replaceSubBlock(ifRegion, newRegion)) {
newRegion.add(ifRegion);
newRegion.add(ifRegion.getElseRegion());
ifRegion.setElseRegion(null);
return true;
}
return false;
}
private static void invertIfRegion(IfRegion ifRegion) {
IContainer elseRegion = ifRegion.getElseRegion();
if (elseRegion != null) {
ifRegion.invert();
}
}
private static boolean isSimpleExitBlock(MethodNode mth, IContainer container) {
if (container == null) {
return false;
}
if (container.contains(AFlag.RETURN) || RegionUtils.isExitBlock(mth, container)) {
return true;
}
if (container instanceof IRegion) {
List<IContainer> subBlocks = ((IRegion) container).getSubBlocks();
return subBlocks.size() == 1 && RegionUtils.isExitBlock(mth, subBlocks.get(0));
}
return false;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/ReturnVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/ReturnVisitor.java | package jadx.core.dex.visitors.regions;
import java.util.List;
import java.util.ListIterator;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IBranchRegion;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.SwitchRegion;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.utils.exceptions.JadxException;
import jadx.core.utils.exceptions.JadxRuntimeException;
/**
* Remove unnecessary return instructions for void methods
*/
public class ReturnVisitor extends AbstractVisitor {
@Override
public void visit(MethodNode mth) throws JadxException {
if (mth.isVoidReturn()) {
DepthRegionTraversal.traverse(mth, new ReturnRemoverVisitor());
}
}
private static final class ReturnRemoverVisitor extends TracedRegionVisitor {
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
super.enterRegion(mth, region);
return !(region instanceof SwitchRegion);
}
@Override
public void processBlockTraced(MethodNode mth, IBlock container, IRegion currentRegion) {
if (container.getClass() != BlockNode.class) {
return;
}
BlockNode block = (BlockNode) container;
if (block.contains(AFlag.RETURN)) {
List<InsnNode> insns = block.getInstructions();
if (insns.size() == 1
&& blockNotInLoop(mth, block)
&& noTrailInstructions(block)) {
insns.remove(0);
block.remove(AFlag.RETURN);
}
}
}
private boolean blockNotInLoop(MethodNode mth, BlockNode block) {
if (mth.getLoopsCount() == 0) {
return true;
}
if (mth.getLoopForBlock(block) != null) {
return false;
}
for (IRegion region : regionStack) {
if (region.getClass() == LoopRegion.class) {
return false;
}
}
return true;
}
/**
* Check that there are no code after this block in regions structure
*/
private boolean noTrailInstructions(BlockNode block) {
IContainer curContainer = block;
for (IRegion region : regionStack) {
// ignore paths on other branches
if (region instanceof IBranchRegion) {
curContainer = region;
continue;
}
List<IContainer> subBlocks = region.getSubBlocks();
if (!subBlocks.isEmpty()) {
ListIterator<IContainer> itSubBlock = subBlocks.listIterator(subBlocks.size());
while (itSubBlock.hasPrevious()) {
IContainer subBlock = itSubBlock.previous();
if (subBlock == curContainer) {
break;
} else if (!isEmpty(subBlock)) {
return false;
}
}
}
curContainer = region;
}
return true;
}
/**
* Check if container not contains instructions,
* don't count one 'return' instruction (it will be removed later).
*/
private static boolean isEmpty(IContainer container) {
if (container instanceof IBlock) {
IBlock block = (IBlock) container;
return block.getInstructions().isEmpty() || block.contains(AFlag.RETURN);
} else if (container instanceof IRegion) {
IRegion region = (IRegion) container;
for (IContainer block : region.getSubBlocks()) {
if (!isEmpty(block)) {
return false;
}
}
return true;
} else {
throw new JadxRuntimeException("Unknown container type: " + container.getClass());
}
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/IRegionIterativeVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/IRegionIterativeVisitor.java | package jadx.core.dex.visitors.regions;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
public interface IRegionIterativeVisitor {
/**
* If return 'true' traversal will be restarted.
*/
boolean visitRegion(MethodNode mth, IRegion region);
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/SwitchBreakVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/SwitchBreakVisitor.java | package jadx.core.dex.visitors.regions;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.CodeFeaturesAttr;
import jadx.core.dex.attributes.nodes.RegionRefAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IBranchRegion;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.SwitchRegion;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.regions.maker.SwitchRegionMaker;
import jadx.core.utils.BlockInsnPair;
import jadx.core.utils.BlockParentContainer;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.ListUtils;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.exceptions.JadxException;
import static jadx.core.dex.attributes.nodes.CodeFeaturesAttr.CodeFeature.SWITCH;
@JadxVisitor(
name = "SwitchBreakVisitor",
desc = "Optimize 'break' instruction: common code extract, remove unreachable",
runAfter = LoopRegionVisitor.class // can add 'continue' at case end
)
public class SwitchBreakVisitor extends AbstractVisitor {
@Override
public void visit(MethodNode mth) throws JadxException {
if (CodeFeaturesAttr.contains(mth, SWITCH)) {
runSwitchTraverse(mth, ExtractCommonBreak::new);
runSwitchTraverse(mth, RemoveUnreachableBreak::new);
IfRegionVisitor.processIfRequested(mth);
}
}
private static void runSwitchTraverse(MethodNode mth, Supplier<BaseSwitchRegionVisitor> builder) {
DepthRegionTraversal.traverse(mth, new IterativeSwitchRegionVisitor(builder));
}
/**
* Add common 'break' if 'break' or exit insn ('return', 'throw', 'continue') found in all branches.
* Remove exist common break if all branches contain exit insn.
*/
private static final class ExtractCommonBreak extends BaseSwitchRegionVisitor {
@Override
public void processRegion(MethodNode mth, IRegion region) {
if (region instanceof IBranchRegion && !(region instanceof SwitchRegion)) {
// if break in all branches extract to parent region
processBranchRegion(mth, region);
}
}
private void processBranchRegion(MethodNode mth, IRegion region) {
IRegion parentRegion = region.getParent();
if (parentRegion.contains(AFlag.FALL_THROUGH)) {
// fallthrough case, can't extract break
return;
}
boolean dontAddCommonBreak = false;
IBlock lastParentBlock = RegionUtils.getLastBlock(parentRegion);
if (BlockUtils.containsExitInsn(lastParentBlock)) {
if (isBreakBlock(lastParentBlock)) {
// parent block already contains 'break'
dontAddCommonBreak = true;
} else {
// can't add 'break' after 'return', 'throw' or 'continue'
return;
}
}
List<IContainer> branches = ((IBranchRegion) region).getBranches();
boolean removeCommonBreak = true; // all branches contain exit insns, common break is unreachable
List<BlockParentContainer> forBreakRemove = new ArrayList<>();
for (IContainer branch : branches) {
if (branch == null) {
removeCommonBreak = false;
continue;
}
BlockInsnPair last = RegionUtils.getLastInsnWithBlock(branch);
if (last == null) {
return;
}
InsnNode lastInsn = last.getInsn();
if (lastInsn.getType() == InsnType.BREAK) {
IBlock block = last.getBlock();
IContainer parent = RegionUtils.getBlockContainer(branch, block);
forBreakRemove.add(new BlockParentContainer(parent, block));
removeCommonBreak = false;
} else if (!lastInsn.isExitEdgeInsn()) {
removeCommonBreak = false;
}
}
if (!forBreakRemove.isEmpty()) {
// common 'break' confirmed
for (BlockParentContainer breakData : forBreakRemove) {
removeBreak(breakData.getBlock(), breakData.getParent());
}
if (!dontAddCommonBreak) {
addBreakRegion.add(parentRegion);
// new 'break' might become 'common' for upper branch region, request to run checks again
requestReRun();
}
// removed 'break' may allow to use 'else-if' chain
mth.add(AFlag.REQUEST_IF_REGION_OPTIMIZE);
}
if (removeCommonBreak && lastParentBlock != null) {
removeBreak(lastParentBlock, parentRegion);
}
}
}
private static final class RemoveUnreachableBreak extends BaseSwitchRegionVisitor {
@Override
public void processRegion(MethodNode mth, IRegion region) {
List<IContainer> subBlocks = region.getSubBlocks();
IContainer lastContainer = ListUtils.last(subBlocks);
if (lastContainer instanceof IBlock) {
IBlock block = (IBlock) lastContainer;
if (isBreakBlock(block) && isPrevInsnIsExit(block, subBlocks)) {
removeBreak(block, region);
}
}
}
private boolean isPrevInsnIsExit(IBlock breakBlock, List<IContainer> subBlocks) {
InsnNode prevInsn = null;
if (breakBlock.getInstructions().size() > 1) {
// check prev insn in same block
List<InsnNode> insns = breakBlock.getInstructions();
prevInsn = insns.get(insns.size() - 2);
} else if (subBlocks.size() > 1) {
IContainer prev = subBlocks.get(subBlocks.size() - 2);
if (prev instanceof IBlock) {
List<InsnNode> insns = ((IBlock) prev).getInstructions();
prevInsn = ListUtils.last(insns);
}
}
return prevInsn != null && prevInsn.isExitEdgeInsn();
}
}
/**
* For every 'switch' region run new instance of provided 'switch' visitor.
* If rerun requested, run traverse for that visitor again.
*/
private static final class IterativeSwitchRegionVisitor extends AbstractRegionVisitor {
private final Supplier<BaseSwitchRegionVisitor> builder;
public IterativeSwitchRegionVisitor(Supplier<BaseSwitchRegionVisitor> builder) {
this.builder = builder;
}
@Override
public void leaveRegion(MethodNode mth, IRegion region) {
if (region instanceof SwitchRegion) {
SwitchRegion switchRegion = (SwitchRegion) region;
BaseSwitchRegionVisitor switchVisitor = builder.get();
switchVisitor.setCurrentSwitch(switchRegion);
boolean runAgain;
int k = 0;
do {
runAgain = false;
DepthRegionTraversal.traverse(mth, switchRegion, switchVisitor);
if (switchVisitor.isReRunRequested()) {
switchVisitor.reset();
runAgain = true;
}
if (k++ > 20) {
// 20 nested 'if' are not expected
mth.addWarnComment("Unexpected iteration count in SwitchBreakVisitor. Please report as an issue");
break;
}
} while (runAgain);
}
}
}
private abstract static class BaseSwitchRegionVisitor extends AbstractRegionVisitor {
protected final Set<IRegion> addBreakRegion = new HashSet<>();
protected final Set<IContainer> cleanupSet = new HashSet<>();
protected SwitchRegion currentSwitch;
private boolean reRunRequested = false;
public abstract void processRegion(MethodNode mth, IRegion region);
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
processRegion(mth, region);
return true;
}
@Override
public void leaveRegion(MethodNode mth, IRegion region) {
if (addBreakRegion.contains(region)) {
addBreakRegion.remove(region);
region.getSubBlocks().add(SwitchRegionMaker.buildBreakContainer(currentSwitch));
}
if (cleanupSet.contains(region)) {
cleanupSet.remove(region);
region.getSubBlocks().removeIf(r -> r.contains(AFlag.REMOVE));
}
}
/**
* Method called before visitor rerun
*/
public void reset() {
reRunRequested = false;
addBreakRegion.clear();
cleanupSet.clear();
}
public void requestReRun() {
reRunRequested = true;
}
public boolean isReRunRequested() {
return reRunRequested;
}
public void setCurrentSwitch(SwitchRegion currentSwitch) {
this.currentSwitch = currentSwitch;
}
protected boolean isBreakBlock(@Nullable IBlock block) {
if (block != null) {
InsnNode lastInsn = ListUtils.last(block.getInstructions());
if (lastInsn != null && lastInsn.getType() == InsnType.BREAK) {
RegionRefAttr regionRefAttr = lastInsn.get(AType.REGION_REF);
return regionRefAttr != null && regionRefAttr.getRegion() == currentSwitch;
}
}
return false;
}
protected void removeBreak(IBlock breakBlock, IContainer parentContainer) {
List<InsnNode> instructions = breakBlock.getInstructions();
InsnNode last = ListUtils.last(instructions);
if (last != null && last.getType() == InsnType.BREAK) {
ListUtils.removeLast(instructions);
if (instructions.isEmpty()) {
breakBlock.add(AFlag.REMOVE);
cleanupSet.add(parentContainer);
}
}
}
}
@Override
public String getName() {
return "SwitchBreakVisitor";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/CleanRegions.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/CleanRegions.java | package jadx.core.dex.visitors.regions;
import java.util.List;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.visitors.AbstractVisitor;
public class CleanRegions extends AbstractVisitor {
private static final IRegionVisitor REMOVE_REGION_VISITOR = new RemoveRegionVisitor();
@Override
public void visit(MethodNode mth) {
process(mth);
}
public static void process(MethodNode mth) {
if (mth.isNoCode() || mth.getBasicBlocks().isEmpty()) {
return;
}
DepthRegionTraversal.traverse(mth, REMOVE_REGION_VISITOR);
}
private static class RemoveRegionVisitor extends AbstractRegionVisitor {
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
if (region instanceof Region) {
region.getSubBlocks().removeIf(RemoveRegionVisitor::canRemoveRegion);
}
return true;
}
private static boolean canRemoveRegion(IContainer container) {
if (container.contains(AFlag.DONT_GENERATE)) {
return true;
}
if (container instanceof BlockNode) {
BlockNode block = (BlockNode) container;
return block.getInstructions().isEmpty();
}
if (container instanceof LoopRegion) {
LoopRegion loopRegion = (LoopRegion) container;
if (loopRegion.isEndless()) {
// keep empty endless loops
return false;
}
}
if (container instanceof IRegion) {
List<IContainer> subBlocks = ((IRegion) container).getSubBlocks();
for (IContainer subBlock : subBlocks) {
if (!canRemoveRegion(subBlock)) {
return false;
}
}
return true;
}
return false;
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/SwitchOverStringVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/SwitchOverStringVisitor.java | package jadx.core.dex.visitors.regions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jetbrains.annotations.Nullable;
import jadx.api.plugins.input.data.annotations.EncodedType;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.IAttributeNode;
import jadx.core.dex.attributes.nodes.CodeFeaturesAttr;
import jadx.core.dex.attributes.nodes.CodeFeaturesAttr.CodeFeature;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.IfOp;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.SwitchRegion;
import jadx.core.dex.regions.conditions.IfCondition;
import jadx.core.dex.regions.conditions.IfRegion;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.InsnUtils;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "SwitchOverStringVisitor",
desc = "Restore switch over string",
runAfter = IfRegionVisitor.class,
runBefore = ReturnVisitor.class
)
public class SwitchOverStringVisitor extends AbstractVisitor implements IRegionIterativeVisitor {
@Override
public void visit(MethodNode mth) throws JadxException {
if (!CodeFeaturesAttr.contains(mth, CodeFeature.SWITCH)) {
return;
}
DepthRegionTraversal.traverseIterative(mth, this);
}
@Override
public boolean visitRegion(MethodNode mth, IRegion region) {
if (region instanceof SwitchRegion) {
return restoreSwitchOverString(mth, (SwitchRegion) region);
}
return false;
}
private boolean restoreSwitchOverString(MethodNode mth, SwitchRegion switchRegion) {
try {
InsnNode swInsn = BlockUtils.getLastInsnWithType(switchRegion.getHeader(), InsnType.SWITCH);
if (swInsn == null) {
return false;
}
RegisterArg strArg = getStrHashCodeArg(swInsn.getArg(0));
if (strArg == null) {
return false;
}
int casesCount = switchRegion.getCases().size();
SSAVar strVar = strArg.getSVar();
if (strVar.getUseCount() - 1 < casesCount) {
// one 'hashCode' invoke and at least one 'equals' per case
return false;
}
// quick checks done, start collecting data to create a new switch region
Map<InsnNode, String> strEqInsns = collectEqualsInsns(mth, strVar);
if (strEqInsns.size() < casesCount) {
return false;
}
SwitchData switchData = new SwitchData(mth, switchRegion);
switchData.setStrEqInsns(strEqInsns);
switchData.setCases(new ArrayList<>(strEqInsns.size()));
for (SwitchRegion.CaseInfo swCaseInfo : switchRegion.getCases()) {
if (!processCase(switchData, swCaseInfo)) {
mth.addWarnComment("Failed to restore switch over string. Please report as a decompilation issue");
return false;
}
}
// match remapping var to collect code from second switch
if (!mergeWithCode(switchData)) {
mth.addWarnComment("Failed to restore switch over string. Please report as a decompilation issue");
return false;
}
// all checks passed, replace with new switch
IRegion parentRegion = switchRegion.getParent();
SwitchRegion replaceRegion = new SwitchRegion(parentRegion, switchRegion.getHeader());
for (SwitchRegion.CaseInfo caseInfo : switchData.getNewCases()) {
replaceRegion.addCase(Collections.unmodifiableList(caseInfo.getKeys()), caseInfo.getContainer());
}
if (!parentRegion.replaceSubBlock(switchRegion, replaceRegion)) {
mth.addWarnComment("Failed to restore switch over string. Please report as a decompilation issue");
return false;
}
// replace confirmed, remove original code
markCodeForRemoval(switchData);
// use string arg directly in switch
swInsn.replaceArg(swInsn.getArg(0), strArg.duplicate());
return true;
} catch (StackOverflowError | Exception e) {
mth.addWarnComment("Failed to restore switch over string. Please report as a decompilation issue", e);
return false;
}
}
private static void markCodeForRemoval(SwitchData switchData) {
MethodNode mth = switchData.getMth();
try {
switchData.getToRemove().forEach(i -> i.add(AFlag.REMOVE));
SwitchRegion codeSwitch = switchData.getCodeSwitch();
if (codeSwitch != null) {
IRegion parentRegion = switchData.getSwitchRegion().getParent();
parentRegion.getSubBlocks().remove(codeSwitch);
codeSwitch.getHeader().add(AFlag.REMOVE);
}
RegisterArg numArg = switchData.getNumArg();
if (numArg != null) {
for (SSAVar ssaVar : numArg.getSVar().getCodeVar().getSsaVars()) {
InsnNode assignInsn = ssaVar.getAssignInsn();
if (assignInsn != null) {
assignInsn.add(AFlag.REMOVE);
}
for (RegisterArg useArg : ssaVar.getUseList()) {
InsnNode parentInsn = useArg.getParentInsn();
if (parentInsn != null) {
parentInsn.add(AFlag.REMOVE);
}
}
mth.removeSVar(ssaVar);
}
}
InsnRemover.removeAllMarked(mth);
} catch (StackOverflowError | Exception e) {
mth.addWarnComment("Failed to clean up code after switch over string restore", e);
}
}
private boolean mergeWithCode(SwitchData switchData) {
List<CaseData> cases = switchData.getCases();
// search index assign in cases code
RegisterArg numArg = null;
int extracted = 0;
for (CaseData caseData : cases) {
IContainer container = caseData.getCode();
List<InsnNode> insns = RegionUtils.collectInsns(switchData.getMth(), container);
insns.removeIf(i -> i.getType() == InsnType.BREAK);
if (insns.size() != 1) {
continue;
}
InsnNode numInsn = insns.get(0);
if (numInsn.getArgsCount() == 1) {
Object constVal = InsnUtils.getConstValueByArg(switchData.getMth().root(), numInsn.getArg(0));
if (constVal instanceof LiteralArg) {
if (numArg == null) {
numArg = numInsn.getResult();
} else {
if (!numArg.sameCodeVar(numInsn.getResult())) {
return false;
}
}
int num = (int) ((LiteralArg) constVal).getLiteral();
caseData.setCodeNum(num);
extracted++;
}
}
}
if (extracted == 0) {
// nothing to merge, code already inside first switch cases
return true;
}
if (extracted != cases.size()) {
return false;
}
// TODO: additional checks for found index numbers
cases.sort(Comparator.comparingInt(CaseData::getCodeNum));
// extract complete, second switch on 'numArg' should be the next region
IContainer nextContainer = RegionUtils.getNextContainer(switchData.getMth(), switchData.getSwitchRegion());
if (!(nextContainer instanceof SwitchRegion)) {
return false;
}
SwitchRegion codeSwitch = (SwitchRegion) nextContainer;
InsnNode swInsn = BlockUtils.getLastInsnWithType(codeSwitch.getHeader(), InsnType.SWITCH);
if (swInsn == null || !swInsn.getArg(0).isSameCodeVar(numArg)) {
return false;
}
Map<Integer, CaseData> casesMap = new HashMap<>(cases.size());
for (CaseData caseData : cases) {
CaseData prev = casesMap.put(caseData.getCodeNum(), caseData);
if (prev != null) {
return false;
}
RegionUtils.visitBlocks(switchData.getMth(), caseData.getCode(),
block -> switchData.getToRemove().add(block));
}
final var newCases = new ArrayList<SwitchRegion.CaseInfo>();
for (SwitchRegion.CaseInfo caseInfo : codeSwitch.getCases()) {
SwitchRegion.CaseInfo newCase = null;
for (Object key : caseInfo.getKeys()) {
final Integer intKey = unwrapIntKey(key);
if (intKey != null) {
final var caseData = casesMap.remove(intKey);
if (caseData == null) {
return false;
}
if (newCase == null) {
final List<Object> keys = new ArrayList<>(caseData.getStrValues());
newCase = new SwitchRegion.CaseInfo(keys, caseInfo.getContainer());
} else {
// merge cases
newCase.getKeys().addAll(caseData.getStrValues());
}
} else if (key == SwitchRegion.DEFAULT_CASE_KEY) {
final var iterator = casesMap.entrySet().iterator();
while (iterator.hasNext()) {
final var caseData = iterator.next().getValue();
if (newCase == null) {
final List<Object> keys = new ArrayList<>(caseData.getStrValues());
newCase = new SwitchRegion.CaseInfo(keys, caseInfo.getContainer());
} else {
// merge cases
newCase.getKeys().addAll(caseData.getStrValues());
}
iterator.remove();
}
if (newCase == null) {
newCase = new SwitchRegion.CaseInfo(new ArrayList<>(), caseInfo.getContainer());
}
newCase.getKeys().add(SwitchRegion.DEFAULT_CASE_KEY);
} else {
return false;
}
}
newCases.add(newCase);
}
switchData.setCodeSwitch(codeSwitch);
switchData.setNumArg(numArg);
switchData.setNewCases(newCases);
return true;
}
private Integer unwrapIntKey(Object key) {
if (key instanceof Integer) {
return (Integer) key;
} else if (key instanceof FieldNode) {
final var encodedValue = ((FieldNode) key).get(JadxAttrType.CONSTANT_VALUE);
if (encodedValue != null && encodedValue.getType() == EncodedType.ENCODED_INT) {
return (Integer) encodedValue.getValue();
} else {
return null;
}
}
return null;
}
private static Map<InsnNode, String> collectEqualsInsns(MethodNode mth, SSAVar strVar) {
Map<InsnNode, String> map = new IdentityHashMap<>(strVar.getUseCount() - 1);
for (RegisterArg useReg : strVar.getUseList()) {
InsnNode parentInsn = useReg.getParentInsn();
if (parentInsn != null && parentInsn.getType() == InsnType.INVOKE) {
InvokeNode inv = (InvokeNode) parentInsn;
if (inv.getCallMth().getRawFullId().equals("java.lang.String.equals(Ljava/lang/Object;)Z")) {
InsnArg strArg = inv.getArg(1);
Object strValue = InsnUtils.getConstValueByArg(mth.root(), strArg);
if (strValue instanceof String) {
map.put(parentInsn, (String) strValue);
}
}
}
}
return map;
}
private boolean processCase(SwitchData switchData, SwitchRegion.CaseInfo caseInfo) {
AtomicBoolean fail = new AtomicBoolean(false);
RegionUtils.visitRegions(switchData.getMth(), caseInfo.getContainer(), region -> {
if (fail.get()) {
return false;
}
if (region instanceof IfRegion) {
CaseData caseData = fillCaseData((IfRegion) region, switchData);
if (caseData == null) {
fail.set(true);
return false;
}
switchData.getCases().add(caseData);
}
return true;
});
return !fail.get();
}
private @Nullable CaseData fillCaseData(IfRegion ifRegion, SwitchData switchData) {
IfCondition condition = Objects.requireNonNull(ifRegion.getCondition());
boolean neg = false;
if (condition.getMode() == IfCondition.Mode.NOT) {
condition = condition.getArgs().get(0);
neg = true;
}
String str = null;
if (condition.isCompare()) {
IfNode ifInsn = condition.getCompare().getInsn();
InsnArg firstArg = ifInsn.getArg(0);
if (firstArg.isInsnWrap()) {
str = switchData.getStrEqInsns().get(((InsnWrapArg) firstArg).getWrapInsn());
}
if (ifInsn.getOp() == IfOp.NE && ifInsn.getArg(1).isTrue()) {
neg = true;
}
if (ifInsn.getOp() == IfOp.EQ && ifInsn.getArg(1).isFalse()) {
neg = true;
}
if (str != null) {
switchData.getToRemove().add(ifInsn);
switchData.getToRemove().addAll(ifRegion.getConditionBlocks());
}
}
if (str == null) {
return null;
}
CaseData caseData = new CaseData();
caseData.getStrValues().add(str);
caseData.setCode(neg ? ifRegion.getElseRegion() : ifRegion.getThenRegion());
return caseData;
}
private @Nullable RegisterArg getStrHashCodeArg(InsnArg arg) {
if (arg.isRegister()) {
return getStrFromInsn(((RegisterArg) arg).getAssignInsn());
}
if (arg.isInsnWrap()) {
return getStrFromInsn(((InsnWrapArg) arg).getWrapInsn());
}
return null;
}
private @Nullable RegisterArg getStrFromInsn(@Nullable InsnNode insn) {
if (insn == null || insn.getType() != InsnType.INVOKE) {
return null;
}
InvokeNode invInsn = (InvokeNode) insn;
MethodInfo callMth = invInsn.getCallMth();
if (!callMth.getRawFullId().equals("java.lang.String.hashCode()I")) {
return null;
}
InsnArg arg = invInsn.getInstanceArg();
if (arg == null || !arg.isRegister()) {
return null;
}
return (RegisterArg) arg;
}
private static final class SwitchData {
private final MethodNode mth;
private final SwitchRegion switchRegion;
private final List<IAttributeNode> toRemove = new ArrayList<>();
private Map<InsnNode, String> strEqInsns;
private List<CaseData> cases;
private List<SwitchRegion.CaseInfo> newCases;
private SwitchRegion codeSwitch;
private RegisterArg numArg;
private SwitchData(MethodNode mth, SwitchRegion switchRegion) {
this.mth = mth;
this.switchRegion = switchRegion;
}
public List<CaseData> getCases() {
return cases;
}
public void setCases(List<CaseData> cases) {
this.cases = cases;
}
public List<SwitchRegion.CaseInfo> getNewCases() {
return newCases;
}
public void setNewCases(List<SwitchRegion.CaseInfo> cases) {
this.newCases = cases;
}
public MethodNode getMth() {
return mth;
}
public Map<InsnNode, String> getStrEqInsns() {
return strEqInsns;
}
public void setStrEqInsns(Map<InsnNode, String> strEqInsns) {
this.strEqInsns = strEqInsns;
}
public SwitchRegion getSwitchRegion() {
return switchRegion;
}
public List<IAttributeNode> getToRemove() {
return toRemove;
}
public SwitchRegion getCodeSwitch() {
return codeSwitch;
}
public void setCodeSwitch(SwitchRegion codeSwitch) {
this.codeSwitch = codeSwitch;
}
public RegisterArg getNumArg() {
return numArg;
}
public void setNumArg(RegisterArg numArg) {
this.numArg = numArg;
}
}
private static final class CaseData {
private final List<String> strValues = new ArrayList<>();
private IContainer code = null;
private int codeNum = -1;
public List<String> getStrValues() {
return strValues;
}
public IContainer getCode() {
return code;
}
public void setCode(IContainer code) {
this.code = code;
}
public int getCodeNum() {
return codeNum;
}
public void setCodeNum(int codeNum) {
this.codeNum = codeNum;
}
@Override
public String toString() {
return "CaseData{" + strValues + '}';
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/RegionMakerVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/RegionMakerVisitor.java | package jadx.core.dex.visitors.regions;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.regions.maker.ExcHandlersRegionMaker;
import jadx.core.dex.visitors.regions.maker.RegionMaker;
import jadx.core.dex.visitors.regions.maker.SynchronizedRegionMaker;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "RegionMakerVisitor",
desc = "Pack blocks into regions for code generation"
)
public class RegionMakerVisitor extends AbstractVisitor {
@Override
public void visit(MethodNode mth) throws JadxException {
if (mth.isNoCode() || mth.getBasicBlocks().isEmpty()) {
return;
}
RegionMaker rm = new RegionMaker(mth);
mth.setRegion(rm.makeMthRegion());
if (!mth.isNoExceptionHandlers()) {
new ExcHandlersRegionMaker(mth, rm).process();
}
processForceInlineInsns(mth);
ProcessTryCatchRegions.process(mth);
PostProcessRegions.process(mth);
CleanRegions.process(mth);
if (mth.getAccessFlags().isSynchronized()) {
SynchronizedRegionMaker.removeSynchronized(mth);
}
}
private static void processForceInlineInsns(MethodNode mth) {
boolean needShrink = mth.getBasicBlocks().stream()
.flatMap(block -> block.getInstructions().stream())
.anyMatch(insn -> insn.contains(AFlag.FORCE_ASSIGN_INLINE));
if (needShrink) {
CodeShrinkVisitor.shrinkMethod(mth);
}
}
@Override
public String getName() {
return "RegionMakerVisitor";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/TracedRegionVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/TracedRegionVisitor.java | package jadx.core.dex.visitors.regions;
import java.util.ArrayDeque;
import java.util.Deque;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
public abstract class TracedRegionVisitor implements IRegionVisitor {
protected final Deque<IRegion> regionStack = new ArrayDeque<>();
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
regionStack.push(region);
return true;
}
@Override
public void processBlock(MethodNode mth, IBlock block) {
IRegion curRegion = regionStack.peek();
processBlockTraced(mth, block, curRegion);
}
public abstract void processBlockTraced(MethodNode mth, IBlock block, IRegion parentRegion);
@Override
public void leaveRegion(MethodNode mth, IRegion region) {
regionStack.pop();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/TernaryMod.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/TernaryMod.java | package jadx.core.dex.visitors.regions;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.instructions.mods.TernaryInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.conditions.IfRegion;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.utils.InsnList;
import jadx.core.utils.InsnRemover;
/**
* Convert 'if' to ternary operation
*/
public class TernaryMod extends AbstractRegionVisitor implements IRegionIterativeVisitor {
private static final TernaryMod INSTANCE = new TernaryMod();
public static void process(MethodNode mth) {
// first: convert all found ternary nodes in one iteration
DepthRegionTraversal.traverse(mth, INSTANCE);
if (mth.contains(AFlag.REQUEST_CODE_SHRINK)) {
CodeShrinkVisitor.shrinkMethod(mth);
}
// second: iterative runs with shrink after each change
DepthRegionTraversal.traverseIterative(mth, INSTANCE);
}
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
if (processRegion(mth, region)) {
mth.add(AFlag.REQUEST_CODE_SHRINK);
}
return true;
}
@Override
public boolean visitRegion(MethodNode mth, IRegion region) {
if (processRegion(mth, region)) {
CodeShrinkVisitor.shrinkMethod(mth);
return true;
}
return false;
}
private static boolean processRegion(MethodNode mth, IRegion region) {
if (region instanceof IfRegion) {
return makeTernaryInsn(mth, (IfRegion) region);
}
return false;
}
private static boolean makeTernaryInsn(MethodNode mth, IfRegion ifRegion) {
if (ifRegion.contains(AFlag.ELSE_IF_CHAIN)) {
return false;
}
IContainer thenRegion = ifRegion.getThenRegion();
IContainer elseRegion = ifRegion.getElseRegion();
if (thenRegion == null) {
return false;
}
if (elseRegion == null) {
return processOneBranchTernary(mth, ifRegion);
}
BlockNode tb = getTernaryInsnBlock(thenRegion);
BlockNode eb = getTernaryInsnBlock(elseRegion);
if (tb == null || eb == null) {
return false;
}
List<BlockNode> conditionBlocks = ifRegion.getConditionBlocks();
if (conditionBlocks.isEmpty()) {
return false;
}
BlockNode header = conditionBlocks.get(0);
InsnNode thenInsn = tb.getInstructions().get(0);
InsnNode elseInsn = eb.getInstructions().get(0);
if (!verifyLineHints(mth, thenInsn, elseInsn)) {
return false;
}
RegisterArg thenResArg = thenInsn.getResult();
RegisterArg elseResArg = elseInsn.getResult();
if (thenResArg != null && elseResArg != null) {
PhiInsn thenPhi = thenResArg.getSVar().getOnlyOneUseInPhi();
PhiInsn elsePhi = elseResArg.getSVar().getOnlyOneUseInPhi();
if (thenPhi == null || thenPhi != elsePhi) {
return false;
}
if (!ifRegion.getParent().replaceSubBlock(ifRegion, header)) {
return false;
}
InsnList.remove(tb, thenInsn);
InsnList.remove(eb, elseInsn);
RegisterArg resArg;
if (thenPhi.getArgsCount() == 2) {
resArg = thenPhi.getResult();
InsnRemover.unbindResult(mth, thenInsn);
} else {
resArg = thenResArg;
thenPhi.removeArg(elseResArg);
}
InsnArg thenArg = InsnArg.wrapInsnIntoArg(thenInsn);
InsnArg elseArg = InsnArg.wrapInsnIntoArg(elseInsn);
TernaryInsn ternInsn = new TernaryInsn(ifRegion.getCondition(), resArg, thenArg, elseArg);
int branchLine = Math.max(thenInsn.getSourceLine(), elseInsn.getSourceLine());
ternInsn.setSourceLine(Math.max(ifRegion.getSourceLine(), branchLine));
thenInsn.setResult(null); // unset without unbind, SSA var still in use
InsnRemover.unbindResult(mth, elseInsn);
// remove 'if' instruction
header.getInstructions().clear();
ternInsn.rebindArgs();
header.getInstructions().add(ternInsn);
clearConditionBlocks(conditionBlocks, header);
return true;
}
if (!mth.isVoidReturn()
&& thenInsn.getType() == InsnType.RETURN
&& elseInsn.getType() == InsnType.RETURN) {
InsnArg thenArg = thenInsn.getArg(0);
InsnArg elseArg = elseInsn.getArg(0);
if (thenArg.isLiteral() != elseArg.isLiteral()) {
// one arg is literal
return false;
}
if (!ifRegion.getParent().replaceSubBlock(ifRegion, header)) {
return false;
}
InsnList.remove(tb, thenInsn);
InsnList.remove(eb, elseInsn);
tb.remove(AFlag.RETURN);
eb.remove(AFlag.RETURN);
TernaryInsn ternInsn = new TernaryInsn(ifRegion.getCondition(), null, thenArg, elseArg);
InsnNode retInsn = new InsnNode(InsnType.RETURN, 1);
InsnArg arg = InsnArg.wrapInsnIntoArg(ternInsn);
arg.setType(thenArg.getType());
retInsn.addArg(arg);
header.getInstructions().clear();
retInsn.rebindArgs();
header.getInstructions().add(retInsn);
header.add(AFlag.RETURN);
clearConditionBlocks(conditionBlocks, header);
return true;
}
return false;
}
private static boolean verifyLineHints(MethodNode mth, InsnNode thenInsn, InsnNode elseInsn) {
if (mth.contains(AFlag.USE_LINES_HINTS)
&& thenInsn.getSourceLine() != elseInsn.getSourceLine()) {
if (thenInsn.getSourceLine() != 0 && elseInsn.getSourceLine() != 0) {
// sometimes source lines incorrect
return checkLineStats(thenInsn, elseInsn);
}
// don't make nested ternary by default
// TODO: add addition checks
return !containsTernary(thenInsn) && !containsTernary(elseInsn);
}
return true;
}
private static void clearConditionBlocks(List<BlockNode> conditionBlocks, BlockNode header) {
for (BlockNode block : conditionBlocks) {
if (block != header) {
block.getInstructions().clear();
block.add(AFlag.REMOVE);
}
}
}
private static BlockNode getTernaryInsnBlock(IContainer thenRegion) {
if (thenRegion instanceof Region) {
Region r = (Region) thenRegion;
if (r.getSubBlocks().size() == 1) {
IContainer container = r.getSubBlocks().get(0);
if (container instanceof BlockNode) {
BlockNode block = (BlockNode) container;
if (block.getInstructions().size() == 1) {
return block;
}
}
}
}
return null;
}
private static boolean containsTernary(InsnNode insn) {
if (insn.getType() == InsnType.TERNARY) {
return true;
}
for (int i = 0; i < insn.getArgsCount(); i++) {
InsnArg arg = insn.getArg(i);
if (arg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
if (containsTernary(wrapInsn)) {
return true;
}
}
}
return false;
}
/**
* Return 'true' if there are several args with same source lines
*/
private static boolean checkLineStats(InsnNode t, InsnNode e) {
if (t.getResult() == null || e.getResult() == null) {
return false;
}
PhiInsn tPhi = t.getResult().getSVar().getOnlyOneUseInPhi();
PhiInsn ePhi = e.getResult().getSVar().getOnlyOneUseInPhi();
if (ePhi == null || tPhi != ePhi) {
return false;
}
Map<Integer, Integer> map = new HashMap<>(tPhi.getArgsCount());
for (InsnArg arg : tPhi.getArguments()) {
if (!arg.isRegister()) {
continue;
}
InsnNode assignInsn = ((RegisterArg) arg).getAssignInsn();
if (assignInsn == null) {
continue;
}
int sourceLine = assignInsn.getSourceLine();
if (sourceLine != 0) {
map.merge(sourceLine, 1, Integer::sum);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() >= 2) {
return true;
}
}
return false;
}
/**
* Convert one variable change with only 'then' branch:
* 'if (c) {r = a;}' to 'r = c ? a : r'
* Convert if 'r' used only once
*/
private static boolean processOneBranchTernary(MethodNode mth, IfRegion ifRegion) {
IContainer thenRegion = ifRegion.getThenRegion();
BlockNode block = getTernaryInsnBlock(thenRegion);
if (block != null) {
InsnNode insn = block.getInstructions().get(0);
RegisterArg result = insn.getResult();
if (result != null) {
replaceWithTernary(mth, ifRegion, block, insn);
}
}
return false;
}
@SuppressWarnings("StatementWithEmptyBody")
private static void replaceWithTernary(MethodNode mth, IfRegion ifRegion, BlockNode block, InsnNode insn) {
RegisterArg resArg = insn.getResult();
if (resArg.getSVar().getUseList().size() != 1) {
return;
}
PhiInsn phiInsn = resArg.getSVar().getOnlyOneUseInPhi();
if (phiInsn == null || phiInsn.getArgsCount() != 2) {
return;
}
RegisterArg otherArg = null;
for (InsnArg arg : phiInsn.getArguments()) {
if (!resArg.sameRegAndSVar(arg)) {
otherArg = (RegisterArg) arg;
break;
}
}
if (otherArg == null) {
return;
}
InsnNode elseAssign = otherArg.getAssignInsn();
if (mth.isConstructor() || (mth.getParentClass().isEnum() && mth.getMethodInfo().isClassInit())) {
// forcing ternary inline for constructors (will help in moving super call to the top) and enums
// skip code style checks
} else {
if (elseAssign != null && elseAssign.isConstInsn()) {
if (!verifyLineHints(mth, insn, elseAssign)) {
return;
}
} else {
if (insn.getResult().sameCodeVar(otherArg)) {
// don't use same variable in else branch to prevent: l = (l == 0) ? 1 : l
return;
}
}
}
// all checks passed
BlockNode header = ifRegion.getConditionBlocks().get(0);
if (!ifRegion.getParent().replaceSubBlock(ifRegion, header)) {
return;
}
InsnArg elseArg;
if (elseAssign != null && elseAssign.isConstInsn()) {
// inline constant
SSAVar elseVar = elseAssign.getResult().getSVar();
if (elseVar.getUseCount() == 1 && elseVar.getOnlyOneUseInPhi() == phiInsn) {
InsnRemover.remove(mth, elseAssign);
}
elseArg = InsnArg.wrapInsnIntoArg(elseAssign);
} else {
elseArg = otherArg.duplicate();
}
InsnArg thenArg = InsnArg.wrapInsnIntoArg(insn);
RegisterArg resultArg = phiInsn.getResult().duplicate();
TernaryInsn ternInsn = new TernaryInsn(ifRegion.getCondition(), resultArg, thenArg, elseArg);
ternInsn.simplifyCondition();
InsnRemover.unbindAllArgs(mth, phiInsn);
InsnRemover.unbindResult(mth, insn);
InsnList.remove(block, insn);
header.getInstructions().clear();
ternInsn.rebindArgs();
header.getInstructions().add(ternInsn);
clearConditionBlocks(ifRegion.getConditionBlocks(), header);
// shrink method again
CodeShrinkVisitor.shrinkMethod(mth);
}
private TernaryMod() {
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/CheckRegions.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/CheckRegions.java | package jadx.core.dex.visitors.regions;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeWriter;
import jadx.api.impl.SimpleCodeWriter;
import jadx.core.Consts;
import jadx.core.codegen.InsnGen;
import jadx.core.codegen.MethodGen;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.utils.exceptions.CodegenException;
import jadx.core.utils.exceptions.JadxException;
public class CheckRegions extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(CheckRegions.class);
@Override
public void visit(MethodNode mth) throws JadxException {
if (mth.isNoCode()
|| mth.getRegion() == null
|| mth.getBasicBlocks().isEmpty()
|| mth.contains(AType.JADX_ERROR)) {
return;
}
// check if all blocks included in regions
Set<BlockNode> blocksInRegions = new HashSet<>();
DepthRegionTraversal.traverse(mth, new AbstractRegionVisitor() {
@Override
public void processBlock(MethodNode mth, IBlock container) {
if (!(container instanceof BlockNode)) {
return;
}
BlockNode block = (BlockNode) container;
if (blocksInRegions.add(block)) {
return;
}
if (Consts.DEBUG_RESTRUCTURE
&& LOG.isDebugEnabled()
&& !block.contains(AFlag.RETURN)
&& !block.contains(AFlag.REMOVE)
&& !block.contains(AFlag.SYNTHETIC)
&& !block.getInstructions().isEmpty()) {
LOG.debug("Duplicated block: {} - {}", mth, block);
}
}
});
if (mth.getBasicBlocks().size() != blocksInRegions.size()) {
for (BlockNode block : mth.getBasicBlocks()) {
if (!blocksInRegions.contains(block)
&& !block.getInstructions().isEmpty()
&& !block.contains(AFlag.ADDED_TO_REGION)
&& !block.contains(AFlag.DONT_GENERATE)
&& !block.contains(AFlag.REMOVE)) {
String blockCode = getBlockInsnStr(mth, block).replace("*/", "*\\/");
mth.addWarn("Code restructure failed: missing block: " + block + ", code lost:" + blockCode);
}
}
}
DepthRegionTraversal.traverse(mth, new AbstractRegionVisitor() {
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
if (region instanceof LoopRegion) {
// check loop conditions
BlockNode loopHeader = ((LoopRegion) region).getHeader();
if (loopHeader != null && loopHeader.getInstructions().size() != 1) {
mth.addWarn("Incorrect condition in loop: " + loopHeader);
}
}
return true;
}
});
}
private static String getBlockInsnStr(MethodNode mth, IBlock block) {
ICodeWriter code = new SimpleCodeWriter();
code.incIndent();
code.newLine();
MethodGen mg = MethodGen.getFallbackMethodGen(mth);
InsnGen ig = new InsnGen(mg, true);
for (InsnNode insn : block.getInstructions()) {
try {
ig.makeInsn(insn, code);
} catch (CodegenException e) {
// ignore
}
}
code.newLine();
return code.getCodeStr();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/ProcessTryCatchRegions.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/ProcessTryCatchRegions.java | package jadx.core.dex.visitors.regions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBranchRegion;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.AbstractRegion;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.TryCatchRegion;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.dex.trycatch.TryCatchBlockAttr;
import jadx.core.utils.RegionUtils;
/**
* Extract blocks to separate try/catch region
*/
public class ProcessTryCatchRegions extends AbstractRegionVisitor {
public static void process(MethodNode mth) {
if (mth.isNoCode() || mth.isNoExceptionHandlers()) {
return;
}
List<TryCatchBlockAttr> tryBlocks = collectTryCatchBlocks(mth);
if (tryBlocks.isEmpty()) {
return;
}
DepthRegionTraversal.traverseIncludingExcHandlers(mth, (regionMth, region) -> {
boolean changed = checkAndWrap(regionMth, tryBlocks, region);
return changed && !tryBlocks.isEmpty();
});
}
private static List<TryCatchBlockAttr> collectTryCatchBlocks(MethodNode mth) {
List<TryCatchBlockAttr> list = mth.getAll(AType.TRY_BLOCKS_LIST);
if (list.isEmpty()) {
return Collections.emptyList();
}
List<TryCatchBlockAttr> tryBlocks = new ArrayList<>(list);
tryBlocks.sort((a, b) -> a == b ? 0 : a.getOuterTryBlock() == b ? 1 : -1); // move parent try block to top
return tryBlocks;
}
private static boolean checkAndWrap(MethodNode mth, List<TryCatchBlockAttr> tryBlocks, IRegion region) {
// search top splitter block in this region (don't need to go deeper)
for (TryCatchBlockAttr tb : tryBlocks) {
BlockNode topSplitter = tb.getTopSplitter();
if (region.getSubBlocks().contains(topSplitter)) {
if (!wrapBlocks(region, tb, topSplitter)) {
mth.addWarn("Can't wrap try/catch for region: " + region);
}
tryBlocks.remove(tb);
return true;
}
}
return false;
}
/**
* Extract all block dominated by 'dominator' to separate region and mark as try/catch block
*/
private static boolean wrapBlocks(IRegion replaceRegion, TryCatchBlockAttr tb, BlockNode dominator) {
if (replaceRegion == null) {
return false;
}
if (replaceRegion instanceof LoopRegion) {
LoopRegion loop = (LoopRegion) replaceRegion;
return wrapBlocks(loop.getBody(), tb, dominator);
}
if (replaceRegion instanceof IBranchRegion) {
return wrapBlocks(replaceRegion.getParent(), tb, dominator);
}
Region tryRegion = new Region(replaceRegion);
List<IContainer> subBlocks = replaceRegion.getSubBlocks();
for (IContainer cont : subBlocks) {
if (RegionUtils.hasPathThroughBlock(dominator, cont)) {
if (isHandlerPath(tb, cont)) {
break;
}
tryRegion.getSubBlocks().add(cont);
}
}
if (tryRegion.getSubBlocks().isEmpty()) {
return false;
}
TryCatchRegion tryCatchRegion = new TryCatchRegion(replaceRegion, tryRegion);
tryRegion.setParent(tryCatchRegion);
tryCatchRegion.setTryCatchBlock(tb);
// replace first node by region
IContainer firstNode = tryRegion.getSubBlocks().get(0);
if (!replaceRegion.replaceSubBlock(firstNode, tryCatchRegion)) {
return false;
}
subBlocks.removeAll(tryRegion.getSubBlocks());
// fix parents for tryRegion sub blocks
for (IContainer cont : tryRegion.getSubBlocks()) {
if (cont instanceof AbstractRegion) {
AbstractRegion aReg = (AbstractRegion) cont;
aReg.setParent(tryRegion);
}
}
return true;
}
private static boolean isHandlerPath(TryCatchBlockAttr tb, IContainer cont) {
for (ExceptionHandler h : tb.getHandlers()) {
BlockNode handlerBlock = h.getHandlerBlock();
if (handlerBlock != null
&& !handlerBlock.contains(AFlag.REMOVE)
&& RegionUtils.hasPathThroughBlock(handlerBlock, cont)) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/AbstractRegionVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/AbstractRegionVisitor.java | package jadx.core.dex.visitors.regions;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
public abstract class AbstractRegionVisitor implements IRegionVisitor {
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
return true;
}
@Override
public void processBlock(MethodNode mth, IBlock block) {
}
@Override
public void leaveRegion(MethodNode mth, IRegion region) {
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/LoopRegionVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/LoopRegionVisitor.java | package jadx.core.dex.visitors.regions;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.ArithNode;
import jadx.core.dex.instructions.ArithOp;
import jadx.core.dex.instructions.IfOp;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.InvokeType;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.conditions.Compare;
import jadx.core.dex.regions.conditions.IfCondition;
import jadx.core.dex.regions.loops.ForEachLoop;
import jadx.core.dex.regions.loops.ForLoop;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.regions.loops.LoopType;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.regions.variables.ProcessVariables;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.InsnUtils;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.exceptions.JadxOverflowException;
@JadxVisitor(
name = "LoopRegionVisitor",
desc = "Convert 'while' loops to 'for' loops (indexed or for-each)",
runBefore = ProcessVariables.class
)
public class LoopRegionVisitor extends AbstractVisitor implements IRegionVisitor {
private static final Logger LOG = LoggerFactory.getLogger(LoopRegionVisitor.class);
@Override
public void visit(MethodNode mth) {
DepthRegionTraversal.traverse(mth, this);
IfRegionVisitor.processIfRequested(mth);
}
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
if (region instanceof LoopRegion) {
if (processLoopRegion(mth, (LoopRegion) region)) {
// optimize `if` block after instructions remove
mth.add(AFlag.REQUEST_IF_REGION_OPTIMIZE);
}
}
return true;
}
private static boolean processLoopRegion(MethodNode mth, LoopRegion loopRegion) {
if (loopRegion.isConditionAtEnd()) {
return false;
}
IfCondition condition = loopRegion.getCondition();
if (condition == null) {
return false;
}
if (checkForIndexedLoop(mth, loopRegion, condition)) {
return true;
}
return checkIterableForEach(mth, loopRegion, condition);
}
/**
* Check for indexed loop.
*/
private static boolean checkForIndexedLoop(MethodNode mth, LoopRegion loopRegion, IfCondition condition) {
BlockNode loopEndBlock = loopRegion.getInfo().getEnd();
InsnNode incrInsn = BlockUtils.getLastInsn(BlockUtils.skipSyntheticPredecessor(loopEndBlock));
if (incrInsn == null) {
return false;
}
RegisterArg incrArg = incrInsn.getResult();
if (incrArg == null
|| incrArg.getSVar() == null
|| !incrArg.getSVar().isUsedInPhi()) {
return false;
}
List<PhiInsn> phiInsnList = incrArg.getSVar().getUsedInPhi();
if (phiInsnList.size() != 1) {
return false;
}
PhiInsn phiInsn = phiInsnList.get(0);
if (phiInsn.getArgsCount() != 2
|| !phiInsn.containsVar(incrArg)
|| incrArg.getSVar().getUseCount() != 1) {
return false;
}
RegisterArg arg = phiInsn.getResult();
List<RegisterArg> condArgs = condition.getRegisterArgs();
if (!condArgs.contains(arg) || arg.getSVar().isUsedInPhi()) {
return false;
}
RegisterArg initArg = phiInsn.getArg(0);
InsnNode initInsn = initArg.getAssignInsn();
if (initInsn == null
|| initInsn.contains(AFlag.DONT_GENERATE)
|| initArg.getSVar().getUseCount() != 1) {
return false;
}
if (!usedOnlyInLoop(mth, loopRegion, arg)) {
return false;
}
// can't make loop if argument from increment instruction is assign in loop
List<RegisterArg> args = new ArrayList<>();
incrInsn.getRegisterArgs(args);
for (RegisterArg iArg : args) {
try {
if (assignOnlyInLoop(mth, loopRegion, iArg)) {
return false;
}
} catch (StackOverflowError error) {
throw new JadxOverflowException("LoopRegionVisitor.assignOnlyInLoop endless recursion");
}
}
// all checks passed
initInsn.add(AFlag.DONT_GENERATE);
incrInsn.add(AFlag.DONT_GENERATE);
LoopType arrForEach = checkArrayForEach(mth, loopRegion, initInsn, incrInsn, condition);
loopRegion.setType(arrForEach != null ? arrForEach : new ForLoop(initInsn, incrInsn));
return true;
}
private static LoopType checkArrayForEach(MethodNode mth, LoopRegion loopRegion, InsnNode initInsn, InsnNode incrInsn,
IfCondition condition) {
if (!(incrInsn instanceof ArithNode)) {
return null;
}
ArithNode arithNode = (ArithNode) incrInsn;
if (arithNode.getOp() != ArithOp.ADD) {
return null;
}
InsnArg lit = incrInsn.getArg(1);
if (!lit.isLiteral() || ((LiteralArg) lit).getLiteral() != 1) {
return null;
}
if (initInsn.getType() != InsnType.CONST
|| !initInsn.getArg(0).isLiteral()
|| ((LiteralArg) initInsn.getArg(0)).getLiteral() != 0) {
return null;
}
InsnArg condArg = incrInsn.getArg(0);
if (!condArg.isRegister()) {
return null;
}
SSAVar sVar = ((RegisterArg) condArg).getSVar();
List<RegisterArg> args = sVar.getUseList();
if (args.size() != 3) {
return null;
}
condArg = InsnUtils.getRegFromInsn(args, InsnType.IF);
if (condArg == null) {
return null;
}
RegisterArg arrIndex = InsnUtils.getRegFromInsn(args, InsnType.AGET);
if (arrIndex == null) {
return null;
}
InsnNode arrGetInsn = arrIndex.getParentInsn();
if (arrGetInsn == null || arrGetInsn.containsWrappedInsn()) {
return null;
}
if (!condition.isCompare()) {
return null;
}
Compare compare = condition.getCompare();
if (compare.getOp() != IfOp.LT || compare.getA() != condArg) {
return null;
}
InsnNode len;
InsnArg bCondArg = compare.getB();
if (bCondArg.isInsnWrap()) {
len = ((InsnWrapArg) bCondArg).getWrapInsn();
} else if (bCondArg.isRegister()) {
len = ((RegisterArg) bCondArg).getAssignInsn();
} else {
return null;
}
if (len == null || len.getType() != InsnType.ARRAY_LENGTH) {
return null;
}
InsnArg arrayArg = len.getArg(0);
if (!arrayArg.equals(arrGetInsn.getArg(0))) {
return null;
}
RegisterArg iterVar = arrGetInsn.getResult();
if (iterVar != null) {
if (!usedOnlyInLoop(mth, loopRegion, iterVar)) {
return null;
}
} else {
if (!arrGetInsn.contains(AFlag.WRAPPED)) {
return null;
}
// create new variable and replace wrapped insn
InsnArg wrapArg = BlockUtils.searchWrappedInsnParent(mth, arrGetInsn);
if (wrapArg == null || wrapArg.getParentInsn() == null) {
mth.addWarnComment("checkArrayForEach: Wrapped insn not found: " + arrGetInsn);
return null;
}
iterVar = mth.makeSyntheticRegArg(wrapArg.getType());
InsnNode parentInsn = wrapArg.getParentInsn();
parentInsn.replaceArg(wrapArg, iterVar.duplicate());
parentInsn.rebindArgs();
}
// array for each loop confirmed
incrInsn.getResult().add(AFlag.DONT_GENERATE);
condArg.add(AFlag.DONT_GENERATE);
bCondArg.add(AFlag.DONT_GENERATE);
arrGetInsn.add(AFlag.DONT_GENERATE);
compare.getInsn().add(AFlag.DONT_GENERATE);
ForEachLoop forEachLoop = new ForEachLoop(iterVar, len.getArg(0));
forEachLoop.injectFakeInsns(loopRegion);
if (InsnUtils.dontGenerateIfNotUsed(len)) {
InsnRemover.remove(mth, len);
}
CodeShrinkVisitor.shrinkMethod(mth);
return forEachLoop;
}
private static boolean checkIterableForEach(MethodNode mth, LoopRegion loopRegion, IfCondition condition) {
List<RegisterArg> condArgs = condition.getRegisterArgs();
if (condArgs.size() != 1) {
return false;
}
RegisterArg iteratorArg = condArgs.get(0);
SSAVar sVar = iteratorArg.getSVar();
if (sVar == null || sVar.isUsedInPhi()) {
return false;
}
List<RegisterArg> itUseList = sVar.getUseList();
InsnNode assignInsn = iteratorArg.getAssignInsn();
if (itUseList.size() != 2) {
return false;
}
if (!checkInvoke(assignInsn, null, "iterator()Ljava/util/Iterator;")) {
return false;
}
InsnArg iterableArg = assignInsn.getArg(0);
InsnNode hasNextCall = itUseList.get(0).getParentInsn();
InsnNode nextCall = itUseList.get(1).getParentInsn();
if (!checkInvoke(hasNextCall, "java.util.Iterator", "hasNext()Z")
|| !checkInvoke(nextCall, "java.util.Iterator", "next()Ljava/lang/Object;")) {
return false;
}
List<InsnNode> toSkip = new ArrayList<>();
RegisterArg iterVar;
if (nextCall.contains(AFlag.WRAPPED)) {
InsnArg wrapArg = BlockUtils.searchWrappedInsnParent(mth, nextCall);
if (wrapArg != null && wrapArg.getParentInsn() != null) {
InsnNode parentInsn = wrapArg.getParentInsn();
BlockNode block = BlockUtils.getBlockByInsn(mth, parentInsn);
if (block == null) {
return false;
}
if (!RegionUtils.isRegionContainsBlock(loopRegion, block)) {
return false;
}
if (parentInsn.getType() == InsnType.CHECK_CAST) {
iterVar = parentInsn.getResult();
if (iterVar == null || !fixIterableType(mth, iterableArg, iterVar)) {
return false;
}
InsnArg castArg = BlockUtils.searchWrappedInsnParent(mth, parentInsn);
if (castArg != null && castArg.getParentInsn() != null) {
castArg.getParentInsn().replaceArg(castArg, iterVar);
} else {
// cast not inlined
toSkip.add(parentInsn);
}
} else {
iterVar = nextCall.getResult();
if (iterVar == null) {
return false;
}
iterVar.remove(AFlag.REMOVE); // restore variable from inlined insn
nextCall.add(AFlag.DONT_GENERATE);
if (!fixIterableType(mth, iterableArg, iterVar)) {
return false;
}
parentInsn.replaceArg(wrapArg, iterVar);
}
} else {
LOG.warn(" checkIterableForEach: Wrapped insn not found: {}, mth: {}", nextCall, mth);
return false;
}
} else {
iterVar = nextCall.getResult();
if (iterVar == null) {
return false;
}
if (!usedOnlyInLoop(mth, loopRegion, iterVar)) {
return false;
}
if (!assignOnlyInLoop(mth, loopRegion, iterVar)) {
return false;
}
toSkip.add(nextCall);
}
assignInsn.add(AFlag.DONT_GENERATE);
assignInsn.getResult().add(AFlag.DONT_GENERATE);
for (InsnNode insnNode : toSkip) {
insnNode.setResult(null);
insnNode.add(AFlag.DONT_GENERATE);
}
for (RegisterArg itArg : itUseList) {
itArg.add(AFlag.DONT_GENERATE);
}
ForEachLoop forEachLoop = new ForEachLoop(iterVar, iterableArg);
forEachLoop.injectFakeInsns(loopRegion);
loopRegion.setType(forEachLoop);
return true;
}
private static boolean fixIterableType(MethodNode mth, InsnArg iterableArg, RegisterArg iterVar) {
ArgType iterableType = iterableArg.getType();
ArgType varType = iterVar.getType();
if (iterableType.isGeneric()) {
List<ArgType> genericTypes = iterableType.getGenericTypes();
if (genericTypes == null || genericTypes.size() != 1) {
return false;
}
ArgType gType = genericTypes.get(0);
if (gType.equals(varType)) {
return true;
}
if (gType.isGenericType()) {
iterVar.setType(gType);
return true;
}
if (ArgType.isInstanceOf(mth.root(), gType, varType)) {
return true;
}
ArgType wildcardType = gType.getWildcardType();
if (wildcardType != null
&& gType.getWildcardBound() == ArgType.WildcardBound.EXTENDS
&& ArgType.isInstanceOf(mth.root(), wildcardType, varType)) {
return true;
}
LOG.warn("Generic type differs: '{}' and '{}' in {}", gType, varType, mth);
return false;
}
if (!iterableArg.isRegister() || !iterableType.isObject()) {
return true;
}
ArgType genericType = ArgType.generic(iterableType.getObject(), varType);
if (iterableArg.isRegister()) {
ArgType immutableType = ((RegisterArg) iterableArg).getImmutableType();
if (immutableType != null && !immutableType.equals(genericType)) {
// can't change type
// allow to iterate over not generified collection only for Object vars
return varType.equals(ArgType.OBJECT);
}
}
iterableArg.setType(genericType);
return true;
}
/**
* Check if instruction is a interface invoke with corresponding parameters.
*/
private static boolean checkInvoke(InsnNode insn, String declClsFullName, String mthId) {
if (insn == null) {
return false;
}
if (insn.getType() == InsnType.INVOKE) {
InvokeNode inv = (InvokeNode) insn;
MethodInfo callMth = inv.getCallMth();
if ((inv.getInvokeType() == InvokeType.INTERFACE || inv.getInvokeType() == InvokeType.VIRTUAL)
&& callMth.getShortId().equals(mthId)) {
if (declClsFullName == null) {
return true;
}
return callMth.getDeclClass().getFullName().equals(declClsFullName);
}
}
return false;
}
private static boolean assignOnlyInLoop(MethodNode mth, LoopRegion loopRegion, RegisterArg arg) {
InsnNode assignInsn = arg.getAssignInsn();
if (assignInsn == null) {
return true;
}
if (!argInLoop(mth, loopRegion, assignInsn.getResult())) {
return false;
}
if (assignInsn instanceof PhiInsn) {
PhiInsn phiInsn = (PhiInsn) assignInsn;
for (InsnArg phiArg : phiInsn.getArguments()) {
if (!assignOnlyInLoop(mth, loopRegion, (RegisterArg) phiArg)) {
return false;
}
}
}
return true;
}
private static boolean usedOnlyInLoop(MethodNode mth, LoopRegion loopRegion, RegisterArg arg) {
List<RegisterArg> useList = arg.getSVar().getUseList();
for (RegisterArg useArg : useList) {
if (!argInLoop(mth, loopRegion, useArg)) {
return false;
}
}
return true;
}
private static boolean argInLoop(MethodNode mth, LoopRegion loopRegion, RegisterArg arg) {
InsnNode parentInsn = arg.getParentInsn();
if (parentInsn == null) {
return false;
}
BlockNode block = BlockUtils.getBlockByInsn(mth, parentInsn);
if (block == null) {
LOG.debug(" LoopRegionVisitor: instruction not found: {}, mth: {}", parentInsn, mth);
return false;
}
return RegionUtils.isRegionContainsBlock(loopRegion, block);
}
@Override
public void leaveRegion(MethodNode mth, IRegion region) {
}
@Override
public void processBlock(MethodNode mth, IBlock container) {
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/variables/ProcessVariables.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/variables/ProcessVariables.java | package jadx.core.dex.visitors.regions.variables;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.DeclareVariablesAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.CodeVar;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.regions.AbstractRegionVisitor;
import jadx.core.dex.visitors.regions.DepthRegionTraversal;
import jadx.core.dex.visitors.typeinference.TypeCompare;
import jadx.core.dex.visitors.typeinference.TypeCompareEnum;
import jadx.core.utils.ListUtils;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxException;
public class ProcessVariables extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(ProcessVariables.class);
@Override
public void visit(MethodNode mth) throws JadxException {
if (mth.isNoCode() || mth.getSVars().isEmpty()) {
return;
}
removeUnusedResults(mth);
List<CodeVar> codeVars = collectCodeVars(mth);
if (codeVars.isEmpty()) {
return;
}
checkCodeVars(mth, codeVars);
// TODO: reduce code vars by name if debug info applied (need checks for variable scopes)
// collect all variables usage
CollectUsageRegionVisitor usageCollector = new CollectUsageRegionVisitor();
DepthRegionTraversal.traverse(mth, usageCollector);
Map<SSAVar, VarUsage> ssaUsageMap = usageCollector.getUsageMap();
if (ssaUsageMap.isEmpty()) {
return;
}
Map<CodeVar, List<VarUsage>> codeVarUsage = mergeUsageMaps(codeVars, ssaUsageMap);
for (Entry<CodeVar, List<VarUsage>> entry : codeVarUsage.entrySet()) {
declareVar(mth, entry.getKey(), entry.getValue());
}
}
private static void removeUnusedResults(MethodNode mth) {
DepthRegionTraversal.traverse(mth, new AbstractRegionVisitor() {
@Override
public void processBlock(MethodNode mth, IBlock container) {
for (InsnNode insn : container.getInstructions()) {
RegisterArg resultArg = insn.getResult();
if (resultArg == null) {
continue;
}
SSAVar ssaVar = resultArg.getSVar();
if (isVarUnused(mth, ssaVar)) {
boolean remove = false;
if (insn.canRemoveResult()) {
// remove unused result
remove = true;
} else if (canRemoveInsn(insn)) {
// remove whole insn
insn.add(AFlag.REMOVE);
insn.add(AFlag.DONT_GENERATE);
remove = true;
}
if (remove) {
insn.setResult(null);
mth.removeSVar(ssaVar);
for (RegisterArg arg : ssaVar.getUseList()) {
arg.resetSSAVar();
}
}
}
}
}
/**
* Remove insn if a result is not used
*/
private boolean canRemoveInsn(InsnNode insn) {
if (insn.isConstInsn()) {
return true;
}
switch (insn.getType()) {
case CAST:
case CHECK_CAST:
return true;
default:
return false;
}
}
private boolean isVarUnused(MethodNode mth, @Nullable SSAVar ssaVar) {
if (ssaVar == null) {
return true;
}
List<RegisterArg> useList = ssaVar.getUseList();
if (useList.isEmpty()) {
return true;
}
if (ssaVar.isUsedInPhi()) {
return false;
}
return ListUtils.allMatch(useList, arg -> isArgUnused(mth, arg));
}
private boolean isArgUnused(MethodNode mth, RegisterArg arg) {
if (arg.contains(AFlag.REMOVE)) {
return true;
}
// check constructors for removed args
InsnNode parentInsn = arg.getParentInsn();
if (parentInsn != null
&& parentInsn.getType() == InsnType.CONSTRUCTOR
&& parentInsn.contains(AType.METHOD_DETAILS)) {
MethodNode resolveMth = mth.root().getMethodUtils().resolveMethod(((ConstructorInsn) parentInsn));
if (resolveMth != null && resolveMth.contains(AType.SKIP_MTH_ARGS)) {
int insnPos = parentInsn.getArgIndex(arg);
List<RegisterArg> mthArgs = resolveMth.getArgRegs();
if (0 <= insnPos && insnPos < mthArgs.size()) {
RegisterArg mthArg = mthArgs.get(insnPos);
if (mthArg.contains(AFlag.REMOVE) && arg.sameType(mthArg)) {
arg.add(AFlag.DONT_GENERATE);
return true;
}
}
}
}
return false;
}
});
}
private void checkCodeVars(MethodNode mth, List<CodeVar> codeVars) {
int unknownTypesCount = 0;
for (CodeVar codeVar : codeVars) {
ArgType codeVarType = codeVar.getType();
if (codeVarType == null) {
codeVar.setType(ArgType.UNKNOWN);
unknownTypesCount++;
} else {
codeVar.getSsaVars()
.forEach(ssaVar -> {
ArgType ssaType = ssaVar.getImmutableType();
if (ssaType != null && ssaType.isTypeKnown()) {
TypeCompare comparator = mth.root().getTypeUpdate().getTypeCompare();
TypeCompareEnum result = comparator.compareTypes(ssaType, codeVarType);
if (result == TypeCompareEnum.CONFLICT || result.isNarrow()) {
mth.addWarn("Incorrect type for immutable var: ssa=" + ssaType
+ ", code=" + codeVarType
+ ", for " + ssaVar.getDetailedVarInfo(mth));
}
}
});
}
}
if (unknownTypesCount != 0) {
mth.addWarn("Unknown variable types count: " + unknownTypesCount);
}
}
private void declareVar(MethodNode mth, CodeVar codeVar, List<VarUsage> usageList) {
if (codeVar.isDeclared()) {
return;
}
VarUsage mergedUsage = new VarUsage(null);
for (VarUsage varUsage : usageList) {
mergedUsage.getAssigns().addAll(varUsage.getAssigns());
mergedUsage.getUses().addAll(varUsage.getUses());
}
if (mergedUsage.getAssigns().isEmpty() && mergedUsage.getUses().isEmpty()) {
return;
}
// check if variable can be declared at one of assigns
if (checkDeclareAtAssign(usageList, mergedUsage)) {
return;
}
// TODO: search closest region for declare
// region not found, declare at method start
declareVarInRegion(mth.getRegion(), codeVar);
}
private List<CodeVar> collectCodeVars(MethodNode mth) {
Map<CodeVar, List<SSAVar>> codeVars = new LinkedHashMap<>();
for (SSAVar ssaVar : mth.getSVars()) {
if (ssaVar.getCodeVar().isThis()) {
continue;
}
CodeVar codeVar = ssaVar.getCodeVar();
List<SSAVar> list = codeVars.computeIfAbsent(codeVar, k -> new ArrayList<>());
list.add(ssaVar);
}
for (Entry<CodeVar, List<SSAVar>> entry : codeVars.entrySet()) {
CodeVar codeVar = entry.getKey();
List<SSAVar> list = entry.getValue();
for (SSAVar ssaVar : list) {
CodeVar localCodeVar = ssaVar.getCodeVar();
codeVar.mergeFlagsFrom(localCodeVar);
}
if (list.size() > 1) {
for (SSAVar ssaVar : list) {
ssaVar.setCodeVar(codeVar);
}
}
codeVar.setSsaVars(list);
}
return new ArrayList<>(codeVars.keySet());
}
private Map<CodeVar, List<VarUsage>> mergeUsageMaps(List<CodeVar> codeVars, Map<SSAVar, VarUsage> ssaUsageMap) {
Map<CodeVar, List<VarUsage>> codeVarUsage = new LinkedHashMap<>(codeVars.size());
for (CodeVar codeVar : codeVars) {
List<VarUsage> list = new ArrayList<>();
for (SSAVar ssaVar : codeVar.getSsaVars()) {
VarUsage usage = ssaUsageMap.get(ssaVar);
if (usage != null) {
list.add(usage);
}
}
codeVarUsage.put(codeVar, Utils.lockList(list));
}
return codeVarUsage;
}
private boolean checkDeclareAtAssign(List<VarUsage> list, VarUsage mergedUsage) {
if (mergedUsage.getAssigns().isEmpty()) {
return false;
}
for (VarUsage u : list) {
for (UsePlace assign : u.getAssigns()) {
if (canDeclareAt(mergedUsage, assign)) {
return checkDeclareAtAssign(u.getVar());
}
}
}
return false;
}
private static boolean canDeclareAt(VarUsage usage, UsePlace usePlace) {
IRegion region = usePlace.getRegion();
// workaround for declare variables used in several loops
if (region instanceof LoopRegion) {
for (UsePlace use : usage.getAssigns()) {
if (!RegionUtils.isRegionContainsRegion(region, use.getRegion())) {
return false;
}
}
}
// can't declare in else-if chain between 'else' and next 'if'
if (region.contains(AFlag.ELSE_IF_CHAIN)) {
return false;
}
return isAllUseAfter(usePlace, usage.getAssigns())
&& isAllUseAfter(usePlace, usage.getUses());
}
/**
* Check if all {@code usePlaces} are after {@code checkPlace}
*/
private static boolean isAllUseAfter(UsePlace checkPlace, List<UsePlace> usePlaces) {
IRegion region = checkPlace.getRegion();
IBlock block = checkPlace.getBlock();
Set<UsePlace> toCheck = new HashSet<>(usePlaces);
boolean blockFound = false;
for (IContainer subBlock : region.getSubBlocks()) {
if (!blockFound && subBlock == block) {
blockFound = true;
}
if (blockFound) {
toCheck.removeIf(usePlace -> isContainerContainsUsePlace(subBlock, usePlace));
if (toCheck.isEmpty()) {
return true;
}
}
}
return false;
}
private static boolean isContainerContainsUsePlace(IContainer subBlock, UsePlace usePlace) {
if (subBlock == usePlace.getBlock()) {
return true;
}
if (subBlock instanceof IRegion) {
// TODO: make index for faster check
return RegionUtils.isRegionContainsRegion(subBlock, usePlace.getRegion());
}
return false;
}
private static boolean checkDeclareAtAssign(SSAVar var) {
RegisterArg arg = var.getAssign();
InsnNode parentInsn = arg.getParentInsn();
if (parentInsn == null
|| parentInsn.contains(AFlag.WRAPPED)
|| parentInsn.getType() == InsnType.PHI) {
return false;
}
if (!arg.equals(parentInsn.getResult())) {
return false;
}
parentInsn.add(AFlag.DECLARE_VAR);
var.getCodeVar().setDeclared(true);
return true;
}
private static void declareVarInRegion(IContainer region, CodeVar var) {
if (var.isDeclared()) {
LOG.warn("Try to declare already declared variable: {}", var);
return;
}
DeclareVariablesAttr dv = region.get(AType.DECLARE_VARIABLES);
if (dv == null) {
dv = new DeclareVariablesAttr();
region.addAttr(dv);
}
dv.addVar(var);
var.setDeclared(true);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/variables/CollectUsageRegionVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/variables/CollectUsageRegionVisitor.java | package jadx.core.dex.visitors.regions.variables;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.loops.ForLoop;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.regions.loops.LoopType;
import jadx.core.dex.visitors.regions.TracedRegionVisitor;
class CollectUsageRegionVisitor extends TracedRegionVisitor {
private final List<RegisterArg> args = new ArrayList<>();
private final Map<SSAVar, VarUsage> usageMap = new LinkedHashMap<>();
public Map<SSAVar, VarUsage> getUsageMap() {
return usageMap;
}
@Override
public void processBlockTraced(MethodNode mth, IBlock block, IRegion curRegion) {
UsePlace usePlace = new UsePlace(curRegion, block);
regionProcess(usePlace);
int len = block.getInstructions().size();
for (int i = 0; i < len; i++) {
InsnNode insn = block.getInstructions().get(i);
processInsn(insn, usePlace);
}
}
private void regionProcess(UsePlace usePlace) {
IRegion region = usePlace.getRegion();
if (region instanceof LoopRegion) {
LoopRegion loopRegion = (LoopRegion) region;
LoopType loopType = loopRegion.getType();
if (loopType instanceof ForLoop) {
ForLoop forLoop = (ForLoop) loopType;
processInsn(forLoop.getInitInsn(), usePlace);
processInsn(forLoop.getIncrInsn(), usePlace);
}
}
}
void processInsn(InsnNode insn, UsePlace usePlace) {
if (insn == null) {
return;
}
// result
RegisterArg result = insn.getResult();
if (result != null && result.isRegister()) {
if (!result.contains(AFlag.DONT_GENERATE)) {
VarUsage usage = getUsage(result.getSVar());
usage.getAssigns().add(usePlace);
}
}
// args
args.clear();
insn.getRegisterArgs(args);
for (RegisterArg arg : args) {
if (!arg.contains(AFlag.DONT_GENERATE)) {
VarUsage usage = getUsage(arg.getSVar());
usage.getUses().add(usePlace);
}
}
}
private VarUsage getUsage(SSAVar ssaVar) {
return usageMap.computeIfAbsent(ssaVar, VarUsage::new);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/variables/VarUsage.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/variables/VarUsage.java | package jadx.core.dex.visitors.regions.variables;
import java.util.ArrayList;
import java.util.List;
import jadx.core.dex.instructions.args.SSAVar;
class VarUsage {
private final SSAVar var;
private final List<UsePlace> assigns = new ArrayList<>(3);
private final List<UsePlace> uses = new ArrayList<>(3);
VarUsage(SSAVar var) {
this.var = var;
}
public SSAVar getVar() {
return var;
}
public List<UsePlace> getAssigns() {
return assigns;
}
public List<UsePlace> getUses() {
return uses;
}
@Override
public String toString() {
return '{' + (var == null ? "-" : var.toShortString()) + ", a:" + assigns + ", u:" + uses + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/variables/UsePlace.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/variables/UsePlace.java | package jadx.core.dex.visitors.regions.variables;
import java.util.Objects;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IRegion;
public class UsePlace {
public final IRegion region;
public final IBlock block;
public UsePlace(IRegion region, IBlock block) {
this.region = region;
this.block = block;
}
public IRegion getRegion() {
return region;
}
public IBlock getBlock() {
return block;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UsePlace usePlace = (UsePlace) o;
return Objects.equals(region, usePlace.region)
&& Objects.equals(block, usePlace.block);
}
@Override
public int hashCode() {
return Objects.hash(region, block);
}
@Override
public String toString() {
return "UsePlace{region=" + region + ", block=" + block + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/RegionMaker.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/RegionMaker.java | package jadx.core.dex.visitors.regions.maker;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.EdgeInsnAttr;
import jadx.core.dex.attributes.nodes.LoopInfo;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.SwitchInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnContainer;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.blocks.BlockSet;
import jadx.core.utils.exceptions.JadxOverflowException;
import static jadx.core.utils.BlockUtils.getNextBlock;
public class RegionMaker {
private final MethodNode mth;
private final RegionStack stack;
private final IfRegionMaker ifMaker;
private final LoopRegionMaker loopMaker;
private final BlockSet processedBlocks;
private final int regionsLimit;
private int regionsCount;
public RegionMaker(MethodNode mth) {
this.mth = mth;
this.stack = new RegionStack(mth);
this.ifMaker = new IfRegionMaker(mth, this);
this.loopMaker = new LoopRegionMaker(mth, this, ifMaker);
this.processedBlocks = BlockSet.empty(mth);
this.regionsLimit = mth.getBasicBlocks().size() * 100;
}
public Region makeMthRegion() {
return makeRegion(mth.getEnterBlock());
}
Region makeRegion(BlockNode startBlock) {
Objects.requireNonNull(startBlock);
Region region = new Region(stack.peekRegion());
if (stack.containsExit(startBlock)) {
insertEdgeInsns(region, startBlock);
return region;
}
if (processedBlocks.addChecked(startBlock)) {
mth.addWarn("Removed duplicated region for block: " + startBlock + ' ' + startBlock.getAttributesString());
return region;
}
BlockNode next = startBlock;
while (next != null) {
next = traverse(region, next);
regionsCount++;
if (regionsCount > regionsLimit) {
throw new JadxOverflowException("Regions count limit reached");
}
}
return region;
}
/**
* Recursively traverse all blocks from 'block' until block from 'exits'
*/
private BlockNode traverse(IRegion r, BlockNode block) {
if (block.contains(AFlag.MTH_EXIT_BLOCK)) {
return null;
}
BlockNode next = null;
boolean processed = false;
List<LoopInfo> loops = block.getAll(AType.LOOP);
int loopCount = loops.size();
if (loopCount != 0 && block.contains(AFlag.LOOP_START)) {
if (loopCount == 1) {
next = loopMaker.process(r, loops.get(0), stack);
processed = true;
} else {
for (LoopInfo loop : loops) {
if (loop.getStart() == block) {
next = loopMaker.process(r, loop, stack);
processed = true;
break;
}
}
}
}
InsnNode insn = BlockUtils.getLastInsn(block);
if (!processed && insn != null) {
switch (insn.getType()) {
case IF:
next = ifMaker.process(r, block, (IfNode) insn, stack);
processed = true;
break;
case SWITCH:
SwitchRegionMaker switchMaker = new SwitchRegionMaker(mth, this);
next = switchMaker.process(r, block, (SwitchInsn) insn, stack);
processed = true;
break;
case MONITOR_ENTER:
SynchronizedRegionMaker syncMaker = new SynchronizedRegionMaker(mth, this);
next = syncMaker.process(r, block, insn, stack);
processed = true;
break;
}
}
if (!processed) {
r.getSubBlocks().add(block);
next = getNextBlock(block);
}
if (next != null && !stack.containsExit(block) && !stack.containsExit(next)) {
return next;
}
return null;
}
private void insertEdgeInsns(Region region, BlockNode exitBlock) {
List<EdgeInsnAttr> edgeInsns = exitBlock.getAll(AType.EDGE_INSN);
if (edgeInsns.isEmpty()) {
return;
}
List<InsnNode> insns = new ArrayList<>(edgeInsns.size());
addOneInsnOfType(insns, edgeInsns, InsnType.BREAK);
addOneInsnOfType(insns, edgeInsns, InsnType.CONTINUE);
region.add(new InsnContainer(insns));
}
private void addOneInsnOfType(List<InsnNode> insns, List<EdgeInsnAttr> edgeInsns, InsnType insnType) {
for (EdgeInsnAttr edgeInsn : edgeInsns) {
InsnNode insn = edgeInsn.getInsn();
if (insn.getType() == insnType) {
insns.add(insn);
return;
}
}
}
RegionStack getStack() {
return stack;
}
boolean isProcessed(BlockNode block) {
return processedBlocks.contains(block);
}
void clearBlockProcessedState(BlockNode block) {
processedBlocks.remove(block);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/LoopRegionMaker.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/LoopRegionMaker.java | package jadx.core.dex.visitors.regions.maker;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.EdgeInsnAttr;
import jadx.core.dex.attributes.nodes.LoopInfo;
import jadx.core.dex.attributes.nodes.LoopLabelAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.Edge;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.conditions.IfInfo;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.ListUtils;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.blocks.BlockSet;
import jadx.core.utils.exceptions.JadxRuntimeException;
import static jadx.core.utils.BlockUtils.getNextBlock;
import static jadx.core.utils.BlockUtils.isPathExists;
final class LoopRegionMaker {
private final MethodNode mth;
private final RegionMaker regionMaker;
private final IfRegionMaker ifMaker;
LoopRegionMaker(MethodNode mth, RegionMaker regionMaker, IfRegionMaker ifMaker) {
this.mth = mth;
this.regionMaker = regionMaker;
this.ifMaker = ifMaker;
}
BlockNode process(IRegion curRegion, LoopInfo loop, RegionStack stack) {
BlockNode loopStart = loop.getStart();
Set<BlockNode> exitBlocksSet = loop.getExitNodes();
// set exit blocks scan order priority
// this can help if loop has several exits (after using 'break' or 'return' in loop)
List<BlockNode> exitBlocks = new ArrayList<>(exitBlocksSet.size());
BlockNode nextStart = getNextBlock(loopStart);
if (nextStart != null && exitBlocksSet.remove(nextStart)) {
exitBlocks.add(nextStart);
}
if (exitBlocksSet.remove(loopStart)) {
exitBlocks.add(loopStart);
}
if (exitBlocksSet.remove(loop.getEnd())) {
exitBlocks.add(loop.getEnd());
}
exitBlocks.addAll(exitBlocksSet);
LoopRegion loopRegion = makeLoopRegion(curRegion, loop, exitBlocks);
if (loopRegion == null) {
BlockNode exit = makeEndlessLoop(curRegion, stack, loop, loopStart);
insertContinue(loop);
return exit;
}
curRegion.getSubBlocks().add(loopRegion);
IRegion outerRegion = stack.peekRegion();
stack.push(loopRegion);
IfInfo condInfo = ifMaker.buildIfInfo(loopRegion);
if (!loop.getLoopBlocks().contains(condInfo.getThenBlock())) {
// invert loop condition if 'then' points to exit
condInfo = IfInfo.invert(condInfo);
}
loopRegion.updateCondition(condInfo);
// prevent if's merge with loop condition
condInfo.getMergedBlocks().forEach(b -> b.add(AFlag.ADDED_TO_REGION));
exitBlocks.removeAll(condInfo.getMergedBlocks().toList());
if (!exitBlocks.isEmpty()) {
BlockNode loopExit = condInfo.getElseBlock();
if (loopExit != null) {
// add 'break' instruction before path cross between main loop exit and sub-exit
for (Edge exitEdge : loop.getExitEdges()) {
if (exitBlocks.contains(exitEdge.getSource())) {
insertLoopBreak(stack, loop, loopExit, exitEdge);
}
}
}
}
BlockNode out;
if (loopRegion.isConditionAtEnd()) {
BlockNode thenBlock = condInfo.getThenBlock();
out = thenBlock == loop.getEnd() || thenBlock == loopStart ? condInfo.getElseBlock() : thenBlock;
out = BlockUtils.followEmptyPath(out);
loopStart.remove(AType.LOOP);
loop.getEnd().add(AFlag.ADDED_TO_REGION);
stack.addExit(loop.getEnd());
regionMaker.clearBlockProcessedState(loopStart);
Region body = regionMaker.makeRegion(loopStart);
loopRegion.setBody(body);
loopStart.addAttr(AType.LOOP, loop);
loop.getEnd().remove(AFlag.ADDED_TO_REGION);
} else {
out = condInfo.getElseBlock();
if (outerRegion != null
&& out != null
&& out.contains(AFlag.LOOP_START)
&& !out.getAll(AType.LOOP).contains(loop)
&& RegionUtils.isRegionContainsBlock(outerRegion, out)) {
// exit to already processed outer loop
out = null;
}
stack.addExit(out);
BlockNode loopBody = condInfo.getThenBlock();
Region body;
if (Objects.equals(loopBody, loopStart)) {
// empty loop body
body = new Region(loopRegion);
} else {
body = regionMaker.makeRegion(loopBody);
}
// add blocks from loop start to first condition block
BlockNode conditionBlock = condInfo.getFirstIfBlock();
if (loopStart != conditionBlock) {
Set<BlockNode> blocks = BlockUtils.getAllPathsBlocks(loopStart, conditionBlock);
blocks.remove(conditionBlock);
for (BlockNode block : blocks) {
if (block.getInstructions().isEmpty()
&& !block.contains(AFlag.ADDED_TO_REGION)
&& !RegionUtils.isRegionContainsBlock(body, block)) {
body.add(block);
}
}
}
loopRegion.setBody(body);
}
stack.pop();
insertContinue(loop);
return out;
}
/**
* Select loop exit and construct LoopRegion
*/
private LoopRegion makeLoopRegion(IRegion curRegion, LoopInfo loop, List<BlockNode> exitBlocks) {
for (BlockNode block : exitBlocks) {
if (block.contains(AType.EXC_HANDLER)) {
continue;
}
InsnNode lastInsn = BlockUtils.getLastInsn(block);
if (lastInsn == null || lastInsn.getType() != InsnType.IF) {
continue;
}
List<LoopInfo> loops = block.getAll(AType.LOOP);
if (!loops.isEmpty() && loops.get(0) != loop) {
// skip nested loop condition
continue;
}
boolean exitAtLoopEnd = isExitAtLoopEnd(block, loop);
LoopRegion loopRegion = new LoopRegion(curRegion, loop, block, exitAtLoopEnd);
boolean found;
if (block == loop.getStart() || exitAtLoopEnd
|| BlockUtils.isEmptySimplePath(loop.getStart(), block)) {
found = true;
} else if (block.getPredecessors().contains(loop.getStart())) {
loopRegion.setPreCondition(loop.getStart());
// if we can't merge pre-condition this is not correct header
found = loopRegion.checkPreCondition();
} else {
found = false;
}
if (found) {
List<LoopInfo> list = mth.getAllLoopsForBlock(block);
if (list.size() >= 2) {
// bad condition if successors going out of all loops
boolean allOuter = true;
for (BlockNode outerBlock : block.getCleanSuccessors()) {
List<LoopInfo> outLoopList = mth.getAllLoopsForBlock(outerBlock);
outLoopList.remove(loop);
if (!outLoopList.isEmpty()) {
// goes to outer loop
allOuter = false;
break;
}
}
if (allOuter) {
found = false;
}
}
}
if (found && !checkLoopExits(loop, block)) {
found = false;
}
if (found) {
return loopRegion;
}
}
// no exit found => endless loop
return null;
}
private static boolean isExitAtLoopEnd(BlockNode exit, LoopInfo loop) {
BlockNode loopEnd = loop.getEnd();
if (exit == loopEnd) {
return true;
}
BlockNode loopStart = loop.getStart();
if (loopStart.getInstructions().isEmpty() && ListUtils.isSingleElement(loopStart.getSuccessors(), exit)) {
return false;
}
return loopEnd.getInstructions().isEmpty() && ListUtils.isSingleElement(loopEnd.getPredecessors(), exit);
}
private boolean checkLoopExits(LoopInfo loop, BlockNode mainExitBlock) {
List<Edge> exitEdges = loop.getExitEdges();
if (exitEdges.size() < 2) {
return true;
}
Optional<Edge> mainEdgeOpt = exitEdges.stream().filter(edge -> edge.getSource() == mainExitBlock).findFirst();
if (mainEdgeOpt.isEmpty()) {
throw new JadxRuntimeException("Not found exit edge by exit block: " + mainExitBlock);
}
Edge mainExitEdge = mainEdgeOpt.get();
BlockNode mainOutBlock = mainExitEdge.getTarget();
for (Edge exitEdge : exitEdges) {
if (exitEdge != mainExitEdge) {
// all exit paths must be same or don't cross (will be inside loop)
BlockNode exitBlock = exitEdge.getTarget();
if (!BlockUtils.isEqualPaths(mainOutBlock, exitBlock)) {
BlockNode crossBlock = BlockUtils.getPathCross(mth, mainOutBlock, exitBlock);
if (crossBlock != null) {
return false;
}
}
}
}
return true;
}
private BlockNode makeEndlessLoop(IRegion curRegion, RegionStack stack, LoopInfo loop, BlockNode loopStart) {
LoopRegion loopRegion = new LoopRegion(curRegion, loop, null, false);
curRegion.getSubBlocks().add(loopRegion);
loopStart.remove(AType.LOOP);
regionMaker.clearBlockProcessedState(loopStart);
stack.push(loopRegion);
BlockNode out = null;
// insert 'break' for exits
List<Edge> exitEdges = loop.getExitEdges();
if (exitEdges.size() == 1) {
Edge exitEdge = exitEdges.get(0);
BlockNode exit = exitEdge.getTarget();
if (insertLoopBreak(stack, loop, exit, exitEdge)) {
BlockNode nextBlock = getNextBlock(exit);
if (nextBlock != null) {
stack.addExit(nextBlock);
out = nextBlock;
}
}
} else {
for (Edge exitEdge : exitEdges) {
BlockNode exit = exitEdge.getTarget();
List<BlockNode> blocks = BlockUtils.bitSetToBlocks(mth, exit.getDomFrontier());
for (BlockNode block : blocks) {
if (BlockUtils.isPathExists(exit, block)) {
stack.addExit(block);
insertLoopBreak(stack, loop, block, exitEdge);
out = block;
} else {
insertLoopBreak(stack, loop, exit, exitEdge);
}
}
}
}
Region body = regionMaker.makeRegion(loopStart);
BlockNode loopEnd = loop.getEnd();
if (!RegionUtils.isRegionContainsBlock(body, loopEnd)
&& !loopEnd.contains(AType.EXC_HANDLER)
&& !inExceptionHandlerBlocks(loopEnd)) {
body.getSubBlocks().add(loopEnd);
}
loopRegion.setBody(body);
if (out == null) {
BlockNode next = getNextBlock(loopEnd);
out = RegionUtils.isRegionContainsBlock(body, next) ? null : next;
}
stack.pop();
loopStart.addAttr(AType.LOOP, loop);
return out;
}
private boolean inExceptionHandlerBlocks(BlockNode loopEnd) {
if (mth.getExceptionHandlersCount() == 0) {
return false;
}
for (ExceptionHandler eh : mth.getExceptionHandlers()) {
if (eh.getBlocks().contains(loopEnd)) {
return true;
}
}
return false;
}
private boolean canInsertBreak(BlockNode exit) {
if (BlockUtils.containsExitInsn(exit)) {
return false;
}
List<BlockNode> simplePath = BlockUtils.buildSimplePath(exit);
if (!simplePath.isEmpty()) {
BlockNode lastBlock = simplePath.get(simplePath.size() - 1);
if (lastBlock.isMthExitBlock()
|| lastBlock.isReturnBlock()
|| mth.isPreExitBlock(lastBlock)) {
return false;
}
}
// check if there no outer switch (TODO: very expensive check)
Set<BlockNode> paths = BlockUtils.getAllPathsBlocks(mth.getEnterBlock(), exit);
for (BlockNode block : paths) {
if (BlockUtils.checkLastInsnType(block, InsnType.SWITCH)) {
return false;
}
}
return true;
}
private boolean insertLoopBreak(RegionStack stack, LoopInfo loop, BlockNode loopExit, Edge exitEdge) {
BlockNode exit = exitEdge.getTarget();
Edge insertEdge = null;
boolean confirm = false;
// process special cases:
// 1. jump to outer loop
BlockNode exitEnd = BlockUtils.followEmptyPath(exit);
List<LoopInfo> loops = exitEnd.getAll(AType.LOOP);
for (LoopInfo loopAtEnd : loops) {
if (loopAtEnd != loop && loop.hasParent(loopAtEnd)) {
insertEdge = exitEdge;
confirm = true;
break;
}
}
if (!confirm) {
BlockNode insertBlock = null;
BlockSet visited = new BlockSet(mth);
while (true) {
if (exit == null || visited.contains(exit)) {
break;
}
visited.add(exit);
if (insertBlock != null && isPathExists(loopExit, exit)) {
// found cross
if (canInsertBreak(insertBlock)) {
insertEdge = new Edge(insertBlock, insertBlock.getSuccessors().get(0));
confirm = true;
break;
}
return false;
}
insertBlock = exit;
List<BlockNode> cs = exit.getCleanSuccessors();
exit = cs.size() == 1 ? cs.get(0) : null;
}
}
if (!confirm) {
return false;
}
InsnNode breakInsn = new InsnNode(InsnType.BREAK, 0);
breakInsn.addAttr(AType.LOOP, loop);
EdgeInsnAttr.addEdgeInsn(insertEdge, breakInsn);
stack.addExit(exit);
// add label to 'break' if needed
addBreakLabel(exitEdge, exit, breakInsn);
return true;
}
private void addBreakLabel(Edge exitEdge, BlockNode exit, InsnNode breakInsn) {
BlockNode outBlock = BlockUtils.getNextBlock(exitEdge.getTarget());
if (outBlock == null) {
return;
}
List<LoopInfo> exitLoop = mth.getAllLoopsForBlock(outBlock);
if (!exitLoop.isEmpty()) {
return;
}
List<LoopInfo> inLoops = mth.getAllLoopsForBlock(exitEdge.getSource());
if (inLoops.size() < 2) {
return;
}
// search for parent loop
LoopInfo parentLoop = null;
for (LoopInfo loop : inLoops) {
if (loop.getParentLoop() == null) {
parentLoop = loop;
break;
}
}
if (parentLoop == null) {
return;
}
if (parentLoop.getEnd() != exit && !parentLoop.getExitNodes().contains(exit)) {
LoopLabelAttr labelAttr = new LoopLabelAttr(parentLoop);
breakInsn.addAttr(labelAttr);
parentLoop.getStart().addAttr(labelAttr);
}
}
private static void insertContinue(LoopInfo loop) {
BlockNode loopEnd = loop.getEnd();
List<BlockNode> predecessors = loopEnd.getPredecessors();
if (predecessors.size() <= 1) {
return;
}
Set<BlockNode> loopExitNodes = loop.getExitNodes();
for (BlockNode pred : predecessors) {
if (canInsertContinue(pred, predecessors, loopEnd, loopExitNodes)) {
InsnNode cont = new InsnNode(InsnType.CONTINUE, 0);
pred.getInstructions().add(cont);
}
}
}
private static boolean canInsertContinue(BlockNode pred, List<BlockNode> predecessors, BlockNode loopEnd,
Set<BlockNode> loopExitNodes) {
if (!pred.contains(AFlag.SYNTHETIC)
|| BlockUtils.checkLastInsnType(pred, InsnType.CONTINUE)) {
return false;
}
List<BlockNode> preds = pred.getPredecessors();
if (preds.isEmpty()) {
return false;
}
BlockNode codePred = preds.get(0);
if (codePred.contains(AFlag.ADDED_TO_REGION)) {
return false;
}
if (loopEnd.isDominator(codePred)
|| loopExitNodes.contains(codePred)) {
return false;
}
if (isDominatedOnBlocks(codePred, predecessors)) {
return false;
}
boolean gotoExit = false;
for (BlockNode exit : loopExitNodes) {
if (BlockUtils.isPathExists(codePred, exit)) {
gotoExit = true;
break;
}
}
return gotoExit;
}
private static boolean isDominatedOnBlocks(BlockNode dom, List<BlockNode> blocks) {
for (BlockNode node : blocks) {
if (!node.isDominator(dom)) {
return false;
}
}
return true;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/IfRegionMaker.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/IfRegionMaker.java | package jadx.core.dex.visitors.regions.maker;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.Consts;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.EdgeInsnAttr;
import jadx.core.dex.attributes.nodes.LoopInfo;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.conditions.IfCondition;
import jadx.core.dex.regions.conditions.IfInfo;
import jadx.core.dex.regions.conditions.IfRegion;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.blocks.BlockSet;
import jadx.core.utils.exceptions.JadxRuntimeException;
import static jadx.core.utils.BlockUtils.isEqualPaths;
import static jadx.core.utils.BlockUtils.isEqualReturnBlocks;
import static jadx.core.utils.BlockUtils.isPathExists;
final class IfRegionMaker {
private static final Logger LOG = LoggerFactory.getLogger(IfRegionMaker.class);
private final MethodNode mth;
private final RegionMaker regionMaker;
IfRegionMaker(MethodNode mth, RegionMaker regionMaker) {
this.mth = mth;
this.regionMaker = regionMaker;
}
BlockNode process(IRegion currentRegion, BlockNode block, IfNode ifnode, RegionStack stack) {
if (block.contains(AFlag.ADDED_TO_REGION)) {
// block already included in other 'if' region
return ifnode.getThenBlock();
}
IfInfo currentIf = makeIfInfo(mth, block);
if (currentIf == null) {
return null;
}
IfInfo mergedIf = mergeNestedIfNodes(currentIf);
if (mergedIf != null) {
currentIf = mergedIf;
} else {
// invert simple condition (compiler often do it)
currentIf = IfInfo.invert(currentIf);
}
IfInfo modifiedIf = restructureIf(mth, block, currentIf);
if (modifiedIf != null) {
currentIf = modifiedIf;
} else {
if (currentIf.getMergedBlocks().size() <= 1) {
return null;
}
currentIf = makeIfInfo(mth, block);
currentIf = restructureIf(mth, block, currentIf);
if (currentIf == null) {
// all attempts failed
return null;
}
}
confirmMerge(currentIf);
IfRegion ifRegion = new IfRegion(currentRegion);
ifRegion.updateCondition(currentIf);
currentRegion.getSubBlocks().add(ifRegion);
BlockNode outBlock = currentIf.getOutBlock();
stack.push(ifRegion);
stack.addExit(outBlock);
BlockNode thenBlock = currentIf.getThenBlock();
if (thenBlock == null) {
// empty then block, not normal, but maybe correct
ifRegion.setThenRegion(new Region(ifRegion));
} else {
ifRegion.setThenRegion(regionMaker.makeRegion(thenBlock));
}
BlockNode elseBlock = currentIf.getElseBlock();
if (elseBlock == null || stack.containsExit(elseBlock)) {
ifRegion.setElseRegion(null);
} else {
ifRegion.setElseRegion(regionMaker.makeRegion(elseBlock));
}
// insert edge insns in new 'else' branch
// TODO: make more common algorithm
if (ifRegion.getElseRegion() == null && outBlock != null) {
List<EdgeInsnAttr> edgeInsnAttrs = outBlock.getAll(AType.EDGE_INSN);
if (!edgeInsnAttrs.isEmpty()) {
Region elseRegion = new Region(ifRegion);
for (EdgeInsnAttr edgeInsnAttr : edgeInsnAttrs) {
if (edgeInsnAttr.getEnd().equals(outBlock)) {
addEdgeInsn(currentIf, elseRegion, edgeInsnAttr);
}
}
ifRegion.setElseRegion(elseRegion);
}
}
stack.pop();
return outBlock;
}
@NotNull
IfInfo buildIfInfo(LoopRegion loopRegion) {
IfInfo condInfo = makeIfInfo(mth, loopRegion.getHeader());
condInfo = searchNestedIf(condInfo);
confirmMerge(condInfo);
return condInfo;
}
private void addEdgeInsn(IfInfo ifInfo, Region region, EdgeInsnAttr edgeInsnAttr) {
BlockNode start = edgeInsnAttr.getStart();
boolean fromThisIf = false;
for (BlockNode ifBlock : ifInfo.getMergedBlocks()) {
if (ifBlock.getSuccessors().contains(start)) {
fromThisIf = true;
break;
}
}
if (!fromThisIf) {
return;
}
region.add(start);
}
@Nullable
static IfInfo makeIfInfo(MethodNode mth, BlockNode ifBlock) {
InsnNode lastInsn = BlockUtils.getLastInsn(ifBlock);
if (lastInsn == null || lastInsn.getType() != InsnType.IF) {
return null;
}
IfNode ifNode = (IfNode) lastInsn;
IfCondition condition = IfCondition.fromIfNode(ifNode);
IfInfo info = new IfInfo(mth, condition, ifNode.getThenBlock(), ifNode.getElseBlock());
info.getMergedBlocks().add(ifBlock);
return info;
}
static IfInfo searchNestedIf(IfInfo info) {
IfInfo next = mergeNestedIfNodes(info);
if (next != null) {
return next;
}
return info;
}
static IfInfo restructureIf(MethodNode mth, BlockNode block, IfInfo info) {
BlockNode thenBlock = info.getThenBlock();
BlockNode elseBlock = info.getElseBlock();
if (Objects.equals(thenBlock, elseBlock)) {
IfInfo ifInfo = new IfInfo(info, null, null);
ifInfo.setOutBlock(thenBlock);
return ifInfo;
}
// select 'then', 'else' and 'exit' blocks
if (thenBlock.contains(AFlag.RETURN) && elseBlock.contains(AFlag.RETURN)) {
info.setOutBlock(null);
return info;
}
// init outblock, which will be used in isBadBranchBlock to compare with branch block
info.setOutBlock(BlockUtils.getPathCross(mth, thenBlock, elseBlock));
boolean badThen = isBadBranchBlock(info, thenBlock);
boolean badElse = isBadBranchBlock(info, elseBlock);
if (badThen && badElse) {
if (Consts.DEBUG_RESTRUCTURE) {
LOG.debug("Stop processing blocks after 'if': {}, method: {}", info.getMergedBlocks(), mth);
}
return null;
}
if (badElse) {
info = new IfInfo(info, thenBlock, null);
info.setOutBlock(elseBlock);
} else if (badThen) {
info = IfInfo.invert(info);
info = new IfInfo(info, elseBlock, null);
info.setOutBlock(thenBlock);
}
if (BlockUtils.isBackEdge(block, info.getOutBlock())) {
info.setOutBlock(null);
}
return info;
}
private static boolean isBadBranchBlock(IfInfo info, BlockNode block) {
// check if block at end of loop edge
if (block.contains(AFlag.LOOP_START) && block.getPredecessors().size() == 1) {
BlockNode pred = block.getPredecessors().get(0);
if (pred.contains(AFlag.LOOP_END)) {
List<LoopInfo> startLoops = block.getAll(AType.LOOP);
List<LoopInfo> endLoops = pred.getAll(AType.LOOP);
// search for same loop
for (LoopInfo startLoop : startLoops) {
for (LoopInfo endLoop : endLoops) {
if (startLoop == endLoop) {
return true;
}
}
}
}
}
// if branch block itself is outblock
if (info.getOutBlock() != null) {
return block == info.getOutBlock();
}
return !allPathsFromIf(block, info);
}
private static boolean allPathsFromIf(BlockNode block, IfInfo info) {
List<BlockNode> preds = block.getPredecessors();
BlockSet ifBlocks = info.getMergedBlocks();
for (BlockNode pred : preds) {
if (pred.contains(AFlag.LOOP_END)) {
// ignore loop back edge
continue;
}
BlockNode top = BlockUtils.skipSyntheticPredecessor(pred);
if (!ifBlocks.contains(top)) {
return false;
}
}
return true;
}
static IfInfo mergeNestedIfNodes(IfInfo currentIf) {
BlockNode curThen = currentIf.getThenBlock();
BlockNode curElse = currentIf.getElseBlock();
if (curThen == curElse) {
return null;
}
if (BlockUtils.isFollowBackEdge(curThen)
|| BlockUtils.isFollowBackEdge(curElse)) {
return null;
}
boolean followThenBranch;
IfInfo nextIf = getNextIf(currentIf, curThen);
if (nextIf != null) {
followThenBranch = true;
} else {
nextIf = getNextIf(currentIf, curElse);
if (nextIf != null) {
followThenBranch = false;
} else {
return null;
}
}
boolean assignInlineNeeded = !nextIf.getForceInlineInsns().isEmpty();
if (assignInlineNeeded) {
for (BlockNode mergedBlock : currentIf.getMergedBlocks()) {
if (mergedBlock.contains(AFlag.LOOP_START)) {
// don't inline assigns into loop condition
return currentIf;
}
}
}
if (isInversionNeeded(currentIf, nextIf)) {
// invert current node for match pattern
nextIf = IfInfo.invert(nextIf);
}
boolean thenPathSame = isEqualPaths(curThen, nextIf.getThenBlock());
boolean elsePathSame = isEqualPaths(curElse, nextIf.getElseBlock());
if (!thenPathSame && !elsePathSame) {
// complex condition, run additional checks
if (checkConditionBranches(curThen, curElse)
|| checkConditionBranches(curElse, curThen)) {
return null;
}
BlockNode otherBranchBlock = followThenBranch ? curElse : curThen;
otherBranchBlock = BlockUtils.followEmptyPath(otherBranchBlock);
if (!isPathExists(nextIf.getFirstIfBlock(), otherBranchBlock)) {
return checkForTernaryInCondition(currentIf);
}
// this is nested conditions with different mode (i.e (a && b) || c),
// search next condition for merge, get null if failed
IfInfo tmpIf = mergeNestedIfNodes(nextIf);
if (tmpIf != null) {
nextIf = tmpIf;
if (isInversionNeeded(currentIf, nextIf)) {
nextIf = IfInfo.invert(nextIf);
}
if (!canMerge(currentIf, nextIf, followThenBranch)) {
return currentIf;
}
} else {
return currentIf;
}
} else {
if (assignInlineNeeded) {
boolean sameOuts = (thenPathSame && !followThenBranch) || (elsePathSame && followThenBranch);
if (!sameOuts) {
// don't inline assigns inside simple condition
currentIf.resetForceInlineInsns();
return currentIf;
}
}
}
IfInfo result = mergeIfInfo(currentIf, nextIf, followThenBranch);
// search next nested if block
return searchNestedIf(result);
}
private static IfInfo checkForTernaryInCondition(IfInfo currentIf) {
IfInfo nextThen = getNextIf(currentIf, currentIf.getThenBlock());
IfInfo nextElse = getNextIf(currentIf, currentIf.getElseBlock());
if (nextThen == null || nextElse == null) {
return null;
}
if (!nextThen.getFirstIfBlock().getDomFrontier().equals(nextElse.getFirstIfBlock().getDomFrontier())) {
return null;
}
nextThen = searchNestedIf(nextThen);
nextElse = searchNestedIf(nextElse);
if (nextThen.getThenBlock() == nextElse.getThenBlock()
&& nextThen.getElseBlock() == nextElse.getElseBlock()) {
return mergeTernaryConditions(currentIf, nextThen, nextElse);
}
if (nextThen.getThenBlock() == nextElse.getElseBlock()
&& nextThen.getElseBlock() == nextElse.getThenBlock()) {
nextElse = IfInfo.invert(nextElse);
return mergeTernaryConditions(currentIf, nextThen, nextElse);
}
return null;
}
private static IfInfo mergeTernaryConditions(IfInfo currentIf, IfInfo nextThen, IfInfo nextElse) {
IfCondition newCondition = IfCondition.ternary(currentIf.getCondition(),
nextThen.getCondition(), nextElse.getCondition());
IfInfo result = new IfInfo(currentIf.getMth(), newCondition, nextThen.getThenBlock(), nextThen.getElseBlock());
result.merge(currentIf, nextThen, nextElse);
confirmMerge(result);
return result;
}
private static boolean isInversionNeeded(IfInfo currentIf, IfInfo nextIf) {
return isEqualPaths(currentIf.getElseBlock(), nextIf.getThenBlock())
|| isEqualPaths(currentIf.getThenBlock(), nextIf.getElseBlock());
}
private static boolean canMerge(IfInfo a, IfInfo b, boolean followThenBranch) {
if (followThenBranch) {
return isEqualPaths(a.getElseBlock(), b.getElseBlock());
} else {
return isEqualPaths(a.getThenBlock(), b.getThenBlock());
}
}
private static boolean checkConditionBranches(BlockNode from, BlockNode to) {
return from.getCleanSuccessors().size() == 1 && from.getCleanSuccessors().contains(to);
}
static IfInfo mergeIfInfo(IfInfo first, IfInfo second, boolean followThenBranch) {
MethodNode mth = first.getMth();
Set<BlockNode> skipBlocks = first.getSkipBlocks();
BlockNode thenBlock;
BlockNode elseBlock;
if (followThenBranch) {
thenBlock = second.getThenBlock();
elseBlock = getBranchBlock(first.getElseBlock(), second.getElseBlock(), skipBlocks, mth);
} else {
thenBlock = getBranchBlock(first.getThenBlock(), second.getThenBlock(), skipBlocks, mth);
elseBlock = second.getElseBlock();
}
IfCondition.Mode mergeOperation = followThenBranch ? IfCondition.Mode.AND : IfCondition.Mode.OR;
IfCondition condition = IfCondition.merge(mergeOperation, first.getCondition(), second.getCondition());
IfInfo result = new IfInfo(mth, condition, thenBlock, elseBlock);
result.merge(first, second);
return result;
}
private static BlockNode getBranchBlock(BlockNode first, BlockNode second, Set<BlockNode> skipBlocks, MethodNode mth) {
if (first == second) {
return second;
}
if (isEqualReturnBlocks(first, second)) {
skipBlocks.add(first);
return second;
}
if (BlockUtils.isDuplicateBlockPath(first, second)) {
first.add(AFlag.REMOVE);
skipBlocks.add(first);
return second;
}
BlockNode cross = BlockUtils.getPathCross(mth, first, second);
if (cross != null) {
BlockUtils.visitBlocksOnPath(mth, first, cross, skipBlocks::add);
BlockUtils.visitBlocksOnPath(mth, second, cross, skipBlocks::add);
skipBlocks.remove(cross);
return cross;
}
BlockNode firstSkip = BlockUtils.followEmptyPath(first);
BlockNode secondSkip = BlockUtils.followEmptyPath(second);
if (firstSkip.equals(secondSkip) || isEqualReturnBlocks(firstSkip, secondSkip)) {
skipBlocks.add(first);
skipBlocks.add(second);
BlockUtils.visitBlocksOnEmptyPath(first, skipBlocks::add);
BlockUtils.visitBlocksOnEmptyPath(second, skipBlocks::add);
return secondSkip;
}
throw new JadxRuntimeException("Unexpected merge pattern");
}
static void confirmMerge(IfInfo info) {
if (info.getMergedBlocks().size() > 1) {
for (BlockNode block : info.getMergedBlocks()) {
if (block != info.getFirstIfBlock()) {
block.add(AFlag.ADDED_TO_REGION);
}
}
}
if (!info.getSkipBlocks().isEmpty()) {
for (BlockNode block : info.getSkipBlocks()) {
block.add(AFlag.ADDED_TO_REGION);
}
info.getSkipBlocks().clear();
}
for (InsnNode forceInlineInsn : info.getForceInlineInsns()) {
forceInlineInsn.add(AFlag.FORCE_ASSIGN_INLINE);
}
}
private static IfInfo getNextIf(IfInfo info, BlockNode block) {
if (!canSelectNext(info, block)) {
return null;
}
return getNextIfNodeInfo(info, block);
}
private static boolean canSelectNext(IfInfo info, BlockNode block) {
if (block.getPredecessors().size() == 1) {
return true;
}
return info.getMergedBlocks().containsAll(block.getPredecessors());
}
private static IfInfo getNextIfNodeInfo(IfInfo info, BlockNode block) {
if (block == null || block.contains(AType.LOOP) || block.contains(AFlag.ADDED_TO_REGION)) {
return null;
}
InsnNode lastInsn = BlockUtils.getLastInsn(block);
if (lastInsn != null && lastInsn.getType() == InsnType.IF) {
return makeIfInfo(info.getMth(), block);
}
// skip this block and search in successors chain
List<BlockNode> successors = block.getSuccessors();
if (successors.size() != 1) {
return null;
}
BlockNode next = successors.get(0);
if (next.getPredecessors().size() != 1 || next.contains(AFlag.ADDED_TO_REGION)) {
return null;
}
List<InsnNode> forceInlineInsns = new ArrayList<>();
if (!checkInsnsInline(block, next, forceInlineInsns)) {
return null;
}
IfInfo nextInfo = makeIfInfo(info.getMth(), next);
if (nextInfo == null) {
return getNextIfNodeInfo(info, next);
}
nextInfo.addInsnsForForcedInline(forceInlineInsns);
return nextInfo;
}
/**
* Check that all instructions can be inlined
*/
private static boolean checkInsnsInline(BlockNode block, BlockNode next, List<InsnNode> forceInlineInsns) {
List<InsnNode> insns = block.getInstructions();
if (insns.isEmpty()) {
return true;
}
boolean pass = true;
for (InsnNode insn : insns) {
RegisterArg res = insn.getResult();
if (res == null) {
return false;
}
List<RegisterArg> useList = res.getSVar().getUseList();
int useCount = useList.size();
if (useCount == 0) {
// TODO?
return false;
}
InsnArg arg = useList.get(0);
InsnNode usePlace = arg.getParentInsn();
if (!BlockUtils.blockContains(block, usePlace)
&& !BlockUtils.blockContains(next, usePlace)) {
return false;
}
if (useCount > 1) {
forceInlineInsns.add(insn);
} else {
// allow only forced assign inline
pass = false;
}
}
return pass;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/SwitchRegionMaker.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/SwitchRegionMaker.java | package jadx.core.dex.visitors.regions.maker;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.nodes.LoopInfo;
import jadx.core.dex.attributes.nodes.RegionRefAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.SwitchInsn;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnContainer;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.SwitchRegion;
import jadx.core.dex.visitors.regions.AbstractRegionVisitor;
import jadx.core.dex.visitors.regions.DepthRegionTraversal;
import jadx.core.dex.visitors.regions.SwitchBreakVisitor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.ListUtils;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.blocks.BlockSet;
import jadx.core.utils.exceptions.JadxRuntimeException;
public final class SwitchRegionMaker {
private final MethodNode mth;
private final RegionMaker regionMaker;
SwitchRegionMaker(MethodNode mth, RegionMaker regionMaker) {
this.mth = mth;
this.regionMaker = regionMaker;
}
BlockNode process(IRegion currentRegion, BlockNode block, SwitchInsn insn, RegionStack stack) {
// map case blocks to keys
int len = insn.getTargets().length;
Map<BlockNode, List<Object>> blocksMap = new LinkedHashMap<>(len);
BlockNode[] targetBlocksArr = insn.getTargetBlocks();
for (int i = 0; i < len; i++) {
List<Object> keys = blocksMap.computeIfAbsent(targetBlocksArr[i], k -> new ArrayList<>(2));
keys.add(insn.getKey(i));
}
BlockNode defCase = insn.getDefTargetBlock();
if (defCase != null) {
List<Object> keys = blocksMap.computeIfAbsent(defCase, k -> new ArrayList<>(1));
keys.add(SwitchRegion.DEFAULT_CASE_KEY);
}
SwitchRegion sw = new SwitchRegion(currentRegion, block);
insn.addAttr(new RegionRefAttr(sw));
currentRegion.getSubBlocks().add(sw);
stack.push(sw);
BlockNode out = calcSwitchOut(block, insn, stack);
stack.addExit(out);
addCases(sw, out, stack, blocksMap);
removeEmptyCases(insn, sw, defCase);
stack.pop();
return out;
}
/**
* Insert 'break' for all cases in switch region
* Executed in {@link jadx.core.dex.visitors.regions.PostProcessRegions} after try/catch wrap to
* handle all blocks
*/
public static void insertBreaks(MethodNode mth, SwitchRegion sw) {
for (SwitchRegion.CaseInfo caseInfo : sw.getCases()) {
insertBreaksForCase(mth, sw, caseInfo.getContainer());
}
}
private void addCases(SwitchRegion sw, @Nullable BlockNode out,
RegionStack stack, Map<BlockNode, List<Object>> blocksMap) {
Map<BlockNode, BlockNode> fallThroughCases = new LinkedHashMap<>();
if (out != null) {
// detect fallthrough cases
BitSet caseBlocks = BlockUtils.blocksToBitSet(mth, blocksMap.keySet());
caseBlocks.clear(out.getPos());
for (BlockNode successor : sw.getHeader().getSuccessors()) {
BitSet df = successor.getDomFrontier();
if (df.intersects(caseBlocks)) {
BlockNode fallThroughBlock = getOneIntersectionBlock(out, caseBlocks, df);
fallThroughCases.put(successor, fallThroughBlock);
}
}
// check fallthrough cases order
if (!fallThroughCases.isEmpty() && isBadCasesOrder(blocksMap, fallThroughCases)) {
Map<BlockNode, List<Object>> newBlocksMap = reOrderSwitchCases(blocksMap, fallThroughCases);
if (isBadCasesOrder(newBlocksMap, fallThroughCases)) {
mth.addWarnComment("Can't fix incorrect switch cases order, some code will duplicate");
fallThroughCases.clear();
} else {
blocksMap = newBlocksMap;
}
}
}
for (Map.Entry<BlockNode, List<Object>> entry : blocksMap.entrySet()) {
List<Object> keysList = entry.getValue();
BlockNode caseBlock = entry.getKey();
Region caseRegion;
if (stack.containsExit(caseBlock)) {
caseRegion = new Region(stack.peekRegion());
} else {
BlockNode next = fallThroughCases.get(caseBlock);
stack.addExit(next);
caseRegion = regionMaker.makeRegion(caseBlock);
stack.removeExit(next);
if (next != null) {
next.add(AFlag.FALL_THROUGH);
caseRegion.add(AFlag.FALL_THROUGH);
}
}
sw.addCase(keysList, caseRegion);
}
}
@Nullable
private BlockNode getOneIntersectionBlock(BlockNode out, BitSet caseBlocks, BitSet fallThroughSet) {
BitSet caseExits = BlockUtils.copyBlocksBitSet(mth, fallThroughSet);
caseExits.clear(out.getPos());
caseExits.and(caseBlocks);
return BlockUtils.bitSetToOneBlock(mth, caseExits);
}
private @Nullable BlockNode calcSwitchOut(BlockNode block, SwitchInsn insn, RegionStack stack) {
// union of case blocks dominance frontier
// works if no fallthrough cases and no returns inside switch
BitSet outs = BlockUtils.newBlocksBitSet(mth);
for (BlockNode s : block.getCleanSuccessors()) {
if (s.contains(AFlag.LOOP_END)) {
// loop end dom frontier is loop start, ignore it
continue;
}
outs.or(s.getDomFrontier());
}
outs.clear(block.getId());
outs.clear(mth.getExitBlock().getId());
BlockNode out = null;
if (outs.cardinality() == 1) {
// single exit
out = BlockUtils.bitSetToOneBlock(mth, outs);
} else {
// several switch exits
// possible 'return', 'continue' or fallthrough in one of the cases
LoopInfo loop = mth.getLoopForBlock(block);
if (loop != null) {
outs.andNot(loop.getStart().getPostDoms());
outs.andNot(loop.getEnd().getPostDoms());
BlockNode loopEnd = loop.getEnd();
if (outs.cardinality() == 2 && outs.get(loopEnd.getId())) {
// insert 'continue' for cases lead to loop end
// expect only 2 exits: loop end and switch out
List<BlockNode> outList = BlockUtils.bitSetToBlocks(mth, outs);
outList.remove(loopEnd);
BlockNode possibleOut = Utils.getOne(outList);
if (possibleOut != null && insertContinueInSwitch(block, possibleOut, loopEnd)) {
outs.clear(loopEnd.getId());
out = possibleOut;
}
}
if (outs.isEmpty()) {
// all exits inside switch, keep inside to exit from loop
return mth.getExitBlock();
}
}
if (out == null) {
BlockNode imPostDom = block.getIPostDom();
if (outs.get(imPostDom.getId())) {
out = imPostDom;
} else {
outs.andNot(block.getPostDoms());
out = BlockUtils.bitSetToOneBlock(mth, outs);
}
}
}
if (out != null && mth.isPreExitBlock(out)) {
// include 'return' or 'throw' in case blocks
out = mth.getExitBlock();
}
BlockNode imPostDom = block.getIPostDom();
if (out == null && imPostDom == mth.getExitBlock()) {
// all exits inside switch
// check if all returns are equals and should be treated as single out block
return allSameReturns(stack);
}
if (imPostDom == insn.getDefTargetBlock()
&& block.getCleanSuccessors().contains(imPostDom)
&& block.getDomFrontier().get(imPostDom.getId())) {
// add exit to stop on empty 'default' block
stack.addExit(imPostDom);
}
if (out == null) {
mth.addWarnComment("Failed to find 'out' block for switch in " + block + ". Please report as an issue.");
// fallback option; should work in most cases
out = block.getIPostDom();
}
if (out != null && regionMaker.isProcessed(out)) {
// 'out' block already processed, prevent endless loop
throw new JadxRuntimeException("Failed to find switch 'out' block (already processed)");
}
return out;
}
private BlockNode allSameReturns(RegionStack stack) {
BlockNode exitBlock = mth.getExitBlock();
List<BlockNode> preds = exitBlock.getPredecessors();
int count = preds.size();
if (count == 1) {
return preds.get(0);
}
if (mth.getReturnType() == ArgType.VOID) {
for (BlockNode pred : preds) {
InsnNode insn = BlockUtils.getLastInsn(pred);
if (insn == null || insn.getType() != InsnType.RETURN) {
return exitBlock;
}
}
} else {
List<InsnArg> returnArgs = new ArrayList<>();
for (BlockNode pred : preds) {
InsnNode insn = BlockUtils.getLastInsn(pred);
if (insn == null || insn.getType() != InsnType.RETURN) {
return exitBlock;
}
returnArgs.add(insn.getArg(0));
}
InsnArg firstArg = returnArgs.get(0);
if (firstArg.isRegister()) {
RegisterArg reg = (RegisterArg) firstArg;
for (int i = 1; i < count; i++) {
InsnArg arg = returnArgs.get(1);
if (!arg.isRegister() || !((RegisterArg) arg).sameCodeVar(reg)) {
return exitBlock;
}
}
} else {
for (int i = 1; i < count; i++) {
InsnArg arg = returnArgs.get(1);
if (!arg.equals(firstArg)) {
return exitBlock;
}
}
}
}
// confirmed
stack.addExits(preds);
// ignore other returns
for (int i = 1; i < count; i++) {
BlockNode block = preds.get(i);
block.add(AFlag.REMOVE);
block.add(AFlag.ADDED_TO_REGION);
}
return preds.get(0);
}
/**
* Remove empty case blocks:
* 1. single 'default' case
* 2. filler cases if switch is 'packed' and 'default' case is empty
*/
private void removeEmptyCases(SwitchInsn insn, SwitchRegion sw, BlockNode defCase) {
boolean defaultCaseIsEmpty;
if (defCase == null) {
defaultCaseIsEmpty = true;
} else {
defaultCaseIsEmpty = sw.getCases().stream()
.anyMatch(c -> c.getKeys().contains(SwitchRegion.DEFAULT_CASE_KEY)
&& RegionUtils.isEmpty(c.getContainer()));
}
if (defaultCaseIsEmpty) {
sw.getCases().removeIf(caseInfo -> {
if (RegionUtils.isEmpty(caseInfo.getContainer())) {
List<Object> keys = caseInfo.getKeys();
if (keys.contains(SwitchRegion.DEFAULT_CASE_KEY)) {
return true;
}
if (insn.isPacked()) {
return true;
}
}
return false;
});
}
}
private boolean isBadCasesOrder(Map<BlockNode, List<Object>> blocksMap, Map<BlockNode, BlockNode> fallThroughCases) {
BlockNode nextCaseBlock = null;
for (BlockNode caseBlock : blocksMap.keySet()) {
if (nextCaseBlock != null && !caseBlock.equals(nextCaseBlock)) {
return true;
}
nextCaseBlock = fallThroughCases.get(caseBlock);
}
return nextCaseBlock != null;
}
private Map<BlockNode, List<Object>> reOrderSwitchCases(Map<BlockNode, List<Object>> blocksMap,
Map<BlockNode, BlockNode> fallThroughCases) {
List<BlockNode> list = new ArrayList<>(blocksMap.size());
list.addAll(blocksMap.keySet());
list.sort((a, b) -> {
BlockNode nextA = fallThroughCases.get(a);
if (nextA != null) {
if (b.equals(nextA)) {
return -1;
}
} else if (a.equals(fallThroughCases.get(b))) {
return 1;
}
return 0;
});
Map<BlockNode, List<Object>> newBlocksMap = new LinkedHashMap<>(blocksMap.size());
for (BlockNode key : list) {
newBlocksMap.put(key, blocksMap.get(key));
}
return newBlocksMap;
}
private boolean insertContinueInSwitch(BlockNode switchBlock, BlockNode switchOut, BlockNode loopEnd) {
boolean inserted = false;
for (BlockNode caseBlock : switchBlock.getCleanSuccessors()) {
if (caseBlock.getDomFrontier().get(loopEnd.getId()) && caseBlock != switchOut) {
// search predecessor of loop end on path from this successor
Set<BlockNode> list = new HashSet<>(BlockUtils.collectBlocksDominatedBy(mth, caseBlock, caseBlock));
if (list.contains(switchOut) || switchOut.getPredecessors().stream().anyMatch(list::contains)) {
// 'continue' not needed
} else {
for (BlockNode p : loopEnd.getPredecessors()) {
if (list.contains(p)) {
if (p.isSynthetic()) {
p.getInstructions().add(new InsnNode(InsnType.CONTINUE, 0));
inserted = true;
}
break;
}
}
}
}
}
return inserted;
}
/**
* Add break to every exit edge from 'case' region.
* 'Break' optimizations (code duplication, unreachable, etc.) will be done at
* {@link SwitchBreakVisitor}
*/
private static void insertBreaksForCase(MethodNode mth, SwitchRegion switchRegion, IContainer caseContainer) {
BlockSet caseBlocks = new BlockSet(mth);
RegionUtils.visitBlockNodes(mth, caseContainer, caseBlocks::add);
DepthRegionTraversal.traverse(mth, caseContainer, new AbstractRegionVisitor() {
@Override
public void leaveRegion(MethodNode mth, IRegion region) {
boolean insertBreak = false;
if (region == caseContainer) {
// top region
insertBreak = true;
} else {
IContainer lastContainer = ListUtils.last(region.getSubBlocks());
if (lastContainer instanceof BlockNode) {
BlockNode lastBlock = (BlockNode) lastContainer;
for (BlockNode successor : lastBlock.getSuccessors()) {
if (!caseBlocks.contains(successor)) {
insertBreak = true;
break;
}
}
}
}
if (insertBreak && canAppendBreak(region)) {
region.getSubBlocks().add(buildBreakContainer(switchRegion));
}
}
});
}
public static boolean canAppendBreak(IRegion region) {
return !region.contains(AFlag.FALL_THROUGH) && !RegionUtils.hasExitBlock(region);
}
public static InsnContainer buildBreakContainer(SwitchRegion switchRegion) {
InsnNode breakInsn = new InsnNode(InsnType.BREAK, 0);
breakInsn.add(AFlag.SYNTHETIC);
breakInsn.addAttr(new RegionRefAttr(switchRegion));
return new InsnContainer(breakInsn);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/SynchronizedRegionMaker.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/SynchronizedRegionMaker.java | package jadx.core.dex.visitors.regions.maker;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.ConstClassNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.SynchronizedRegion;
import jadx.core.dex.visitors.regions.CleanRegions;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.Utils;
import static jadx.core.utils.BlockUtils.getNextBlock;
import static jadx.core.utils.BlockUtils.isPathExists;
public class SynchronizedRegionMaker {
private static final Logger LOG = LoggerFactory.getLogger(SynchronizedRegionMaker.class);
private final MethodNode mth;
private final RegionMaker regionMaker;
SynchronizedRegionMaker(MethodNode mth, RegionMaker regionMaker) {
this.mth = mth;
this.regionMaker = regionMaker;
}
BlockNode process(IRegion curRegion, BlockNode block, InsnNode insn, RegionStack stack) {
SynchronizedRegion synchRegion = new SynchronizedRegion(curRegion, insn);
synchRegion.getSubBlocks().add(block);
curRegion.getSubBlocks().add(synchRegion);
Set<BlockNode> exits = new LinkedHashSet<>();
Set<BlockNode> cacheSet = new HashSet<>();
traverseMonitorExits(synchRegion, insn.getArg(0), block, exits, cacheSet);
for (InsnNode exitInsn : synchRegion.getExitInsns()) {
BlockNode insnBlock = BlockUtils.getBlockByInsn(mth, exitInsn);
if (insnBlock != null) {
insnBlock.add(AFlag.DONT_GENERATE);
}
// remove arg from MONITOR_EXIT to allow inline in MONITOR_ENTER
exitInsn.removeArg(0);
exitInsn.add(AFlag.DONT_GENERATE);
}
BlockNode body = getNextBlock(block);
if (body == null) {
mth.addWarn("Unexpected end of synchronized block");
return null;
}
BlockNode exit = null;
if (exits.size() == 1) {
exit = getNextBlock(exits.iterator().next());
} else if (exits.size() > 1) {
cacheSet.clear();
exit = traverseMonitorExitsCross(body, exits, cacheSet);
}
stack.push(synchRegion);
if (exit != null) {
stack.addExit(exit);
} else {
for (BlockNode exitBlock : exits) {
// don't add exit blocks which leads to method end blocks ('return', 'throw', etc)
List<BlockNode> list = BlockUtils.buildSimplePath(exitBlock);
if (list.isEmpty() || !BlockUtils.isExitBlock(mth, Utils.last(list))) {
stack.addExit(exitBlock);
// we can still try using this as an exit block to make sure it's visited.
exit = exitBlock;
}
}
}
synchRegion.getSubBlocks().add(regionMaker.makeRegion(body));
stack.pop();
return exit;
}
/**
* Traverse from monitor-enter thru successors and collect blocks contains monitor-exit
*/
private static void traverseMonitorExits(SynchronizedRegion region, InsnArg arg, BlockNode block, Set<BlockNode> exits,
Set<BlockNode> visited) {
visited.add(block);
for (InsnNode insn : block.getInstructions()) {
if (insn.getType() == InsnType.MONITOR_EXIT
&& insn.getArgsCount() > 0
&& insn.getArg(0).equals(arg)) {
exits.add(block);
region.getExitInsns().add(insn);
return;
}
}
for (BlockNode node : block.getSuccessors()) {
if (!visited.contains(node)) {
traverseMonitorExits(region, arg, node, exits, visited);
}
}
}
/**
* Traverse from monitor-enter thru successors and search for exit paths cross
*/
private static BlockNode traverseMonitorExitsCross(BlockNode block, Set<BlockNode> exits, Set<BlockNode> visited) {
visited.add(block);
for (BlockNode node : block.getCleanSuccessors()) {
boolean cross = true;
for (BlockNode exitBlock : exits) {
boolean p = isPathExists(exitBlock, node);
if (!p) {
cross = false;
break;
}
}
if (cross) {
return node;
}
if (!visited.contains(node)) {
BlockNode res = traverseMonitorExitsCross(node, exits, visited);
if (res != null) {
return res;
}
}
}
return null;
}
public static void removeSynchronized(MethodNode mth) {
Region startRegion = mth.getRegion();
List<IContainer> subBlocks = startRegion.getSubBlocks();
if (!subBlocks.isEmpty() && subBlocks.get(0) instanceof SynchronizedRegion) {
SynchronizedRegion synchRegion = (SynchronizedRegion) subBlocks.get(0);
InsnNode syncInsn = synchRegion.getEnterInsn();
if (canRemoveSyncBlock(mth, syncInsn)) {
// replace synchronized block with an inner region
startRegion.getSubBlocks().set(0, synchRegion.getRegion());
// remove 'monitor-enter' instruction
InsnRemover.remove(mth, syncInsn);
// remove 'monitor-exit' instruction
for (InsnNode exit : synchRegion.getExitInsns()) {
InsnRemover.remove(mth, exit);
}
// run region cleaner again
CleanRegions.process(mth);
// assume that CodeShrinker will be run after this
}
}
}
private static boolean canRemoveSyncBlock(MethodNode mth, InsnNode synchInsn) {
InsnArg syncArg = synchInsn.getArg(0);
if (mth.getAccessFlags().isStatic()) {
if (syncArg.isInsnWrap() && syncArg.isConst()) {
InsnNode constInsn = syncArg.unwrap();
if (constInsn.getType() == InsnType.CONST_CLASS) {
ArgType clsType = ((ConstClassNode) constInsn).getClsType();
if (clsType.equals(mth.getParentClass().getType())) {
return true;
}
}
}
mth.addWarnComment("In static synchronized method top region not synchronized by class const: " + syncArg);
} else {
if (syncArg.isThis()) {
return true;
}
mth.addWarnComment("In synchronized method top region not synchronized by 'this': " + syncArg);
}
return false;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/ExcHandlersRegionMaker.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/ExcHandlersRegionMaker.java | package jadx.core.dex.visitors.regions.maker;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.trycatch.ExcHandlerAttr;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.dex.trycatch.TryCatchBlockAttr;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.RegionUtils;
public class ExcHandlersRegionMaker {
private final MethodNode mth;
private final RegionMaker regionMaker;
public ExcHandlersRegionMaker(MethodNode mth, RegionMaker regionMaker) {
this.mth = mth;
this.regionMaker = regionMaker;
}
public void process() {
if (mth.isNoExceptionHandlers()) {
return;
}
IRegion excOutBlock = collectHandlerRegions();
if (excOutBlock != null) {
mth.getRegion().add(excOutBlock);
}
}
private @Nullable IRegion collectHandlerRegions() {
List<TryCatchBlockAttr> tcs = mth.getAll(AType.TRY_BLOCKS_LIST);
for (TryCatchBlockAttr tc : tcs) {
List<BlockNode> blocks = new ArrayList<>(tc.getHandlersCount());
Set<BlockNode> splitters = new HashSet<>();
for (ExceptionHandler handler : tc.getHandlers()) {
BlockNode handlerBlock = handler.getHandlerBlock();
if (handlerBlock != null) {
blocks.add(handlerBlock);
splitters.add(BlockUtils.getTopSplitterForHandler(handlerBlock));
} else {
mth.addDebugComment("No exception handler block: " + handler);
}
}
Set<BlockNode> exits = new HashSet<>();
for (BlockNode splitter : splitters) {
for (BlockNode handler : blocks) {
if (handler.contains(AFlag.REMOVE)) {
continue;
}
List<BlockNode> s = splitter.getSuccessors();
if (s.isEmpty()) {
mth.addDebugComment("No successors for splitter: " + splitter);
continue;
}
BlockNode ss = s.get(0);
BlockNode cross = BlockUtils.getPathCross(mth, ss, handler);
if (cross != null && cross != ss && cross != handler) {
exits.add(cross);
}
}
}
for (ExceptionHandler handler : tc.getHandlers()) {
processExcHandler(handler, exits);
}
}
return processHandlersOutBlocks(tcs);
}
/**
* Search handlers successor blocks aren't included in any region.
*/
private @Nullable IRegion processHandlersOutBlocks(List<TryCatchBlockAttr> tcs) {
Set<IBlock> allRegionBlocks = new HashSet<>();
RegionUtils.getAllRegionBlocks(mth.getRegion(), allRegionBlocks);
Set<IBlock> successorBlocks = new HashSet<>();
for (TryCatchBlockAttr tc : tcs) {
for (ExceptionHandler handler : tc.getHandlers()) {
IContainer region = handler.getHandlerRegion();
if (region != null) {
IBlock lastBlock = RegionUtils.getLastBlock(region);
if (lastBlock instanceof BlockNode) {
successorBlocks.addAll(((BlockNode) lastBlock).getSuccessors());
}
RegionUtils.getAllRegionBlocks(region, allRegionBlocks);
}
}
}
successorBlocks.removeAll(allRegionBlocks);
if (successorBlocks.isEmpty()) {
return null;
}
RegionStack stack = regionMaker.getStack();
Region excOutRegion = new Region(mth.getRegion());
for (IBlock block : successorBlocks) {
if (block instanceof BlockNode) {
stack.clear();
stack.push(excOutRegion);
excOutRegion.add(regionMaker.makeRegion((BlockNode) block));
}
}
return excOutRegion;
}
private void processExcHandler(ExceptionHandler handler, Set<BlockNode> exits) {
BlockNode start = handler.getHandlerBlock();
if (start == null) {
return;
}
RegionStack stack = regionMaker.getStack().clear();
BlockNode dom;
if (handler.isFinally()) {
dom = BlockUtils.getTopSplitterForHandler(start);
} else {
dom = start;
stack.addExits(exits);
}
if (dom.contains(AFlag.REMOVE)) {
return;
}
BitSet domFrontier = dom.getDomFrontier();
List<BlockNode> handlerExits = BlockUtils.bitSetToBlocks(mth, domFrontier);
boolean inLoop = mth.getLoopForBlock(start) != null;
for (BlockNode exit : handlerExits) {
if ((!inLoop || BlockUtils.isPathExists(start, exit))
&& RegionUtils.isRegionContainsBlock(mth.getRegion(), exit)) {
stack.addExit(exit);
}
}
handler.setHandlerRegion(regionMaker.makeRegion(start));
ExcHandlerAttr excHandlerAttr = start.get(AType.EXC_HANDLER);
if (excHandlerAttr == null) {
mth.addWarn("Missing exception handler attribute for start block: " + start);
} else {
handler.getHandlerRegion().addAttr(excHandlerAttr);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/RegionStack.java | jadx-core/src/main/java/jadx/core/dex/visitors/regions/maker/RegionStack.java | package jadx.core.dex.visitors.regions.maker;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.exceptions.JadxOverflowException;
final class RegionStack {
private static final Logger LOG = LoggerFactory.getLogger(RegionStack.class);
private static final boolean DEBUG = false;
private static final int REGIONS_STACK_LIMIT = 1000;
static {
if (DEBUG) {
LOG.debug("Debug enabled for {}", RegionStack.class);
}
}
private static final class State {
final Set<BlockNode> exits;
IRegion region;
public State() {
exits = new HashSet<>();
}
private State(State c, IRegion region) {
this.exits = new HashSet<>(c.exits);
this.region = region;
}
public State copyWith(IRegion region) {
return new State(this, region);
}
@Override
public String toString() {
return "Region: " + region + ", exits: " + exits;
}
}
private final Deque<State> stack;
private State curState;
public RegionStack(MethodNode mth) {
if (DEBUG) {
LOG.debug("New RegionStack: {}", mth);
}
this.stack = new ArrayDeque<>();
this.curState = new State();
}
public void push(IRegion region) {
stack.push(curState);
if (stack.size() > REGIONS_STACK_LIMIT) {
throw new JadxOverflowException("Regions stack size limit reached");
}
curState = curState.copyWith(region);
if (DEBUG) {
LOG.debug("Stack push: {}: {}", size(), curState);
}
}
public void pop() {
curState = stack.pop();
if (DEBUG) {
LOG.debug("Stack pop: {}: {}", size(), curState);
}
}
/**
* Add boundary(exit) node for current stack frame
*
* @param exit boundary node, null will be ignored
*/
public void addExit(@Nullable BlockNode exit) {
if (exit != null) {
curState.exits.add(exit);
}
}
public void addExits(Collection<BlockNode> exits) {
for (BlockNode exit : exits) {
addExit(exit);
}
}
public void removeExit(@Nullable BlockNode exit) {
if (exit != null) {
curState.exits.remove(exit);
}
}
public boolean containsExit(BlockNode exit) {
return curState.exits.contains(exit);
}
public IRegion peekRegion() {
return curState.region;
}
public int size() {
return stack.size();
}
public RegionStack clear() {
stack.clear();
curState = new State();
return this;
}
@Override
public String toString() {
return "Region stack size: " + size() + ", last: " + curState;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/blocks/FixMultiEntryLoops.java | jadx-core/src/main/java/jadx/core/dex/visitors/blocks/FixMultiEntryLoops.java | package jadx.core.dex.visitors.blocks;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.SpecialEdgeAttr;
import jadx.core.dex.attributes.nodes.SpecialEdgeAttr.SpecialEdgeType;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.ListUtils;
public class FixMultiEntryLoops {
public static boolean process(MethodNode mth) {
try {
detectSpecialEdges(mth);
} catch (Exception e) {
mth.addWarnComment("Failed to detect multi-entry loops", e);
return false;
}
List<SpecialEdgeAttr> specialEdges = mth.getAll(AType.SPECIAL_EDGE);
List<SpecialEdgeAttr> multiEntryLoops = specialEdges.stream()
.filter(e -> e.getType() == SpecialEdgeType.BACK_EDGE && !isSingleEntryLoop(e))
.collect(Collectors.toList());
if (multiEntryLoops.isEmpty()) {
return false;
}
try {
List<SpecialEdgeAttr> crossEdges = ListUtils.filter(specialEdges, e -> e.getType() == SpecialEdgeType.CROSS_EDGE);
boolean changed = false;
for (SpecialEdgeAttr backEdge : multiEntryLoops) {
changed |= fixLoop(mth, backEdge, crossEdges);
}
return changed;
} catch (Exception e) {
mth.addWarnComment("Failed to fix multi-entry loops", e);
return false;
}
}
private static boolean fixLoop(MethodNode mth, SpecialEdgeAttr backEdge, List<SpecialEdgeAttr> crossEdges) {
if (isHeaderSuccessorEntry(mth, backEdge, crossEdges)) {
return true;
}
if (isEndBlockEntry(mth, backEdge, crossEdges)) {
return true;
}
mth.addWarnComment("Unsupported multi-entry loop pattern (" + backEdge + "). Please report as a decompilation issue!!!");
return false;
}
private static boolean isHeaderSuccessorEntry(MethodNode mth, SpecialEdgeAttr backEdge, List<SpecialEdgeAttr> crossEdges) {
BlockNode header = backEdge.getEnd();
BlockNode headerIDom = header.getIDom();
SpecialEdgeAttr subEntry = ListUtils.filterOnlyOne(crossEdges, e -> e.getStart() == headerIDom);
if (subEntry == null || !ListUtils.isSingleElement(header.getSuccessors(), subEntry.getEnd())) {
return false;
}
BlockNode loopEnd = backEdge.getStart();
BlockNode subEntryBlock = subEntry.getEnd();
BlockNode copyHeader = BlockSplitter.insertBlockBetween(mth, loopEnd, header);
BlockSplitter.copyBlockData(header, copyHeader);
BlockSplitter.replaceConnection(copyHeader, header, subEntryBlock);
mth.addDebugComment("Duplicate block (" + header + ") to fix multi-entry loop: " + backEdge);
return true;
}
private static boolean isEndBlockEntry(MethodNode mth, SpecialEdgeAttr backEdge, List<SpecialEdgeAttr> crossEdges) {
BlockNode loopEnd = backEdge.getStart();
SpecialEdgeAttr subEntry = ListUtils.filterOnlyOne(crossEdges, e -> e.getEnd() == loopEnd);
if (subEntry == null) {
return false;
}
dupPath(mth, subEntry.getStart(), loopEnd, backEdge.getEnd());
mth.addDebugComment("Duplicate block (" + loopEnd + ") to fix multi-entry loop: " + backEdge);
return true;
}
/**
* Duplicate 'center' block on path from 'start' to 'end'
*/
private static void dupPath(MethodNode mth, BlockNode start, BlockNode center, BlockNode end) {
BlockNode copyCenter = BlockSplitter.insertBlockBetween(mth, start, end);
BlockSplitter.copyBlockData(center, copyCenter);
BlockSplitter.removeConnection(start, center);
}
private static boolean isSingleEntryLoop(SpecialEdgeAttr e) {
BlockNode header = e.getEnd();
BlockNode loopEnd = e.getStart();
return header == loopEnd
|| loopEnd.getDoms().get(header.getId()); // header dominates loop end
}
private enum BlockColor {
WHITE, GRAY, BLACK
}
private static void detectSpecialEdges(MethodNode mth) {
BlockColor[] colors = new BlockColor[mth.getBasicBlocks().size()];
Arrays.fill(colors, BlockColor.WHITE);
colorDFS(mth, colors, mth.getEnterBlock());
}
// TODO: transform to non-recursive form
private static void colorDFS(MethodNode mth, BlockColor[] colors, BlockNode block) {
colors[block.getId()] = BlockColor.GRAY;
for (BlockNode v : block.getSuccessors()) {
switch (colors[v.getId()]) {
case WHITE:
colorDFS(mth, colors, v);
break;
case GRAY:
mth.addAttr(AType.SPECIAL_EDGE, new SpecialEdgeAttr(SpecialEdgeType.BACK_EDGE, block, v));
break;
case BLACK:
mth.addAttr(AType.SPECIAL_EDGE, new SpecialEdgeAttr(SpecialEdgeType.CROSS_EDGE, block, v));
break;
}
}
colors[block.getId()] = BlockColor.BLACK;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/blocks/BlockProcessor.java | jadx-core/src/main/java/jadx/core/dex/visitors/blocks/BlockProcessor.java | package jadx.core.dex.visitors.blocks;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.plugins.input.data.attributes.IJadxAttrType;
import jadx.api.plugins.input.data.attributes.IJadxAttribute;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.LoopInfo;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.Edge;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.trycatch.ExcHandlerAttr;
import jadx.core.dex.trycatch.TryCatchBlockAttr;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;
import static jadx.core.dex.visitors.blocks.BlockSplitter.connect;
public class BlockProcessor extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(BlockProcessor.class);
private static final boolean DEBUG_MODS = false;
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode() || mth.getBasicBlocks().isEmpty()) {
return;
}
processBlocksTree(mth);
}
private static void processBlocksTree(MethodNode mth) {
removeUnreachableBlocks(mth);
computeDominators(mth);
if (independentBlockTreeMod(mth)) {
checkForUnreachableBlocks(mth);
computeDominators(mth);
}
if (FixMultiEntryLoops.process(mth)) {
computeDominators(mth);
}
updateCleanSuccessors(mth);
int blocksCount = mth.getBasicBlocks().size();
int modLimit = Math.max(100, blocksCount);
if (DEBUG_MODS) {
mth.addAttr(new DebugModAttr());
}
int i = 0;
while (modifyBlocksTree(mth)) {
computeDominators(mth);
if (i++ > modLimit) {
mth.addWarn("CFG modification limit reached, blocks count: " + blocksCount);
break;
}
}
if (DEBUG_MODS && i != 0) {
String stats = "CFG modifications count: " + i
+ ", blocks count: " + blocksCount + '\n'
+ mth.get(DebugModAttr.TYPE).formatStats() + '\n';
mth.addDebugComment(stats);
LOG.debug("Method: {}\n{}", mth, stats);
mth.remove(DebugModAttr.TYPE);
}
checkForUnreachableBlocks(mth);
DominatorTree.computeDominanceFrontier(mth);
registerLoops(mth);
processNestedLoops(mth);
PostDominatorTree.compute(mth);
updateCleanSuccessors(mth);
}
/**
* Recalculate all additional info attached to blocks:
*
* <pre>
* - dominators
* - dominance frontier
* - post dominators (only if {@link AFlag#COMPUTE_POST_DOM} added to method)
* - loops and nested loop info
* </pre>
* <p>
* This method should be called after changing a block tree in custom passes added before
* {@link BlockFinisher}.
*/
public static void updateBlocksData(MethodNode mth) {
clearBlocksState(mth);
DominatorTree.compute(mth);
markLoops(mth);
DominatorTree.computeDominanceFrontier(mth);
registerLoops(mth);
processNestedLoops(mth);
PostDominatorTree.compute(mth);
updateCleanSuccessors(mth);
}
static void updateCleanSuccessors(MethodNode mth) {
mth.getBasicBlocks().forEach(BlockNode::updateCleanSuccessors);
}
private static void checkForUnreachableBlocks(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
if (block.getPredecessors().isEmpty() && block != mth.getEnterBlock()) {
throw new JadxRuntimeException("Unreachable block: " + block);
}
}
}
private static boolean deduplicateBlockInsns(MethodNode mth, BlockNode block) {
if (block.contains(AFlag.LOOP_START) || block.contains(AFlag.LOOP_END)) {
// search for same instruction at end of all predecessors blocks
List<BlockNode> predecessors = block.getPredecessors();
int predsCount = predecessors.size();
if (predsCount > 1) {
InsnNode lastInsn = BlockUtils.getLastInsn(block);
if (lastInsn != null && lastInsn.getType() == InsnType.IF) {
return false;
}
if (BlockUtils.checkFirstInsn(block, insn -> insn.contains(AType.EXC_HANDLER))) {
return false;
}
// TODO: implement insn extraction into separate block for partial predecessors
int sameInsnCount = getSameLastInsnCount(predecessors);
if (sameInsnCount > 0) {
List<InsnNode> insns = getLastInsns(predecessors.get(0), sameInsnCount);
insertAtStart(block, insns);
predecessors.forEach(pred -> getLastInsns(pred, sameInsnCount).clear());
mth.addDebugComment("Move duplicate insns, count: " + sameInsnCount + " to block " + block);
return true;
}
}
}
return false;
}
private static List<InsnNode> getLastInsns(BlockNode blockNode, int sameInsnCount) {
List<InsnNode> instructions = blockNode.getInstructions();
int size = instructions.size();
return instructions.subList(size - sameInsnCount, size);
}
private static void insertAtStart(BlockNode block, List<InsnNode> insns) {
List<InsnNode> blockInsns = block.getInstructions();
List<InsnNode> newInsnList = new ArrayList<>(insns.size() + blockInsns.size());
newInsnList.addAll(insns);
newInsnList.addAll(blockInsns);
blockInsns.clear();
blockInsns.addAll(newInsnList);
}
private static int getSameLastInsnCount(List<BlockNode> predecessors) {
int sameInsnCount = 0;
while (true) {
InsnNode insn = null;
for (BlockNode pred : predecessors) {
InsnNode curInsn = getInsnsFromEnd(pred, sameInsnCount);
if (curInsn == null) {
return sameInsnCount;
}
if (insn == null) {
insn = curInsn;
} else {
if (!isSame(insn, curInsn)) {
return sameInsnCount;
}
}
}
sameInsnCount++;
}
}
private static boolean isSame(InsnNode insn, InsnNode curInsn) {
return isInsnsEquals(insn, curInsn) && insn.canReorder();
}
private static boolean isInsnsEquals(InsnNode insn, InsnNode otherInsn) {
if (insn == otherInsn) {
return true;
}
if (insn.isSame(otherInsn)
&& sameArgs(insn.getResult(), otherInsn.getResult())) {
int argsCount = insn.getArgsCount();
for (int i = 0; i < argsCount; i++) {
if (!sameArgs(insn.getArg(i), otherInsn.getArg(i))) {
return false;
}
}
return true;
}
return false;
}
private static boolean sameArgs(@Nullable InsnArg arg, @Nullable InsnArg otherArg) {
if (arg == otherArg) {
return true;
}
if (arg == null || otherArg == null) {
return false;
}
if (arg.getClass().equals(otherArg.getClass())) {
if (arg.isRegister()) {
return ((RegisterArg) arg).getRegNum() == ((RegisterArg) otherArg).getRegNum();
}
if (arg.isLiteral()) {
return ((LiteralArg) arg).getLiteral() == ((LiteralArg) otherArg).getLiteral();
}
throw new JadxRuntimeException("Unexpected InsnArg types: " + arg + " and " + otherArg);
}
return false;
}
private static InsnNode getInsnsFromEnd(BlockNode block, int number) {
List<InsnNode> instructions = block.getInstructions();
int insnCount = instructions.size();
if (insnCount <= number) {
return null;
}
return instructions.get(insnCount - number - 1);
}
private static void computeDominators(MethodNode mth) {
clearBlocksState(mth);
DominatorTree.compute(mth);
markLoops(mth);
}
private static void markLoops(MethodNode mth) {
mth.getBasicBlocks().forEach(block -> {
// Every successor that dominates its predecessor is a header of a loop,
// block -> successor is a back edge.
block.getSuccessors().forEach(successor -> {
if (block.getDoms().get(successor.getId()) || block == successor) {
successor.add(AFlag.LOOP_START);
block.add(AFlag.LOOP_END);
Set<BlockNode> loopBlocks = BlockUtils.getAllPathsBlocks(successor, block);
LoopInfo loop = new LoopInfo(successor, block, loopBlocks);
successor.addAttr(AType.LOOP, loop);
block.addAttr(AType.LOOP, loop);
}
});
});
}
private static void registerLoops(MethodNode mth) {
mth.resetLoops();
mth.getBasicBlocks().forEach(block -> {
if (block.contains(AFlag.LOOP_START)) {
block.getAll(AType.LOOP).forEach(mth::registerLoop);
}
});
}
private static void processNestedLoops(MethodNode mth) {
if (mth.getLoopsCount() == 0) {
return;
}
for (LoopInfo outLoop : mth.getLoops()) {
for (LoopInfo innerLoop : mth.getLoops()) {
if (outLoop == innerLoop) {
continue;
}
if (outLoop.getLoopBlocks().containsAll(innerLoop.getLoopBlocks())) {
LoopInfo parentLoop = innerLoop.getParentLoop();
if (parentLoop != null) {
if (parentLoop.getLoopBlocks().containsAll(outLoop.getLoopBlocks())) {
outLoop.setParentLoop(parentLoop);
innerLoop.setParentLoop(outLoop);
} else {
parentLoop.setParentLoop(outLoop);
}
} else {
innerLoop.setParentLoop(outLoop);
}
}
}
}
}
private static boolean modifyBlocksTree(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
if (checkLoops(mth, block)) {
return true;
}
}
if (mergeConstReturn(mth)) {
return true;
}
return splitExitBlocks(mth);
}
private static boolean mergeConstReturn(MethodNode mth) {
if (mth.isVoidReturn()) {
return false;
}
boolean changed = false;
for (BlockNode retBlock : new ArrayList<>(mth.getPreExitBlocks())) {
BlockNode pred = Utils.getOne(retBlock.getPredecessors());
if (pred != null) {
InsnNode constInsn = Utils.getOne(pred.getInstructions());
if (constInsn != null && constInsn.isConstInsn()) {
RegisterArg constArg = constInsn.getResult();
InsnNode returnInsn = BlockUtils.getLastInsn(retBlock);
if (returnInsn != null && returnInsn.getType() == InsnType.RETURN) {
InsnArg retArg = returnInsn.getArg(0);
if (constArg.sameReg(retArg)) {
mergeConstAndReturnBlocks(mth, retBlock, pred);
changed = true;
}
}
}
}
}
if (changed) {
removeMarkedBlocks(mth);
if (DEBUG_MODS) {
mth.get(DebugModAttr.TYPE).addEvent("Merge const return");
}
}
return changed;
}
private static void mergeConstAndReturnBlocks(MethodNode mth, BlockNode retBlock, BlockNode pred) {
pred.getInstructions().addAll(retBlock.getInstructions());
pred.copyAttributesFrom(retBlock);
BlockSplitter.removeConnection(pred, retBlock);
retBlock.getInstructions().clear();
retBlock.add(AFlag.REMOVE);
BlockNode exitBlock = mth.getExitBlock();
BlockSplitter.removeConnection(retBlock, exitBlock);
BlockSplitter.connect(pred, exitBlock);
pred.updateCleanSuccessors();
}
private static boolean independentBlockTreeMod(MethodNode mth) {
boolean changed = false;
List<BlockNode> basicBlocks = mth.getBasicBlocks();
for (BlockNode basicBlock : basicBlocks) {
if (deduplicateBlockInsns(mth, basicBlock)) {
changed = true;
}
}
if (BlockExceptionHandler.process(mth)) {
changed = true;
}
for (BlockNode basicBlock : basicBlocks) {
if (BlockSplitter.removeEmptyBlock(basicBlock)) {
changed = true;
}
}
if (BlockSplitter.removeEmptyDetachedBlocks(mth)) {
changed = true;
}
return changed;
}
private static boolean simplifyLoopEnd(MethodNode mth, LoopInfo loop) {
BlockNode loopEnd = loop.getEnd();
if (loopEnd.getSuccessors().size() <= 1) {
return false;
}
// make loop end a simple path block
BlockNode newLoopEnd = BlockSplitter.startNewBlock(mth, -1);
newLoopEnd.add(AFlag.SYNTHETIC);
newLoopEnd.add(AFlag.LOOP_END);
BlockNode loopStart = loop.getStart();
BlockSplitter.replaceConnection(loopEnd, loopStart, newLoopEnd);
BlockSplitter.connect(newLoopEnd, loopStart);
if (DEBUG_MODS) {
mth.get(DebugModAttr.TYPE).addEvent("Simplify loop end");
}
return true;
}
private static boolean checkLoops(MethodNode mth, BlockNode block) {
if (!block.contains(AFlag.LOOP_START)) {
return false;
}
List<LoopInfo> loops = block.getAll(AType.LOOP);
int loopsCount = loops.size();
if (loopsCount == 0) {
return false;
}
for (LoopInfo loop : loops) {
if (insertBlocksForBreak(mth, loop)) {
return true;
}
}
if (loopsCount > 1 && splitLoops(mth, block, loops)) {
return true;
}
if (loopsCount == 1) {
LoopInfo loop = loops.get(0);
return insertBlocksForContinue(mth, loop)
|| insertPreHeader(mth, loop)
|| simplifyLoopEnd(mth, loop);
}
return false;
}
/**
* Insert simple path block before loop header
*/
private static boolean insertPreHeader(MethodNode mth, LoopInfo loop) {
BlockNode start = loop.getStart();
List<BlockNode> preds = start.getPredecessors();
int predsCount = preds.size() - 1; // don't count back edge
if (predsCount == 1) {
return false;
}
if (predsCount == 0) {
if (!start.contains(AFlag.MTH_ENTER_BLOCK)) {
mth.addWarnComment("Unexpected block without predecessors: " + start);
}
BlockNode newEnterBlock = BlockSplitter.startNewBlock(mth, -1);
newEnterBlock.add(AFlag.SYNTHETIC);
newEnterBlock.add(AFlag.MTH_ENTER_BLOCK);
mth.setEnterBlock(newEnterBlock);
start.remove(AFlag.MTH_ENTER_BLOCK);
BlockSplitter.connect(newEnterBlock, start);
} else {
// multiple predecessors
BlockNode preHeader = BlockSplitter.startNewBlock(mth, -1);
preHeader.add(AFlag.SYNTHETIC);
BlockNode loopEnd = loop.getEnd();
for (BlockNode pred : new ArrayList<>(preds)) {
if (pred != loopEnd) {
BlockSplitter.replaceConnection(pred, start, preHeader);
}
}
BlockSplitter.connect(preHeader, start);
}
if (DEBUG_MODS) {
mth.get(DebugModAttr.TYPE).addEvent("Insert loop pre header");
}
return true;
}
/**
* Insert additional blocks for possible 'break' insertion
*/
private static boolean insertBlocksForBreak(MethodNode mth, LoopInfo loop) {
boolean change = false;
List<Edge> edges = loop.getExitEdges();
if (!edges.isEmpty()) {
for (Edge edge : edges) {
BlockNode target = edge.getTarget();
BlockNode source = edge.getSource();
if (!target.contains(AFlag.SYNTHETIC) && !source.contains(AFlag.SYNTHETIC)) {
BlockSplitter.insertBlockBetween(mth, source, target);
change = true;
}
}
}
if (DEBUG_MODS && change) {
mth.get(DebugModAttr.TYPE).addEvent("Insert loop break blocks");
}
return change;
}
/**
* Insert additional blocks for possible 'continue' insertion
*/
private static boolean insertBlocksForContinue(MethodNode mth, LoopInfo loop) {
BlockNode loopEnd = loop.getEnd();
boolean change = false;
List<BlockNode> preds = loopEnd.getPredecessors();
if (preds.size() > 1) {
for (BlockNode pred : new ArrayList<>(preds)) {
if (!pred.contains(AFlag.SYNTHETIC)) {
BlockSplitter.insertBlockBetween(mth, pred, loopEnd);
change = true;
}
}
}
if (DEBUG_MODS && change) {
mth.get(DebugModAttr.TYPE).addEvent("Insert loop continue block");
}
return change;
}
private static boolean splitLoops(MethodNode mth, BlockNode block, List<LoopInfo> loops) {
boolean oneHeader = true;
for (LoopInfo loop : loops) {
if (loop.getStart() != block) {
oneHeader = false;
break;
}
}
if (!oneHeader) {
return false;
}
// several back edges connected to one loop header => make additional block
BlockNode newLoopEnd = BlockSplitter.startNewBlock(mth, block.getStartOffset());
newLoopEnd.add(AFlag.SYNTHETIC);
connect(newLoopEnd, block);
for (LoopInfo la : loops) {
BlockSplitter.replaceConnection(la.getEnd(), block, newLoopEnd);
}
if (DEBUG_MODS) {
mth.get(DebugModAttr.TYPE).addEvent("Split loops");
}
return true;
}
private static boolean splitExitBlocks(MethodNode mth) {
boolean changed = false;
for (BlockNode preExitBlock : mth.getPreExitBlocks()) {
if (splitReturn(mth, preExitBlock)) {
changed = true;
} else if (splitThrow(mth, preExitBlock)) {
changed = true;
}
}
if (changed) {
updateExitBlockConnections(mth);
if (DEBUG_MODS) {
mth.get(DebugModAttr.TYPE).addEvent("Split exit block");
}
}
return changed;
}
private static void updateExitBlockConnections(MethodNode mth) {
BlockNode exitBlock = mth.getExitBlock();
BlockSplitter.removePredecessors(exitBlock);
for (BlockNode block : mth.getBasicBlocks()) {
if (block != exitBlock
&& block.getSuccessors().isEmpty()
&& !block.contains(AFlag.REMOVE)) {
BlockSplitter.connect(block, exitBlock);
}
}
}
/**
* Splice return block if several predecessors presents
*/
private static boolean splitReturn(MethodNode mth, BlockNode returnBlock) {
if (returnBlock.contains(AFlag.SYNTHETIC)
|| returnBlock.contains(AFlag.ORIG_RETURN)
|| returnBlock.contains(AType.EXC_HANDLER)) {
return false;
}
List<BlockNode> preds = returnBlock.getPredecessors();
if (preds.size() < 2) {
return false;
}
InsnNode returnInsn = BlockUtils.getLastInsn(returnBlock);
if (returnInsn == null) {
return false;
}
if (returnInsn.getArgsCount() == 1
&& returnBlock.getInstructions().size() == 1
&& !isArgAssignInPred(preds, returnInsn.getArg(0))) {
return false;
}
boolean first = true;
for (BlockNode pred : new ArrayList<>(preds)) {
if (first) {
returnBlock.add(AFlag.ORIG_RETURN);
first = false;
} else {
BlockNode newRetBlock = BlockSplitter.startNewBlock(mth, -1);
newRetBlock.add(AFlag.SYNTHETIC);
newRetBlock.add(AFlag.RETURN);
for (InsnNode oldInsn : returnBlock.getInstructions()) {
InsnNode copyInsn = oldInsn.copyWithoutSsa();
copyInsn.add(AFlag.SYNTHETIC);
newRetBlock.getInstructions().add(copyInsn);
}
BlockSplitter.replaceConnection(pred, returnBlock, newRetBlock);
}
}
return true;
}
private static boolean splitThrow(MethodNode mth, BlockNode exitBlock) {
if (exitBlock.contains(AFlag.IGNORE_THROW_SPLIT)) {
return false;
}
List<BlockNode> preds = exitBlock.getPredecessors();
if (preds.size() < 2) {
return false;
}
InsnNode throwInsn = BlockUtils.getLastInsn(exitBlock);
if (throwInsn == null || throwInsn.getType() != InsnType.THROW) {
return false;
}
// split only for several exception handlers
// traverse predecessors to exception handler
Map<BlockNode, ExcHandlerAttr> handlersMap = new HashMap<>(preds.size());
Set<BlockNode> handlers = new HashSet<>(preds.size());
for (BlockNode pred : preds) {
BlockUtils.visitPredecessorsUntil(mth, pred, block -> {
ExcHandlerAttr excHandlerAttr = block.get(AType.EXC_HANDLER);
if (excHandlerAttr == null) {
return false;
}
boolean correctHandler = excHandlerAttr.getHandler().getBlocks().contains(block);
if (correctHandler && isArgAssignInPred(Collections.singletonList(block), throwInsn.getArg(0))) {
handlersMap.put(pred, excHandlerAttr);
handlers.add(block);
}
return correctHandler;
});
}
if (handlers.size() == 1) {
exitBlock.add(AFlag.IGNORE_THROW_SPLIT);
return false;
}
boolean first = true;
for (BlockNode pred : new ArrayList<>(preds)) {
if (first) {
first = false;
} else {
BlockNode newThrowBlock = BlockSplitter.startNewBlock(mth, -1);
newThrowBlock.add(AFlag.SYNTHETIC);
for (InsnNode oldInsn : exitBlock.getInstructions()) {
InsnNode copyInsn = oldInsn.copyWithoutSsa();
copyInsn.add(AFlag.SYNTHETIC);
newThrowBlock.getInstructions().add(copyInsn);
}
newThrowBlock.copyAttributesFrom(exitBlock);
ExcHandlerAttr excHandlerAttr = handlersMap.get(pred);
if (excHandlerAttr != null) {
excHandlerAttr.getHandler().addBlock(newThrowBlock);
}
BlockSplitter.replaceConnection(pred, exitBlock, newThrowBlock);
}
}
return true;
}
private static boolean isArgAssignInPred(List<BlockNode> preds, InsnArg arg) {
if (arg.isRegister()) {
int regNum = ((RegisterArg) arg).getRegNum();
for (BlockNode pred : preds) {
for (InsnNode insnNode : pred.getInstructions()) {
RegisterArg result = insnNode.getResult();
if (result != null && result.getRegNum() == regNum) {
return true;
}
}
}
}
return false;
}
public static void removeMarkedBlocks(MethodNode mth) {
boolean removed = mth.getBasicBlocks().removeIf(block -> {
if (block.contains(AFlag.REMOVE)) {
if (!block.getPredecessors().isEmpty() || !block.getSuccessors().isEmpty()) {
LOG.warn("Block {} not deleted, method: {}", block, mth);
} else {
TryCatchBlockAttr tryBlockAttr = block.get(AType.TRY_BLOCK);
if (tryBlockAttr != null) {
tryBlockAttr.removeBlock(block);
}
return true;
}
}
return false;
});
if (removed) {
mth.updateBlockPositions();
}
}
private static void removeUnreachableBlocks(MethodNode mth) {
Set<BlockNode> toRemove = new LinkedHashSet<>();
for (BlockNode block : mth.getBasicBlocks()) {
computeUnreachableFromBlock(toRemove, block, mth);
}
removeFromMethod(toRemove, mth);
}
public static void removeUnreachableBlock(BlockNode blockToRemove, MethodNode mth) {
Set<BlockNode> toRemove = new LinkedHashSet<>();
computeUnreachableFromBlock(toRemove, blockToRemove, mth);
removeFromMethod(toRemove, mth);
}
private static void computeUnreachableFromBlock(Set<BlockNode> toRemove, BlockNode block, MethodNode mth) {
if (block.getPredecessors().isEmpty() && block != mth.getEnterBlock()) {
BlockSplitter.collectSuccessors(block, mth.getEnterBlock(), toRemove);
}
}
private static void removeFromMethod(Set<BlockNode> toRemove, MethodNode mth) {
if (toRemove.isEmpty()) {
return;
}
long notEmptyBlocks = toRemove.stream().filter(block -> !block.getInstructions().isEmpty()).count();
if (notEmptyBlocks != 0) {
int insnsCount = toRemove.stream().mapToInt(block -> block.getInstructions().size()).sum();
mth.addWarnComment("Unreachable blocks removed: " + notEmptyBlocks + ", instructions: " + insnsCount);
}
toRemove.forEach(BlockSplitter::detachBlock);
mth.getBasicBlocks().removeAll(toRemove);
mth.updateBlockPositions();
}
private static void clearBlocksState(MethodNode mth) {
mth.getBasicBlocks().forEach(block -> {
block.remove(AType.LOOP);
block.remove(AFlag.LOOP_START);
block.remove(AFlag.LOOP_END);
block.setDoms(null);
block.setIDom(null);
block.setDomFrontier(null);
block.getDominatesOn().clear();
});
}
private static final class DebugModAttr implements IJadxAttribute {
static final IJadxAttrType<DebugModAttr> TYPE = IJadxAttrType.create("DebugModAttr");
private final Map<String, Integer> statMap = new HashMap<>();
public void addEvent(String name) {
statMap.merge(name, 1, Integer::sum);
}
public String formatStats() {
return statMap.entrySet().stream()
.map(entry -> " " + entry.getKey() + ": " + entry.getValue())
.collect(Collectors.joining("\n"));
}
@Override
public IJadxAttrType<DebugModAttr> getAttrType() {
return TYPE;
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/blocks/BlockExceptionHandler.java | jadx-core/src/main/java/jadx/core/dex/visitors/blocks/BlockExceptionHandler.java | package jadx.core.dex.visitors.blocks;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.plugins.utils.Utils;
import jadx.core.Consts;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.TmpEdgeAttr;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.NamedArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.trycatch.CatchAttr;
import jadx.core.dex.trycatch.ExcHandlerAttr;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.dex.trycatch.TryCatchBlockAttr;
import jadx.core.dex.visitors.typeinference.TypeCompare;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.ListUtils;
import jadx.core.utils.blocks.BlockSet;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class BlockExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(BlockExceptionHandler.class);
public static boolean process(MethodNode mth) {
if (mth.isNoExceptionHandlers()) {
return false;
}
BlockProcessor.updateCleanSuccessors(mth);
DominatorTree.computeDominanceFrontier(mth);
processCatchAttr(mth);
initExcHandlers(mth);
List<TryCatchBlockAttr> tryBlocks = prepareTryBlocks(mth);
connectExcHandlers(mth, tryBlocks);
mth.addAttr(AType.TRY_BLOCKS_LIST, tryBlocks);
mth.getBasicBlocks().forEach(BlockNode::updateCleanSuccessors);
for (ExceptionHandler eh : mth.getExceptionHandlers()) {
removeMonitorExitFromExcHandler(mth, eh);
}
BlockProcessor.removeMarkedBlocks(mth);
BlockSet sorted = new BlockSet(mth);
BlockUtils.visitDFS(mth, sorted::add);
removeUnusedExcHandlers(mth, tryBlocks, sorted);
return true;
}
/**
* Wrap try blocks with top/bottom splitter and connect them to handler block.
* Sometimes try block can be handler block itself and should be connected before wrapping.
* Use queue for postpone try blocks not ready for wrap.
*/
private static void connectExcHandlers(MethodNode mth, List<TryCatchBlockAttr> tryBlocks) {
if (tryBlocks.isEmpty()) {
return;
}
int limit = tryBlocks.size() * 3;
int count = 0;
Deque<TryCatchBlockAttr> queue = new ArrayDeque<>(tryBlocks);
while (!queue.isEmpty()) {
TryCatchBlockAttr tryBlock = queue.removeFirst();
boolean complete = wrapBlocksWithTryCatch(mth, tryBlock);
if (!complete) {
queue.addLast(tryBlock); // return to queue at the end
}
if (count++ > limit) {
throw new JadxRuntimeException("Try blocks wrapping queue limit reached! Please report as an issue!");
}
}
}
private static void processCatchAttr(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
for (InsnNode insn : block.getInstructions()) {
if (insn.contains(AType.EXC_CATCH) && !insn.canThrowException()) {
insn.remove(AType.EXC_CATCH);
}
}
}
// if all instructions in block have same 'catch' attribute -> add this attribute for whole block.
for (BlockNode block : mth.getBasicBlocks()) {
CatchAttr commonCatchAttr = getCommonCatchAttr(block);
if (commonCatchAttr != null) {
block.addAttr(commonCatchAttr);
for (InsnNode insn : block.getInstructions()) {
if (insn.contains(AFlag.TRY_ENTER)) {
block.add(AFlag.TRY_ENTER);
}
if (insn.contains(AFlag.TRY_LEAVE)) {
block.add(AFlag.TRY_LEAVE);
}
}
}
}
}
@Nullable
private static CatchAttr getCommonCatchAttr(BlockNode block) {
CatchAttr commonCatchAttr = null;
for (InsnNode insn : block.getInstructions()) {
CatchAttr catchAttr = insn.get(AType.EXC_CATCH);
if (catchAttr != null) {
if (commonCatchAttr == null) {
commonCatchAttr = catchAttr;
continue;
}
if (!commonCatchAttr.equals(catchAttr)) {
return null;
}
}
}
return commonCatchAttr;
}
@SuppressWarnings("ForLoopReplaceableByForEach")
private static void initExcHandlers(MethodNode mth) {
List<BlockNode> blocks = mth.getBasicBlocks();
int blocksCount = blocks.size();
for (int i = 0; i < blocksCount; i++) { // will add new blocks to list end
BlockNode block = blocks.get(i);
InsnNode firstInsn = BlockUtils.getFirstInsn(block);
if (firstInsn == null) {
continue;
}
ExcHandlerAttr excHandlerAttr = firstInsn.get(AType.EXC_HANDLER);
if (excHandlerAttr == null) {
continue;
}
firstInsn.remove(AType.EXC_HANDLER);
removeTmpConnection(block);
ExceptionHandler excHandler = excHandlerAttr.getHandler();
if (block.getPredecessors().isEmpty()) {
excHandler.setHandlerBlock(block);
block.addAttr(excHandlerAttr);
excHandler.addBlock(block);
BlockUtils.collectBlocksDominatedByWithExcHandlers(mth, block, block)
.forEach(excHandler::addBlock);
} else {
// ignore already connected handlers -> make catch empty
BlockNode emptyHandlerBlock = BlockSplitter.startNewBlock(mth, block.getStartOffset());
emptyHandlerBlock.add(AFlag.SYNTHETIC);
emptyHandlerBlock.addAttr(excHandlerAttr);
BlockSplitter.connect(emptyHandlerBlock, block);
excHandler.setHandlerBlock(emptyHandlerBlock);
excHandler.addBlock(emptyHandlerBlock);
}
fixMoveExceptionInsn(block, excHandlerAttr);
}
}
private static void removeTmpConnection(BlockNode block) {
TmpEdgeAttr tmpEdgeAttr = block.get(AType.TMP_EDGE);
if (tmpEdgeAttr != null) {
// remove temp connection
BlockSplitter.removeConnection(tmpEdgeAttr.getBlock(), block);
block.remove(AType.TMP_EDGE);
}
}
private static List<TryCatchBlockAttr> prepareTryBlocks(MethodNode mth) {
Map<ExceptionHandler, List<BlockNode>> blocksByHandler = new HashMap<>();
for (BlockNode block : mth.getBasicBlocks()) {
CatchAttr catchAttr = block.get(AType.EXC_CATCH);
if (catchAttr != null) {
for (ExceptionHandler eh : catchAttr.getHandlers()) {
blocksByHandler
.computeIfAbsent(eh, c -> new ArrayList<>())
.add(block);
}
}
}
if (Consts.DEBUG_EXC_HANDLERS) {
LOG.debug("Input exception handlers:");
blocksByHandler.forEach((eh, blocks) -> LOG.debug(" {}, throw blocks: {}, handler blocks: {}", eh, blocks, eh.getBlocks()));
}
if (blocksByHandler.isEmpty()) {
// no catch blocks -> remove all handlers
mth.getExceptionHandlers().forEach(eh -> removeExcHandler(mth, eh));
} else {
// remove handlers without blocks in catch attribute
blocksByHandler.forEach((eh, blocks) -> {
if (blocks.isEmpty()) {
removeExcHandler(mth, eh);
}
});
}
BlockSplitter.detachMarkedBlocks(mth);
mth.clearExceptionHandlers();
if (mth.isNoExceptionHandlers()) {
return Collections.emptyList();
}
blocksByHandler.forEach((eh, blocks) -> {
// remove catches from same handler
blocks.removeAll(eh.getBlocks());
});
List<TryCatchBlockAttr> tryBlocks = new ArrayList<>();
blocksByHandler.forEach((eh, blocks) -> {
List<ExceptionHandler> handlers = new ArrayList<>(1);
handlers.add(eh);
tryBlocks.add(new TryCatchBlockAttr(tryBlocks.size(), handlers, blocks));
});
if (tryBlocks.size() > 1) {
// merge or mark as outer/inner
while (true) {
boolean restart = combineTryCatchBlocks(tryBlocks);
if (!restart) {
break;
}
}
}
checkForMultiCatch(mth, tryBlocks);
clearTryBlocks(mth, tryBlocks);
sortHandlers(mth, tryBlocks);
if (Consts.DEBUG_EXC_HANDLERS) {
LOG.debug("Result try-catch blocks:");
tryBlocks.forEach(tryBlock -> LOG.debug(" {}", tryBlock));
}
return tryBlocks;
}
private static void clearTryBlocks(MethodNode mth, List<TryCatchBlockAttr> tryBlocks) {
tryBlocks.forEach(tc -> tc.getBlocks().removeIf(b -> b.contains(AFlag.REMOVE)));
tryBlocks.removeIf(tb -> tb.getBlocks().isEmpty() || tb.getHandlers().isEmpty());
mth.clearExceptionHandlers();
BlockSplitter.detachMarkedBlocks(mth);
}
private static boolean combineTryCatchBlocks(List<TryCatchBlockAttr> tryBlocks) {
for (TryCatchBlockAttr outerTryBlock : tryBlocks) {
for (TryCatchBlockAttr innerTryBlock : tryBlocks) {
if (outerTryBlock == innerTryBlock || innerTryBlock.getOuterTryBlock() != null) {
continue;
}
if (checkTryCatchRelation(tryBlocks, outerTryBlock, innerTryBlock)) {
return true;
}
}
}
return false;
}
private static boolean checkTryCatchRelation(List<TryCatchBlockAttr> tryBlocks,
TryCatchBlockAttr outerTryBlock, TryCatchBlockAttr innerTryBlock) {
if (outerTryBlock.getBlocks().equals(innerTryBlock.getBlocks())) {
// same try blocks -> merge handlers
List<ExceptionHandler> handlers = Utils.concatDistinct(outerTryBlock.getHandlers(), innerTryBlock.getHandlers());
tryBlocks.add(new TryCatchBlockAttr(tryBlocks.size(), handlers, outerTryBlock.getBlocks()));
tryBlocks.remove(outerTryBlock);
tryBlocks.remove(innerTryBlock);
return true;
}
Set<BlockNode> handlerBlocks = innerTryBlock.getHandlers().stream()
.flatMap(eh -> eh.getBlocks().stream())
.collect(Collectors.toSet());
boolean catchInHandler = handlerBlocks.stream().anyMatch(isHandlersIntersects(outerTryBlock));
boolean catchInTry = innerTryBlock.getBlocks().stream().anyMatch(isHandlersIntersects(outerTryBlock));
boolean blocksOutsideHandler = outerTryBlock.getBlocks().stream().anyMatch(b -> !handlerBlocks.contains(b));
if (catchInHandler && (catchInTry || blocksOutsideHandler)) {
// convert to inner
List<BlockNode> mergedBlocks = Utils.concatDistinct(outerTryBlock.getBlocks(), innerTryBlock.getBlocks());
innerTryBlock.getHandlers().removeAll(outerTryBlock.getHandlers());
innerTryBlock.setOuterTryBlock(outerTryBlock);
outerTryBlock.addInnerTryBlock(innerTryBlock);
outerTryBlock.setBlocks(mergedBlocks);
return false;
}
Set<ExceptionHandler> innerHandlerSet = new HashSet<>(innerTryBlock.getHandlers());
if (innerHandlerSet.containsAll(outerTryBlock.getHandlers())) {
// merge
List<BlockNode> mergedBlocks = Utils.concatDistinct(outerTryBlock.getBlocks(), innerTryBlock.getBlocks());
List<ExceptionHandler> handlers = Utils.concatDistinct(outerTryBlock.getHandlers(), innerTryBlock.getHandlers());
tryBlocks.add(new TryCatchBlockAttr(tryBlocks.size(), handlers, mergedBlocks));
tryBlocks.remove(outerTryBlock);
tryBlocks.remove(innerTryBlock);
return true;
}
return false;
}
@NotNull
private static Predicate<BlockNode> isHandlersIntersects(TryCatchBlockAttr outerTryBlock) {
return block -> {
CatchAttr catchAttr = block.get(AType.EXC_CATCH);
return catchAttr != null && Objects.equals(catchAttr.getHandlers(), outerTryBlock.getHandlers());
};
}
private static void removeExcHandler(MethodNode mth, ExceptionHandler excHandler) {
excHandler.markForRemove();
BlockSplitter.removeConnection(mth.getEnterBlock(), excHandler.getHandlerBlock());
}
private static boolean wrapBlocksWithTryCatch(MethodNode mth, TryCatchBlockAttr tryCatchBlock) {
List<BlockNode> blocks = tryCatchBlock.getBlocks();
BlockNode top = searchTopBlock(mth, blocks);
if (top.getPredecessors().isEmpty() && top != mth.getEnterBlock()) {
return false;
}
BlockNode bottom = searchBottomBlock(mth, blocks);
BlockNode splitReturn;
if (bottom != null && bottom.isReturnBlock()) {
if (Consts.DEBUG_EXC_HANDLERS) {
LOG.debug("TryCatch #{} bottom block ({}) is return, split", tryCatchBlock.id(), bottom);
}
splitReturn = bottom;
bottom = BlockSplitter.blockSplitTop(mth, bottom);
bottom.add(AFlag.SYNTHETIC);
} else {
splitReturn = null;
}
if (Consts.DEBUG_EXC_HANDLERS) {
LOG.debug("TryCatch #{} split: top {}, bottom: {}", tryCatchBlock.id(), top, bottom);
}
BlockNode topSplitterBlock = getTopSplitterBlock(mth, top);
topSplitterBlock.add(AFlag.EXC_TOP_SPLITTER);
topSplitterBlock.add(AFlag.SYNTHETIC);
int totalHandlerBlocks = tryCatchBlock.getHandlers().stream().mapToInt(eh -> eh.getBlocks().size()).sum();
BlockNode bottomSplitterBlock;
if (bottom == null || totalHandlerBlocks == 0) {
bottomSplitterBlock = null;
} else {
BlockNode existBottomSplitter = BlockUtils.getBlockWithFlag(bottom.getSuccessors(), AFlag.EXC_BOTTOM_SPLITTER);
bottomSplitterBlock = existBottomSplitter != null ? existBottomSplitter : BlockSplitter.startNewBlock(mth, -1);
bottomSplitterBlock.add(AFlag.EXC_BOTTOM_SPLITTER);
bottomSplitterBlock.add(AFlag.SYNTHETIC);
BlockSplitter.connect(bottom, bottomSplitterBlock);
if (splitReturn != null) {
// redirect handler to return block instead synthetic split block to avoid self-loop
BlockSet bottomPreds = BlockSet.from(mth, bottom.getPredecessors());
for (ExceptionHandler handler : tryCatchBlock.getHandlers()) {
if (bottomPreds.intersects(handler.getBlocks())) {
BlockNode lastBlock = bottomPreds.intersect(handler.getBlocks()).getOne();
if (lastBlock != null) {
BlockSplitter.replaceConnection(lastBlock, bottom, splitReturn);
}
}
}
}
}
if (Consts.DEBUG_EXC_HANDLERS) {
LOG.debug("TryCatch #{} result splitters: top {}, bottom: {}",
tryCatchBlock.id(), topSplitterBlock, bottomSplitterBlock);
}
connectSplittersAndHandlers(tryCatchBlock, topSplitterBlock, bottomSplitterBlock);
for (BlockNode block : blocks) {
TryCatchBlockAttr currentTCBAttr = block.get(AType.TRY_BLOCK);
if (currentTCBAttr == null || currentTCBAttr.getInnerTryBlocks().contains(tryCatchBlock)) {
block.addAttr(tryCatchBlock);
}
}
tryCatchBlock.setTopSplitter(topSplitterBlock);
topSplitterBlock.updateCleanSuccessors();
if (bottomSplitterBlock != null) {
bottomSplitterBlock.updateCleanSuccessors();
}
return true;
}
private static BlockNode getTopSplitterBlock(MethodNode mth, BlockNode top) {
if (top == mth.getEnterBlock()) {
BlockNode fixedTop = mth.getEnterBlock().getSuccessors().get(0);
return BlockSplitter.blockSplitTop(mth, fixedTop);
}
BlockNode existPredTopSplitter = BlockUtils.getBlockWithFlag(top.getPredecessors(), AFlag.EXC_TOP_SPLITTER);
if (existPredTopSplitter != null) {
return existPredTopSplitter;
}
// try to reuse exists splitter on empty simple path below top block
if (top.getCleanSuccessors().size() == 1 && top.getInstructions().isEmpty()) {
BlockNode otherTopSplitter = BlockUtils.getBlockWithFlag(top.getCleanSuccessors(), AFlag.EXC_TOP_SPLITTER);
if (otherTopSplitter != null && otherTopSplitter.getPredecessors().size() == 1) {
return otherTopSplitter;
}
}
return BlockSplitter.blockSplitTop(mth, top);
}
private static BlockNode searchTopBlock(MethodNode mth, List<BlockNode> blocks) {
BlockNode top = BlockUtils.getTopBlock(blocks);
if (top != null) {
return adjustTopBlock(top);
}
BlockNode topDom = BlockUtils.getCommonDominator(mth, blocks);
if (topDom != null) {
// dominator always return one up block if blocks already contains dominator, use successor instead
if (topDom.getSuccessors().size() == 1) {
BlockNode upBlock = topDom.getSuccessors().get(0);
if (blocks.contains(upBlock)) {
return upBlock;
}
}
return adjustTopBlock(topDom);
}
throw new JadxRuntimeException("Failed to find top block for try-catch from: " + blocks);
}
private static BlockNode adjustTopBlock(BlockNode topBlock) {
if (topBlock.getSuccessors().size() == 1 && !topBlock.contains(AType.EXC_CATCH)) {
// top block can be lifted by other exception handlers included in blocks list, trying to undo that
return topBlock.getSuccessors().get(0);
}
return topBlock;
}
@Nullable
private static BlockNode searchBottomBlock(MethodNode mth, List<BlockNode> blocks) {
// search common post-dominator block inside input set
BlockNode bottom = BlockUtils.getBottomBlock(blocks);
if (bottom != null) {
return bottom;
}
// not found -> blocks don't have same dominator
// try to search common cross block outside input set
// NOTE: bottom block not needed for exit nodes (no data flow from them)
BlockNode pathCross = BlockUtils.getPathCross(mth, blocks);
if (pathCross == null) {
return null;
}
List<BlockNode> preds = new ArrayList<>(pathCross.getPredecessors());
preds.removeAll(blocks);
List<BlockNode> outsidePredecessors = preds.stream()
.filter(p -> !BlockUtils.atLeastOnePathExists(blocks, p))
.collect(Collectors.toList());
if (outsidePredecessors.isEmpty()) {
return pathCross;
}
// some predecessors outside of input set paths -> split block only for input set
BlockNode splitCross = BlockSplitter.blockSplitTop(mth, pathCross);
splitCross.add(AFlag.SYNTHETIC);
for (BlockNode outsidePredecessor : outsidePredecessors) {
// return predecessors to split bottom block (original)
BlockSplitter.replaceConnection(outsidePredecessor, splitCross, pathCross);
}
return splitCross;
}
private static void connectSplittersAndHandlers(TryCatchBlockAttr tryCatchBlock, BlockNode topSplitterBlock,
@Nullable BlockNode bottomSplitterBlock) {
for (ExceptionHandler handler : tryCatchBlock.getHandlers()) {
BlockNode handlerBlock = handler.getHandlerBlock();
BlockSplitter.connect(topSplitterBlock, handlerBlock);
if (bottomSplitterBlock != null) {
BlockSplitter.connect(bottomSplitterBlock, handlerBlock);
}
}
TryCatchBlockAttr outerTryBlock = tryCatchBlock.getOuterTryBlock();
if (outerTryBlock != null) {
connectSplittersAndHandlers(outerTryBlock, topSplitterBlock, bottomSplitterBlock);
}
}
private static void fixMoveExceptionInsn(BlockNode block, ExcHandlerAttr excHandlerAttr) {
ExceptionHandler excHandler = excHandlerAttr.getHandler();
ArgType argType = excHandler.getArgType();
InsnNode me = BlockUtils.getLastInsn(block);
if (me != null && me.getType() == InsnType.MOVE_EXCEPTION) {
// set correct type for 'move-exception' operation
RegisterArg resArg = InsnArg.reg(me.getResult().getRegNum(), argType);
resArg.copyAttributesFrom(me);
me.setResult(resArg);
me.add(AFlag.DONT_INLINE);
resArg.add(AFlag.CUSTOM_DECLARE);
excHandler.setArg(resArg);
me.addAttr(excHandlerAttr);
return;
}
// handler arguments not used
excHandler.setArg(new NamedArg("unused", argType));
}
private static void removeMonitorExitFromExcHandler(MethodNode mth, ExceptionHandler excHandler) {
for (BlockNode excBlock : excHandler.getBlocks()) {
InsnRemover remover = new InsnRemover(mth, excBlock);
for (InsnNode insn : excBlock.getInstructions()) {
if (insn.getType() == InsnType.MONITOR_ENTER) {
break;
}
if (insn.getType() == InsnType.MONITOR_EXIT) {
remover.addAndUnbind(insn);
}
}
remover.perform();
}
}
private static void checkForMultiCatch(MethodNode mth, List<TryCatchBlockAttr> tryBlocks) {
boolean merged = false;
for (TryCatchBlockAttr tryBlock : tryBlocks) {
if (mergeMultiCatch(mth, tryBlock)) {
merged = true;
}
}
if (merged) {
BlockSplitter.detachMarkedBlocks(mth);
mth.clearExceptionHandlers();
}
}
private static boolean mergeMultiCatch(MethodNode mth, TryCatchBlockAttr tryCatch) {
if (tryCatch.getHandlers().size() < 2) {
return false;
}
for (ExceptionHandler handler : tryCatch.getHandlers()) {
if (handler.getBlocks().size() != 1) {
return false;
}
BlockNode block = handler.getHandlerBlock();
if (block.getInstructions().size() != 1
|| !BlockUtils.checkLastInsnType(block, InsnType.MOVE_EXCEPTION)) {
return false;
}
}
List<BlockNode> handlerBlocks = ListUtils.map(tryCatch.getHandlers(), ExceptionHandler::getHandlerBlock);
List<BlockNode> successorBlocks = handlerBlocks.stream()
.flatMap(h -> h.getSuccessors().stream())
.distinct()
.collect(Collectors.toList());
if (successorBlocks.size() != 1) {
return false;
}
BlockNode successorBlock = successorBlocks.get(0);
if (!ListUtils.unorderedEquals(successorBlock.getPredecessors(), handlerBlocks)) {
return false;
}
List<RegisterArg> regs = tryCatch.getHandlers().stream()
.map(h -> Objects.requireNonNull(BlockUtils.getLastInsn(h.getHandlerBlock())).getResult())
.distinct()
.collect(Collectors.toList());
if (regs.size() != 1) {
return false;
}
// merge confirm, leave only first handler, remove others
ExceptionHandler resultHandler = tryCatch.getHandlers().get(0);
tryCatch.getHandlers().removeIf(handler -> {
if (handler == resultHandler) {
return false;
}
resultHandler.addCatchTypes(mth, handler.getCatchTypes());
handler.markForRemove();
return true;
});
return true;
}
private static void sortHandlers(MethodNode mth, List<TryCatchBlockAttr> tryBlocks) {
TypeCompare typeCompare = mth.root().getTypeCompare();
Comparator<ArgType> comparator = typeCompare.getReversedComparator();
for (TryCatchBlockAttr tryBlock : tryBlocks) {
for (ExceptionHandler handler : tryBlock.getHandlers()) {
handler.getCatchTypes().sort((first, second) -> compareByTypeAndName(comparator, first, second));
}
tryBlock.getHandlers().sort((first, second) -> {
if (first.equals(second)) {
throw new JadxRuntimeException("Same handlers in try block: " + tryBlock);
}
if (first.isCatchAll()) {
return 1;
}
if (second.isCatchAll()) {
return -1;
}
return compareByTypeAndName(comparator,
ListUtils.first(first.getCatchTypes()), ListUtils.first(second.getCatchTypes()));
});
}
}
@SuppressWarnings("ComparatorResultComparison")
private static int compareByTypeAndName(Comparator<ArgType> comparator, ClassInfo first, ClassInfo second) {
int r = comparator.compare(first.getType(), second.getType());
if (r == -2) {
// on conflict sort by name
return first.compareTo(second);
}
return r;
}
/**
* Remove excHandlers that were not used when connecting.
* Check first if the blocks are unreachable.
*/
private static void removeUnusedExcHandlers(MethodNode mth, List<TryCatchBlockAttr> tryBlocks, BlockSet blocks) {
for (ExceptionHandler eh : mth.getExceptionHandlers()) {
boolean notProcessed = true;
BlockNode handlerBlock = eh.getHandlerBlock();
if (handlerBlock == null || blocks.contains(handlerBlock)) {
continue;
}
for (TryCatchBlockAttr tcb : tryBlocks) {
if (tcb.getHandlers().contains(eh)) {
notProcessed = false;
break;
}
}
if (notProcessed) {
BlockProcessor.removeUnreachableBlock(handlerBlock, mth);
}
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/blocks/BlockSplitter.java | jadx-core/src/main/java/jadx/core/dex/visitors/blocks/BlockSplitter.java | package jadx.core.dex.visitors.blocks;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.JumpInfo;
import jadx.core.dex.attributes.nodes.TmpEdgeAttr;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.TargetInsnNode;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.trycatch.CatchAttr;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class BlockSplitter extends AbstractVisitor {
/**
* Leave these instructions alone in the block node
*/
private static final Set<InsnType> SEPARATE_INSNS = EnumSet.of(
InsnType.RETURN,
InsnType.IF,
InsnType.SWITCH,
InsnType.MONITOR_ENTER,
InsnType.MONITOR_EXIT,
InsnType.THROW,
InsnType.MOVE_EXCEPTION);
public static boolean isSeparate(InsnType insnType) {
return SEPARATE_INSNS.contains(insnType);
}
/**
* Split without connecting to the next block
*/
private static final Set<InsnType> SPLIT_WITHOUT_CONNECT = EnumSet.of(
InsnType.RETURN,
InsnType.THROW,
InsnType.GOTO,
InsnType.IF,
InsnType.SWITCH,
InsnType.JAVA_JSR,
InsnType.JAVA_RET);
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode()) {
return;
}
mth.initBasicBlocks();
Map<Integer, BlockNode> blocksMap = splitBasicBlocks(mth);
setupConnectionsFromJumps(mth, blocksMap);
initBlocksInTargetNodes(mth);
expandMoveMulti(mth);
if (mth.contains(AFlag.RESOLVE_JAVA_JSR)) {
ResolveJavaJSR.process(mth);
}
removeJumpAttr(mth);
removeInsns(mth);
removeEmptyDetachedBlocks(mth);
mth.getBasicBlocks().removeIf(BlockSplitter::removeEmptyBlock);
addTempConnectionsForExcHandlers(mth, blocksMap);
setupExitConnections(mth);
mth.updateBlockPositions();
mth.unloadInsnArr();
}
private static Map<Integer, BlockNode> splitBasicBlocks(MethodNode mth) {
BlockNode enterBlock = startNewBlock(mth, -1);
enterBlock.add(AFlag.MTH_ENTER_BLOCK);
mth.setEnterBlock(enterBlock);
BlockNode exitBlock = startNewBlock(mth, -1);
exitBlock.add(AFlag.MTH_EXIT_BLOCK);
mth.setExitBlock(exitBlock);
Map<Integer, BlockNode> blocksMap = new HashMap<>();
BlockNode curBlock = enterBlock;
InsnNode prevInsn = null;
for (InsnNode insn : mth.getInstructions()) {
if (insn == null) {
continue;
}
if (insn.getType() == InsnType.NOP && insn.isAttrStorageEmpty()) {
continue;
}
int insnOffset = insn.getOffset();
if (prevInsn == null) {
// first block after method enter block
curBlock = connectNewBlock(mth, curBlock, insnOffset);
} else {
InsnType prevType = prevInsn.getType();
if (SPLIT_WITHOUT_CONNECT.contains(prevType)) {
curBlock = startNewBlock(mth, insnOffset);
} else if (isSeparate(prevType)
|| isSeparate(insn.getType())
|| insn.contains(AFlag.TRY_ENTER)
|| prevInsn.contains(AFlag.TRY_LEAVE)
|| insn.contains(AType.EXC_HANDLER)
|| isSplitByJump(prevInsn, insn)
|| isDoWhile(blocksMap, curBlock, insn)) {
curBlock = connectNewBlock(mth, curBlock, insnOffset);
}
}
blocksMap.put(insnOffset, curBlock);
curBlock.getInstructions().add(insn);
prevInsn = insn;
}
return blocksMap;
}
/**
* Init 'then' and 'else' blocks for 'if' instruction.
*/
private static void initBlocksInTargetNodes(MethodNode mth) {
mth.getBasicBlocks().forEach(block -> {
InsnNode lastInsn = BlockUtils.getLastInsn(block);
if (lastInsn instanceof TargetInsnNode) {
((TargetInsnNode) lastInsn).initBlocks(block);
}
});
}
static BlockNode connectNewBlock(MethodNode mth, BlockNode block, int offset) {
BlockNode newBlock = startNewBlock(mth, offset);
connect(block, newBlock);
return newBlock;
}
static BlockNode startNewBlock(MethodNode mth, int offset) {
List<BlockNode> blocks = mth.getBasicBlocks();
BlockNode block = new BlockNode(mth.getNextBlockCId(), blocks.size(), offset);
blocks.add(block);
return block;
}
public static void connect(BlockNode from, BlockNode to) {
if (!from.getSuccessors().contains(to)) {
from.getSuccessors().add(to);
}
if (!to.getPredecessors().contains(from)) {
to.getPredecessors().add(from);
}
}
public static void removeConnection(BlockNode from, BlockNode to) {
from.getSuccessors().remove(to);
to.getPredecessors().remove(from);
}
public static void removePredecessors(BlockNode block) {
for (BlockNode pred : block.getPredecessors()) {
pred.getSuccessors().remove(block);
}
block.getPredecessors().clear();
}
public static void replaceConnection(BlockNode source, BlockNode oldDest, BlockNode newDest) {
removeConnection(source, oldDest);
connect(source, newDest);
replaceTarget(source, oldDest, newDest);
}
static BlockNode insertBlockBetween(MethodNode mth, BlockNode source, BlockNode target) {
BlockNode newBlock = startNewBlock(mth, target.getStartOffset());
newBlock.add(AFlag.SYNTHETIC);
removeConnection(source, target);
connect(source, newBlock);
connect(newBlock, target);
replaceTarget(source, target, newBlock);
source.updateCleanSuccessors();
newBlock.updateCleanSuccessors();
return newBlock;
}
static BlockNode blockSplitTop(MethodNode mth, BlockNode block) {
BlockNode newBlock = startNewBlock(mth, block.getStartOffset());
for (BlockNode pred : new ArrayList<>(block.getPredecessors())) {
replaceConnection(pred, block, newBlock);
pred.updateCleanSuccessors();
}
connect(newBlock, block);
newBlock.updateCleanSuccessors();
return newBlock;
}
static void copyBlockData(BlockNode from, BlockNode to) {
List<InsnNode> toInsns = to.getInstructions();
for (InsnNode insn : from.getInstructions()) {
toInsns.add(insn.copyWithoutSsa());
}
to.copyAttributesFrom(from);
}
static List<BlockNode> copyBlocksTree(MethodNode mth, List<BlockNode> blocks) {
List<BlockNode> copyBlocks = new ArrayList<>(blocks.size());
Map<BlockNode, BlockNode> map = new HashMap<>();
for (BlockNode block : blocks) {
BlockNode newBlock = startNewBlock(mth, block.getStartOffset());
copyBlockData(block, newBlock);
copyBlocks.add(newBlock);
map.put(block, newBlock);
}
for (BlockNode block : blocks) {
BlockNode newBlock = getNewBlock(block, map);
for (BlockNode successor : block.getSuccessors()) {
BlockNode newSuccessor = getNewBlock(successor, map);
BlockSplitter.connect(newBlock, newSuccessor);
}
}
return copyBlocks;
}
private static BlockNode getNewBlock(BlockNode block, Map<BlockNode, BlockNode> map) {
BlockNode newBlock = map.get(block);
if (newBlock == null) {
throw new JadxRuntimeException("Copy blocks tree failed. Missing block for connection: " + block);
}
return newBlock;
}
static void replaceTarget(BlockNode source, BlockNode oldTarget, BlockNode newTarget) {
InsnNode lastInsn = BlockUtils.getLastInsn(source);
if (lastInsn instanceof TargetInsnNode) {
((TargetInsnNode) lastInsn).replaceTargetBlock(oldTarget, newTarget);
}
}
private static void setupConnectionsFromJumps(MethodNode mth, Map<Integer, BlockNode> blocksMap) {
for (BlockNode block : mth.getBasicBlocks()) {
for (InsnNode insn : block.getInstructions()) {
List<JumpInfo> jumps = insn.getAll(AType.JUMP);
for (JumpInfo jump : jumps) {
BlockNode srcBlock = getBlock(jump.getSrc(), blocksMap);
BlockNode thisBlock = getBlock(jump.getDest(), blocksMap);
connect(srcBlock, thisBlock);
}
}
}
}
/**
* Connect exception handlers to the throw block.
* This temporary connection is necessary to build close to a final dominator tree.
* Will be used and removed in {@code jadx.core.dex.visitors.blocks.BlockExceptionHandler}
*/
private static void addTempConnectionsForExcHandlers(MethodNode mth, Map<Integer, BlockNode> blocksMap) {
if (mth.isNoExceptionHandlers()) {
return;
}
for (BlockNode block : mth.getBasicBlocks()) {
for (InsnNode insn : block.getInstructions()) {
CatchAttr catchAttr = insn.get(AType.EXC_CATCH);
if (catchAttr == null) {
continue;
}
for (ExceptionHandler handler : catchAttr.getHandlers()) {
BlockNode handlerBlock = getBlock(handler.getHandlerOffset(), blocksMap);
if (!handlerBlock.contains(AType.TMP_EDGE)) {
List<BlockNode> preds = block.getPredecessors();
if (preds.isEmpty()) {
throw new JadxRuntimeException("Unexpected missing predecessor for block: " + block);
}
BlockNode start = preds.size() == 1 ? preds.get(0) : block;
if (!start.getSuccessors().contains(handlerBlock)) {
connect(start, handlerBlock);
handlerBlock.addAttr(new TmpEdgeAttr(start));
}
}
}
}
}
}
private static void setupExitConnections(MethodNode mth) {
BlockNode exitBlock = mth.getExitBlock();
for (BlockNode block : mth.getBasicBlocks()) {
if (block.getSuccessors().isEmpty() && block != exitBlock) {
connect(block, exitBlock);
if (BlockUtils.checkLastInsnType(block, InsnType.RETURN)) {
block.add(AFlag.RETURN);
}
}
}
}
private static boolean isSplitByJump(InsnNode prevInsn, InsnNode currentInsn) {
List<JumpInfo> pJumps = prevInsn.getAll(AType.JUMP);
for (JumpInfo jump : pJumps) {
if (jump.getSrc() == prevInsn.getOffset()) {
return true;
}
}
List<JumpInfo> cJumps = currentInsn.getAll(AType.JUMP);
for (JumpInfo jump : cJumps) {
if (jump.getDest() == currentInsn.getOffset()) {
return true;
}
}
return false;
}
private static boolean isDoWhile(Map<Integer, BlockNode> blocksMap, BlockNode curBlock, InsnNode insn) {
// split 'do-while' block (last instruction: 'if', target this block)
if (insn.getType() != InsnType.IF) {
return false;
}
IfNode ifs = (IfNode) insn;
BlockNode targetBlock = blocksMap.get(ifs.getTarget());
return targetBlock == curBlock;
}
private static BlockNode getBlock(int offset, Map<Integer, BlockNode> blocksMap) {
BlockNode block = blocksMap.get(offset);
if (block == null) {
throw new JadxRuntimeException("Missing block: " + offset);
}
return block;
}
private static void expandMoveMulti(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
List<InsnNode> insnsList = block.getInstructions();
int len = insnsList.size();
for (int i = 0; i < len; i++) {
InsnNode insn = insnsList.get(i);
if (insn.getType() == InsnType.MOVE_MULTI) {
int mvCount = insn.getArgsCount() / 2;
for (int j = 0; j < mvCount; j++) {
InsnNode mv = new InsnNode(InsnType.MOVE, 1);
int startArg = j * 2;
mv.setResult((RegisterArg) insn.getArg(startArg));
mv.addArg(insn.getArg(startArg + 1));
mv.copyAttributesFrom(insn);
if (j == 0) {
mv.setOffset(insn.getOffset());
insnsList.set(i, mv);
} else {
insnsList.add(i + j, mv);
}
}
i += mvCount - 1;
len = insnsList.size();
}
}
}
}
private static void removeJumpAttr(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
for (InsnNode insn : block.getInstructions()) {
insn.remove(AType.JUMP);
}
}
}
private static void removeInsns(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
block.getInstructions().removeIf(insn -> {
if (!insn.isAttrStorageEmpty()) {
return false;
}
InsnType insnType = insn.getType();
return insnType == InsnType.GOTO || insnType == InsnType.NOP;
});
}
}
public static void detachMarkedBlocks(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
if (block.contains(AFlag.REMOVE)) {
detachBlock(block);
}
}
}
static boolean removeEmptyDetachedBlocks(MethodNode mth) {
return mth.getBasicBlocks().removeIf(block -> block.getInstructions().isEmpty()
&& block.getPredecessors().isEmpty()
&& block.getSuccessors().isEmpty()
&& !block.contains(AFlag.MTH_ENTER_BLOCK)
&& !block.contains(AFlag.MTH_EXIT_BLOCK));
}
static boolean removeEmptyBlock(BlockNode block) {
if (canRemoveBlock(block)) {
if (block.getSuccessors().size() == 1) {
BlockNode successor = block.getSuccessors().get(0);
block.getPredecessors().forEach(pred -> {
pred.getSuccessors().remove(block);
BlockSplitter.connect(pred, successor);
BlockSplitter.replaceTarget(pred, block, successor);
pred.updateCleanSuccessors();
});
BlockSplitter.removeConnection(block, successor);
} else {
block.getPredecessors().forEach(pred -> {
pred.getSuccessors().remove(block);
pred.updateCleanSuccessors();
});
}
block.add(AFlag.REMOVE);
block.getSuccessors().clear();
block.getPredecessors().clear();
return true;
}
return false;
}
private static boolean canRemoveBlock(BlockNode block) {
return block.getInstructions().isEmpty()
&& block.isAttrStorageEmpty()
&& block.getSuccessors().size() <= 1
&& !block.getPredecessors().isEmpty()
&& !block.contains(AFlag.MTH_ENTER_BLOCK)
&& !block.contains(AFlag.MTH_EXIT_BLOCK)
&& !block.getSuccessors().contains(block); // no self loop
}
static void collectSuccessors(BlockNode startBlock, BlockNode methodEnterBlock, Set<BlockNode> toRemove) {
Deque<BlockNode> stack = new ArrayDeque<>();
stack.add(startBlock);
while (!stack.isEmpty()) {
BlockNode block = stack.pop();
if (!toRemove.contains(block)) {
toRemove.add(block);
for (BlockNode successor : block.getSuccessors()) {
if (successor != methodEnterBlock && toRemove.containsAll(successor.getPredecessors())) {
stack.push(successor);
}
}
}
}
}
static void detachBlock(BlockNode block) {
for (BlockNode pred : block.getPredecessors()) {
pred.getSuccessors().remove(block);
pred.updateCleanSuccessors();
}
for (BlockNode successor : block.getSuccessors()) {
successor.getPredecessors().remove(block);
}
block.add(AFlag.REMOVE);
block.getPredecessors().clear();
block.getSuccessors().clear();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/blocks/ResolveJavaJSR.java | jadx-core/src/main/java/jadx/core/dex/visitors/blocks/ResolveJavaJSR.java | package jadx.core.dex.visitors.blocks;
import java.util.ArrayList;
import java.util.List;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.ListUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
/**
* Duplicate code to resolve java jsr/ret.
* JSR (jump subroutine) allows executing the same code from different places.
* Used mostly for 'finally' blocks, deprecated in Java 7.
*/
public class ResolveJavaJSR {
public static void process(MethodNode mth) {
int blocksCount = mth.getBasicBlocks().size();
int k = 0;
while (true) {
boolean changed = resolve(mth);
if (!changed) {
break;
}
if (k++ > blocksCount) {
throw new JadxRuntimeException("Fail to resolve jsr instructions");
}
}
}
private static boolean resolve(MethodNode mth) {
List<BlockNode> blocks = mth.getBasicBlocks();
int blocksCount = blocks.size();
for (BlockNode block : blocks) {
if (BlockUtils.checkLastInsnType(block, InsnType.JAVA_RET)) {
resolveForRetBlock(mth, block);
if (blocksCount != mth.getBasicBlocks().size()) {
return true;
}
}
}
return false;
}
private static void resolveForRetBlock(MethodNode mth, BlockNode retBlock) {
BlockUtils.visitPredecessorsUntil(mth, retBlock, startBlock -> {
List<BlockNode> preds = startBlock.getPredecessors();
if (preds.size() > 1
&& preds.stream().allMatch(p -> BlockUtils.checkLastInsnType(p, InsnType.JAVA_JSR))) {
List<BlockNode> jsrBlocks = new ArrayList<>(preds);
List<BlockNode> dupBlocks = BlockUtils.collectAllSuccessors(mth, startBlock, false);
removeInsns(retBlock, startBlock, jsrBlocks);
processBlocks(mth, retBlock, startBlock, jsrBlocks, dupBlocks);
return true;
}
return false;
});
}
private static void removeInsns(BlockNode retBlock, BlockNode startBlock, List<BlockNode> jsrBlocks) {
InsnNode retInsn = ListUtils.removeLast(retBlock.getInstructions());
if (retInsn != null && retInsn.getType() == InsnType.JAVA_RET) {
InsnArg retArg = retInsn.getArg(0);
if (retArg.isRegister()) {
int regNum = ((RegisterArg) retArg).getRegNum();
InsnNode startInsn = BlockUtils.getFirstInsn(startBlock);
if (startInsn != null
&& startInsn.getType() == InsnType.MOVE
&& startInsn.getResult().getRegNum() == regNum) {
startBlock.getInstructions().remove(0);
}
}
}
jsrBlocks.forEach(p -> ListUtils.removeLast(p.getInstructions()));
}
private static void processBlocks(MethodNode mth, BlockNode retBlock, BlockNode startBlock,
List<BlockNode> jsrBlocks, List<BlockNode> dupBlocks) {
BlockNode first = null;
for (BlockNode jsrBlock : jsrBlocks) {
if (first == null) {
first = jsrBlock;
} else {
BlockNode pathBlock = BlockUtils.selectOther(startBlock, jsrBlock.getSuccessors());
BlockSplitter.removeConnection(jsrBlock, startBlock);
BlockSplitter.removeConnection(jsrBlock, pathBlock);
List<BlockNode> newBlocks = BlockSplitter.copyBlocksTree(mth, dupBlocks);
BlockNode newStart = newBlocks.get(dupBlocks.indexOf(startBlock));
BlockNode newRetBlock = newBlocks.get(dupBlocks.indexOf(retBlock));
BlockSplitter.connect(jsrBlock, newStart);
BlockSplitter.connect(newRetBlock, pathBlock);
}
}
if (first != null) {
BlockNode pathBlock = BlockUtils.selectOther(startBlock, first.getSuccessors());
BlockSplitter.removeConnection(first, pathBlock);
BlockSplitter.connect(retBlock, pathBlock);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/blocks/BlockFinisher.java | jadx-core/src/main/java/jadx/core/dex/visitors/blocks/BlockFinisher.java | package jadx.core.dex.visitors.blocks;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.AbstractVisitor;
public class BlockFinisher extends AbstractVisitor {
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode() || mth.getBasicBlocks().isEmpty()) {
return;
}
if (!mth.contains(AFlag.DISABLE_BLOCKS_LOCK)) {
mth.finishBasicBlocks();
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/blocks/PostDominatorTree.java | jadx-core/src/main/java/jadx/core/dex/visitors/blocks/PostDominatorTree.java | package jadx.core.dex.visitors.blocks;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.EmptyBitSet;
public class PostDominatorTree {
public static void compute(MethodNode mth) {
if (!mth.contains(AFlag.COMPUTE_POST_DOM)) {
return;
}
try {
int mthBlocksCount = mth.getBasicBlocks().size();
List<BlockNode> sorted = new ArrayList<>(mthBlocksCount);
BlockUtils.visitReverseDFS(mth, sorted::add);
// temporary set block positions to match reverse sorted order
// save old positions for later remapping
int blocksCount = sorted.size();
int[] posMapping = new int[mthBlocksCount];
for (int i = 0; i < blocksCount; i++) {
posMapping[i] = sorted.get(i).getPos();
}
BlockNode.updateBlockPositions(sorted);
BlockNode[] postDoms = DominatorTree.build(sorted, BlockNode::getSuccessors);
BlockNode firstBlock = sorted.get(0);
firstBlock.setPostDoms(EmptyBitSet.EMPTY);
firstBlock.setIPostDom(null);
for (int i = 1; i < blocksCount; i++) {
BlockNode block = sorted.get(i);
BlockNode iPostDom = postDoms[i];
block.setIPostDom(iPostDom);
BitSet postDomBS = DominatorTree.collectDoms(postDoms, iPostDom);
block.setPostDoms(postDomBS);
}
for (int i = 1; i < blocksCount; i++) {
BlockNode block = sorted.get(i);
BitSet bs = new BitSet(blocksCount);
block.getPostDoms().stream().forEach(n -> bs.set(posMapping[n]));
bs.clear(posMapping[i]);
block.setPostDoms(bs);
}
// check for missing blocks in 'sorted' list
// can be caused by infinite loops
int blocksDelta = mthBlocksCount - blocksCount;
if (blocksDelta != 0) {
int insnsCount = 0;
for (BlockNode block : mth.getBasicBlocks()) {
if (block.getPostDoms() == null) {
block.setPostDoms(EmptyBitSet.EMPTY);
block.setIPostDom(null);
insnsCount += block.getInstructions().size();
}
}
mth.addInfoComment("Infinite loop detected, blocks: " + blocksDelta + ", insns: " + insnsCount);
}
} catch (StackOverflowError | Exception e) {
// show error as a warning because this info not always used
mth.addWarnComment("Failed to build post-dominance tree", e);
} finally {
// revert block positions change
mth.updateBlockPositions();
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/blocks/DominatorTree.java | jadx-core/src/main/java/jadx/core/dex/visitors/blocks/DominatorTree.java | package jadx.core.dex.visitors.blocks;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.function.Function;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.EmptyBitSet;
import jadx.core.utils.exceptions.JadxRuntimeException;
/**
* Build dominator tree based on the algorithm described in paper:
* Cooper, Keith D.; Harvey, Timothy J; Kennedy, Ken (2001).
* "A Simple, Fast Dominance Algorithm"
* http://www.hipersoft.rice.edu/grads/publications/dom14.pdf
*/
@SuppressWarnings("JavadocLinkAsPlainText")
public class DominatorTree {
public static void compute(MethodNode mth) {
List<BlockNode> sorted = sortBlocks(mth);
BlockNode[] doms = build(sorted, BlockNode::getPredecessors);
apply(sorted, doms);
}
private static List<BlockNode> sortBlocks(MethodNode mth) {
int blocksCount = mth.getBasicBlocks().size();
List<BlockNode> sorted = new ArrayList<>(blocksCount);
BlockUtils.visitDFS(mth, sorted::add);
if (sorted.size() != blocksCount) {
throw new JadxRuntimeException("Found unreachable blocks");
}
mth.setBasicBlocks(sorted);
return sorted;
}
static BlockNode[] build(List<BlockNode> sorted, Function<BlockNode, List<BlockNode>> predFunc) {
int blocksCount = sorted.size();
BlockNode[] doms = new BlockNode[blocksCount];
doms[0] = sorted.get(0);
boolean changed = true;
while (changed) {
changed = false;
for (int blockId = 1; blockId < blocksCount; blockId++) {
BlockNode b = sorted.get(blockId);
List<BlockNode> preds = predFunc.apply(b);
int pickedPred = -1;
BlockNode newIDom = null;
for (BlockNode pred : preds) {
int id = pred.getId();
if (doms[id] != null) {
newIDom = pred;
pickedPred = id;
break;
}
}
if (newIDom == null) {
throw new JadxRuntimeException("No immediate dominator for block: " + b);
}
for (BlockNode predBlock : preds) {
int predId = predBlock.getId();
if (predId == pickedPred) {
continue;
}
if (doms[predId] != null) {
newIDom = intersect(sorted, doms, predBlock, newIDom);
}
}
if (doms[blockId] != newIDom) {
doms[blockId] = newIDom;
changed = true;
}
}
}
return doms;
}
private static BlockNode intersect(List<BlockNode> sorted, BlockNode[] doms, BlockNode b1, BlockNode b2) {
int f1 = b1.getId();
int f2 = b2.getId();
while (f1 != f2) {
while (f1 > f2) {
f1 = doms[f1].getId();
}
while (f2 > f1) {
f2 = doms[f2].getId();
}
}
return sorted.get(f1);
}
private static void apply(List<BlockNode> sorted, BlockNode[] doms) {
BlockNode enterBlock = sorted.get(0);
enterBlock.setDoms(EmptyBitSet.EMPTY);
enterBlock.setIDom(null);
int blocksCount = sorted.size();
for (int i = 1; i < blocksCount; i++) {
BlockNode block = sorted.get(i);
BlockNode idom = doms[i];
block.setIDom(idom);
idom.addDominatesOn(block);
BitSet domBS = collectDoms(doms, idom);
domBS.clear(i);
block.setDoms(domBS);
}
}
static BitSet collectDoms(BlockNode[] doms, BlockNode idom) {
BitSet domBS = new BitSet(doms.length);
BlockNode nextIDom = idom;
while (true) {
int id = nextIDom.getId();
if (domBS.get(id)) {
break;
}
domBS.set(id);
BitSet curDoms = nextIDom.getDoms();
if (curDoms != null) {
// use already collected set
domBS.or(curDoms);
break;
}
nextIDom = doms[id];
}
return domBS;
}
public static void computeDominanceFrontier(MethodNode mth) {
List<BlockNode> blocks = mth.getBasicBlocks();
for (BlockNode block : blocks) {
block.setDomFrontier(null);
}
int blocksCount = blocks.size();
for (BlockNode block : blocks) {
List<BlockNode> preds = block.getPredecessors();
if (preds.size() >= 2) {
BlockNode idom = block.getIDom();
for (BlockNode pred : preds) {
BlockNode runner = pred;
while (runner != idom) {
addToDF(runner, block, blocksCount);
runner = runner.getIDom();
}
}
}
}
for (BlockNode block : blocks) {
BitSet df = block.getDomFrontier();
if (df == null || df.isEmpty()) {
block.setDomFrontier(EmptyBitSet.EMPTY);
}
}
}
private static void addToDF(BlockNode block, BlockNode dfBlock, int blocksCount) {
BitSet df = block.getDomFrontier();
if (df == null) {
df = new BitSet(blocksCount);
block.setDomFrontier(df);
}
df.set(dfBlock.getId());
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/kotlin/ProcessKotlinInternals.java | jadx-core/src/main/java/jadx/core/dex/visitors/kotlin/ProcessKotlinInternals.java | package jadx.core.dex.visitors.kotlin;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.JadxArgs.UseKotlinMethodsForVarNames;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.core.deobf.NameMapper;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.ConstStringNode;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.InitCodeVariables;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.debuginfo.DebugInfoApplyVisitor;
import jadx.core.dex.visitors.rename.CodeRenameVisitor;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "ProcessKotlinInternals",
desc = "Use variable names from Kotlin intrinsic1 methods",
runAfter = {
InitCodeVariables.class,
DebugInfoApplyVisitor.class
},
runBefore = {
CodeRenameVisitor.class
}
)
public class ProcessKotlinInternals extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(ProcessKotlinInternals.class);
private static final String KOTLIN_INTERNAL_PKG = "kotlin.jvm.internal.";
private static final String KOTLIN_INTRINSICS_CLS_SHORT_NAME = "Intrinsics";
private static final String KOTLIN_INTRINSICS_CLS = KOTLIN_INTERNAL_PKG + KOTLIN_INTRINSICS_CLS_SHORT_NAME;
private static final String KOTLIN_VARNAME_SOURCE_MTH1 = "(Ljava/lang/Object;Ljava/lang/String;)V";
private static final String KOTLIN_VARNAME_SOURCE_MTH2 = "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)V";
private @Nullable ClassInfo kotlinIntrinsicsCls;
private Set<MethodInfo> kotlinVarNameSourceMethods;
private boolean hideInsns;
@Override
public void init(RootNode root) throws JadxException {
ClassNode kotlinCls = searchKotlinIntrinsicsClass(root);
if (kotlinCls != null) {
kotlinIntrinsicsCls = kotlinCls.getClassInfo();
kotlinVarNameSourceMethods = collectMethods(kotlinCls);
LOG.debug("Kotlin Intrinsics class: {}, methods: {}", kotlinCls, kotlinVarNameSourceMethods.size());
} else {
kotlinIntrinsicsCls = null;
LOG.debug("Kotlin Intrinsics class not found");
}
hideInsns = root.getArgs().getUseKotlinMethodsForVarNames() == UseKotlinMethodsForVarNames.APPLY_AND_HIDE;
}
@Override
public boolean visit(ClassNode cls) {
if (kotlinIntrinsicsCls == null) {
return false;
}
for (MethodNode mth : cls.getMethods()) {
processMth(mth);
}
return true;
}
private void processMth(MethodNode mth) {
if (mth.isNoCode() || mth.contains(AType.JADX_ERROR)) {
return;
}
for (BlockNode block : mth.getBasicBlocks()) {
for (InsnNode insn : block.getInstructions()) {
if (insn.getType() == InsnType.INVOKE) {
try {
processInvoke(mth, insn);
} catch (Exception e) {
mth.addWarnComment("Failed to extract var names", e);
}
}
}
}
}
private void processInvoke(MethodNode mth, InsnNode insn) {
int argsCount = insn.getArgsCount();
if (argsCount < 2) {
return;
}
MethodInfo invokeMth = ((InvokeNode) insn).getCallMth();
if (!kotlinVarNameSourceMethods.contains(invokeMth)) {
return;
}
InsnArg firstArg = insn.getArg(0);
if (!firstArg.isRegister()) {
return;
}
RegisterArg varArg = (RegisterArg) firstArg;
boolean renamed = false;
if (argsCount == 2) {
String str = getConstString(mth, insn, 1);
if (str != null) {
renamed = checkAndRename(varArg, str);
}
} else if (argsCount == 3) {
// TODO: use second arg for rename class
String str = getConstString(mth, insn, 2);
if (str != null) {
renamed = checkAndRename(varArg, str);
}
}
if (renamed && hideInsns) {
insn.add(AFlag.DONT_GENERATE);
}
}
private boolean checkAndRename(RegisterArg arg, String str) {
String name = trimName(str);
if (NameMapper.isValidAndPrintable(name)) {
arg.getSVar().getCodeVar().setName(name);
return true;
}
return false;
}
@Nullable
private String getConstString(MethodNode mth, InsnNode insn, int arg) {
InsnArg strArg = insn.getArg(arg);
if (!strArg.isInsnWrap()) {
return null;
}
InsnNode constInsn = ((InsnWrapArg) strArg).getWrapInsn();
InsnType insnType = constInsn.getType();
if (insnType == InsnType.CONST_STR) {
return ((ConstStringNode) constInsn).getString();
}
if (insnType == InsnType.SGET) {
// revert const field inline :(
FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) constInsn).getIndex();
FieldNode fieldNode = mth.root().resolveField(fieldInfo);
if (fieldNode != null) {
String str = (String) fieldNode.get(JadxAttrType.CONSTANT_VALUE).getValue();
InsnArg newArg = InsnArg.wrapArg(new ConstStringNode(str));
insn.replaceArg(strArg, newArg);
return str;
}
}
return null;
}
private String trimName(String str) {
if (str.startsWith("$this$")) {
return str.substring(6);
}
if (str.startsWith("$")) {
return str.substring(1);
}
return str;
}
@Nullable
private static ClassNode searchKotlinIntrinsicsClass(RootNode root) {
ClassNode kotlinCls = root.resolveClass(KOTLIN_INTRINSICS_CLS);
if (kotlinCls != null) {
return kotlinCls;
}
List<ClassNode> candidates = new ArrayList<>();
for (ClassNode cls : root.getClasses()) {
if (isKotlinIntrinsicsClass(cls)) {
candidates.add(cls);
}
}
return Utils.getOne(candidates);
}
private static boolean isKotlinIntrinsicsClass(ClassNode cls) {
ClassInfo clsInfo = cls.getClassInfo();
if (clsInfo.getAliasShortName().equals(KOTLIN_INTRINSICS_CLS_SHORT_NAME)
&& clsInfo.getAliasFullName().equals(KOTLIN_INTRINSICS_CLS)) {
return true;
}
if (!clsInfo.getFullName().startsWith(KOTLIN_INTERNAL_PKG)) {
return false;
}
if (cls.getMethods().size() < 5) {
return false;
}
int mthCount = 0;
for (MethodNode mth : cls.getMethods()) {
if (mth.getAccessFlags().isStatic()
&& mth.getMethodInfo().getShortId().endsWith(KOTLIN_VARNAME_SOURCE_MTH1)) {
mthCount++;
}
}
return mthCount > 2;
}
private Set<MethodInfo> collectMethods(ClassNode kotlinCls) {
Set<MethodInfo> set = new HashSet<>();
for (MethodNode mth : kotlinCls.getMethods()) {
if (!mth.getAccessFlags().isStatic()) {
continue;
}
String shortId = mth.getMethodInfo().getShortId();
if (shortId.endsWith(KOTLIN_VARNAME_SOURCE_MTH1) || shortId.endsWith(KOTLIN_VARNAME_SOURCE_MTH2)) {
set.add(mth.getMethodInfo());
}
}
return set;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/debuginfo/DebugInfoAttachVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/debuginfo/DebugInfoAttachVisitor.java | package jadx.core.dex.visitors.debuginfo;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import jadx.api.plugins.input.data.IDebugInfo;
import jadx.api.plugins.input.data.ILocalVar;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.nodes.LocalVarsDebugInfoAttr;
import jadx.core.dex.attributes.nodes.RegDebugInfoAttr;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.parser.SignatureParser;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.blocks.BlockSplitter;
import jadx.core.dex.visitors.ssa.SSATransform;
import jadx.core.utils.exceptions.InvalidDataException;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "Debug Info Parser",
desc = "Attach debug information (variable names and types, instruction lines)",
runBefore = {
BlockSplitter.class,
SSATransform.class
}
)
public class DebugInfoAttachVisitor extends AbstractVisitor {
@Override
public void visit(MethodNode mth) throws JadxException {
try {
IDebugInfo debugInfo = mth.getDebugInfo();
if (debugInfo != null) {
processDebugInfo(mth, debugInfo);
}
} catch (InvalidDataException e) {
mth.addWarnComment(e.getMessage());
} catch (Exception e) {
mth.addWarnComment("Failed to parse debug info", e);
}
}
private void processDebugInfo(MethodNode mth, IDebugInfo debugInfo) {
InsnNode[] insnArr = mth.getInstructions();
attachSourceLines(mth, debugInfo.getSourceLineMapping(), insnArr);
attachDebugInfo(mth, debugInfo.getLocalVars(), insnArr);
setMethodSourceLine(mth, insnArr);
}
private void attachSourceLines(MethodNode mth, Map<Integer, Integer> lineMapping, InsnNode[] insnArr) {
if (lineMapping.isEmpty()) {
return;
}
for (Map.Entry<Integer, Integer> entry : lineMapping.entrySet()) {
try {
InsnNode insn = insnArr[entry.getKey()];
if (insn != null) {
insn.setSourceLine(entry.getValue());
}
} catch (Exception e) {
mth.addWarnComment("Error attach source line", e);
return;
}
}
String ignoreReason = verifyDebugLines(lineMapping);
if (ignoreReason != null) {
mth.addDebugComment("Don't trust debug lines info. " + ignoreReason);
} else {
mth.add(AFlag.USE_LINES_HINTS);
}
}
private String verifyDebugLines(Map<Integer, Integer> lineMapping) {
// search min line in method
int minLine = lineMapping.values().stream().mapToInt(v -> v).min().orElse(Integer.MAX_VALUE);
if (minLine < 3) {
return "Lines numbers was adjusted: min line is " + minLine;
}
// count repeating lines
// 3 here is allowed maximum for line repeat count
// can occur in indexed 'for' loops (3 instructions with the same line)
var repeatingLines = lineMapping.values().stream()
.collect(Collectors.toMap(l -> l, l -> 1, Integer::sum))
.entrySet().stream()
.filter(p -> p.getValue() > 3)
.collect(Collectors.toList());
if (!repeatingLines.isEmpty()) {
return "Repeating lines: " + repeatingLines;
}
return null;
}
private void attachDebugInfo(MethodNode mth, List<ILocalVar> localVars, InsnNode[] insnArr) {
if (localVars.isEmpty()) {
return;
}
for (ILocalVar var : localVars) {
int regNum = var.getRegNum();
int start = var.getStartOffset();
int end = var.getEndOffset();
ArgType type = getVarType(mth, var);
RegDebugInfoAttr debugInfoAttr = new RegDebugInfoAttr(type, var.getName());
if (start <= 0) {
// attach to method arguments
RegisterArg thisArg = mth.getThisArg();
if (thisArg != null) {
attachDebugInfo(thisArg, debugInfoAttr, regNum);
}
for (RegisterArg arg : mth.getArgRegs()) {
attachDebugInfo(arg, debugInfoAttr, regNum);
}
start = 0;
}
for (int i = start; i <= end; i++) {
InsnNode insn = insnArr[i];
if (insn == null) {
continue;
}
int count = 0;
for (InsnArg arg : insn.getArguments()) {
count += attachDebugInfo(arg, debugInfoAttr, regNum);
}
if (count != 0) {
// don't apply same info for result if applied to args
continue;
}
attachDebugInfo(insn.getResult(), debugInfoAttr, regNum);
}
}
mth.addAttr(new LocalVarsDebugInfoAttr(localVars));
}
private int attachDebugInfo(InsnArg arg, RegDebugInfoAttr debugInfoAttr, int regNum) {
if (arg instanceof RegisterArg) {
RegisterArg reg = (RegisterArg) arg;
if (regNum == reg.getRegNum()) {
reg.addAttr(debugInfoAttr);
return 1;
}
}
return 0;
}
public static ArgType getVarType(MethodNode mth, ILocalVar var) {
ArgType type = ArgType.parse(var.getType());
String sign = var.getSignature();
if (sign == null) {
return type;
}
try {
ArgType gType = new SignatureParser(sign).consumeType();
ArgType expandedType = mth.root().getTypeUtils().expandTypeVariables(mth, gType);
if (checkSignature(mth, type, expandedType)) {
return expandedType;
}
} catch (Exception e) {
mth.addWarnComment("Can't parse signature for local variable: " + sign, e);
}
return type;
}
private static boolean checkSignature(MethodNode mth, ArgType type, ArgType gType) {
boolean apply;
ArgType el = gType.getArrayRootElement();
if (el.isGeneric()) {
if (!type.getArrayRootElement().getObject().equals(el.getObject())) {
mth.addWarnComment("Generic types in debug info not equals: " + type + " != " + gType);
}
apply = true;
} else {
apply = el.isGenericType();
}
return apply;
}
/**
* Set method source line from first instruction
*/
private void setMethodSourceLine(MethodNode mth, InsnNode[] insnArr) {
for (InsnNode insn : insnArr) {
if (insn != null) {
int line = insn.getSourceLine();
if (line != 0) {
mth.setSourceLine(line - 1);
return;
}
}
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/debuginfo/DebugInfoApplyVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/debuginfo/DebugInfoApplyVisitor.java | package jadx.core.dex.visitors.debuginfo;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.OptionalInt;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.api.plugins.input.data.ILocalVar;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.api.plugins.input.data.attributes.types.MethodParametersAttr;
import jadx.core.Consts;
import jadx.core.deobf.NameMapper;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.LocalVarsDebugInfoAttr;
import jadx.core.dex.attributes.nodes.RegDebugInfoAttr;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.CodeVar;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.Named;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.ssa.SSATransform;
import jadx.core.dex.visitors.typeinference.TypeInferenceVisitor;
import jadx.core.dex.visitors.typeinference.TypeUpdateResult;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "Debug Info Apply",
desc = "Apply debug info to registers (type and names)",
runAfter = {
SSATransform.class,
TypeInferenceVisitor.class
}
)
public class DebugInfoApplyVisitor extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(DebugInfoApplyVisitor.class);
@Override
public void visit(MethodNode mth) throws JadxException {
try {
if (mth.contains(AType.LOCAL_VARS_DEBUG_INFO)) {
applyDebugInfo(mth);
mth.remove(AType.LOCAL_VARS_DEBUG_INFO);
}
processMethodParametersAttribute(mth);
} catch (Exception e) {
mth.addWarnComment("Failed to apply debug info", e);
}
}
private static void applyDebugInfo(MethodNode mth) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.info("Apply debug info for method: {}", mth);
}
mth.getSVars().forEach(ssaVar -> searchAndApplyVarDebugInfo(mth, ssaVar));
fixLinesForReturn(mth);
fixNamesForPhiInsns(mth);
}
private static void searchAndApplyVarDebugInfo(MethodNode mth, SSAVar ssaVar) {
if (applyDebugInfo(mth, ssaVar, ssaVar.getAssign())) {
return;
}
for (RegisterArg useArg : ssaVar.getUseList()) {
if (applyDebugInfo(mth, ssaVar, useArg)) {
return;
}
}
searchDebugInfoByOffset(mth, ssaVar);
}
private static void searchDebugInfoByOffset(MethodNode mth, SSAVar ssaVar) {
LocalVarsDebugInfoAttr debugInfoAttr = mth.get(AType.LOCAL_VARS_DEBUG_INFO);
if (debugInfoAttr == null) {
return;
}
OptionalInt max = ssaVar.getUseList().stream().mapToInt(DebugInfoApplyVisitor::getInsnOffsetByArg).max();
if (max.isEmpty()) {
return;
}
int startOffset = getInsnOffsetByArg(ssaVar.getAssign());
int endOffset = max.getAsInt();
int regNum = ssaVar.getRegNum();
for (ILocalVar localVar : debugInfoAttr.getLocalVars()) {
if (localVar.getRegNum() == regNum) {
int startAddr = localVar.getStartOffset();
int endAddr = localVar.getEndOffset();
if (isInside(startOffset, startAddr, endAddr) || isInside(endOffset, startAddr, endAddr)) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Apply debug info by offset for: {} to {}", ssaVar, localVar);
}
ArgType type = DebugInfoAttachVisitor.getVarType(mth, localVar);
applyDebugInfo(mth, ssaVar, type, localVar.getName());
break;
}
}
}
}
private static boolean isInside(int var, int start, int end) {
return start <= var && var <= end;
}
private static int getInsnOffsetByArg(InsnArg arg) {
if (arg != null) {
InsnNode insn = arg.getParentInsn();
if (insn != null) {
return insn.getOffset();
}
}
return -1;
}
public static boolean applyDebugInfo(MethodNode mth, SSAVar ssaVar, RegisterArg arg) {
RegDebugInfoAttr debugInfoAttr = arg.get(AType.REG_DEBUG_INFO);
if (debugInfoAttr == null) {
return false;
}
return applyDebugInfo(mth, ssaVar, debugInfoAttr.getRegType(), debugInfoAttr.getName());
}
public static boolean applyDebugInfo(MethodNode mth, SSAVar ssaVar, ArgType type, String varName) {
TypeUpdateResult result = mth.root().getTypeUpdate().applyDebugInfo(mth, ssaVar, type);
if (result == TypeUpdateResult.REJECT) {
if (Consts.DEBUG_TYPE_INFERENCE) {
LOG.debug("Reject debug info of type: {} and name: '{}' for {}, mth: {}", type, varName, ssaVar, mth);
}
return false;
}
if (NameMapper.isValidAndPrintable(varName)) {
ssaVar.setName(varName);
}
return true;
}
/**
* Fix debug info for splitter 'return' instructions
*/
private static void fixLinesForReturn(MethodNode mth) {
if (mth.isVoidReturn()) {
return;
}
InsnNode origReturn = null;
List<InsnNode> newReturns = new ArrayList<>(mth.getPreExitBlocks().size());
for (BlockNode exit : mth.getPreExitBlocks()) {
InsnNode ret = BlockUtils.getLastInsn(exit);
if (ret != null) {
if (ret.contains(AFlag.ORIG_RETURN)) {
origReturn = ret;
} else {
newReturns.add(ret);
}
}
}
if (origReturn != null) {
for (InsnNode ret : newReturns) {
InsnArg oldArg = origReturn.getArg(0);
InsnArg newArg = ret.getArg(0);
if (oldArg.isRegister() && newArg.isRegister()) {
RegisterArg oldArgReg = (RegisterArg) oldArg;
RegisterArg newArgReg = (RegisterArg) newArg;
applyDebugInfo(mth, newArgReg.getSVar(), oldArgReg.getType(), oldArgReg.getName());
}
ret.setSourceLine(origReturn.getSourceLine());
}
}
}
private static void fixNamesForPhiInsns(MethodNode mth) {
mth.getSVars().forEach(ssaVar -> {
for (PhiInsn phiInsn : ssaVar.getUsedInPhi()) {
Set<String> names = new HashSet<>(1 + phiInsn.getArgsCount());
addArgName(phiInsn.getResult(), names);
phiInsn.getArguments().forEach(arg -> addArgName(arg, names));
if (names.size() == 1) {
setNameForInsn(phiInsn, names.iterator().next());
} else if (names.size() > 1) {
mth.addDebugComment("Different variable names in phi insn: " + names + ", use first");
setNameForInsn(phiInsn, names.iterator().next());
}
}
});
}
private static void addArgName(InsnArg arg, Set<String> names) {
if (arg instanceof Named) {
String name = ((Named) arg).getName();
if (name != null) {
names.add(name);
}
}
}
private static void setNameForInsn(PhiInsn phiInsn, String name) {
phiInsn.getResult().setName(name);
phiInsn.getArguments().forEach(arg -> {
if (arg instanceof Named) {
((Named) arg).setName(name);
}
});
}
private void processMethodParametersAttribute(MethodNode mth) {
MethodParametersAttr parametersAttr = mth.get(JadxAttrType.METHOD_PARAMETERS);
if (parametersAttr == null) {
return;
}
try {
List<MethodParametersAttr.Info> params = parametersAttr.getList();
if (params.size() != mth.getMethodInfo().getArgsCount()) {
return;
}
int i = 0;
for (RegisterArg mthArg : mth.getArgRegs()) {
MethodParametersAttr.Info paramInfo = params.get(i++);
String name = paramInfo.getName();
if (NameMapper.isValidAndPrintable(name)) {
CodeVar codeVar = mthArg.getSVar().getCodeVar();
codeVar.setName(name);
if (AccessFlags.hasFlag(paramInfo.getAccFlags(), AccessFlags.FINAL)) {
codeVar.setFinal(true);
}
}
}
} catch (Exception e) {
mth.addWarnComment("Failed to process method parameters attribute: " + parametersAttr.getList(), e);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/gradle/NonFinalResIdsVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/gradle/NonFinalResIdsVisitor.java | package jadx.core.dex.visitors.gradle;
import java.util.Map;
import jadx.api.plugins.input.data.annotations.AnnotationVisibility;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.api.plugins.input.data.annotations.IAnnotation;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.api.plugins.input.data.attributes.types.AnnotationsAttr;
import jadx.core.dex.attributes.nodes.CodeFeaturesAttr;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.IFieldInfoRef;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.regions.SwitchRegion;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.FixSwitchOverEnum;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.regions.DepthRegionTraversal;
import jadx.core.dex.visitors.regions.IRegionIterativeVisitor;
import jadx.core.export.GradleInfoStorage;
import jadx.core.utils.android.AndroidResourcesUtils;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "NonFinalResIdsVisitor",
desc = "Detect usage of android resource constants in cases where constant expressions are required.",
runAfter = FixSwitchOverEnum.class
)
public class NonFinalResIdsVisitor extends AbstractVisitor implements IRegionIterativeVisitor {
private boolean nonFinalResIdsFlagRequired = false;
private GradleInfoStorage gradleInfoStorage;
public void init(RootNode root) throws JadxException {
gradleInfoStorage = root.getGradleInfoStorage();
}
@Override
public boolean visit(ClassNode cls) throws JadxException {
if (nonFinalResIdsFlagRequired) {
return false;
}
AnnotationsAttr annotationsList = cls.get(JadxAttrType.ANNOTATION_LIST);
if (visitAnnotationList(annotationsList)) {
return false;
}
return super.visit(cls);
}
private static boolean isCustomResourceClass(ClassInfo cls) {
ClassInfo parentClass = cls.getParentClass();
return parentClass != null && parentClass.getShortName().equals("R") && !parentClass.getFullName().equals("android.R");
}
@Override
public void visit(MethodNode mth) throws JadxException {
AnnotationsAttr annotationsList = mth.get(JadxAttrType.ANNOTATION_LIST);
if (visitAnnotationList(annotationsList)) {
nonFinalResIdsFlagRequired = true;
return;
}
if (nonFinalResIdsFlagRequired || !CodeFeaturesAttr.contains(mth, CodeFeaturesAttr.CodeFeature.SWITCH)) {
return;
}
DepthRegionTraversal.traverseIterative(mth, this);
}
private boolean visitAnnotationList(AnnotationsAttr annotationsList) {
if (annotationsList != null) {
for (IAnnotation annotation : annotationsList.getAll()) {
if (annotation.getVisibility() == AnnotationVisibility.SYSTEM) {
continue;
}
for (Map.Entry<String, EncodedValue> entry : annotation.getValues().entrySet()) {
Object value = entry.getValue().getValue();
if (value instanceof IFieldInfoRef && isCustomResourceClass(((IFieldInfoRef) value).getFieldInfo().getDeclClass())) {
gradleInfoStorage.setNonFinalResIds(true);
return true;
}
}
}
}
return false;
}
@Override
public boolean visitRegion(MethodNode mth, IRegion region) {
if (nonFinalResIdsFlagRequired) {
return false;
}
if (region instanceof SwitchRegion) {
return detectSwitchOverResIds((SwitchRegion) region);
}
return false;
}
private boolean detectSwitchOverResIds(SwitchRegion switchRegion) {
for (SwitchRegion.CaseInfo caseInfo : switchRegion.getCases()) {
for (Object key : caseInfo.getKeys()) {
if (key instanceof FieldNode) {
ClassNode topParentClass = ((FieldNode) key).getTopParentClass();
if (AndroidResourcesUtils.isResourceClass(topParentClass) && !"android.R".equals(topParentClass.getFullName())) {
this.nonFinalResIdsFlagRequired = true;
gradleInfoStorage.setNonFinalResIds(true);
return false;
}
}
}
}
return false;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/shrink/WrapInfo.java | jadx-core/src/main/java/jadx/core/dex/visitors/shrink/WrapInfo.java | package jadx.core.dex.visitors.shrink;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.nodes.InsnNode;
final class WrapInfo {
private final InsnNode insn;
private final RegisterArg arg;
WrapInfo(InsnNode assignInsn, RegisterArg arg) {
this.insn = assignInsn;
this.arg = arg;
}
InsnNode getInsn() {
return insn;
}
RegisterArg getArg() {
return arg;
}
@Override
public String toString() {
return "WrapInfo: " + arg + " -> " + insn;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/shrink/CodeShrinkVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/shrink/CodeShrinkVisitor.java | package jadx.core.dex.visitors.shrink;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.InvokeCustomNode;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.Named;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.ModVisitor;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnList;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
@JadxVisitor(
name = "CodeShrinkVisitor",
desc = "Inline variables to make code smaller",
runAfter = { ModVisitor.class }
)
public class CodeShrinkVisitor extends AbstractVisitor {
@Override
public void visit(MethodNode mth) {
shrinkMethod(mth);
}
public static void shrinkMethod(MethodNode mth) {
if (mth.isNoCode()) {
return;
}
mth.remove(AFlag.REQUEST_CODE_SHRINK);
for (BlockNode block : mth.getBasicBlocks()) {
shrinkBlock(mth, block);
simplifyMoveInsns(mth, block);
}
}
private static void shrinkBlock(MethodNode mth, BlockNode block) {
if (block.getInstructions().isEmpty()) {
return;
}
InsnList insnList = new InsnList(block.getInstructions());
int insnCount = insnList.size();
List<ArgsInfo> argsList = new ArrayList<>(insnCount);
for (int i = 0; i < insnCount; i++) {
argsList.add(new ArgsInfo(insnList.get(i), argsList, i));
}
List<WrapInfo> wrapList = new ArrayList<>();
for (ArgsInfo argsInfo : argsList) {
List<RegisterArg> args = argsInfo.getArgs();
for (int i = args.size() - 1; i >= 0; i--) {
RegisterArg arg = args.get(i);
checkInline(mth, block, insnList, wrapList, argsInfo, arg);
}
}
if (!wrapList.isEmpty()) {
for (WrapInfo wrapInfo : wrapList) {
inline(mth, wrapInfo.getArg(), wrapInfo.getInsn(), block);
}
}
}
private static void checkInline(MethodNode mth, BlockNode block, InsnList insnList,
List<WrapInfo> wrapList, ArgsInfo argsInfo, RegisterArg arg) {
if (arg.contains(AFlag.DONT_INLINE)
|| arg.getParentInsn() == null
|| arg.getParentInsn().contains(AFlag.DONT_GENERATE)) {
return;
}
SSAVar sVar = arg.getSVar();
if (sVar == null || sVar.getAssign().contains(AFlag.DONT_INLINE)) {
return;
}
InsnNode assignInsn = sVar.getAssign().getParentInsn();
if (assignInsn == null
|| assignInsn.contains(AFlag.DONT_INLINE)
|| assignInsn.contains(AFlag.WRAPPED)) {
return;
}
boolean assignInline = assignInsn.contains(AFlag.FORCE_ASSIGN_INLINE);
if (!assignInline && sVar.isUsedInPhi()) {
return;
}
// allow inline only one use arg
int useCount = 0;
for (RegisterArg useArg : sVar.getUseList()) {
InsnNode parentInsn = useArg.getParentInsn();
if (parentInsn != null && parentInsn.contains(AFlag.DONT_GENERATE)) {
continue;
}
if (!assignInline && useArg.contains(AFlag.DONT_INLINE_CONST)) {
return;
}
useCount++;
}
if (!assignInline && useCount != 1) {
return;
}
if (!assignInline && sVar.getName() != null) {
if (searchArgWithName(assignInsn, sVar.getName())) {
// allow inline if name is reused in result
} else if (varWithSameNameExists(mth, sVar)) {
// allow inline if var name is duplicated
} else {
// reject inline of named variable
return;
}
}
if (!checkLambdaInline(arg, assignInsn)) {
return;
}
int assignPos = insnList.getIndex(assignInsn);
if (assignPos != -1) {
WrapInfo wrapInfo = argsInfo.checkInline(assignPos, arg);
if (wrapInfo != null) {
wrapList.add(wrapInfo);
}
} else {
// another block
BlockNode assignBlock = BlockUtils.getBlockByInsn(mth, assignInsn);
if (assignBlock != null
&& assignInsn != arg.getParentInsn()
&& canMoveBetweenBlocks(mth, assignInsn, assignBlock, block, argsInfo.getInsn())) {
if (assignInline) {
assignInline(mth, arg, assignInsn, assignBlock);
} else {
inline(mth, arg, assignInsn, assignBlock);
}
}
}
}
/**
* Forbid inline lambda into invoke as an instance arg, i.e. this will not compile:
* {@code () -> { ... }.apply(); }
*/
private static boolean checkLambdaInline(RegisterArg arg, InsnNode assignInsn) {
if (assignInsn.getType() == InsnType.INVOKE && assignInsn instanceof InvokeCustomNode) {
for (RegisterArg useArg : arg.getSVar().getUseList()) {
InsnNode parentInsn = useArg.getParentInsn();
if (parentInsn != null && parentInsn.getType() == InsnType.INVOKE) {
InvokeNode invokeNode = (InvokeNode) parentInsn;
InsnArg instArg = invokeNode.getInstanceArg();
if (instArg != null && instArg == useArg) {
return false;
}
}
}
}
return true;
}
private static boolean varWithSameNameExists(MethodNode mth, SSAVar inlineVar) {
for (SSAVar ssaVar : mth.getSVars()) {
if (ssaVar == inlineVar || ssaVar.getCodeVar() == inlineVar.getCodeVar()) {
continue;
}
if (Objects.equals(ssaVar.getName(), inlineVar.getName())) {
return ssaVar.getUseCount() > inlineVar.getUseCount();
}
}
return false;
}
private static boolean searchArgWithName(InsnNode assignInsn, String varName) {
InsnArg result = assignInsn.visitArgs(insnArg -> {
if (insnArg instanceof Named) {
String argName = ((Named) insnArg).getName();
if (Objects.equals(argName, varName)) {
return insnArg;
}
}
return null;
});
return result != null;
}
private static boolean assignInline(MethodNode mth, RegisterArg arg, InsnNode assignInsn, BlockNode assignBlock) {
RegisterArg useArg = arg.getSVar().getUseList().get(0);
InsnNode useInsn = useArg.getParentInsn();
if (useInsn == null || useInsn.contains(AFlag.DONT_GENERATE)) {
return false;
}
if (!InsnRemover.removeWithoutUnbind(mth, assignBlock, assignInsn)) {
return false;
}
InsnArg replaceArg = InsnArg.wrapInsnIntoArg(assignInsn);
useInsn.replaceArg(useArg, replaceArg);
return true;
}
private static boolean inline(MethodNode mth, RegisterArg arg, InsnNode insn, BlockNode block) {
if (insn.contains(AFlag.FORCE_ASSIGN_INLINE)) {
return assignInline(mth, arg, insn, block);
}
// just move instruction into arg, don't unbind/copy/duplicate
InsnArg wrappedArg = arg.wrapInstruction(mth, insn, false);
boolean replaced = wrappedArg != null;
if (replaced) {
InsnNode parentInsn = arg.getParentInsn();
if (parentInsn != null) {
parentInsn.inheritMetadata(insn);
}
InsnRemover.unbindResult(mth, insn);
InsnRemover.removeWithoutUnbind(mth, block, insn);
}
return replaced;
}
private static boolean canMoveBetweenBlocks(MethodNode mth, InsnNode assignInsn, BlockNode assignBlock,
BlockNode useBlock, InsnNode useInsn) {
if (!BlockUtils.isPathExists(assignBlock, useBlock)) {
return false;
}
List<RegisterArg> argsList = ArgsInfo.getArgs(assignInsn);
BitSet args = new BitSet();
for (RegisterArg arg : argsList) {
args.set(arg.getRegNum());
}
boolean startCheck = false;
for (InsnNode insn : assignBlock.getInstructions()) {
if (startCheck && (!insn.canReorder() || ArgsInfo.usedArgAssign(insn, args))) {
return false;
}
if (insn == assignInsn) {
startCheck = true;
}
}
Set<BlockNode> pathsBlocks = BlockUtils.getAllPathsBlocks(assignBlock, useBlock);
pathsBlocks.remove(assignBlock);
pathsBlocks.remove(useBlock);
for (BlockNode block : pathsBlocks) {
if (block.contains(AFlag.DONT_GENERATE)) {
if (BlockUtils.checkLastInsnType(block, InsnType.MONITOR_EXIT)) {
if (RegionUtils.isBlocksInSameRegion(mth, assignBlock, useBlock)) {
// allow move inside same synchronized region
} else {
// don't move from synchronized block
return false;
}
}
// skip checks for not generated blocks
continue;
}
for (InsnNode insn : block.getInstructions()) {
if (!insn.canReorder() || ArgsInfo.usedArgAssign(insn, args)) {
return false;
}
}
}
for (InsnNode insn : useBlock.getInstructions()) {
if (insn == useInsn) {
return true;
}
if (!insn.canReorder() || ArgsInfo.usedArgAssign(insn, args)) {
return false;
}
}
throw new JadxRuntimeException("Can't process instruction move : " + assignBlock);
}
private static void simplifyMoveInsns(MethodNode mth, BlockNode block) {
List<InsnNode> insns = block.getInstructions();
int size = insns.size();
for (int i = 0; i < size; i++) {
InsnNode insn = insns.get(i);
if (insn.getType() == InsnType.MOVE) {
// replace 'move' with wrapped insn
InsnArg arg = insn.getArg(0);
if (arg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
InsnRemover.unbindResult(mth, wrapInsn);
wrapInsn.setResult(insn.getResult().duplicate());
wrapInsn.inheritMetadata(insn);
wrapInsn.setOffset(insn.getOffset());
wrapInsn.remove(AFlag.WRAPPED);
block.getInstructions().set(i, wrapInsn);
}
}
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/shrink/ArgsInfo.java | jadx-core/src/main/java/jadx/core/dex/visitors/shrink/ArgsInfo.java | package jadx.core.dex.visitors.shrink;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.mods.TernaryInsn;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.utils.EmptyBitSet;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;
final class ArgsInfo {
private final InsnNode insn;
private final List<ArgsInfo> argsList;
private final List<RegisterArg> args;
private final int pos;
private int inlineBorder;
private ArgsInfo inlinedInsn;
private @Nullable List<ArgsInfo> wrappedInsns;
public ArgsInfo(InsnNode insn, List<ArgsInfo> argsList, int pos) {
this.insn = insn;
this.argsList = argsList;
this.pos = pos;
this.inlineBorder = pos;
this.args = getArgs(insn);
}
public static List<RegisterArg> getArgs(InsnNode insn) {
List<RegisterArg> args = new ArrayList<>();
addArgs(insn, args);
return args;
}
private static void addArgs(InsnNode insn, List<RegisterArg> args) {
if (insn.getType() == InsnType.TERNARY) {
args.addAll(((TernaryInsn) insn).getCondition().getRegisterArgs());
}
for (InsnArg arg : insn.getArguments()) {
if (arg.isRegister()) {
args.add((RegisterArg) arg);
}
}
for (InsnArg arg : insn.getArguments()) {
if (arg.isInsnWrap()) {
addArgs(((InsnWrapArg) arg).getWrapInsn(), args);
}
}
}
public InsnNode getInsn() {
return insn;
}
List<RegisterArg> getArgs() {
return args;
}
public BitSet getArgsSet() {
if (args.isEmpty() && Utils.isEmpty(wrappedInsns)) {
return EmptyBitSet.EMPTY;
}
BitSet set = new BitSet();
fillArgsSet(set);
return set;
}
private void fillArgsSet(BitSet set) {
for (RegisterArg arg : args) {
set.set(arg.getRegNum());
}
List<ArgsInfo> wrapList = wrappedInsns;
if (wrapList != null) {
for (ArgsInfo wrappedInsn : wrapList) {
wrappedInsn.fillArgsSet(set);
}
}
}
public WrapInfo checkInline(int assignPos, RegisterArg arg) {
if (assignPos >= inlineBorder || !canMove(assignPos, inlineBorder)) {
return null;
}
inlineBorder = assignPos;
return inline(assignPos, arg);
}
private boolean canMove(int from, int to) {
ArgsInfo startInfo = argsList.get(from);
int start = from + 1;
if (start == to) {
// previous instruction or on edge of inline border
return true;
}
if (start > to) {
throw new JadxRuntimeException("Invalid inline insn positions: " + start + " - " + to);
}
BitSet movedSet = startInfo.getArgsSet();
if (movedSet == EmptyBitSet.EMPTY && startInfo.insn.isConstInsn()) {
return true;
}
boolean canReorder = startInfo.canReorder();
for (int i = start; i < to; i++) {
ArgsInfo argsInfo = argsList.get(i);
if (argsInfo.getInlinedInsn() == this) {
continue;
}
InsnNode curInsn = argsInfo.insn;
if (canReorder) {
if (usedArgAssign(curInsn, movedSet)) {
return false;
}
} else {
if (!curInsn.canReorder() || usedArgAssign(curInsn, movedSet)) {
return false;
}
}
}
return true;
}
private boolean canReorder() {
if (!insn.canReorder()) {
return false;
}
List<ArgsInfo> wrapList = wrappedInsns;
if (wrapList != null) {
for (ArgsInfo wrapInsn : wrapList) {
if (!wrapInsn.canReorder()) {
return false;
}
}
}
return true;
}
static boolean usedArgAssign(InsnNode insn, BitSet args) {
if (args.isEmpty()) {
return false;
}
RegisterArg result = insn.getResult();
if (result == null) {
return false;
}
return args.get(result.getRegNum());
}
WrapInfo inline(int assignInsnPos, RegisterArg arg) {
ArgsInfo argsInfo = argsList.get(assignInsnPos);
argsInfo.inlinedInsn = this;
if (wrappedInsns == null) {
wrappedInsns = new ArrayList<>(args.size());
}
wrappedInsns.add(argsInfo);
return new WrapInfo(argsInfo.insn, arg);
}
ArgsInfo getInlinedInsn() {
if (inlinedInsn != null) {
ArgsInfo parent = inlinedInsn.getInlinedInsn();
if (parent != null) {
inlinedInsn = parent;
}
}
return inlinedInsn;
}
@Override
public String toString() {
return "ArgsInfo: |" + inlineBorder
+ " ->" + (inlinedInsn == null ? "-" : inlinedInsn.pos)
+ ' ' + args + " : " + insn;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/usage/UsageInfo.java | jadx-core/src/main/java/jadx/core/dex/visitors/usage/UsageInfo.java | package jadx.core.dex.visitors.usage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import jadx.api.usage.IUsageInfoData;
import jadx.api.usage.IUsageInfoVisitor;
import jadx.core.clsp.ClspClass;
import jadx.core.clsp.ClspClassSource;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.ICodeNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
import static jadx.core.utils.Utils.notEmpty;
public class UsageInfo implements IUsageInfoData {
private final RootNode root;
private final UseSet<ClassNode, ClassNode> clsDeps = new UseSet<>();
private final UseSet<ClassNode, ClassNode> clsUsage = new UseSet<>();
private final UseSet<ClassNode, MethodNode> clsUseInMth = new UseSet<>();
private final UseSet<FieldNode, MethodNode> fieldUsage = new UseSet<>();
private final UseSet<MethodNode, MethodNode> mthUsage = new UseSet<>();
public UsageInfo(RootNode root) {
this.root = root;
}
@Override
public void apply() {
clsDeps.visit((cls, deps) -> cls.setDependencies(sortedList(deps)));
clsUsage.visit((cls, deps) -> cls.setUseIn(sortedList(deps)));
clsUseInMth.visit((cls, methods) -> cls.setUseInMth(sortedList(methods)));
fieldUsage.visit((field, methods) -> field.setUseIn(sortedList(methods)));
mthUsage.visit((mth, methods) -> mth.setUseIn(sortedList(methods)));
}
@Override
public void applyForClass(ClassNode cls) {
cls.setDependencies(sortedList(clsDeps.get(cls)));
cls.setUseIn(sortedList(clsUsage.get(cls)));
cls.setUseInMth(sortedList(clsUseInMth.get(cls)));
for (FieldNode fld : cls.getFields()) {
fld.setUseIn(sortedList(fieldUsage.get(fld)));
}
for (MethodNode mth : cls.getMethods()) {
mth.setUseIn(sortedList(mthUsage.get(mth)));
}
}
@Override
public void visitUsageData(IUsageInfoVisitor visitor) {
clsDeps.visit((cls, deps) -> visitor.visitClassDeps(cls, sortedList(deps)));
clsUsage.visit((cls, deps) -> visitor.visitClassUsage(cls, sortedList(deps)));
clsUseInMth.visit((cls, methods) -> visitor.visitClassUseInMethods(cls, sortedList(methods)));
fieldUsage.visit((field, methods) -> visitor.visitFieldsUsage(field, sortedList(methods)));
mthUsage.visit((mth, methods) -> visitor.visitMethodsUsage(mth, sortedList(methods)));
visitor.visitComplete();
}
public void clsUse(ClassNode cls, ArgType useType) {
processType(useType, depCls -> clsUse(cls, depCls));
}
public void clsUse(MethodNode mth, ArgType useType) {
processType(useType, depCls -> clsUse(mth, depCls));
}
public void clsUse(ICodeNode node, ArgType useType) {
Consumer<ClassNode> consumer;
switch (node.getAnnType()) {
case CLASS:
ClassNode cls = (ClassNode) node;
consumer = depCls -> clsUse(cls, depCls);
break;
case METHOD:
MethodNode mth = (MethodNode) node;
consumer = depCls -> clsUse(mth, depCls);
break;
case FIELD:
FieldNode fld = (FieldNode) node;
ClassNode fldCls = fld.getParentClass();
consumer = depCls -> clsUse(fldCls, depCls);
break;
default:
throw new JadxRuntimeException("Unexpected use type: " + node.getAnnType());
}
processType(useType, consumer);
}
public void clsUse(MethodNode mth, ClassNode useCls) {
ClassNode parentClass = mth.getParentClass();
clsUse(parentClass, useCls);
if (parentClass != useCls) {
// exclude class usage in self methods
clsUseInMth.add(useCls, mth);
}
}
public void clsUse(ClassNode cls, ClassNode depCls) {
ClassNode topParentClass = cls.getTopParentClass();
clsDeps.add(topParentClass, depCls.getTopParentClass());
clsUsage.add(depCls, cls);
clsUsage.add(depCls, topParentClass);
}
/**
* Add method usage: {@code useMth} occurrence found in {@code mth} code
*/
public void methodUse(MethodNode mth, MethodNode useMth) {
clsUse(mth, useMth.getParentClass());
mthUsage.add(useMth, mth);
// implicit usage
clsUse(mth, useMth.getReturnType());
useMth.getMethodInfo().getArgumentsTypes().forEach(argType -> clsUse(mth, argType));
}
public void fieldUse(MethodNode mth, FieldNode useFld) {
clsUse(mth, useFld.getParentClass());
fieldUsage.add(useFld, mth);
// implicit usage
clsUse(mth, useFld.getType());
}
public void fieldUse(ICodeNode node, FieldInfo useFld) {
FieldNode fld = root.resolveField(useFld);
if (fld == null) {
return;
}
switch (node.getAnnType()) {
case CLASS:
// TODO: support "field in class" usage?
// now use field parent class for "class in class" usage
clsUse((ClassNode) node, fld.getParentClass());
break;
case METHOD:
fieldUse((MethodNode) node, fld);
break;
}
}
/**
* Visit all class nodes found in subtypes of the provided type.
*/
private void processType(ArgType type, Consumer<ClassNode> consumer) {
if (type == null || type == ArgType.OBJECT) {
return;
}
if (type.isArray()) {
processType(type.getArrayRootElement(), consumer);
return;
}
if (type.isObject()) {
// TODO: support custom handlers via API
ClspClass clsDetails = root.getClsp().getClsDetails(type);
if (clsDetails != null && clsDetails.getSource() == ClspClassSource.APACHE_HTTP_LEGACY_CLIENT) {
root.getGradleInfoStorage().setUseApacheHttpLegacy(true);
}
ClassNode clsNode = root.resolveClass(type);
if (clsNode != null) {
consumer.accept(clsNode);
}
List<ArgType> genericTypes = type.getGenericTypes();
if (notEmpty(genericTypes)) {
for (ArgType argType : genericTypes) {
processType(argType, consumer);
}
}
List<ArgType> extendTypes = type.getExtendTypes();
if (notEmpty(extendTypes)) {
for (ArgType extendType : extendTypes) {
processType(extendType, consumer);
}
}
ArgType wildcardType = type.getWildcardType();
if (wildcardType != null) {
processType(wildcardType, consumer);
}
// TODO: process 'outer' types (check TestOuterGeneric test)
}
}
private static <T extends Comparable<T>> List<T> sortedList(Set<T> nodes) {
if (nodes == null || nodes.isEmpty()) {
return Collections.emptyList();
}
List<T> list = new ArrayList<>(nodes);
Collections.sort(list);
return list;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/usage/UsageInfoVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/usage/UsageInfoVisitor.java | package jadx.core.dex.visitors.usage;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.plugins.input.data.ICallSite;
import jadx.api.plugins.input.data.ICodeReader;
import jadx.api.plugins.input.data.IFieldRef;
import jadx.api.plugins.input.data.IMethodHandle;
import jadx.api.plugins.input.data.IMethodRef;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.api.plugins.input.data.annotations.IAnnotation;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.api.plugins.input.data.attributes.types.AnnotationMethodParamsAttr;
import jadx.api.plugins.input.data.attributes.types.AnnotationsAttr;
import jadx.api.plugins.input.insns.InsnData;
import jadx.api.plugins.input.insns.Opcode;
import jadx.api.plugins.input.insns.custom.ICustomPayload;
import jadx.api.usage.IUsageInfoCache;
import jadx.api.usage.IUsageInfoData;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.ICodeNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.OverrideMethodVisitor;
import jadx.core.dex.visitors.SignatureProcessor;
import jadx.core.dex.visitors.rename.RenameVisitor;
import jadx.core.utils.ListUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.utils.input.InsnDataUtils;
@JadxVisitor(
name = "UsageInfoVisitor",
desc = "Scan class and methods to collect usage info and class dependencies",
runAfter = {
SignatureProcessor.class, // use types with generics
OverrideMethodVisitor.class, // add method override as use
RenameVisitor.class // sort by alias name
}
)
public class UsageInfoVisitor extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(UsageInfoVisitor.class);
@Override
public void init(RootNode root) {
IUsageInfoCache usageCache = root.getArgs().getUsageInfoCache();
IUsageInfoData usageInfoData = usageCache.get(root);
if (usageInfoData != null) {
try {
apply(usageInfoData);
return;
} catch (Exception e) {
LOG.error("Failed to apply cached usage data", e);
}
}
IUsageInfoData collectedInfoData = buildUsageData(root);
usageCache.set(root, collectedInfoData);
apply(collectedInfoData);
}
private static void apply(IUsageInfoData usageInfoData) {
long start = System.currentTimeMillis();
usageInfoData.apply();
if (LOG.isDebugEnabled()) {
LOG.debug("Apply usage data in {}ms", System.currentTimeMillis() - start);
}
}
private static IUsageInfoData buildUsageData(RootNode root) {
UsageInfo usageInfo = new UsageInfo(root);
for (ClassNode cls : root.getClasses()) {
processClass(cls, usageInfo);
}
return usageInfo;
}
private static void processClass(ClassNode cls, UsageInfo usageInfo) {
usageInfo.clsUse(cls, cls.getSuperClass());
for (ArgType interfaceType : cls.getInterfaces()) {
usageInfo.clsUse(cls, interfaceType);
}
for (ArgType genericTypeParameter : cls.getGenericTypeParameters()) {
usageInfo.clsUse(cls, genericTypeParameter);
}
for (FieldNode fieldNode : cls.getFields()) {
usageInfo.clsUse(cls, fieldNode.getType());
processAnnotations(fieldNode, usageInfo);
// TODO: process types from field 'constant value'
}
processAnnotations(cls, usageInfo);
for (MethodNode methodNode : cls.getMethods()) {
processMethod(methodNode, usageInfo);
}
}
private static void processMethod(MethodNode mth, UsageInfo usageInfo) {
processMethodAnnotations(mth, usageInfo);
usageInfo.clsUse(mth, mth.getReturnType());
for (ArgType argType : mth.getArgTypes()) {
usageInfo.clsUse(mth, argType);
}
// TODO: process exception classes from 'throws'
try {
processInstructions(mth, usageInfo);
} catch (Exception e) {
mth.addError("Dependency scan failed", e);
}
}
private static void processInstructions(MethodNode mth, UsageInfo usageInfo) {
if (mth.isNoCode()) {
return;
}
ICodeReader codeReader = mth.getCodeReader();
if (codeReader == null) {
return;
}
RootNode root = mth.root();
codeReader.visitInstructions(insnData -> {
try {
processInsn(root, mth, insnData, usageInfo);
} catch (Exception e) {
throw new JadxRuntimeException(
"Usage info collection failed with error: " + e.getMessage() + " at insn: " + insnData, e);
}
});
}
private static void processInsn(RootNode root, MethodNode mth, InsnData insnData, UsageInfo usageInfo) {
if (insnData.getOpcode() == Opcode.UNKNOWN) {
return;
}
switch (insnData.getIndexType()) {
case TYPE_REF:
insnData.decode();
ArgType usedType = ArgType.parse(insnData.getIndexAsType());
usageInfo.clsUse(mth, usedType);
break;
case FIELD_REF:
insnData.decode();
FieldNode fieldNode = root.resolveField(FieldInfo.fromRef(root, insnData.getIndexAsField()));
if (fieldNode != null) {
usageInfo.fieldUse(mth, fieldNode);
}
break;
case METHOD_REF: {
insnData.decode();
IMethodRef mthRef;
ICustomPayload payload = insnData.getPayload();
if (payload != null) {
mthRef = (IMethodRef) payload;
} else {
mthRef = insnData.getIndexAsMethod();
}
MethodNode methodNode = root.resolveMethod(MethodInfo.fromRef(root, mthRef));
if (methodNode != null) {
usageInfo.methodUse(mth, methodNode);
}
break;
}
case CALL_SITE: {
insnData.decode();
ICallSite callSite = InsnDataUtils.getCallSite(insnData);
IMethodHandle methodHandle = InsnDataUtils.getMethodHandleAt(callSite, 4);
if (methodHandle != null) {
IMethodRef mthRef = methodHandle.getMethodRef();
MethodNode mthNode = root.resolveMethod(MethodInfo.fromRef(root, mthRef));
if (mthNode != null) {
usageInfo.methodUse(mth, mthNode);
}
}
break;
}
}
}
private static void processAnnotations(ICodeNode node, UsageInfo usageInfo) {
AnnotationsAttr annAttr = node.get(JadxAttrType.ANNOTATION_LIST);
processAnnotationAttr(node, annAttr, usageInfo);
}
private static void processMethodAnnotations(MethodNode mth, UsageInfo usageInfo) {
processAnnotations(mth, usageInfo);
AnnotationMethodParamsAttr paramsAttr = mth.get(JadxAttrType.ANNOTATION_MTH_PARAMETERS);
if (paramsAttr != null) {
for (AnnotationsAttr annAttr : paramsAttr.getParamList()) {
processAnnotationAttr(mth, annAttr, usageInfo);
}
}
}
private static void processAnnotationAttr(ICodeNode node, AnnotationsAttr annAttr, UsageInfo usageInfo) {
if (annAttr == null || annAttr.isEmpty()) {
return;
}
for (IAnnotation ann : annAttr.getList()) {
processAnnotation(node, ann, usageInfo);
}
}
private static void processAnnotation(ICodeNode node, IAnnotation ann, UsageInfo usageInfo) {
usageInfo.clsUse(node, ArgType.parse(ann.getAnnotationClass()));
for (EncodedValue value : ann.getValues().values()) {
processAnnotationValue(node, value, usageInfo);
}
}
@SuppressWarnings("unchecked")
private static void processAnnotationValue(ICodeNode node, EncodedValue value, UsageInfo usageInfo) {
Object obj = value.getValue();
switch (value.getType()) {
case ENCODED_TYPE:
usageInfo.clsUse(node, ArgType.parse((String) obj));
break;
case ENCODED_ENUM:
case ENCODED_FIELD:
if (obj instanceof IFieldRef) {
usageInfo.fieldUse(node, FieldInfo.fromRef(node.root(), (IFieldRef) obj));
} else if (obj instanceof FieldInfo) {
usageInfo.fieldUse(node, (FieldInfo) obj);
} else {
throw new JadxRuntimeException("Unexpected field type class: " + value.getClass());
}
break;
case ENCODED_ARRAY:
for (EncodedValue encodedValue : (List<EncodedValue>) obj) {
processAnnotationValue(node, encodedValue, usageInfo);
}
break;
case ENCODED_ANNOTATION:
processAnnotation(node, (IAnnotation) obj, usageInfo);
break;
}
}
public static void replaceMethodUsage(MethodNode mergeIntoMth, MethodNode sourceMth) {
List<MethodNode> mergedUsage = ListUtils.distinctMergeSortedLists(mergeIntoMth.getUseIn(), sourceMth.getUseIn());
mergedUsage.remove(sourceMth);
mergeIntoMth.setUseIn(mergedUsage);
sourceMth.setUseIn(Collections.emptyList());
}
@Override
public String getName() {
return "UsageInfoVisitor";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/usage/UseSet.java | jadx-core/src/main/java/jadx/core/dex/visitors/usage/UseSet.java | package jadx.core.dex.visitors.usage;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
public class UseSet<K, V> {
private final Map<K, Set<V>> useMap = new HashMap<>();
public void add(K obj, V use) {
if (obj == use) {
// self excluded
return;
}
Set<V> set = useMap.computeIfAbsent(obj, k -> new HashSet<>());
set.add(use);
}
public Set<V> get(K obj) {
return useMap.get(obj);
}
public void visit(BiConsumer<K, Set<V>> consumer) {
for (Map.Entry<K, Set<V>> entry : useMap.entrySet()) {
consumer.accept(entry.getKey(), entry.getValue());
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/finaly/FinallyExtractInfo.java | jadx-core/src/main/java/jadx/core/dex/visitors/finaly/FinallyExtractInfo.java | package jadx.core.dex.visitors.finaly;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.utils.Utils;
public class FinallyExtractInfo {
private final MethodNode mth;
private final ExceptionHandler finallyHandler;
private final List<BlockNode> allHandlerBlocks;
private final List<InsnsSlice> duplicateSlices = new ArrayList<>();
private final Set<BlockNode> checkedBlocks = new HashSet<>();
private final InsnsSlice finallyInsnsSlice = new InsnsSlice();
private final BlockNode startBlock;
private InsnsSlice curDupSlice;
private List<InsnNode> curDupInsns;
private int curDupInsnsOffset;
public FinallyExtractInfo(MethodNode mth, ExceptionHandler finallyHandler, BlockNode startBlock, List<BlockNode> allHandlerBlocks) {
this.mth = mth;
this.finallyHandler = finallyHandler;
this.startBlock = startBlock;
this.allHandlerBlocks = allHandlerBlocks;
}
public MethodNode getMth() {
return mth;
}
public ExceptionHandler getFinallyHandler() {
return finallyHandler;
}
public List<BlockNode> getAllHandlerBlocks() {
return allHandlerBlocks;
}
public InsnsSlice getFinallyInsnsSlice() {
return finallyInsnsSlice;
}
public List<InsnsSlice> getDuplicateSlices() {
return duplicateSlices;
}
public Set<BlockNode> getCheckedBlocks() {
return checkedBlocks;
}
public BlockNode getStartBlock() {
return startBlock;
}
public InsnsSlice getCurDupSlice() {
return curDupSlice;
}
public void setCurDupSlice(InsnsSlice curDupSlice) {
this.curDupSlice = curDupSlice;
}
public List<InsnNode> getCurDupInsns() {
return curDupInsns;
}
public int getCurDupInsnsOffset() {
return curDupInsnsOffset;
}
public void setCurDupInsns(List<InsnNode> insns, int offset) {
this.curDupInsns = insns;
this.curDupInsnsOffset = offset;
}
@Override
public String toString() {
return "FinallyExtractInfo{"
+ "\n finally:\n " + finallyInsnsSlice
+ "\n dups:\n " + Utils.listToString(duplicateSlices, "\n ")
+ "\n}";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/finaly/InsnsSlice.java | jadx-core/src/main/java/jadx/core/dex/visitors/finaly/InsnsSlice.java | package jadx.core.dex.visitors.finaly;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
public class InsnsSlice {
private final List<InsnNode> insnsList = new ArrayList<>();
private final Map<InsnNode, BlockNode> insnMap = new IdentityHashMap<>();
private boolean complete;
public void addInsn(InsnNode insn, BlockNode block) {
insnsList.add(insn);
insnMap.put(insn, block);
}
public void addBlock(BlockNode block) {
for (InsnNode insn : block.getInstructions()) {
addInsn(insn, block);
}
}
public void addInsns(BlockNode block, int startIndex, int endIndex) {
List<InsnNode> insns = block.getInstructions();
for (int i = startIndex; i < endIndex; i++) {
addInsn(insns.get(i), block);
}
}
@Nullable
public BlockNode getBlock(InsnNode insn) {
return insnMap.get(insn);
}
public List<InsnNode> getInsnsList() {
return insnsList;
}
public Set<BlockNode> getBlocks() {
Set<BlockNode> set = new LinkedHashSet<>();
for (InsnNode insn : insnsList) {
set.add(insnMap.get(insn));
}
return set;
}
public void resetIncomplete() {
if (!complete) {
insnsList.clear();
insnMap.clear();
}
}
public boolean isComplete() {
return complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
@Override
public String toString() {
return "{["
+ insnsList.stream().map(insn -> insn.getType().toString()).collect(Collectors.joining(", "))
+ ']'
+ (complete ? " complete" : "")
+ '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/finaly/MarkFinallyVisitor.java | jadx-core/src/main/java/jadx/core/dex/visitors/finaly/MarkFinallyVisitor.java | package jadx.core.dex.visitors.finaly;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.Consts;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.RegDebugInfoAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.dex.trycatch.TryCatchBlockAttr;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.ConstInlineVisitor;
import jadx.core.dex.visitors.DepthTraversal;
import jadx.core.dex.visitors.IDexTreeVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.ssa.SSATransform;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.InsnList;
import jadx.core.utils.ListUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.blocks.BlockPair;
@JadxVisitor(
name = "MarkFinallyVisitor",
desc = "Search and mark duplicate code generated for finally block",
runAfter = SSATransform.class,
runBefore = ConstInlineVisitor.class
)
public class MarkFinallyVisitor extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(MarkFinallyVisitor.class);
@Override
public void visit(MethodNode mth) {
if (mth.isNoCode() || mth.isNoExceptionHandlers()) {
return;
}
try {
boolean applied = false;
List<TryCatchBlockAttr> tryBlocks = mth.getAll(AType.TRY_BLOCKS_LIST);
for (TryCatchBlockAttr tryBlock : tryBlocks) {
applied |= processTryBlock(mth, tryBlock);
}
if (applied) {
mth.clearExceptionHandlers();
// remove merged or empty try blocks from list in method attribute
List<TryCatchBlockAttr> clearedTryBlocks = new ArrayList<>(tryBlocks);
if (clearedTryBlocks.removeIf(tb -> tb.isMerged() || tb.getHandlers().isEmpty())) {
mth.remove(AType.TRY_BLOCKS_LIST);
mth.addAttr(AType.TRY_BLOCKS_LIST, clearedTryBlocks);
}
}
} catch (Exception e) {
mth.addWarnComment("Undo finally extract visitor", e);
undoFinallyVisitor(mth);
}
}
private static boolean processTryBlock(MethodNode mth, TryCatchBlockAttr tryBlock) {
if (tryBlock.isMerged()) {
return false;
}
ExceptionHandler allHandler = null;
InsnNode reThrowInsn = null;
for (ExceptionHandler excHandler : tryBlock.getHandlers()) {
if (excHandler.isCatchAll()) {
allHandler = excHandler;
for (BlockNode excBlock : excHandler.getBlocks()) {
InsnNode lastInsn = BlockUtils.getLastInsn(excBlock);
if (lastInsn != null && lastInsn.getType() == InsnType.THROW) {
reThrowInsn = BlockUtils.getLastInsn(excBlock);
}
}
break;
}
}
if (allHandler != null && reThrowInsn != null) {
if (extractFinally(mth, tryBlock, allHandler)) {
reThrowInsn.add(AFlag.DONT_GENERATE);
return true;
}
}
return false;
}
/**
* Search and mark common code from 'try' block and 'handlers'.
*/
private static boolean extractFinally(MethodNode mth, TryCatchBlockAttr tryBlock, ExceptionHandler allHandler) {
BlockNode handlerBlock = allHandler.getHandlerBlock();
List<BlockNode> handlerBlocks =
new ArrayList<>(BlockUtils.collectBlocksDominatedByWithExcHandlers(mth, handlerBlock, handlerBlock));
handlerBlocks.remove(handlerBlock); // exclude block with 'move-exception'
cutPathEnds(mth, handlerBlocks);
if (handlerBlocks.isEmpty() || BlockUtils.isAllBlocksEmpty(handlerBlocks)) {
// remove empty catch
allHandler.getTryBlock().removeHandler(allHandler);
return true;
}
BlockNode startBlock = Utils.getOne(handlerBlock.getCleanSuccessors());
FinallyExtractInfo extractInfo = new FinallyExtractInfo(mth, allHandler, startBlock, handlerBlocks);
if (Consts.DEBUG_FINALLY) {
LOG.debug("Finally info: handler=({}), start={}, blocks={}", allHandler, startBlock, handlerBlocks);
}
boolean hasInnerBlocks = !tryBlock.getInnerTryBlocks().isEmpty();
List<ExceptionHandler> handlers;
if (hasInnerBlocks) {
// collect handlers from this and all inner blocks
// (intentionally not using recursive collect for now)
handlers = new ArrayList<>(tryBlock.getHandlers());
for (TryCatchBlockAttr innerTryBlock : tryBlock.getInnerTryBlocks()) {
handlers.addAll(innerTryBlock.getHandlers());
}
} else {
handlers = tryBlock.getHandlers();
}
if (handlers.isEmpty()) {
return false;
}
// search 'finally' instructions in other handlers
for (ExceptionHandler otherHandler : handlers) {
if (otherHandler == allHandler) {
continue;
}
for (BlockNode checkBlock : otherHandler.getBlocks()) {
if (searchDuplicateInsns(checkBlock, extractInfo)) {
break;
} else {
extractInfo.getFinallyInsnsSlice().resetIncomplete();
}
}
}
if (Consts.DEBUG_FINALLY) {
LOG.debug("Handlers slices:\n{}", extractInfo);
}
boolean mergeInnerTryBlocks;
int duplicatesCount = extractInfo.getDuplicateSlices().size();
if (duplicatesCount == (handlers.size() - 1)) {
// all collected handlers have duplicate block
mergeInnerTryBlocks = hasInnerBlocks;
} else {
// some handlers don't have duplicated blocks
if (!hasInnerBlocks || duplicatesCount != (tryBlock.getHandlers().size() - 1)) {
// unexpected count of duplicated slices
return false;
}
mergeInnerTryBlocks = false;
}
// remove 'finally' from 'try' blocks,
// check all up paths on each exit (connected with 'finally' exit)
List<BlockNode> tryBlocks = allHandler.getTryBlock().getBlocks();
BlockNode bottomBlock = BlockUtils.getBottomBlock(allHandler.getBlocks());
if (bottomBlock == null) {
if (Consts.DEBUG_FINALLY) {
LOG.warn("No bottom block for handler: {} and blocks: {}", allHandler, allHandler.getBlocks());
}
return false;
}
BlockNode bottomFinallyBlock = BlockUtils.followEmptyPath(bottomBlock);
BlockNode bottom = BlockUtils.getNextBlock(bottomFinallyBlock);
if (bottom == null) {
if (Consts.DEBUG_FINALLY) {
LOG.warn("Finally bottom block not found for: {} and: {}", bottomBlock, bottomFinallyBlock);
}
return false;
}
boolean found = false;
List<BlockNode> pathBlocks = getPathStarts(mth, bottom, bottomFinallyBlock);
for (BlockNode pred : pathBlocks) {
List<BlockNode> upPath = BlockUtils.collectPredecessors(mth, pred, tryBlocks);
if (upPath.size() < handlerBlocks.size()) {
continue;
}
if (Consts.DEBUG_FINALLY) {
LOG.debug("Checking dup path starts: {} from {}", upPath, pred);
}
for (BlockNode block : upPath) {
if (searchDuplicateInsns(block, extractInfo)) {
found = true;
if (Consts.DEBUG_FINALLY) {
LOG.debug("Found dup in: {} from {}", block, pred);
}
break;
} else {
extractInfo.getFinallyInsnsSlice().resetIncomplete();
}
}
}
if (!found) {
if (Consts.DEBUG_FINALLY) {
LOG.info("Dup not found for all handler: {}", allHandler);
}
return false;
}
if (Consts.DEBUG_FINALLY) {
LOG.debug("Result slices:\n{}", extractInfo);
}
if (!checkSlices(extractInfo)) {
mth.addWarnComment("Finally extract failed");
return false;
}
// 'finally' extract confirmed, apply
apply(extractInfo);
allHandler.setFinally(true);
if (mergeInnerTryBlocks) {
List<TryCatchBlockAttr> innerTryBlocks = tryBlock.getInnerTryBlocks();
for (TryCatchBlockAttr innerTryBlock : innerTryBlocks) {
tryBlock.getHandlers().addAll(innerTryBlock.getHandlers());
tryBlock.getBlocks().addAll(innerTryBlock.getBlocks());
innerTryBlock.setMerged(true);
}
tryBlock.setBlocks(ListUtils.distinctList(tryBlock.getBlocks()));
innerTryBlocks.clear();
}
return true;
}
private static void cutPathEnds(MethodNode mth, List<BlockNode> handlerBlocks) {
List<BlockNode> throwBlocks = ListUtils.filter(handlerBlocks,
b -> BlockUtils.checkLastInsnType(b, InsnType.THROW));
if (throwBlocks.size() != 1) {
mth.addDebugComment("Finally have unexpected throw blocks count: " + throwBlocks.size() + ", expect 1");
return;
}
BlockNode throwBlock = throwBlocks.get(0);
handlerBlocks.remove(throwBlock);
removeEmptyUpPath(handlerBlocks, throwBlock);
}
private static void removeEmptyUpPath(List<BlockNode> handlerBlocks, BlockNode startBlock) {
for (BlockNode pred : startBlock.getPredecessors()) {
if (pred.isEmpty()) {
if (handlerBlocks.remove(pred) && !BlockUtils.isBackEdge(pred, startBlock)) {
removeEmptyUpPath(handlerBlocks, pred);
}
}
}
}
private static List<BlockNode> getPathStarts(MethodNode mth, BlockNode bottom, BlockNode bottomFinallyBlock) {
Stream<BlockNode> preds = bottom.getPredecessors().stream().filter(b -> b != bottomFinallyBlock);
if (bottom == mth.getExitBlock()) {
preds = preds.flatMap(r -> r.getPredecessors().stream());
}
return preds.collect(Collectors.toList());
}
private static boolean checkSlices(FinallyExtractInfo extractInfo) {
InsnsSlice finallySlice = extractInfo.getFinallyInsnsSlice();
List<InsnNode> finallyInsnsList = finallySlice.getInsnsList();
for (InsnsSlice dupSlice : extractInfo.getDuplicateSlices()) {
List<InsnNode> dupInsnsList = dupSlice.getInsnsList();
if (dupInsnsList.size() != finallyInsnsList.size()) {
extractInfo.getMth().addDebugComment(
"Incorrect finally slice size: " + dupSlice + ", expected: " + finallySlice);
return false;
}
}
for (int i = 0; i < finallyInsnsList.size(); i++) {
InsnNode finallyInsn = finallyInsnsList.get(i);
for (InsnsSlice dupSlice : extractInfo.getDuplicateSlices()) {
List<InsnNode> insnsList = dupSlice.getInsnsList();
InsnNode dupInsn = insnsList.get(i);
if (finallyInsn.getType() != dupInsn.getType()) {
extractInfo.getMth().addDebugComment(
"Incorrect finally slice insn: " + dupInsn + ", expected: " + finallyInsn);
return false;
}
}
}
return true;
}
private static void apply(FinallyExtractInfo extractInfo) {
markSlice(extractInfo.getFinallyInsnsSlice(), AFlag.FINALLY_INSNS);
for (InsnsSlice dupSlice : extractInfo.getDuplicateSlices()) {
markSlice(dupSlice, AFlag.DONT_GENERATE);
}
InsnsSlice finallySlice = extractInfo.getFinallyInsnsSlice();
List<InsnNode> finallyInsnsList = finallySlice.getInsnsList();
for (int i = 0; i < finallyInsnsList.size(); i++) {
InsnNode finallyInsn = finallyInsnsList.get(i);
for (InsnsSlice dupSlice : extractInfo.getDuplicateSlices()) {
InsnNode dupInsn = dupSlice.getInsnsList().get(i);
copyCodeVars(finallyInsn, dupInsn);
}
}
}
private static void markSlice(InsnsSlice slice, AFlag flag) {
List<InsnNode> insnsList = slice.getInsnsList();
for (InsnNode insn : insnsList) {
insn.add(flag);
}
for (BlockNode block : slice.getBlocks()) {
boolean allInsnMarked = true;
for (InsnNode insn : block.getInstructions()) {
if (!insn.contains(flag)) {
allInsnMarked = false;
break;
}
}
if (allInsnMarked) {
block.add(flag);
}
}
}
private static void copyCodeVars(InsnNode fromInsn, InsnNode toInsn) {
copyCodeVars(fromInsn.getResult(), toInsn.getResult());
int argsCount = fromInsn.getArgsCount();
for (int i = 0; i < argsCount; i++) {
copyCodeVars(fromInsn.getArg(i), toInsn.getArg(i));
}
}
private static void copyCodeVars(InsnArg fromArg, InsnArg toArg) {
if (fromArg == null || toArg == null
|| !fromArg.isRegister() || !toArg.isRegister()) {
return;
}
SSAVar fromSsaVar = ((RegisterArg) fromArg).getSVar();
SSAVar toSsaVar = ((RegisterArg) toArg).getSVar();
toSsaVar.setCodeVar(fromSsaVar.getCodeVar());
}
private static boolean searchDuplicateInsns(BlockNode checkBlock, FinallyExtractInfo extractInfo) {
boolean isNew = extractInfo.getCheckedBlocks().add(checkBlock);
if (!isNew) {
return false;
}
BlockNode startBlock = extractInfo.getStartBlock();
InsnsSlice dupSlice = searchFromFirstBlock(checkBlock, startBlock, extractInfo);
if (dupSlice == null) {
return false;
}
extractInfo.getDuplicateSlices().add(dupSlice);
return true;
}
private static InsnsSlice searchFromFirstBlock(BlockNode dupBlock, BlockNode startBlock, FinallyExtractInfo extractInfo) {
InsnsSlice dupSlice = isStartBlock(dupBlock, startBlock, extractInfo);
if (dupSlice == null) {
return null;
}
if (!dupSlice.isComplete()) {
Map<BlockPair, Boolean> checkCache = new HashMap<>();
if (checkBlocksTree(dupBlock, startBlock, dupSlice, extractInfo, checkCache)) {
dupSlice.setComplete(true);
extractInfo.getFinallyInsnsSlice().setComplete(true);
} else {
return null;
}
}
return checkTempSlice(dupSlice);
}
@Nullable
private static InsnsSlice checkTempSlice(InsnsSlice slice) {
List<InsnNode> insnsList = slice.getInsnsList();
if (insnsList.isEmpty()) {
return null;
}
// ignore slice with only one 'if' insn
if (insnsList.size() == 1) {
InsnNode insnNode = insnsList.get(0);
if (insnNode.getType() == InsnType.IF) {
return null;
}
}
return slice;
}
/**
* 'Finally' instructions can start in the middle of the first block.
*/
private static InsnsSlice isStartBlock(BlockNode dupBlock, BlockNode finallyBlock, FinallyExtractInfo extractInfo) {
extractInfo.setCurDupSlice(null);
List<InsnNode> dupInsns = dupBlock.getInstructions();
List<InsnNode> finallyInsns = finallyBlock.getInstructions();
int dupSize = dupInsns.size();
int finSize = finallyInsns.size();
if (dupSize < finSize) {
return null;
}
int startPos;
int endPos = 0;
if (dupSize == finSize) {
if (!checkInsns(extractInfo, dupInsns, finallyInsns, 0)) {
return null;
}
startPos = 0;
} else {
// dupSize > finSize
startPos = dupSize - finSize;
// fast check from end of block
if (!checkInsns(extractInfo, dupInsns, finallyInsns, startPos)) {
// search start insn
boolean found = false;
for (int i = 1; i < startPos; i++) {
if (checkInsns(extractInfo, dupInsns, finallyInsns, i)) {
startPos = i;
endPos = finSize + i;
found = true;
break;
}
}
if (!found) {
return null;
}
}
}
// put instructions into slices
boolean complete;
InsnsSlice slice = new InsnsSlice();
extractInfo.setCurDupSlice(slice);
int endIndex;
if (endPos != 0) {
endIndex = endPos + 1;
// both slices completed
complete = true;
} else {
endIndex = dupSize;
complete = false;
}
// fill dup insns slice
for (int i = startPos; i < endIndex; i++) {
slice.addInsn(dupInsns.get(i), dupBlock);
}
// fill finally insns slice
InsnsSlice finallySlice = extractInfo.getFinallyInsnsSlice();
if (finallySlice.isComplete()) {
// compare slices
if (finallySlice.getInsnsList().size() != slice.getInsnsList().size()) {
extractInfo.getMth().addDebugComment(
"Another duplicated slice has different insns count: " + slice + ", finally: " + finallySlice);
return null;
}
// TODO: add additional slices checks
// and try to extract common part if found difference
} else {
for (InsnNode finallyInsn : finallyInsns) {
finallySlice.addInsn(finallyInsn, finallyBlock);
}
}
if (complete) {
slice.setComplete(true);
finallySlice.setComplete(true);
}
return slice;
}
private static boolean checkInsns(FinallyExtractInfo extractInfo, List<InsnNode> dupInsns, List<InsnNode> finallyInsns, int delta) {
extractInfo.setCurDupInsns(dupInsns, delta);
for (int i = finallyInsns.size() - 1; i >= 0; i--) {
InsnNode startInsn = finallyInsns.get(i);
InsnNode dupInsn = dupInsns.get(delta + i);
if (!sameInsns(extractInfo, dupInsn, startInsn)) {
return false;
}
}
return true;
}
private static boolean checkBlocksTree(BlockNode dupBlock, BlockNode finallyBlock,
InsnsSlice dupSlice, FinallyExtractInfo extractInfo,
Map<BlockPair, Boolean> checksCache) {
BlockPair checkBlocks = new BlockPair(dupBlock, finallyBlock);
Boolean checked = checksCache.get(checkBlocks);
if (checked != null) {
return checked;
}
boolean same;
InsnsSlice finallySlice = extractInfo.getFinallyInsnsSlice();
List<BlockNode> finallyCS = getSuccessorsWithoutLoop(finallyBlock);
List<BlockNode> dupCS = getSuccessorsWithoutLoop(dupBlock);
if (finallyCS.size() == dupCS.size()) {
same = true;
for (int i = 0; i < finallyCS.size(); i++) {
BlockNode finSBlock = finallyCS.get(i);
BlockNode dupSBlock = dupCS.get(i);
if (extractInfo.getAllHandlerBlocks().contains(finSBlock)) {
if (!compareBlocks(dupSBlock, finSBlock, dupSlice, extractInfo)) {
same = false;
break;
}
if (!checkBlocksTree(dupSBlock, finSBlock, dupSlice, extractInfo, checksCache)) {
same = false;
break;
}
dupSlice.addBlock(dupSBlock);
finallySlice.addBlock(finSBlock);
}
}
} else {
// stop checks at start blocks (already compared)
same = true;
}
checksCache.put(checkBlocks, same);
return same;
}
private static List<BlockNode> getSuccessorsWithoutLoop(BlockNode block) {
if (block.contains(AFlag.LOOP_END)) {
return block.getCleanSuccessors();
}
return block.getSuccessors();
}
private static boolean compareBlocks(BlockNode dupBlock, BlockNode finallyBlock, InsnsSlice dupSlice, FinallyExtractInfo extractInfo) {
List<InsnNode> dupInsns = dupBlock.getInstructions();
List<InsnNode> finallyInsns = finallyBlock.getInstructions();
int dupInsnCount = dupInsns.size();
int finallyInsnCount = finallyInsns.size();
if (finallyInsnCount == 0) {
return dupInsnCount == 0;
}
if (dupInsnCount < finallyInsnCount) {
return false;
}
extractInfo.setCurDupInsns(dupInsns, 0);
for (int i = 0; i < finallyInsnCount; i++) {
if (!sameInsns(extractInfo, dupInsns.get(i), finallyInsns.get(i))) {
return false;
}
}
if (dupInsnCount > finallyInsnCount) {
dupSlice.addInsns(dupBlock, 0, finallyInsnCount);
dupSlice.setComplete(true);
InsnsSlice finallyInsnsSlice = extractInfo.getFinallyInsnsSlice();
finallyInsnsSlice.addBlock(finallyBlock);
finallyInsnsSlice.setComplete(true);
}
return true;
}
private static boolean sameInsns(FinallyExtractInfo extractInfo, InsnNode dupInsn, InsnNode fInsn) {
if (!dupInsn.isSame(fInsn)) {
return false;
}
// TODO: check instance arg in ConstructorInsn
for (int i = 0; i < dupInsn.getArgsCount(); i++) {
InsnArg dupArg = dupInsn.getArg(i);
InsnArg fArg = fInsn.getArg(i);
if (!isSameArgs(extractInfo, dupArg, fArg)) {
return false;
}
}
return true;
}
@SuppressWarnings("RedundantIfStatement")
private static boolean isSameArgs(FinallyExtractInfo extractInfo, InsnArg dupArg, InsnArg fArg) {
boolean isReg = dupArg.isRegister();
if (isReg != fArg.isRegister()) {
return false;
}
if (isReg) {
RegisterArg dupReg = (RegisterArg) dupArg;
RegisterArg fReg = (RegisterArg) fArg;
if (!dupReg.sameCodeVar(fReg)
&& !sameDebugInfo(dupReg, fReg)
&& assignedOutsideHandler(extractInfo, dupReg, fReg)
&& assignInsnDifferent(dupReg, fReg)) {
return false;
}
}
boolean remConst = dupArg.isConst();
if (remConst != fArg.isConst()) {
return false;
}
if (remConst && !dupArg.isSameConst(fArg)) {
return false;
}
return true;
}
private static boolean sameDebugInfo(RegisterArg dupReg, RegisterArg fReg) {
RegDebugInfoAttr fDbgInfo = fReg.get(AType.REG_DEBUG_INFO);
RegDebugInfoAttr dupDbgInfo = dupReg.get(AType.REG_DEBUG_INFO);
if (fDbgInfo == null || dupDbgInfo == null) {
return false;
}
return dupDbgInfo.equals(fDbgInfo);
}
private static boolean assignInsnDifferent(RegisterArg dupReg, RegisterArg fReg) {
InsnNode assignInsn = fReg.getAssignInsn();
InsnNode dupAssign = dupReg.getAssignInsn();
if (assignInsn == null || dupAssign == null) {
return true;
}
if (!assignInsn.isSame(dupAssign)) {
return true;
}
if (assignInsn.isConstInsn() && dupAssign.isConstInsn()) {
return !assignInsn.isDeepEquals(dupAssign);
}
return false;
}
@SuppressWarnings("RedundantIfStatement")
private static boolean assignedOutsideHandler(FinallyExtractInfo extractInfo, RegisterArg dupReg, RegisterArg fReg) {
if (InsnList.contains(extractInfo.getFinallyInsnsSlice().getInsnsList(), fReg.getAssignInsn())) {
return false;
}
InsnNode dupAssign = dupReg.getAssignInsn();
InsnsSlice curDupSlice = extractInfo.getCurDupSlice();
if (curDupSlice != null && InsnList.contains(curDupSlice.getInsnsList(), dupAssign)) {
return false;
}
List<InsnNode> curDupInsns = extractInfo.getCurDupInsns();
if (Utils.notEmpty(curDupInsns) && InsnList.contains(curDupInsns, dupAssign, extractInfo.getCurDupInsnsOffset())) {
return false;
}
return true;
}
/**
* Reload method without applying this visitor
*/
private static void undoFinallyVisitor(MethodNode mth) {
try {
// TODO: make more common and less hacky
mth.unload();
mth.load();
for (IDexTreeVisitor visitor : mth.root().getPasses()) {
if (visitor instanceof MarkFinallyVisitor) {
break;
}
DepthTraversal.visit(visitor, mth);
}
} catch (Exception e) {
mth.addError("Undo finally extract failed", e);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/prepare/CollectConstValues.java | jadx-core/src/main/java/jadx/core/dex/visitors/prepare/CollectConstValues.java | package jadx.core.dex.visitors.prepare;
import org.jetbrains.annotations.Nullable;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.info.ConstStorage;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.dex.visitors.usage.UsageInfoVisitor;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "CollectConstValues",
desc = "Collect and store values from static final fields",
runAfter = {
UsageInfoVisitor.class // check field usage (do not restore if used somewhere)
}
)
public class CollectConstValues extends AbstractVisitor {
@Override
public boolean visit(ClassNode cls) throws JadxException {
RootNode root = cls.root();
if (!root.getArgs().isReplaceConsts()) {
return true;
}
if (cls.getFields().isEmpty()) {
return true;
}
ConstStorage constStorage = root.getConstValues();
for (FieldNode fld : cls.getFields()) {
try {
Object value = getFieldConstValue(fld);
if (value != null) {
constStorage.addConstField(fld, value, fld.getAccessFlags().isPublic());
}
} catch (Exception e) {
cls.addWarnComment("Failed to process value of field: " + fld, e);
}
}
return true;
}
public static @Nullable Object getFieldConstValue(FieldNode fld) {
AccessInfo accFlags = fld.getAccessFlags();
if (!accFlags.isStatic() || !accFlags.isFinal()) {
return null;
}
EncodedValue constVal = fld.get(JadxAttrType.CONSTANT_VALUE);
if (constVal == null || constVal == EncodedValue.NULL) {
return null;
}
if (!fld.getUseIn().isEmpty()) {
// field still used somewhere and not inlined by compiler, so we don't need to restore it
return null;
}
return constVal.getValue();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/visitors/prepare/AddAndroidConstants.java | jadx-core/src/main/java/jadx/core/dex/visitors/prepare/AddAndroidConstants.java | package jadx.core.dex.visitors.prepare;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.ConstStorage;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.JadxVisitor;
import jadx.core.utils.android.AndroidResourcesMap;
import jadx.core.utils.exceptions.JadxException;
// TODO: move this pass to separate "Android plugin"
@JadxVisitor(
name = "AddAndroidConstants",
desc = "Insert Android constants from resource mapping file",
runBefore = {
CollectConstValues.class
}
)
public class AddAndroidConstants extends AbstractVisitor {
private static final String R_CLS = "android.R";
private static final String R_INNER_CLS = R_CLS + '$';
@Override
public void init(RootNode root) throws JadxException {
if (!root.getArgs().isReplaceConsts()) {
return;
}
if (root.resolveClass(R_CLS) != null) {
// Android R class already loaded
return;
}
ConstStorage constStorage = root.getConstValues();
AndroidResourcesMap.getMap().forEach((resId, path) -> {
int sep = path.indexOf('/');
String clsName = R_INNER_CLS + path.substring(0, sep);
String resName = path.substring(sep + 1);
ClassInfo cls = ClassInfo.fromName(root, clsName);
FieldInfo field = FieldInfo.from(root, cls, resName, ArgType.INT);
constStorage.addGlobalConstField(field, resId);
});
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/info/MethodInfo.java | jadx-core/src/main/java/jadx/core/dex/info/MethodInfo.java | package jadx.core.dex.info;
import java.util.List;
import java.util.Objects;
import org.jetbrains.annotations.Nullable;
import jadx.api.plugins.input.data.IMethodProto;
import jadx.api.plugins.input.data.IMethodRef;
import jadx.core.codegen.TypeGen;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.Utils;
public final class MethodInfo implements Comparable<MethodInfo> {
private final String name;
private final ArgType retType;
private final List<ArgType> argTypes;
private final ClassInfo declClass;
private final String shortId;
private final String rawFullId;
private final int hash;
private String alias;
private MethodInfo(ClassInfo declClass, String name, List<ArgType> args, ArgType retType) {
this.name = name;
this.alias = name;
this.declClass = declClass;
this.argTypes = args;
this.retType = retType;
this.shortId = makeShortId(name, argTypes, retType);
this.rawFullId = declClass.makeRawFullName() + '.' + shortId;
this.hash = calcHashCode();
}
public static MethodInfo fromRef(RootNode root, IMethodRef methodRef) {
InfoStorage infoStorage = root.getInfoStorage();
int uniqId = methodRef.getUniqId();
if (uniqId != 0) {
MethodInfo prevMth = infoStorage.getByUniqId(uniqId);
if (prevMth != null) {
return prevMth;
}
}
methodRef.load();
ArgType parentClsType = ArgType.parse(methodRef.getParentClassType());
ClassInfo parentClass = ClassInfo.fromType(root, parentClsType);
ArgType returnType = ArgType.parse(methodRef.getReturnType());
List<ArgType> args = Utils.collectionMap(methodRef.getArgTypes(), ArgType::parse);
MethodInfo newMth = new MethodInfo(parentClass, methodRef.getName(), args, returnType);
MethodInfo uniqMth = infoStorage.putMethod(newMth);
if (uniqId != 0) {
infoStorage.putByUniqId(uniqId, uniqMth);
}
return uniqMth;
}
public static MethodInfo fromDetails(RootNode root, ClassInfo declClass, String name, List<ArgType> args, ArgType retType) {
MethodInfo newMth = new MethodInfo(declClass, name, args, retType);
return root.getInfoStorage().putMethod(newMth);
}
public static MethodInfo fromMethodProto(RootNode root, ClassInfo declClass, String name, IMethodProto proto) {
List<ArgType> args = Utils.collectionMap(proto.getArgTypes(), ArgType::parse);
ArgType returnType = ArgType.parse(proto.getReturnType());
return fromDetails(root, declClass, name, args, returnType);
}
public String makeSignature(boolean includeRetType) {
return makeSignature(false, includeRetType);
}
public String makeSignature(boolean useAlias, boolean includeRetType) {
return makeShortId(useAlias ? alias : name,
argTypes,
includeRetType ? retType : null);
}
public static String makeShortId(String name, List<ArgType> argTypes, @Nullable ArgType retType) {
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append('(');
for (ArgType arg : argTypes) {
sb.append(TypeGen.signature(arg));
}
sb.append(')');
if (retType != null) {
sb.append(TypeGen.signature(retType));
}
return sb.toString();
}
public boolean isOverloadedBy(MethodInfo otherMthInfo) {
return argTypes.size() == otherMthInfo.argTypes.size()
&& name.equals(otherMthInfo.name)
&& !Objects.equals(this.shortId, otherMthInfo.shortId);
}
public String getName() {
return name;
}
public String getFullName() {
return declClass.getFullName() + '.' + name;
}
public String getAliasFullName() {
return declClass.getAliasFullName() + '.' + alias;
}
public String getFullId() {
return declClass.getFullName() + '.' + shortId;
}
public String getRawFullId() {
return rawFullId;
}
/**
* Method name and signature
*/
public String getShortId() {
return shortId;
}
public ClassInfo getDeclClass() {
return declClass;
}
public ArgType getReturnType() {
return retType;
}
public List<ArgType> getArgumentsTypes() {
return argTypes;
}
public int getArgsCount() {
return argTypes.size();
}
public boolean isConstructor() {
return name.equals("<init>");
}
public boolean isClassInit() {
return name.equals("<clinit>");
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public void removeAlias() {
this.alias = name;
}
public boolean hasAlias() {
return !name.equals(alias);
}
public int calcHashCode() {
return shortId.hashCode() + 31 * declClass.hashCode();
}
@Override
public int hashCode() {
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof MethodInfo)) {
return false;
}
MethodInfo other = (MethodInfo) obj;
return shortId.equals(other.shortId)
&& declClass.equals(other.declClass);
}
@Override
public int compareTo(MethodInfo other) {
int clsCmp = declClass.compareTo(other.declClass);
if (clsCmp != 0) {
return clsCmp;
}
return shortId.compareTo(other.shortId);
}
@Override
public String toString() {
return declClass.getFullName() + '.' + name
+ '(' + Utils.listToString(argTypes) + "):" + retType;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/info/ClassAliasInfo.java | jadx-core/src/main/java/jadx/core/dex/info/ClassAliasInfo.java | package jadx.core.dex.info;
import org.jetbrains.annotations.Nullable;
import jadx.core.utils.StringUtils;
class ClassAliasInfo {
private final String shortName;
@Nullable
private final String pkg;
@Nullable
private String fullName;
ClassAliasInfo(@Nullable String pkg, String shortName) {
if (StringUtils.isEmpty(shortName)) {
throw new IllegalArgumentException("Class alias can't be empty");
}
this.pkg = pkg;
this.shortName = shortName;
}
@Nullable
public String getPkg() {
return pkg;
}
public String getShortName() {
return shortName;
}
@Nullable
public String getFullName() {
return fullName;
}
public void setFullName(@Nullable String fullName) {
this.fullName = fullName;
}
@Override
public String toString() {
return "Alias{" + shortName + ", pkg=" + pkg + ", fullName=" + fullName + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/info/ConstStorage.java | jadx-core/src/main/java/jadx/core/dex/info/ConstStorage.java | package jadx.core.dex.info;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.jetbrains.annotations.Nullable;
import jadx.api.JadxArgs;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.IFieldInfoRef;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.prepare.CollectConstValues;
public class ConstStorage {
private static final class ValueStorage {
private final Map<Object, IFieldInfoRef> values = new ConcurrentHashMap<>();
private final Set<Object> duplicates = new HashSet<>();
public Map<Object, IFieldInfoRef> getValues() {
return values;
}
public IFieldInfoRef get(Object key) {
return values.get(key);
}
/**
* @return true if this value is duplicated
*/
public boolean put(Object value, IFieldInfoRef fld) {
if (duplicates.contains(value)) {
values.remove(value);
return true;
}
IFieldInfoRef prev = values.put(value, fld);
if (prev != null) {
values.remove(value);
duplicates.add(value);
return true;
}
return false;
}
public boolean contains(Object value) {
return duplicates.contains(value) || values.containsKey(value);
}
void removeForCls(ClassNode cls) {
values.entrySet().removeIf(entry -> {
IFieldInfoRef field = entry.getValue();
if (field instanceof FieldNode) {
return ((FieldNode) field).getParentClass().equals(cls);
}
return false;
});
}
}
private final boolean replaceEnabled;
private final ValueStorage globalValues = new ValueStorage();
private final Map<ClassNode, ValueStorage> classes = new HashMap<>();
private Map<Integer, String> resourcesNames = new HashMap<>();
public ConstStorage(JadxArgs args) {
this.replaceEnabled = args.isReplaceConsts();
}
public void addConstField(FieldNode fld, Object value, boolean isPublic) {
if (isPublic) {
addGlobalConstField(fld, value);
} else {
getClsValues(fld.getParentClass()).put(value, fld);
}
}
public void addGlobalConstField(IFieldInfoRef fld, Object value) {
globalValues.put(value, fld);
}
/**
* Use method from CollectConstValues class
*/
@Deprecated
public static @Nullable Object getFieldConstValue(FieldNode fld) {
return CollectConstValues.getFieldConstValue(fld);
}
public void removeForClass(ClassNode cls) {
classes.remove(cls);
globalValues.removeForCls(cls);
}
private ValueStorage getClsValues(ClassNode cls) {
return classes.computeIfAbsent(cls, c -> new ValueStorage());
}
public @Nullable IFieldInfoRef getConstField(ClassNode cls, Object value, boolean searchGlobal) {
if (!replaceEnabled) {
return null;
}
RootNode root = cls.root();
if (value instanceof Integer) {
FieldNode rField = getResourceField((Integer) value, root);
if (rField != null) {
return rField;
}
}
boolean foundInGlobal = globalValues.contains(value);
if (foundInGlobal && !searchGlobal) {
return null;
}
ClassNode current = cls;
while (current != null) {
ValueStorage classValues = classes.get(current);
if (classValues != null) {
IFieldInfoRef field = classValues.get(value);
if (field != null) {
if (foundInGlobal) {
return null;
}
return field;
}
}
ClassInfo parentClass = current.getClassInfo().getParentClass();
if (parentClass == null) {
break;
}
current = root.resolveClass(parentClass);
}
if (searchGlobal) {
return globalValues.get(value);
}
return null;
}
@Nullable
private FieldNode getResourceField(Integer value, RootNode root) {
String str = resourcesNames.get(value);
if (str == null) {
return null;
}
ClassNode appResClass = root.getAppResClass();
if (appResClass == null) {
return null;
}
String[] parts = str.split("/", 2);
if (parts.length != 2) {
return null;
}
String typeName = parts[0];
String fieldName = parts[1];
for (ClassNode innerClass : appResClass.getInnerClasses()) {
if (innerClass.getClassInfo().getShortName().equals(typeName)) {
return innerClass.searchFieldByName(fieldName);
}
}
appResClass.addWarn("Not found resource field with id: " + value + ", name: " + str.replace('/', '.'));
return null;
}
public @Nullable IFieldInfoRef getConstFieldByLiteralArg(ClassNode cls, LiteralArg arg) {
if (!replaceEnabled) {
return null;
}
PrimitiveType type = arg.getType().getPrimitiveType();
if (type == null) {
return null;
}
long literal = arg.getLiteral();
switch (type) {
case BOOLEAN:
return getConstField(cls, literal == 1, false);
case CHAR:
return getConstField(cls, (char) literal, Math.abs(literal) > 10);
case BYTE:
return getConstField(cls, (byte) literal, Math.abs(literal) > 10);
case SHORT:
return getConstField(cls, (short) literal, Math.abs(literal) > 100);
case INT:
return getConstField(cls, (int) literal, Math.abs(literal) > 100);
case LONG:
return getConstField(cls, literal, Math.abs(literal) > 1000);
case FLOAT:
float f = Float.intBitsToFloat((int) literal);
return getConstField(cls, f, Float.compare(f, 0) == 0);
case DOUBLE:
double d = Double.longBitsToDouble(literal);
return getConstField(cls, d, Double.compare(d, 0) == 0);
default:
return null;
}
}
public void setResourcesNames(Map<Integer, String> resourcesNames) {
this.resourcesNames = resourcesNames;
}
public Map<Integer, String> getResourcesNames() {
return resourcesNames;
}
public Map<Object, IFieldInfoRef> getGlobalConstFields() {
return globalValues.getValues();
}
public boolean isReplaceEnabled() {
return replaceEnabled;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/info/AccessInfo.java | jadx-core/src/main/java/jadx/core/dex/info/AccessInfo.java | package jadx.core.dex.info;
import org.intellij.lang.annotations.MagicConstant;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.core.Consts;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class AccessInfo {
public static final int VISIBILITY_FLAGS = AccessFlags.PUBLIC | AccessFlags.PROTECTED | AccessFlags.PRIVATE;
private final int accFlags;
public enum AFType {
CLASS, FIELD, METHOD
}
private final AFType type;
public AccessInfo(int accessFlags, AFType type) {
this.accFlags = accessFlags;
this.type = type;
}
@MagicConstant(valuesFromClass = AccessFlags.class)
public boolean containsFlag(int flag) {
return (accFlags & flag) != 0;
}
@MagicConstant(valuesFromClass = AccessFlags.class)
public boolean containsFlags(int... flags) {
for (int flag : flags) {
if ((accFlags & flag) == 0) {
return false;
}
}
return true;
}
public AccessInfo remove(int flag) {
if (containsFlag(flag)) {
return new AccessInfo(accFlags & ~flag, type);
}
return this;
}
public AccessInfo add(int flag) {
if (!containsFlag(flag)) {
return new AccessInfo(accFlags | flag, type);
}
return this;
}
public AccessInfo changeVisibility(int flag) {
int currentVisFlags = accFlags & VISIBILITY_FLAGS;
if (currentVisFlags == flag) {
return this;
}
int unsetAllVisFlags = accFlags & ~VISIBILITY_FLAGS;
return new AccessInfo(unsetAllVisFlags | flag, type);
}
public AccessInfo getVisibility() {
return new AccessInfo(accFlags & VISIBILITY_FLAGS, type);
}
public boolean isVisibilityWeakerThan(AccessInfo otherAccInfo) {
int thisVis = accFlags & VISIBILITY_FLAGS;
int otherVis = otherAccInfo.accFlags & VISIBILITY_FLAGS;
if (thisVis == otherVis) {
return false;
}
return orderedVisibility(thisVis) < orderedVisibility(otherVis);
}
private static int orderedVisibility(int flag) {
switch (flag) {
case AccessFlags.PRIVATE:
return 1;
case 0: // package-private
return 2;
case AccessFlags.PROTECTED:
return 3;
case AccessFlags.PUBLIC:
return 4;
default:
throw new JadxRuntimeException("Unexpected visibility flag: " + flag);
}
}
public boolean isPublic() {
return (accFlags & AccessFlags.PUBLIC) != 0;
}
public boolean isProtected() {
return (accFlags & AccessFlags.PROTECTED) != 0;
}
public boolean isPrivate() {
return (accFlags & AccessFlags.PRIVATE) != 0;
}
public boolean isPackagePrivate() {
return (accFlags & VISIBILITY_FLAGS) == 0;
}
public boolean isAbstract() {
return (accFlags & AccessFlags.ABSTRACT) != 0;
}
public boolean isInterface() {
return (accFlags & AccessFlags.INTERFACE) != 0;
}
public boolean isAnnotation() {
return (accFlags & AccessFlags.ANNOTATION) != 0;
}
public boolean isNative() {
return (accFlags & AccessFlags.NATIVE) != 0;
}
public boolean isStatic() {
return (accFlags & AccessFlags.STATIC) != 0;
}
public boolean isFinal() {
return (accFlags & AccessFlags.FINAL) != 0;
}
public boolean isConstructor() {
return (accFlags & AccessFlags.CONSTRUCTOR) != 0;
}
public boolean isEnum() {
return (accFlags & AccessFlags.ENUM) != 0;
}
public boolean isSynthetic() {
return (accFlags & AccessFlags.SYNTHETIC) != 0;
}
public boolean isBridge() {
return (accFlags & AccessFlags.BRIDGE) != 0;
}
public boolean isVarArgs() {
return (accFlags & AccessFlags.VARARGS) != 0;
}
public boolean isSynchronized() {
return (accFlags & (AccessFlags.SYNCHRONIZED | AccessFlags.DECLARED_SYNCHRONIZED)) != 0;
}
public boolean isTransient() {
return (accFlags & AccessFlags.TRANSIENT) != 0;
}
public boolean isVolatile() {
return (accFlags & AccessFlags.VOLATILE) != 0;
}
public boolean isModuleInfo() {
return (accFlags & AccessFlags.MODULE) != 0;
}
public boolean isData() {
return (accFlags & AccessFlags.DATA) != 0;
}
public AFType getType() {
return type;
}
public String makeString(boolean showHidden) {
StringBuilder code = new StringBuilder();
if (isPublic()) {
code.append("public ");
}
if (isPrivate()) {
code.append("private ");
}
if (isProtected()) {
code.append("protected ");
}
if (isStatic()) {
code.append("static ");
}
if (isFinal()) {
code.append("final ");
}
if (isAbstract()) {
code.append("abstract ");
}
if (isNative()) {
code.append("native ");
}
switch (type) {
case METHOD:
if (isSynchronized()) {
code.append("synchronized ");
}
if (showHidden) {
if (isBridge()) {
code.append("/* bridge */ ");
}
if (Consts.DEBUG && isVarArgs()) {
code.append("/* varargs */ ");
}
}
break;
case FIELD:
if (isVolatile()) {
code.append("volatile ");
}
if (isTransient()) {
code.append("transient ");
}
break;
case CLASS:
if ((accFlags & AccessFlags.STRICT) != 0) {
code.append("strict ");
}
if (showHidden) {
if (isData()) {
code.append("/* data */ ");
}
if (isModuleInfo()) {
code.append("/* module-info */ ");
}
if (Consts.DEBUG) {
if ((accFlags & AccessFlags.SUPER) != 0) {
code.append("/* super */ ");
}
if ((accFlags & AccessFlags.ENUM) != 0) {
code.append("/* enum */ ");
}
}
}
break;
}
if (isSynthetic() && showHidden) {
code.append("/* synthetic */ ");
}
return code.toString();
}
public String visibilityName() {
if (isPackagePrivate()) {
return "package-private";
}
if (isPublic()) {
return "public";
}
if (isPrivate()) {
return "private";
}
if (isProtected()) {
return "protected";
}
throw new JadxRuntimeException("Unknown visibility flags: " + getVisibility());
}
public int rawValue() {
return accFlags;
}
@Override
public String toString() {
return "AccessInfo: " + type + " 0x" + Integer.toHexString(accFlags) + " (" + makeString(true) + ')';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.