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/nodes/Edge.java
jadx-core/src/main/java/jadx/core/dex/nodes/Edge.java
package jadx.core.dex.nodes; public class Edge { private final BlockNode source; private final BlockNode target; public Edge(BlockNode source, BlockNode target) { this.source = source; this.target = target; } public BlockNode getSource() { return source; } public BlockNode getTarget() { return target; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Edge edge = (Edge) o; return source.equals(edge.source) && target.equals(edge.target); } @Override public int hashCode() { return source.hashCode() + 31 * target.hashCode(); } @Override public String toString() { return "Edge: " + source + " -> " + target; } }
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/nodes/IPackageUpdate.java
jadx-core/src/main/java/jadx/core/dex/nodes/IPackageUpdate.java
package jadx.core.dex.nodes; public interface IPackageUpdate { void onParentPackageUpdate(PackageNode updatedPkg); }
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/nodes/InsnNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/InsnNode.java
package jadx.core.dex.nodes; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Function; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.LineAttrNode; 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.InsnWrapArg; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.instructions.args.SSAVar; import jadx.core.utils.InsnRemover; import jadx.core.utils.InsnUtils; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; public class InsnNode extends LineAttrNode { protected final InsnType insnType; private RegisterArg result; private final List<InsnArg> arguments; protected int offset; public InsnNode(InsnType type, int argsCount) { this(type, argsCount == 0 ? Collections.emptyList() : new ArrayList<>(argsCount)); } public InsnNode(InsnType type, List<InsnArg> args) { this.insnType = type; this.arguments = args; this.offset = -1; for (InsnArg arg : args) { attachArg(arg); } } public static InsnNode wrapArg(InsnArg arg) { InsnNode insn = new InsnNode(InsnType.ONE_ARG, 1); insn.addArg(arg); return insn; } public void setResult(@Nullable RegisterArg res) { this.result = res; if (res != null) { res.setParentInsn(this); SSAVar ssaVar = res.getSVar(); if (ssaVar != null) { ssaVar.setAssign(res); } } } public void addArg(InsnArg arg) { arguments.add(arg); attachArg(arg); } public void setArg(int n, InsnArg arg) { arguments.set(n, arg); attachArg(arg); } protected void attachArg(InsnArg arg) { arg.setParentInsn(this); if (arg.isRegister()) { RegisterArg reg = (RegisterArg) arg; SSAVar ssaVar = reg.getSVar(); if (ssaVar != null) { ssaVar.use(reg); } } } public InsnType getType() { return insnType; } public RegisterArg getResult() { return result; } public Iterable<InsnArg> getArguments() { return arguments; } public List<InsnArg> getArgList() { return arguments; } public int getArgsCount() { return arguments.size(); } public InsnArg getArg(int n) { return arguments.get(n); } public boolean containsArg(InsnArg arg) { if (getArgsCount() == 0) { return false; } for (InsnArg a : arguments) { if (a == arg) { return true; } } return false; } public boolean containsVar(RegisterArg arg) { if (getArgsCount() == 0) { return false; } return InsnUtils.containsVar(arguments, arg); } /** * Replace instruction arg with another using recursive search. */ public boolean replaceArg(InsnArg from, InsnArg to) { int count = getArgsCount(); for (int i = 0; i < count; i++) { InsnArg arg = arguments.get(i); if (arg == from) { InsnRemover.unbindArgUsage(null, arg); setArg(i, to); return true; } if (arg.isInsnWrap() && ((InsnWrapArg) arg).getWrapInsn().replaceArg(from, to)) { return true; } } return false; } protected boolean removeArg(InsnArg arg) { int index = getArgIndex(arg); if (index == -1) { return false; } removeArg(index); return true; } public InsnArg removeArg(int index) { InsnArg arg = arguments.get(index); arguments.remove(index); InsnRemover.unbindArgUsage(null, arg); return arg; } public int getArgIndex(InsnArg arg) { int count = getArgsCount(); for (int i = 0; i < count; i++) { if (arg == arguments.get(i)) { return i; } } return -1; } protected void addReg(InsnData insn, int i, ArgType type) { addArg(InsnArg.reg(insn, i, type)); } protected void addReg(int regNum, ArgType type) { addArg(InsnArg.reg(regNum, type)); } protected void addLit(long literal, ArgType type) { addArg(InsnArg.lit(literal, type)); } protected void addLit(InsnData insn, ArgType type) { addArg(InsnArg.lit(insn, type)); } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public void getRegisterArgs(Collection<RegisterArg> collection) { for (InsnArg arg : this.getArguments()) { if (arg.isRegister()) { collection.add((RegisterArg) arg); } else if (arg.isInsnWrap()) { ((InsnWrapArg) arg).getWrapInsn().getRegisterArgs(collection); } } } public boolean isConstInsn() { switch (getType()) { case CONST: case CONST_STR: case CONST_CLASS: return true; default: return false; } } public boolean isExitEdgeInsn() { switch (getType()) { case RETURN: case THROW: case CONTINUE: case BREAK: return true; default: return false; } } public boolean canRemoveResult() { switch (getType()) { case INVOKE: case CONSTRUCTOR: return true; default: return false; } } public boolean canReorder() { if (contains(AFlag.DONT_GENERATE)) { if (getType() == InsnType.MONITOR_EXIT) { return false; } return true; } for (InsnArg arg : getArguments()) { if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); if (!wrapInsn.canReorder()) { return false; } } } switch (getType()) { case CONST: case CONST_STR: case CONST_CLASS: case CAST: case MOVE: case ARITH: case NEG: case CMP_L: case CMP_G: case CHECK_CAST: case INSTANCE_OF: case FILL_ARRAY: case FILLED_NEW_ARRAY: case NEW_ARRAY: case STR_CONCAT: return true; case SGET: case IGET: // TODO: allow to move final fields return false; default: return false; } } public boolean containsWrappedInsn() { for (InsnArg arg : this.getArguments()) { if (arg.isInsnWrap()) { return true; } } return false; } /** * Visit this instruction and all inner (wrapped) instructions */ public void visitInsns(Consumer<InsnNode> visitor) { visitor.accept(this); for (InsnArg arg : this.getArguments()) { if (arg.isInsnWrap()) { ((InsnWrapArg) arg).getWrapInsn().visitInsns(visitor); } } } /** * Visit this instruction and all inner (wrapped) instructions * To terminate visiting return non-null value */ @Nullable public <R> R visitInsns(Function<InsnNode, R> visitor) { R result = visitor.apply(this); if (result != null) { return result; } for (InsnArg arg : this.getArguments()) { if (arg.isInsnWrap()) { InsnNode innerInsn = ((InsnWrapArg) arg).getWrapInsn(); R res = innerInsn.visitInsns(visitor); if (res != null) { return res; } } } return null; } /** * Visit all args recursively (including inner instructions), but excluding wrapped args */ public void visitArgs(Consumer<InsnArg> visitor) { for (InsnArg arg : getArguments()) { if (arg.isInsnWrap()) { ((InsnWrapArg) arg).getWrapInsn().visitArgs(visitor); } else { visitor.accept(arg); } } } /** * Visit all args recursively (including inner instructions), but excluding wrapped args. * To terminate visiting return non-null value */ @Nullable public <R> R visitArgs(Function<InsnArg, R> visitor) { for (InsnArg arg : getArguments()) { R result; if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); result = wrapInsn.visitArgs(visitor); } else { result = visitor.apply(arg); } if (result != null) { return result; } } return null; } /** * 'Soft' equals, don't compare arguments, only instruction specific parameters. */ public boolean isSame(InsnNode other) { if (this == other) { return true; } if (insnType != other.insnType) { return false; } int size = arguments.size(); if (size != other.arguments.size()) { return false; } // check wrapped instructions for (int i = 0; i < size; i++) { InsnArg arg = arguments.get(i); InsnArg otherArg = other.arguments.get(i); if (arg.isInsnWrap()) { if (!otherArg.isInsnWrap()) { return false; } InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); InsnNode otherWrapInsn = ((InsnWrapArg) otherArg).getWrapInsn(); if (!wrapInsn.isSame(otherWrapInsn)) { return false; } } } return true; } /** * 'Hard' equals, compare all arguments */ public boolean isDeepEquals(InsnNode other) { if (this == other) { return true; } return isSame(other) && Objects.equals(result, other.result) && Objects.equals(arguments, other.arguments); } protected final <T extends InsnNode> T copyCommonParams(T copy) { if (copy.getArgsCount() == 0) { for (InsnArg arg : this.getArguments()) { copy.addArg(arg.duplicate()); } } copy.copyAttributesFrom(this); copy.copyLines(this); copy.setOffset(this.getOffset()); return copy; } public void copyAttributesFrom(InsnNode attrNode) { super.copyAttributesFrom(attrNode); this.addSourceLineFrom(attrNode); } /** * Make copy of InsnNode object. * <br> * NOTE: can't copy instruction with result argument * (SSA variable can't be used in two different assigns). * <br> * Prefer use next methods: * <ul> * <li>{@link #copyWithoutResult()} to explicitly state that result not needed * <li>{@link #copy(RegisterArg)} to provide new result arg * <li>{@link #copyWithNewSsaVar(MethodNode)} to make new SSA variable for result arg * </ul> */ public InsnNode copy() { if (this.getClass() != InsnNode.class) { throw new JadxRuntimeException("Copy method not implemented in insn class " + this.getClass().getSimpleName()); } return copyCommonParams(new InsnNode(insnType, getArgsCount())); } /** * See {@link #copy()} */ @SuppressWarnings("unchecked") public <T extends InsnNode> T copyWithoutResult() { return (T) copy(); } public InsnNode copyWithoutSsa() { InsnNode copy = copyWithoutResult(); if (result != null) { if (result.getSVar() == null) { copy.setResult(result.duplicate()); } else { throw new JadxRuntimeException("Can't copy if SSA var is set"); } } return copy; } /** * See {@link #copy()} */ public InsnNode copy(RegisterArg newReturnArg) { InsnNode copy = copy(); copy.setResult(newReturnArg); return copy; } /** * See {@link #copy()} */ public InsnNode copyWithNewSsaVar(MethodNode mth) { RegisterArg result = getResult(); if (result == null) { throw new JadxRuntimeException("Result in null"); } int regNum = result.getRegNum(); RegisterArg resDupArg = result.duplicate(regNum, null); mth.makeNewSVar(resDupArg); return copy(resDupArg); } /** * Fix SSAVar info in register arguments. * Must be used after altering instructions. */ public void rebindArgs() { RegisterArg resArg = getResult(); if (resArg != null) { SSAVar ssaVar = resArg.getSVar(); if (ssaVar == null) { throw new JadxRuntimeException("No SSA var for result arg: " + resArg + " from " + resArg.getParentInsn()); } ssaVar.setAssign(resArg); } for (InsnArg arg : getArguments()) { if (arg instanceof RegisterArg) { RegisterArg reg = (RegisterArg) arg; SSAVar ssaVar = reg.getSVar(); ssaVar.use(reg); ssaVar.updateUsedInPhiList(); } else if (arg instanceof InsnWrapArg) { ((InsnWrapArg) arg).getWrapInsn().rebindArgs(); } } } public boolean canThrowException() { switch (getType()) { case RETURN: case IF: case GOTO: case MOVE: case MOVE_EXCEPTION: case NEG: case CONST: case CONST_STR: case CONST_CLASS: case CMP_L: case CMP_G: case NOP: return false; default: return true; } } public void inheritMetadata(InsnNode sourceInsn) { if (insnType == InsnType.RETURN) { this.copyLines(sourceInsn); if (this.contains(AFlag.SYNTHETIC)) { this.setOffset(sourceInsn.getOffset()); this.rewriteAttributeFrom(sourceInsn, AType.CODE_COMMENTS); } else { this.copyAttributeFrom(sourceInsn, AType.CODE_COMMENTS); } } else { this.copyAttributeFrom(sourceInsn, AType.CODE_COMMENTS); this.addSourceLineFrom(sourceInsn); } } /** * Compare instruction only by identity. */ @SuppressWarnings("EmptyMethod") @Override public final int hashCode() { return super.hashCode(); } /** * Compare instruction only by identity. */ @Override public final boolean equals(Object obj) { return super.equals(obj); } /** * Append arguments type, wrap line if too long * * @return true if args wrapped */ protected boolean appendArgs(StringBuilder sb) { if (arguments.isEmpty()) { return false; } String argsStr = Utils.listToString(arguments); if (argsStr.length() < 120) { sb.append(argsStr); return false; } // wrap args String separator = "\n "; sb.append(separator).append(Utils.listToString(arguments, separator)); sb.append('\n'); return true; } protected String attributesString() { StringBuilder sb = new StringBuilder(); appendAttributes(sb); return sb.toString(); } protected void appendAttributes(StringBuilder sb) { if (!isAttrStorageEmpty()) { sb.append(' ').append(getAttributesString()); } if (getSourceLine() != 0) { sb.append(" (LINE:").append(getSourceLine()).append(')'); } } protected String baseString() { StringBuilder sb = new StringBuilder(); if (offset != -1) { sb.append(InsnUtils.formatOffset(offset)).append(": "); } sb.append(insnType).append(' '); if (result != null) { sb.append(result).append(" = "); } appendArgs(sb); return sb.toString(); } @Override public String toString() { return baseString() + attributesString(); } }
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/nodes/IContainer.java
jadx-core/src/main/java/jadx/core/dex/nodes/IContainer.java
package jadx.core.dex.nodes; import jadx.api.ICodeWriter; import jadx.core.codegen.RegionGen; import jadx.core.dex.attributes.IAttributeNode; import jadx.core.utils.exceptions.CodegenException; public interface IContainer extends IAttributeNode { /** * Unique id for use in 'toString()' method */ String baseString(); /** * Dispatch to needed generate method in RegionGen */ default void generate(RegionGen regionGen, ICodeWriter code) throws CodegenException { throw new CodegenException("Code generate not implemented for container: " + getClass().getSimpleName()); } }
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/nodes/IRegion.java
jadx-core/src/main/java/jadx/core/dex/nodes/IRegion.java
package jadx.core.dex.nodes; import java.util.List; public interface IRegion extends IContainer { IRegion getParent(); void setParent(IRegion parent); List<IContainer> getSubBlocks(); boolean replaceSubBlock(IContainer oldBlock, IContainer newBlock); }
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/nodes/MethodNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/MethodNode.java
package jadx.core.dex.nodes; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.JavaMethod; import jadx.api.metadata.ICodeNodeRef; import jadx.api.metadata.annotations.NodeDeclareRef; import jadx.api.metadata.annotations.VarNode; import jadx.api.plugins.input.data.ICodeReader; import jadx.api.plugins.input.data.IDebugInfo; import jadx.api.plugins.input.data.IMethodData; import jadx.api.plugins.input.data.attributes.JadxAttrType; import jadx.api.plugins.input.data.attributes.types.ExceptionsAttr; import jadx.api.utils.CodeUtils; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.LoopInfo; import jadx.core.dex.attributes.nodes.MethodOverrideAttr; import jadx.core.dex.attributes.nodes.MethodThrowsAttr; import jadx.core.dex.attributes.nodes.NotificationAttrNode; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.info.AccessInfo.AFType; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.InsnDecoder; 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.utils.TypeUtils; import jadx.core.dex.regions.Region; import jadx.core.dex.trycatch.ExceptionHandler; import jadx.core.dex.visitors.InitCodeVariables; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.DecodeException; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.utils.Utils.lockList; public class MethodNode extends NotificationAttrNode implements IMethodDetails, ILoadable, ICodeNode, Comparable<MethodNode> { private static final Logger LOG = LoggerFactory.getLogger(MethodNode.class); private static final InsnNode[] EMPTY_INSN_ARRAY = new InsnNode[0]; private final MethodInfo mthInfo; private final ClassNode parentClass; private AccessInfo accFlags; private final ICodeReader codeReader; private final int insnsCount; private boolean noCode; private int regsCount; private int argsStartReg; private boolean loaded; // additional info available after load, keep on unload private ArgType retType; private List<ArgType> argTypes; private List<ArgType> typeParameters; // decompilation data, reset on unload private RegisterArg thisArg; private List<RegisterArg> argsList; private InsnNode[] instructions; private List<BlockNode> blocks; private int blocksMaxCId; private BlockNode enterBlock; private BlockNode exitBlock; private List<SSAVar> sVars; private List<ExceptionHandler> exceptionHandlers; private List<LoopInfo> loops; private Region region; private List<MethodNode> useIn = Collections.emptyList(); private JavaMethod javaNode; public static MethodNode build(ClassNode classNode, IMethodData methodData) { MethodNode methodNode = new MethodNode(classNode, methodData); methodNode.addAttrs(methodData.getAttributes()); return methodNode; } private MethodNode(ClassNode classNode, IMethodData mthData) { this.mthInfo = MethodInfo.fromRef(classNode.root(), mthData.getMethodRef()); this.parentClass = classNode; this.accFlags = new AccessInfo(mthData.getAccessFlags(), AFType.METHOD); ICodeReader codeReader = mthData.getCodeReader(); this.noCode = codeReader == null; if (noCode) { this.codeReader = null; this.insnsCount = 0; } else { this.codeReader = codeReader.copy(); this.insnsCount = codeReader.getUnitsCount(); } this.retType = mthInfo.getReturnType(); this.argTypes = mthInfo.getArgumentsTypes(); this.typeParameters = Collections.emptyList(); unload(); } @Override public void unload() { loaded = false; // don't unload retType, argTypes, typeParameters thisArg = null; argsList = null; sVars = Collections.emptyList(); instructions = null; blocks = null; enterBlock = null; exitBlock = null; region = null; exceptionHandlers = Collections.emptyList(); loops = Collections.emptyList(); unloadAttributes(); } public void updateTypes(List<ArgType> argTypes, ArgType retType) { this.argTypes = argTypes; this.retType = retType; } public void updateTypeParameters(List<ArgType> typeParameters) { this.typeParameters = typeParameters; } @Override public void load() throws DecodeException { if (loaded) { // method already loaded return; } try { loaded = true; if (noCode) { regsCount = 0; // TODO: registers not needed without code initArguments(this.argTypes); return; } this.regsCount = codeReader.getRegistersCount(); this.argsStartReg = codeReader.getArgsStartReg(); initArguments(this.argTypes); if (contains(AType.JADX_ERROR)) { // don't load instructions for method with errors this.instructions = EMPTY_INSN_ARRAY; } else { InsnDecoder decoder = new InsnDecoder(this); this.instructions = decoder.process(codeReader); } } catch (Exception e) { if (!noCode) { unload(); noCode = true; // load without code load(); noCode = false; } throw new DecodeException(this, "Load method exception: " + e.getClass().getSimpleName() + ": " + e.getMessage(), e); } } public void reload() { unload(); try { load(); } catch (DecodeException e) { throw new JadxRuntimeException("Failed to reload method " + getClass().getName() + "." + getName()); } } private void initArguments(List<ArgType> args) { int pos = getArgsStartPos(args); TypeUtils typeUtils = root().getTypeUtils(); if (accFlags.isStatic()) { thisArg = null; } else { ArgType thisClsType = typeUtils.expandTypeVariables(this, parentClass.getType()); RegisterArg arg = InsnArg.reg(pos++, thisClsType); arg.add(AFlag.THIS); arg.add(AFlag.IMMUTABLE_TYPE); thisArg = arg; } if (args.isEmpty()) { argsList = Collections.emptyList(); return; } argsList = new ArrayList<>(args.size()); for (ArgType argType : args) { ArgType expandedType = typeUtils.expandTypeVariables(this, argType); RegisterArg regArg = InsnArg.reg(pos, expandedType); regArg.add(AFlag.METHOD_ARGUMENT); regArg.add(AFlag.IMMUTABLE_TYPE); argsList.add(regArg); pos += argType.getRegCount(); } } private int getArgsStartPos(List<ArgType> args) { if (noCode) { return 0; } if (argsStartReg != -1) { return argsStartReg; } int pos = regsCount; for (ArgType arg : args) { pos -= arg.getRegCount(); } if (!accFlags.isStatic()) { pos--; } return pos; } @Override @NotNull public List<ArgType> getArgTypes() { if (argTypes == null) { throw new JadxRuntimeException("Method generic types not initialized: " + this); } return argTypes; } public void updateArgTypes(List<ArgType> newArgTypes, String comment) { this.addDebugComment(comment + ", original types: " + getArgTypes()); this.argTypes = Collections.unmodifiableList(newArgTypes); initArguments(newArgTypes); } public boolean containsGenericArgs() { return !Objects.equals(mthInfo.getArgumentsTypes(), getArgTypes()); } @Override @NotNull public ArgType getReturnType() { return retType; } public void updateReturnType(ArgType type) { this.retType = type; } public boolean isVoidReturn() { return mthInfo.getReturnType().equals(ArgType.VOID); } public List<VarNode> collectArgNodes() { ICodeInfo codeInfo = getTopParentClass().getCode(); int mthDefPos = getDefPosition(); int lineEndPos = CodeUtils.getLineEndForPos(codeInfo.getCodeStr(), mthDefPos); int argsCount = mthInfo.getArgsCount(); List<VarNode> args = new ArrayList<>(argsCount); codeInfo.getCodeMetadata().searchDown(mthDefPos, (pos, ann) -> { if (pos > lineEndPos) { // Stop at line end return Boolean.TRUE; } if (ann instanceof NodeDeclareRef) { ICodeNodeRef declRef = ((NodeDeclareRef) ann).getNode(); if (declRef instanceof VarNode) { VarNode varNode = (VarNode) declRef; if (!varNode.getMth().equals(this)) { // Stop if we've gone too far and have entered a different method return Boolean.TRUE; } args.add(varNode); } } return null; }); if (args.size() != argsCount) { LOG.warn("Incorrect args count, expected: {}, got: {}", argsCount, args.size()); } return args; } public List<RegisterArg> getArgRegs() { if (argsList == null) { throw new JadxRuntimeException("Method arg registers not loaded: " + this + ", class status: " + parentClass.getTopParentClass().getState()); } return argsList; } public List<RegisterArg> getAllArgRegs() { List<RegisterArg> argRegs = getArgRegs(); if (thisArg != null) { List<RegisterArg> list = new ArrayList<>(argRegs.size() + 1); list.add(thisArg); list.addAll(argRegs); return list; } return argRegs; } @Nullable public RegisterArg getThisArg() { return thisArg; } public void skipFirstArgument() { this.add(AFlag.SKIP_FIRST_ARG); } @Override public List<ArgType> getTypeParameters() { return typeParameters; } public String getName() { return mthInfo.getName(); } public String getAlias() { return mthInfo.getAlias(); } @Override public ClassNode getDeclaringClass() { return parentClass; } public ClassNode getParentClass() { return parentClass; } public ClassNode getTopParentClass() { return parentClass.getTopParentClass(); } public boolean isNoCode() { return noCode; } public InsnNode[] getInstructions() { return instructions; } public void unloadInsnArr() { this.instructions = null; } public void initBasicBlocks() { blocks = new ArrayList<>(); } public void finishBasicBlocks() { blocks = lockList(blocks); loops = lockList(loops); blocks.forEach(BlockNode::lock); } public List<BlockNode> getBasicBlocks() { return blocks; } public void setBasicBlocks(List<BlockNode> blocks) { this.blocks = blocks; updateBlockPositions(); } public void updateBlockPositions() { BlockNode.updateBlockPositions(blocks); } public int getNextBlockCId() { return blocksMaxCId++; } public BlockNode getEnterBlock() { return enterBlock; } public void setEnterBlock(BlockNode enterBlock) { this.enterBlock = enterBlock; } public BlockNode getExitBlock() { return exitBlock; } public void setExitBlock(BlockNode exitBlock) { this.exitBlock = exitBlock; } public List<BlockNode> getPreExitBlocks() { return exitBlock.getPredecessors(); } public boolean isPreExitBlock(BlockNode block) { List<BlockNode> successors = block.getSuccessors(); if (successors.size() == 1) { return successors.get(0).equals(exitBlock); } return exitBlock.getPredecessors().contains(block); } public void resetLoops() { this.loops = new ArrayList<>(); } public void registerLoop(LoopInfo loop) { if (loops.isEmpty()) { loops = new ArrayList<>(5); } loop.setId(loops.size()); loops.add(loop); } @Nullable public LoopInfo getLoopForBlock(BlockNode block) { if (loops.isEmpty()) { return null; } for (LoopInfo loop : loops) { if (loop.getLoopBlocks().contains(block)) { return loop; } } return null; } public List<LoopInfo> getAllLoopsForBlock(BlockNode block) { if (loops.isEmpty()) { return Collections.emptyList(); } List<LoopInfo> list = new ArrayList<>(loops.size()); for (LoopInfo loop : loops) { if (loop.getLoopBlocks().contains(block)) { list.add(loop); } } return list; } public int getLoopsCount() { return loops.size(); } public Iterable<LoopInfo> getLoops() { return loops; } public ExceptionHandler addExceptionHandler(ExceptionHandler handler) { if (exceptionHandlers.isEmpty()) { exceptionHandlers = new ArrayList<>(2); } exceptionHandlers.add(handler); return handler; } public boolean clearExceptionHandlers() { return exceptionHandlers.removeIf(ExceptionHandler::isRemoved); } public Iterable<ExceptionHandler> getExceptionHandlers() { return exceptionHandlers; } public boolean isNoExceptionHandlers() { return exceptionHandlers.isEmpty(); } public int getExceptionHandlersCount() { return exceptionHandlers.size(); } @Override public List<ArgType> getThrows() { MethodThrowsAttr throwsAttr = get(AType.METHOD_THROWS); if (throwsAttr != null) { return Utils.collectionMap(throwsAttr.getList(), ArgType::object); } ExceptionsAttr exceptionsAttr = get(JadxAttrType.EXCEPTIONS); if (exceptionsAttr != null) { return Utils.collectionMap(exceptionsAttr.getList(), ArgType::object); } return Collections.emptyList(); } /** * Return true if exists method with same name and arguments count */ public boolean isArgsOverloaded() { MethodInfo thisMthInfo = this.mthInfo; // quick check in current class for (MethodNode method : parentClass.getMethods()) { if (method == this) { continue; } if (method.getMethodInfo().isOverloadedBy(thisMthInfo)) { return true; } } return root().getMethodUtils().isMethodArgsOverloaded(parentClass.getClassInfo().getType(), thisMthInfo); } public boolean isConstructor() { return accFlags.isConstructor() && mthInfo.isConstructor(); } public boolean isDefaultConstructor() { if (isConstructor()) { int defaultArgCount = 0; // workaround for non-static inner class constructor, that has synthetic argument if (parentClass.getClassInfo().isInner() && !parentClass.getAccessFlags().isStatic()) { ClassNode outerCls = parentClass.getParentClass(); if (argsList != null && !argsList.isEmpty() && argsList.get(0).getInitType().equals(outerCls.getClassInfo().getType())) { defaultArgCount = 1; } } return argsList == null || argsList.size() == defaultArgCount; } return false; } public int getRegsCount() { return regsCount; } public int getArgsStartReg() { return argsStartReg; } /** * Create new fake register arg. */ public RegisterArg makeSyntheticRegArg(ArgType type) { RegisterArg arg = InsnArg.reg(0, type); arg.add(AFlag.SYNTHETIC); SSAVar ssaVar = makeNewSVar(arg); InitCodeVariables.initCodeVar(ssaVar); ssaVar.setType(type); return arg; } public RegisterArg makeSyntheticRegArg(ArgType type, String name) { RegisterArg arg = makeSyntheticRegArg(type); arg.setName(name); return arg; } public SSAVar makeNewSVar(@NotNull RegisterArg assignArg) { int regNum = assignArg.getRegNum(); return makeNewSVar(regNum, getNextSVarVersion(regNum), assignArg); } public SSAVar makeNewSVar(int regNum, int version, @NotNull RegisterArg assignArg) { SSAVar var = new SSAVar(regNum, version, assignArg); if (sVars.isEmpty()) { sVars = new ArrayList<>(); } sVars.add(var); return var; } private int getNextSVarVersion(int regNum) { int v = -1; for (SSAVar sVar : sVars) { if (sVar.getRegNum() == regNum) { v = Math.max(v, sVar.getVersion()); } } v++; return v; } public void removeSVar(SSAVar var) { sVars.remove(var); } public List<SSAVar> getSVars() { return sVars; } @Override public int getRawAccessFlags() { return accFlags.rawValue(); } @Override public AccessInfo getAccessFlags() { return accFlags; } @Override public void setAccessFlags(AccessInfo newAccessFlags) { this.accFlags = newAccessFlags; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } @Override public RootNode root() { return parentClass.root(); } @Override public String typeName() { return "method"; } @Override public String getInputFileName() { return parentClass.getInputFileName(); } @Override public MethodInfo getMethodInfo() { return mthInfo; } public long getMethodCodeOffset() { return noCode ? 0 : codeReader.getCodeOffset(); } @Nullable public IDebugInfo getDebugInfo() { return noCode ? null : codeReader.getDebugInfo(); } public void ignoreMethod() { add(AFlag.DONT_GENERATE); noCode = true; } @Override public void rename(String newName) { MethodOverrideAttr overrideAttr = get(AType.METHOD_OVERRIDE); if (overrideAttr != null) { for (MethodNode relatedMth : overrideAttr.getRelatedMthNodes()) { relatedMth.getMethodInfo().setAlias(newName); } } else { mthInfo.setAlias(newName); } } /** * Calculate instructions count at current stage */ public long countInsns() { if (instructions != null) { return instructions.length; } if (blocks != null) { return blocks.stream().mapToLong(block -> block.getInstructions().size()).sum(); } return -1; } /** * Raw instructions count in method bytecode */ public int getInsnsCount() { return insnsCount; } /** * Returns method code with comments and annotations */ public String getCodeStr() { return CodeUtils.extractMethodCode(this, getTopParentClass().getCode()); } @Override public boolean isVarArg() { return accFlags.isVarArgs(); } public boolean isLoaded() { return loaded; } public @Nullable ICodeReader getCodeReader() { return codeReader; } public List<MethodNode> getUseIn() { return useIn; } public void setUseIn(List<MethodNode> useIn) { this.useIn = useIn; } public JavaMethod getJavaNode() { return javaNode; } @ApiStatus.Internal public void setJavaNode(JavaMethod javaNode) { this.javaNode = javaNode; } @Override public AnnType getAnnType() { return AnnType.METHOD; } @Override public int hashCode() { return mthInfo.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } MethodNode other = (MethodNode) obj; return mthInfo.equals(other.mthInfo); } @Override public int compareTo(@NotNull MethodNode o) { return mthInfo.compareTo(o.mthInfo); } @Override public String toAttrString() { return IMethodDetails.super.toAttrString() + " (m)"; } @Override public String toString() { return parentClass + "." + mthInfo.getName() + '(' + 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/nodes/RootNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/RootNode.java
package jadx.core.dex.nodes; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; 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.DecompilationMode; import jadx.api.ICodeCache; import jadx.api.ICodeWriter; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.api.ResourceFile; import jadx.api.ResourceType; import jadx.api.ResourcesLoader; import jadx.api.data.ICodeData; import jadx.api.impl.passes.DecompilePassWrapper; import jadx.api.impl.passes.PreparePassWrapper; import jadx.api.plugins.input.ICodeLoader; import jadx.api.plugins.input.data.IClassData; import jadx.api.plugins.pass.JadxPass; import jadx.api.plugins.pass.types.JadxDecompilePass; import jadx.api.plugins.pass.types.JadxPassType; import jadx.api.plugins.pass.types.JadxPreparePass; import jadx.core.Jadx; import jadx.core.ProcessClass; import jadx.core.clsp.ClspGraph; import jadx.core.dex.attributes.AttributeStorage; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.ConstStorage; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.info.InfoStorage; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.info.PackageInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.utils.MethodUtils; import jadx.core.dex.nodes.utils.SelectFromDuplicates; import jadx.core.dex.nodes.utils.TypeUtils; import jadx.core.dex.visitors.DepthTraversal; import jadx.core.dex.visitors.IDexTreeVisitor; import jadx.core.dex.visitors.typeinference.TypeCompare; import jadx.core.dex.visitors.typeinference.TypeUpdate; import jadx.core.export.GradleInfoStorage; import jadx.core.utils.CacheStorage; import jadx.core.utils.DebugChecks; import jadx.core.utils.ErrorsCounter; import jadx.core.utils.PassMerge; import jadx.core.utils.StringUtils; import jadx.core.utils.Utils; import jadx.core.utils.android.AndroidResourcesUtils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.xmlgen.IResTableParser; import jadx.core.xmlgen.ManifestAttributes; import jadx.core.xmlgen.ResourceStorage; import jadx.core.xmlgen.entry.ResourceEntry; import jadx.core.xmlgen.entry.ValuesParser; public class RootNode { private static final Logger LOG = LoggerFactory.getLogger(RootNode.class); private final JadxArgs args; private final ErrorsCounter errorsCounter = new ErrorsCounter(); private final StringUtils stringUtils; private final ConstStorage constValues; private final InfoStorage infoStorage = new InfoStorage(); private final CacheStorage cacheStorage = new CacheStorage(); private final TypeUpdate typeUpdate; private final MethodUtils methodUtils; private final TypeUtils typeUtils; private final AttributeStorage attributes = new AttributeStorage(); private final List<ICodeDataUpdateListener> codeDataUpdateListeners = new ArrayList<>(); private final GradleInfoStorage gradleInfoStorage = new GradleInfoStorage(); private final Map<ClassInfo, ClassNode> clsMap = new HashMap<>(); private final Map<String, ClassNode> rawClsMap = new HashMap<>(); private List<ClassNode> classes = new ArrayList<>(); private final Map<String, PackageNode> pkgMap = new HashMap<>(); private final List<PackageNode> packages = new ArrayList<>(); private List<IDexTreeVisitor> preDecompilePasses; private ProcessClass processClasses; private ClspGraph clsp; private @Nullable String appPackage; private @Nullable ClassNode appResClass; /** * Optional decompiler reference */ private @Nullable JadxDecompiler decompiler; private @Nullable ManifestAttributes manifestAttributes; public RootNode(JadxDecompiler decompiler) { this(decompiler, decompiler.getArgs()); } /** * Deprecated. Prefer {@link #RootNode(JadxDecompiler)} */ @Deprecated public RootNode(JadxArgs args) { this(null, args); } private RootNode(@Nullable JadxDecompiler decompiler, JadxArgs args) { this.decompiler = decompiler; this.args = args; this.preDecompilePasses = Jadx.getPreDecompilePassesList(); this.processClasses = new ProcessClass(Jadx.getPassesList(args)); this.stringUtils = new StringUtils(args); this.constValues = new ConstStorage(args); this.typeUpdate = new TypeUpdate(this); this.methodUtils = new MethodUtils(this); this.typeUtils = new TypeUtils(this); } public void init() { if (args.isDeobfuscationOn() || !args.getRenameFlags().isEmpty()) { args.getAliasProvider().init(this); } if (args.isDeobfuscationOn()) { args.getRenameCondition().init(this); } } public void loadClasses(List<ICodeLoader> loadedInputs) { for (ICodeLoader codeLoader : loadedInputs) { codeLoader.visitClasses(cls -> { try { addClassNode(new ClassNode(RootNode.this, cls)); } catch (Exception e) { addDummyClass(cls, e); } Utils.checkThreadInterrupt(); }); } } public void finishClassLoad() { if (classes.size() != clsMap.size()) { // class name duplication detected fixDuplicatedClasses(); } classes = new ArrayList<>(clsMap.values()); // print stats for loaded classes int mthCount = classes.stream().mapToInt(c -> c.getMethods().size()).sum(); int insnsCount = classes.stream().flatMap(c -> c.getMethods().stream()).mapToInt(MethodNode::getInsnsCount).sum(); LOG.info("Loaded classes: {}, methods: {}, instructions: {}", classes.size(), mthCount, insnsCount); // sort classes by name, expect top classes before inner classes.sort(Comparator.comparing(ClassNode::getRawName)); if (args.isMoveInnerClasses()) { // detect and move inner classes initInnerClasses(); } // sort packages Collections.sort(packages); } private void addDummyClass(IClassData classData, Exception exc) { try { String typeStr = classData.getType(); String name = null; try { ClassInfo clsInfo = ClassInfo.fromName(this, typeStr); if (clsInfo != null) { name = clsInfo.getShortName(); } } catch (Exception e) { LOG.error("Failed to get name for class with type {}", typeStr, e); } if (name == null || name.isEmpty()) { name = "CLASS_" + typeStr; } ClassNode clsNode = ClassNode.addSyntheticClass(this, name, classData.getAccessFlags()); ErrorsCounter.error(clsNode, "Load error", exc); } catch (Exception innerExc) { LOG.error("Failed to load class from file: {}", classData.getInputFileName(), exc); } } private void fixDuplicatedClasses() { classes.stream() .collect(Collectors.groupingBy(ClassNode::getClassInfo)) .entrySet() .stream() .filter(entry -> entry.getValue().size() > 1) .forEach(entry -> { ClassInfo clsInfo = entry.getKey(); List<ClassNode> dupClsList = entry.getValue(); ClassNode selectedCls = SelectFromDuplicates.process(dupClsList); // keep only selected class in classes maps clsMap.put(clsInfo, selectedCls); rawClsMap.put(selectedCls.getRawName(), selectedCls); String selectedSource = selectedCls.getInputFileName(); String sources = dupClsList.stream() .map(ClassNode::getInputFileName) .sorted() .collect(Collectors.joining("\n ")); LOG.warn("Found duplicated class: {}, count: {}, sources:" + "\n {}\n Keep class with source: {}, others will be removed.", clsInfo, dupClsList.size(), sources, selectedSource); selectedCls.addWarnComment("Classes with same name are omitted, all sources:\n " + sources + '\n'); }); } public void addClassNode(ClassNode clsNode) { classes.add(clsNode); clsMap.put(clsNode.getClassInfo(), clsNode); rawClsMap.put(clsNode.getRawName(), clsNode); } public void loadResources(ResourcesLoader resLoader, List<ResourceFile> resources) { ResourceFile arsc = getResourceFile(resources); if (arsc == null) { LOG.debug("'resources.arsc' or 'resources.pb' file not found"); return; } try { IResTableParser parser = ResourcesLoader.decodeStream(arsc, (size, is) -> resLoader.decodeTable(arsc, is)); if (parser != null) { processResources(parser.getResStorage()); updateObfuscatedFiles(parser, resources); initManifestAttributes().updateAttributes(parser); } } catch (Exception e) { LOG.error("Failed to parse 'resources.pb'/'.arsc' file", e); } } private @Nullable ResourceFile getResourceFile(List<ResourceFile> resources) { for (ResourceFile rf : resources) { if (rf.getType() == ResourceType.ARSC) { return rf; } } return null; } public void processResources(ResourceStorage resStorage) { constValues.setResourcesNames(resStorage.getResourcesNames()); appPackage = resStorage.getAppPackage(); appResClass = AndroidResourcesUtils.searchAppResClass(this, resStorage); } public void initClassPath() { try { if (this.clsp == null) { ClspGraph newClsp = new ClspGraph(this); if (args.isLoadJadxClsSetFile()) { newClsp.loadClsSetFile(); } newClsp.addApp(classes); newClsp.initCache(); this.clsp = newClsp; } } catch (Exception e) { throw new JadxRuntimeException("Error loading jadx class set", e); } } private void updateObfuscatedFiles(IResTableParser parser, List<ResourceFile> resources) { if (args.isSkipResources()) { return; } boolean useHeaders = args.isUseHeadersForDetectResourceExtensions(); long start = System.currentTimeMillis(); int renamedCount = 0; ResourceStorage resStorage = parser.getResStorage(); ValuesParser valuesParser = new ValuesParser(parser.getStrings(), resStorage.getResourcesNames()); Map<String, ResourceEntry> entryNames = new HashMap<>(); for (ResourceEntry resEntry : resStorage.getResources()) { String val = valuesParser.getSimpleValueString(resEntry); if (val != null) { entryNames.put(val, resEntry); } } for (ResourceFile resource : resources) { ResourceEntry resEntry = entryNames.get(resource.getOriginalName()); if (resEntry != null) { if (resource.setAlias(resEntry, useHeaders)) { renamedCount++; } } } if (LOG.isDebugEnabled()) { LOG.debug("Renamed obfuscated resources: {}, duration: {}ms", renamedCount, System.currentTimeMillis() - start); } } private void initInnerClasses() { // move inner classes List<ClassNode> inner = new ArrayList<>(); for (ClassNode cls : classes) { if (cls.getClassInfo().isInner()) { inner.add(cls); } } List<ClassNode> updated = new ArrayList<>(); for (ClassNode cls : inner) { ClassInfo clsInfo = cls.getClassInfo(); ClassNode parent = resolveParentClass(clsInfo); if (parent == null) { updated.add(cls); cls.notInner(); } else { parent.addInnerClass(cls); } } // reload names for inner classes of updated parents for (ClassNode updCls : updated) { for (ClassNode innerCls : updCls.getInnerClasses()) { innerCls.getClassInfo().updateNames(this); } } for (PackageNode pkg : packages) { pkg.getClasses().removeIf(cls -> cls.getClassInfo().isInner()); } } public void mergePasses(Map<JadxPassType, List<JadxPass>> customPasses) { DecompilationMode mode = args.getDecompilationMode(); if (mode == DecompilationMode.FALLBACK || mode == DecompilationMode.SIMPLE) { // for predefined modes ignore custom (and plugin) passes return; } new PassMerge(preDecompilePasses) .merge(customPasses.get(JadxPreparePass.TYPE), p -> new PreparePassWrapper((JadxPreparePass) p)); new PassMerge(processClasses.getPasses()) .merge(customPasses.get(JadxDecompilePass.TYPE), p -> new DecompilePassWrapper((JadxDecompilePass) p)); if (args.isRunDebugChecks()) { preDecompilePasses = DebugChecks.insertPasses(preDecompilePasses); processClasses = new ProcessClass(DebugChecks.insertPasses(processClasses.getPasses())); } List<String> disabledPasses = args.getDisabledPasses(); if (!disabledPasses.isEmpty()) { Set<String> disabledSet = new HashSet<>(disabledPasses); Predicate<IDexTreeVisitor> filter = p -> { if (disabledSet.contains(p.getName())) { LOG.debug("Disable pass: {}", p.getName()); return true; } return false; }; preDecompilePasses.removeIf(filter); processClasses.getPasses().removeIf(filter); } } public void runPreDecompileStage() { boolean debugEnabled = LOG.isDebugEnabled(); for (IDexTreeVisitor pass : preDecompilePasses) { Utils.checkThreadInterrupt(); long start = debugEnabled ? System.currentTimeMillis() : 0; try { pass.init(this); } catch (Exception e) { LOG.error("Visitor init failed: {}", pass.getClass().getSimpleName(), e); } for (ClassNode cls : classes) { if (cls.isInner()) { continue; } DepthTraversal.visit(pass, cls); } if (debugEnabled) { LOG.debug("Prepare pass: '{}' - {}ms", pass, System.currentTimeMillis() - start); } } } public void runPreDecompileStageForClass(ClassNode cls) { for (IDexTreeVisitor pass : preDecompilePasses) { DepthTraversal.visit(pass, cls); } } // TODO: make better API for reload passes lists public void resetPasses() { preDecompilePasses.clear(); preDecompilePasses.addAll(Jadx.getPreDecompilePassesList()); processClasses.getPasses().clear(); processClasses.getPasses().addAll(Jadx.getPassesList(args)); } public void restartVisitors() { for (ClassNode cls : classes) { cls.unload(); cls.clearAttributes(); cls.unloadFromCache(); } runPreDecompileStage(); } public List<ClassNode> getClasses() { return classes; } public List<ClassNode> getClassesWithoutInner() { return getClasses(false); } public List<ClassNode> getClasses(boolean includeInner) { if (includeInner) { return classes; } List<ClassNode> notInnerClasses = new ArrayList<>(); for (ClassNode cls : classes) { if (!cls.getClassInfo().isInner()) { notInnerClasses.add(cls); } } return notInnerClasses; } public List<PackageNode> getPackages() { return packages; } public @Nullable PackageNode resolvePackage(String fullPkg) { return pkgMap.get(fullPkg); } public @Nullable PackageNode resolvePackage(@Nullable PackageInfo pkgInfo) { return pkgInfo == null ? null : pkgMap.get(pkgInfo.getFullName()); } public void addPackage(PackageNode pkg) { pkgMap.put(pkg.getPkgInfo().getFullName(), pkg); packages.add(pkg); } public void removePackage(PackageNode pkg) { if (pkgMap.remove(pkg.getPkgInfo().getFullName()) != null) { packages.remove(pkg); PackageNode parentPkg = pkg.getParentPkg(); if (parentPkg != null) { parentPkg.getSubPackages().remove(pkg); if (parentPkg.isEmpty()) { removePackage(parentPkg); } } for (PackageNode subPkg : pkg.getSubPackages()) { removePackage(subPkg); } } } public void sortPackages() { Collections.sort(packages); } public void removeClsFromPackage(PackageNode pkg, ClassNode cls) { boolean removed = pkg.getClasses().remove(cls); if (removed && pkg.isEmpty()) { removePackage(pkg); } } /** * Update sub packages */ public void runPackagesUpdate() { for (PackageNode pkg : getPackages()) { if (pkg.isRoot()) { pkg.updatePackages(); } } } @Nullable public ClassNode resolveClass(ClassInfo clsInfo) { return clsMap.get(clsInfo); } @Nullable public ClassNode resolveClass(ArgType clsType) { if (!clsType.isTypeKnown() || clsType.isGenericType()) { return null; } if (clsType.getWildcardBound() == ArgType.WildcardBound.UNBOUND) { return null; } if (clsType.isGeneric()) { clsType = ArgType.object(clsType.getObject()); } return resolveClass(ClassInfo.fromType(this, clsType)); } @Nullable public ClassNode resolveClass(String fullName) { ClassInfo clsInfo = ClassInfo.fromName(this, fullName); return resolveClass(clsInfo); } @Nullable public ClassNode resolveRawClass(String rawFullName) { return rawClsMap.get(rawFullName); } /** * Find and correct the parent of an inner class. * <br> * Sometimes inner ClassInfo generated wrong parent info. * e.g. inner is `Cls$mth$1`, current parent = `Cls$mth`, real parent = `Cls` */ @Nullable public ClassNode resolveParentClass(ClassInfo clsInfo) { ClassInfo parentInfo = clsInfo.getParentClass(); ClassNode parentNode = resolveClass(parentInfo); if (parentNode == null && parentInfo != null) { String parClsName = parentInfo.getFullName(); // strip last part as method name int sep = parClsName.lastIndexOf('.'); if (sep > 0 && sep != parClsName.length() - 1) { String mthName = parClsName.substring(sep + 1); String upperParClsName = parClsName.substring(0, sep); ClassNode tmpParent = resolveClass(upperParClsName); if (tmpParent != null && tmpParent.searchMethodByShortName(mthName) != null) { parentNode = tmpParent; clsInfo.convertToInner(parentNode); } } } return parentNode; } /** * Searches for ClassNode by its full name (original or alias name) * <br> * Warning: This method has a runtime of O(n) (n = number of classes). * If you need to call it more than once consider {@link #buildFullAliasClassCache()} instead */ @Nullable public ClassNode searchClassByFullAlias(String fullName) { for (ClassNode cls : classes) { ClassInfo classInfo = cls.getClassInfo(); if (classInfo.getFullName().equals(fullName) || classInfo.getAliasFullName().equals(fullName)) { return cls; } } return null; } public Map<String, ClassNode> buildFullAliasClassCache() { Map<String, ClassNode> classNameCache = new HashMap<>(classes.size()); for (ClassNode cls : classes) { ClassInfo classInfo = cls.getClassInfo(); String fullName = classInfo.getFullName(); String alias = classInfo.getAliasFullName(); classNameCache.put(fullName, cls); if (alias != null && !fullName.equals(alias)) { classNameCache.put(alias, cls); } } return classNameCache; } public List<ClassNode> searchClassByShortName(String shortName) { List<ClassNode> list = new ArrayList<>(); for (ClassNode cls : classes) { if (cls.getClassInfo().getShortName().equals(shortName)) { list.add(cls); } } return list; } @Nullable public MethodNode resolveMethod(@NotNull MethodInfo mth) { ClassNode cls = resolveClass(mth.getDeclClass()); if (cls == null) { return null; } MethodNode methodNode = cls.searchMethod(mth); if (methodNode != null) { return methodNode; } return deepResolveMethod(cls, mth.makeSignature(false)); } public @NotNull MethodNode resolveDirectMethod(String rawClsName, String mthShortId) { ClassNode clsNode = resolveRawClass(rawClsName); if (clsNode == null) { throw new RuntimeException("Class not found: " + rawClsName); } MethodNode methodNode = clsNode.searchMethodByShortId(mthShortId); if (methodNode == null) { throw new RuntimeException("Method not found: " + rawClsName + "." + mthShortId); } return methodNode; } @Nullable private MethodNode deepResolveMethod(@NotNull ClassNode cls, String signature) { for (MethodNode m : cls.getMethods()) { if (m.getMethodInfo().getShortId().startsWith(signature)) { return m; } } MethodNode found; ArgType superClass = cls.getSuperClass(); if (superClass != null) { ClassNode superNode = resolveClass(superClass); if (superNode != null) { found = deepResolveMethod(superNode, signature); if (found != null) { return found; } } } for (ArgType iFaceType : cls.getInterfaces()) { ClassNode iFaceNode = resolveClass(iFaceType); if (iFaceNode != null) { found = deepResolveMethod(iFaceNode, signature); if (found != null) { return found; } } } return null; } @Nullable public FieldNode resolveField(FieldInfo field) { ClassNode cls = resolveClass(field.getDeclClass()); if (cls == null) { return null; } FieldNode fieldNode = cls.searchField(field); if (fieldNode != null) { return fieldNode; } return deepResolveField(cls, field); } @Nullable private FieldNode deepResolveField(@NotNull ClassNode cls, FieldInfo fieldInfo) { FieldNode field = cls.searchFieldByNameAndType(fieldInfo); if (field != null) { return field; } ArgType superClass = cls.getSuperClass(); if (superClass != null) { ClassNode superNode = resolveClass(superClass); if (superNode != null) { FieldNode found = deepResolveField(superNode, fieldInfo); if (found != null) { return found; } } } for (ArgType iFaceType : cls.getInterfaces()) { ClassNode iFaceNode = resolveClass(iFaceType); if (iFaceNode != null) { FieldNode found = deepResolveField(iFaceNode, fieldInfo); if (found != null) { return found; } } } return null; } public ProcessClass getProcessClasses() { return processClasses; } public List<IDexTreeVisitor> getPasses() { return processClasses.getPasses(); } public List<IDexTreeVisitor> getPreDecompilePasses() { return preDecompilePasses; } public void initPasses() { processClasses.initPasses(this); } public ICodeWriter makeCodeWriter() { JadxArgs jadxArgs = this.args; return jadxArgs.getCodeWriterProvider().apply(jadxArgs); } public void registerCodeDataUpdateListener(ICodeDataUpdateListener listener) { this.codeDataUpdateListeners.add(listener); } public void notifyCodeDataListeners() { ICodeData codeData = args.getCodeData(); codeDataUpdateListeners.forEach(l -> l.updated(codeData)); } public ClspGraph getClsp() { return clsp; } public ErrorsCounter getErrorsCounter() { return errorsCounter; } @Nullable public String getAppPackage() { return appPackage; } @Nullable public ClassNode getAppResClass() { return appResClass; } public StringUtils getStringUtils() { return stringUtils; } public ConstStorage getConstValues() { return constValues; } public InfoStorage getInfoStorage() { return infoStorage; } public CacheStorage getCacheStorage() { return cacheStorage; } public JadxArgs getArgs() { return args; } public @Nullable JadxDecompiler getDecompiler() { return decompiler; } public TypeUpdate getTypeUpdate() { return typeUpdate; } public TypeCompare getTypeCompare() { return typeUpdate.getTypeCompare(); } public ICodeCache getCodeCache() { return args.getCodeCache(); } public MethodUtils getMethodUtils() { return methodUtils; } public TypeUtils getTypeUtils() { return typeUtils; } public AttributeStorage getAttributes() { return attributes; } public GradleInfoStorage getGradleInfoStorage() { return gradleInfoStorage; } public synchronized ManifestAttributes initManifestAttributes() { ManifestAttributes attrs = manifestAttributes; if (attrs == null) { attrs = new ManifestAttributes(args.getSecurity()); manifestAttributes = attrs; } return attrs; } }
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/nodes/ProcessState.java
jadx-core/src/main/java/jadx/core/dex/nodes/ProcessState.java
package jadx.core.dex.nodes; public enum ProcessState { NOT_LOADED, LOADED, PROCESS_STARTED, PROCESS_COMPLETE, GENERATED_AND_UNLOADED; public boolean isProcessComplete() { return this == PROCESS_COMPLETE || this == GENERATED_AND_UNLOADED; } }
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/nodes/ICodeNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/ICodeNode.java
package jadx.core.dex.nodes; import jadx.api.metadata.ICodeNodeRef; import jadx.core.dex.attributes.IAttributeNode; import jadx.core.dex.info.AccessInfo; public interface ICodeNode extends IDexNode, IAttributeNode, IUsageInfoNode, ICodeNodeRef { ClassNode getDeclaringClass(); AccessInfo getAccessFlags(); void setAccessFlags(AccessInfo newAccessFlags); }
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/nodes/IUsageInfoNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/IUsageInfoNode.java
package jadx.core.dex.nodes; import java.util.List; public interface IUsageInfoNode { List<? extends ICodeNode> getUseIn(); }
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/nodes/FieldNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/FieldNode.java
package jadx.core.dex.nodes; import java.util.Collections; import java.util.List; import jadx.api.JavaField; import jadx.api.plugins.input.data.IFieldData; import jadx.core.dex.attributes.nodes.NotificationAttrNode; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.info.AccessInfo.AFType; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.utils.ListUtils; public class FieldNode extends NotificationAttrNode implements ICodeNode, IFieldInfoRef { private final ClassNode parentClass; private final FieldInfo fieldInfo; private AccessInfo accFlags; private ArgType type; private List<MethodNode> useIn = Collections.emptyList(); private JavaField javaNode; public static FieldNode build(ClassNode cls, IFieldData fieldData) { FieldInfo fieldInfo = FieldInfo.fromRef(cls.root(), fieldData); FieldNode fieldNode = new FieldNode(cls, fieldInfo, fieldData.getAccessFlags()); fieldNode.addAttrs(fieldData.getAttributes()); return fieldNode; } public FieldNode(ClassNode cls, FieldInfo fieldInfo, int accessFlags) { this.parentClass = cls; this.fieldInfo = fieldInfo; this.type = fieldInfo.getType(); this.accFlags = new AccessInfo(accessFlags, AFType.FIELD); } public void unload() { unloadAttributes(); } public void updateType(ArgType type) { this.type = type; } @Override public FieldInfo getFieldInfo() { return fieldInfo; } @Override public AccessInfo getAccessFlags() { return accFlags; } @Override public void setAccessFlags(AccessInfo accFlags) { this.accFlags = accFlags; } public boolean isStatic() { return accFlags.isStatic(); } public boolean isInstance() { return !accFlags.isStatic(); } public String getName() { return fieldInfo.getName(); } public String getAlias() { return fieldInfo.getAlias(); } @Override public void rename(String alias) { fieldInfo.setAlias(alias); } public ArgType getType() { return type; } @Override public ClassNode getDeclaringClass() { return parentClass; } public ClassNode getParentClass() { return parentClass; } public ClassNode getTopParentClass() { return parentClass.getTopParentClass(); } public List<MethodNode> getUseIn() { return useIn; } public void setUseIn(List<MethodNode> useIn) { this.useIn = useIn; } public synchronized void addUseIn(MethodNode mth) { useIn = ListUtils.safeAdd(useIn, mth); } @Override public String typeName() { return "field"; } @Override public String getInputFileName() { return parentClass.getInputFileName(); } @Override public RootNode root() { return parentClass.root(); } public JavaField getJavaNode() { return javaNode; } public void setJavaNode(JavaField javaNode) { this.javaNode = javaNode; } @Override public AnnType getAnnType() { return AnnType.FIELD; } @Override public int hashCode() { return fieldInfo.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } FieldNode other = (FieldNode) obj; return fieldInfo.equals(other.fieldInfo); } @Override public String toString() { return fieldInfo.getDeclClass() + "." + fieldInfo.getName() + " :" + 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/nodes/ClassNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/ClassNode.java
package jadx.core.dex.nodes; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.DecompilationMode; import jadx.api.ICodeCache; import jadx.api.ICodeInfo; import jadx.api.JadxArgs; import jadx.api.JavaClass; import jadx.api.impl.SimpleCodeInfo; import jadx.api.impl.SimpleCodeWriter; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.annotations.NodeDeclareRef; import jadx.api.metadata.annotations.VarRef; import jadx.api.plugins.input.data.IClassData; import jadx.api.plugins.input.data.IFieldData; import jadx.api.plugins.input.data.IMethodData; import jadx.api.plugins.input.data.annotations.EncodedValue; import jadx.api.plugins.input.data.attributes.JadxAttrType; import jadx.api.plugins.input.data.attributes.types.AnnotationDefaultAttr; import jadx.api.plugins.input.data.attributes.types.AnnotationDefaultClassAttr; import jadx.api.plugins.input.data.attributes.types.InnerClassesAttr; import jadx.api.plugins.input.data.attributes.types.InnerClsInfo; import jadx.api.plugins.input.data.attributes.types.SourceFileAttr; import jadx.api.plugins.input.data.impl.ListConsumer; import jadx.api.usage.IUsageInfoData; import jadx.core.Consts; import jadx.core.Jadx; import jadx.core.ProcessClass; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.InlinedAttr; import jadx.core.dex.attributes.nodes.NotificationAttrNode; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.info.AccessInfo.AFType; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.LiteralArg; import jadx.core.dex.nodes.utils.TypeUtils; import jadx.core.utils.ListUtils; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.dex.nodes.ProcessState.LOADED; import static jadx.core.dex.nodes.ProcessState.NOT_LOADED; public class ClassNode extends NotificationAttrNode implements ILoadable, ICodeNode, IPackageUpdate, Comparable<ClassNode> { private static final Logger LOG = LoggerFactory.getLogger(ClassNode.class); private final RootNode root; private final IClassData clsData; private final ClassInfo clsInfo; private PackageNode packageNode; private AccessInfo accessFlags; private ArgType superClass; private List<ArgType> interfaces; private List<ArgType> generics = Collections.emptyList(); private String inputFileName; private List<MethodNode> methods; private List<FieldNode> fields; private List<ClassNode> innerClasses = Collections.emptyList(); private List<ClassNode> inlinedClasses = Collections.emptyList(); // store smali private String smali; // store parent for inner classes or 'this' otherwise private ClassNode parentClass = this; private volatile ProcessState state = ProcessState.NOT_LOADED; private LoadStage loadStage = LoadStage.NONE; /** * Top level classes used in this class (only for top level classes, empty for inners) */ private List<ClassNode> dependencies = Collections.emptyList(); /** * Top level classes needed for code generation stage */ private List<ClassNode> codegenDeps = Collections.emptyList(); /** * Classes which uses this class */ private List<ClassNode> useIn = Collections.emptyList(); /** * Methods which uses this class (by instructions only, definition is excluded) */ private List<MethodNode> useInMth = Collections.emptyList(); // cache maps private Map<MethodInfo, MethodNode> mthInfoMap = Collections.emptyMap(); private JavaClass javaNode; public ClassNode(RootNode root, IClassData cls) { this.root = root; this.clsInfo = ClassInfo.fromType(root, ArgType.object(cls.getType())); this.packageNode = PackageNode.getForClass(root, clsInfo.getPackage(), this); this.clsData = cls.copy(); load(clsData, false); } private void load(IClassData cls, boolean reloading) { try { addAttrs(cls.getAttributes()); this.accessFlags = new AccessInfo(getAccessFlags(cls), AFType.CLASS); this.superClass = checkSuperType(cls); this.interfaces = Utils.collectionMap(cls.getInterfacesTypes(), ArgType::object); setInputFileName(cls.getInputFileName()); ListConsumer<IFieldData, FieldNode> fieldsConsumer = new ListConsumer<>(fld -> FieldNode.build(this, fld)); ListConsumer<IMethodData, MethodNode> methodsConsumer = new ListConsumer<>(mth -> MethodNode.build(this, mth)); cls.visitFieldsAndMethods(fieldsConsumer, methodsConsumer); this.fields = fieldsConsumer.getResult(); this.methods = methodsConsumer.getResult(); if (reloading) { restoreUsageData(); } initStaticValues(fields); processAttributes(this); processSpecialClasses(this); buildCache(); // TODO: implement module attribute parsing if (this.accessFlags.isModuleInfo()) { this.addWarnComment("Modules not supported yet"); } } catch (Exception e) { throw new JadxRuntimeException("Error decode class: " + clsInfo, e); } } private void restoreUsageData() { IUsageInfoData usageInfoData = root.getArgs().getUsageInfoCache().get(root); if (usageInfoData != null) { usageInfoData.applyForClass(this); } else { LOG.warn("Can't restore usage data for class: {}", this); } } private ArgType checkSuperType(IClassData cls) { String superType = cls.getSuperType(); if (superType == null) { if (clsInfo.getType().getObject().equals(Consts.CLASS_OBJECT)) { // java.lang.Object don't have super class return null; } if (this.accessFlags.isModuleInfo()) { // module-info also don't have super class return null; } throw new JadxRuntimeException("No super class in " + clsInfo.getType()); } return ArgType.object(superType); } public void updateGenericClsData(List<ArgType> generics, ArgType superClass, List<ArgType> interfaces) { this.generics = generics; this.superClass = superClass; this.interfaces = interfaces; } private static void processSpecialClasses(ClassNode cls) { if (cls.getName().equals("package-info") && cls.getFields().isEmpty() && cls.getMethods().isEmpty()) { cls.add(AFlag.PACKAGE_INFO); cls.add(AFlag.DONT_RENAME); } } private static void processAttributes(ClassNode cls) { // move AnnotationDefault from cls to methods (dex specific) AnnotationDefaultClassAttr defAttr = cls.get(JadxAttrType.ANNOTATION_DEFAULT_CLASS); if (defAttr != null) { cls.remove(JadxAttrType.ANNOTATION_DEFAULT_CLASS); for (Map.Entry<String, EncodedValue> entry : defAttr.getValues().entrySet()) { MethodNode mth = cls.searchMethodByShortName(entry.getKey()); if (mth != null) { mth.addAttr(new AnnotationDefaultAttr(entry.getValue())); } else { cls.addWarnComment("Method from annotation default annotation not found: " + entry.getKey()); } } } // check source file attribute if (!cls.checkSourceFilenameAttr()) { cls.remove(JadxAttrType.SOURCE_FILE); } } private int getAccessFlags(IClassData cls) { InnerClassesAttr innerClassesAttr = get(JadxAttrType.INNER_CLASSES); if (innerClassesAttr != null) { InnerClsInfo innerClsInfo = innerClassesAttr.getMap().get(cls.getType()); if (innerClsInfo != null) { return innerClsInfo.getAccessFlags(); } } return cls.getAccessFlags(); } public static ClassNode addSyntheticClass(RootNode root, String name, int accessFlags) { ClassInfo clsInfo = ClassInfo.fromName(root, name); ClassNode existCls = root.resolveClass(clsInfo); if (existCls != null) { throw new JadxRuntimeException("Class already exist: " + name); } return addSyntheticClass(root, clsInfo, accessFlags); } public static ClassNode addSyntheticClass(RootNode root, ClassInfo clsInfo, int accessFlags) { ClassNode cls = new ClassNode(root, clsInfo, accessFlags); cls.add(AFlag.SYNTHETIC); cls.setInputFileName("synthetic"); cls.setState(ProcessState.PROCESS_COMPLETE); root.addClassNode(cls); return cls; } // Create empty class private ClassNode(RootNode root, ClassInfo clsInfo, int accessFlags) { this.root = root; this.clsData = null; this.clsInfo = clsInfo; this.interfaces = new ArrayList<>(); this.methods = new ArrayList<>(); this.fields = new ArrayList<>(); this.accessFlags = new AccessInfo(accessFlags, AFType.CLASS); this.packageNode = PackageNode.getForClass(root, clsInfo.getPackage(), this); } private void initStaticValues(List<FieldNode> fields) { if (fields.isEmpty()) { return; } // bytecode can omit field initialization to 0 (of any type) // add explicit init to all static final fields // incorrect initializations will be removed if assign found in class init for (FieldNode fld : fields) { AccessInfo accFlags = fld.getAccessFlags(); if (accFlags.isStatic() && accFlags.isFinal() && fld.get(JadxAttrType.CONSTANT_VALUE) == null) { fld.addAttr(EncodedValue.NULL); } } } private boolean checkSourceFilenameAttr() { SourceFileAttr sourceFileAttr = get(JadxAttrType.SOURCE_FILE); if (sourceFileAttr == null) { return true; } String fileName = sourceFileAttr.getFileName(); if (fileName.endsWith(".java")) { fileName = fileName.substring(0, fileName.length() - 5); } if (fileName.isEmpty() || fileName.equals("SourceFile")) { return false; } if (clsInfo != null) { String name = clsInfo.getShortName(); if (fileName.equals(name)) { return false; } ClassInfo parentCls = clsInfo.getParentClass(); while (parentCls != null) { String parentName = parentCls.getShortName(); if (parentName.equals(fileName) || parentName.startsWith(fileName + '$')) { return false; } parentCls = parentCls.getParentClass(); } if (fileName.contains("$") && fileName.endsWith('$' + name)) { return false; } if (name.contains("$") && name.startsWith(fileName)) { return false; } } return true; } public boolean checkProcessed() { return getTopParentClass().getState().isProcessComplete(); } public void ensureProcessed() { if (!checkProcessed()) { ClassNode topParentClass = getTopParentClass(); throw new JadxRuntimeException("Expected class to be processed at this point," + " class: " + topParentClass + ", state: " + topParentClass.getState()); } } public ICodeInfo decompile() { return decompile(true); } private static final Object DECOMPILE_WITH_MODE_SYNC = new Object(); /** * WARNING: Slow operation! Use with caution! */ public ICodeInfo decompileWithMode(DecompilationMode mode) { DecompilationMode baseMode = root.getArgs().getDecompilationMode(); if (mode == baseMode) { return decompile(true); } synchronized (DECOMPILE_WITH_MODE_SYNC) { JadxArgs args = root.getArgs(); try { unload(); args.setDecompilationMode(mode); ProcessClass process = new ProcessClass(Jadx.getPassesList(args)); process.initPasses(root); ICodeInfo code = process.forceGenerateCode(this); return Utils.getOrElse(code, ICodeInfo.EMPTY); } finally { args.setDecompilationMode(baseMode); unload(); } } } public ICodeInfo getCode() { return decompile(true); } public ICodeInfo reloadCode() { add(AFlag.CLASS_DEEP_RELOAD); return decompile(false); } public void unloadCode() { if (state == NOT_LOADED) { return; } add(AFlag.CLASS_UNLOADED); unloadFromCache(); deepUnload(); } public void deepUnload() { if (clsData == null) { // manually added class return; } clearAttributes(); unload(); root().getConstValues().removeForClass(this); load(clsData, true); innerClasses.forEach(ClassNode::deepUnload); } public void unloadFromCache() { if (isInner()) { return; } ICodeCache codeCache = root().getCodeCache(); codeCache.remove(getRawName()); } private synchronized ICodeInfo decompile(boolean searchInCache) { if (isInner()) { return ICodeInfo.EMPTY; } ICodeCache codeCache = root().getCodeCache(); String clsRawName = getRawName(); if (searchInCache) { ICodeInfo code = codeCache.get(clsRawName); if (code != ICodeInfo.EMPTY) { return code; } } ICodeInfo codeInfo = generateClassCode(); if (codeInfo != ICodeInfo.EMPTY) { codeCache.add(clsRawName, codeInfo); } return codeInfo; } private ICodeInfo generateClassCode() { try { if (Consts.DEBUG) { LOG.debug("Decompiling class: {}", this); } ICodeInfo codeInfo = root.getProcessClasses().generateCode(this); processDefinitionAnnotations(codeInfo); return codeInfo; } catch (StackOverflowError | Exception e) { addError("Code generation failed", e); return new SimpleCodeInfo(Utils.getStackTrace(e)); } } /** * Save node definition positions found in code */ private static void processDefinitionAnnotations(ICodeInfo codeInfo) { Map<Integer, ICodeAnnotation> annotations = codeInfo.getCodeMetadata().getAsMap(); if (annotations.isEmpty()) { return; } for (Map.Entry<Integer, ICodeAnnotation> entry : annotations.entrySet()) { ICodeAnnotation ann = entry.getValue(); if (ann.getAnnType() == AnnType.DECLARATION) { NodeDeclareRef declareRef = (NodeDeclareRef) ann; int pos = entry.getKey(); declareRef.setDefPos(pos); declareRef.getNode().setDefPosition(pos); } } // validate var refs annotations.values().removeIf(v -> { if (v.getAnnType() == ICodeAnnotation.AnnType.VAR_REF) { VarRef varRef = (VarRef) v; if (varRef.getRefPos() == 0) { if (LOG.isDebugEnabled()) { LOG.debug("Var reference '{}' incorrect (ref pos is zero) and was removed from metadata", varRef); } return true; } return false; } return false; }); } @Nullable public ICodeInfo getCodeFromCache() { ICodeCache codeCache = root().getCodeCache(); String clsRawName = getRawName(); ICodeInfo codeInfo = codeCache.get(clsRawName); if (codeInfo == ICodeInfo.EMPTY) { return null; } return codeInfo; } @Override public void load() { for (MethodNode mth : getMethods()) { try { mth.load(); } catch (Exception e) { mth.addError("Method load error", e); } } for (ClassNode innerCls : getInnerClasses()) { innerCls.load(); } setState(LOADED); } @Override public void unload() { if (state == NOT_LOADED) { return; } synchronized (clsInfo) { // decompilation sync methods.forEach(MethodNode::unload); innerClasses.forEach(ClassNode::unload); fields.forEach(FieldNode::unload); unloadAttributes(); setState(NOT_LOADED); this.loadStage = LoadStage.NONE; this.smali = null; } } private void buildCache() { mthInfoMap = new HashMap<>(methods.size()); for (MethodNode mth : methods) { mthInfoMap.put(mth.getMethodInfo(), mth); } } @Nullable public ArgType getSuperClass() { return superClass; } public List<ArgType> getInterfaces() { return interfaces; } public List<ArgType> getGenericTypeParameters() { return generics; } public ArgType getType() { ArgType clsType = clsInfo.getType(); if (Utils.notEmpty(generics)) { return ArgType.generic(clsType, generics); } return clsType; } public List<MethodNode> getMethods() { return methods; } public List<FieldNode> getFields() { return fields; } public void addField(FieldNode fld) { if (fields == null || fields.isEmpty()) { fields = new ArrayList<>(1); } fields.add(fld); } public @Nullable IFieldInfoRef getConstField(Object obj) { return getConstField(obj, true); } public @Nullable IFieldInfoRef getConstField(Object obj, boolean searchGlobal) { return root().getConstValues().getConstField(this, obj, searchGlobal); } public @Nullable IFieldInfoRef getConstFieldByLiteralArg(LiteralArg arg) { return root().getConstValues().getConstFieldByLiteralArg(this, arg); } public FieldNode searchField(FieldInfo field) { for (FieldNode f : fields) { if (f.getFieldInfo().equals(field)) { return f; } } return null; } public FieldNode searchFieldByNameAndType(FieldInfo field) { for (FieldNode f : fields) { if (f.getFieldInfo().equalsNameAndType(field)) { return f; } } return null; } public FieldNode searchFieldByName(String name) { for (FieldNode f : fields) { if (f.getName().equals(name)) { return f; } } return null; } public FieldNode searchFieldByShortId(String shortId) { for (FieldNode f : fields) { if (f.getFieldInfo().getShortId().equals(shortId)) { return f; } } return null; } public MethodNode searchMethod(MethodInfo mth) { return mthInfoMap.get(mth); } public MethodNode searchMethodByShortId(String shortId) { for (MethodNode m : methods) { if (m.getMethodInfo().getShortId().equals(shortId)) { return m; } } return null; } /** * Return first method by original short name * Note: methods are not unique by name (class can have several methods with same name but different * signature) */ @Nullable public MethodNode searchMethodByShortName(String name) { for (MethodNode m : methods) { if (m.getMethodInfo().getName().equals(name)) { return m; } } return null; } @Override public ClassNode getDeclaringClass() { return isInner() ? parentClass : null; } public ClassNode getParentClass() { return parentClass; } public void notInner() { this.clsInfo.notInner(root); this.parentClass = this; } /** * Change class name and package (if full name provided) * Leading dot can be used to move to default package. * Package for inner classes can't be changed. */ @Override public void rename(String newName) { if (newName.indexOf('.') == -1) { clsInfo.changeShortName(newName); return; } // full name provided ClassInfo newClsInfo = ClassInfo.fromNameWithoutCache(root, newName, clsInfo.isInner()); // change class package String newPkg = newClsInfo.getPackage(); String newShortName = newClsInfo.getShortName(); if (clsInfo.isInner()) { if (!newPkg.equals(clsInfo.getPackage())) { addWarn("Can't change package for inner class: " + this + " to " + newName); } clsInfo.changeShortName(newShortName); } else { if (changeClassNodePackage(newPkg)) { clsInfo.changePkgAndName(newPkg, newShortName); } else { clsInfo.changeShortName(newShortName); } } } private boolean changeClassNodePackage(String fullPkg) { if (fullPkg.equals(clsInfo.getAliasPkg())) { return false; } if (clsInfo.isInner()) { throw new JadxRuntimeException("Can't change package for inner class: " + clsInfo); } root.removeClsFromPackage(packageNode, this); packageNode = PackageNode.getForClass(root, fullPkg, this); root.sortPackages(); return true; } public void removeAlias() { if (!clsInfo.isInner()) { changeClassNodePackage(clsInfo.getPackage()); } clsInfo.removeAlias(); } @Override public void onParentPackageUpdate(PackageNode updatedPkg) { if (clsInfo.isInner()) { return; } clsInfo.changePkg(packageNode.getAliasPkgInfo().getFullName()); } public PackageNode getPackageNode() { return packageNode; } public ClassNode getTopParentClass() { ClassNode parent = getParentClass(); return parent == this ? this : parent.getTopParentClass(); } public void visitParentClasses(Consumer<ClassNode> consumer) { ClassNode currentCls = this; ClassNode parentCls = currentCls.getParentClass(); while (parentCls != currentCls) { consumer.accept(parentCls); currentCls = parentCls; parentCls = currentCls.getParentClass(); } } public void visitSuperTypes(BiConsumer<ArgType, ArgType> consumer) { TypeUtils typeUtils = root.getTypeUtils(); ArgType thisType = this.getType(); if (!superClass.equals(ArgType.OBJECT)) { consumer.accept(thisType, superClass); typeUtils.visitSuperTypes(superClass, consumer); } for (ArgType iface : interfaces) { consumer.accept(thisType, iface); typeUtils.visitSuperTypes(iface, consumer); } } public boolean hasNotGeneratedParent() { if (contains(AFlag.DONT_GENERATE)) { return true; } ClassNode parent = getParentClass(); if (parent == this) { return false; } return parent.hasNotGeneratedParent(); } public List<ClassNode> getInnerClasses() { return innerClasses; } public List<ClassNode> getInlinedClasses() { return inlinedClasses; } /** * Get all inner and inlined classes recursively * * @param resultClassesSet all identified inner and inlined classes are added to this set */ public void getInnerAndInlinedClassesRecursive(Set<ClassNode> resultClassesSet) { for (ClassNode innerCls : innerClasses) { if (resultClassesSet.add(innerCls)) { innerCls.getInnerAndInlinedClassesRecursive(resultClassesSet); } } for (ClassNode inlinedCls : inlinedClasses) { if (resultClassesSet.add(inlinedCls)) { inlinedCls.getInnerAndInlinedClassesRecursive(resultClassesSet); } } } public void addInnerClass(ClassNode cls) { if (innerClasses.isEmpty()) { innerClasses = new ArrayList<>(5); } innerClasses.add(cls); cls.parentClass = this; } public void addInlinedClass(ClassNode cls) { if (inlinedClasses.isEmpty()) { inlinedClasses = new ArrayList<>(5); } cls.addAttr(new InlinedAttr(this)); inlinedClasses.add(cls); } public boolean isEnum() { return getAccessFlags().isEnum() && getSuperClass() != null && getSuperClass().getObject().equals(ArgType.ENUM.getObject()); } public boolean isAnonymous() { return contains(AType.ANONYMOUS_CLASS); } public boolean isSynthetic() { return contains(AFlag.SYNTHETIC); } public boolean isInner() { return parentClass != this; } public boolean isTopClass() { return parentClass == this; } @Nullable public MethodNode getClassInitMth() { return searchMethodByShortId("<clinit>()V"); } @Nullable public MethodNode getDefaultConstructor() { for (MethodNode mth : methods) { if (mth.isDefaultConstructor()) { return mth; } } return null; } @Override public AccessInfo getAccessFlags() { return accessFlags; } @Override public void setAccessFlags(AccessInfo accessFlags) { this.accessFlags = accessFlags; } @Override public RootNode root() { return root; } @Override public String typeName() { return "class"; } public String getRawName() { return clsInfo.getRawName(); } /** * Internal class info (don't use in code generation and external api). */ public ClassInfo getClassInfo() { return clsInfo; } public String getName() { return clsInfo.getShortName(); } public String getAlias() { return clsInfo.getAliasShortName(); } /** * Deprecated. Use {@link #getAlias()} */ @Deprecated public String getShortName() { return clsInfo.getAliasShortName(); } public String getFullName() { return clsInfo.getAliasFullName(); } public String getPackage() { return clsInfo.getAliasPkg(); } public String getDisassembledCode() { if (smali == null) { SimpleCodeWriter code = new SimpleCodeWriter(root.getArgs()); getDisassembledCode(code); Set<ClassNode> allInlinedClasses = new LinkedHashSet<>(); getInnerAndInlinedClassesRecursive(allInlinedClasses); for (ClassNode innerClass : allInlinedClasses) { innerClass.getDisassembledCode(code); } smali = code.finish().getCodeStr(); } return smali; } protected void getDisassembledCode(SimpleCodeWriter code) { if (clsData == null) { code.startLine(String.format("###### Class %s is created by jadx", getFullName())); return; } code.startLine(String.format("###### Class %s (%s)", getFullName(), getRawName())); try { code.startLine(clsData.getDisassembledCode()); } catch (Exception e) { code.startLine("Failed to disassemble class:"); code.startLine(Utils.getStackTrace(e)); } } /** * Low level class data access. * * @return null for classes generated by jadx */ public @Nullable IClassData getClsData() { return clsData; } public ProcessState getState() { return state; } public void setState(ProcessState state) { this.state = state; } public LoadStage getLoadStage() { return loadStage; } public void setLoadStage(LoadStage loadStage) { this.loadStage = loadStage; } public void reloadAtCodegenStage() { ClassNode topCls = this.getTopParentClass(); if (topCls.getLoadStage() == LoadStage.CODEGEN_STAGE) { throw new JadxRuntimeException("Class not yet loaded at codegen stage: " + topCls); } topCls.add(AFlag.RELOAD_AT_CODEGEN_STAGE); } public List<ClassNode> getDependencies() { return dependencies; } public void setDependencies(List<ClassNode> dependencies) { this.dependencies = dependencies; } public void removeDependency(ClassNode dep) { this.dependencies = ListUtils.safeRemoveAndTrim(this.dependencies, dep); } public List<ClassNode> getCodegenDeps() { return codegenDeps; } public void setCodegenDeps(List<ClassNode> codegenDeps) { this.codegenDeps = codegenDeps; } public void addCodegenDep(ClassNode dep) { if (!codegenDeps.contains(dep)) { this.codegenDeps = ListUtils.safeAdd(this.codegenDeps, dep); } } public int getTotalDepsCount() { return dependencies.size() + codegenDeps.size(); } public List<ClassNode> getUseIn() { return useIn; } public void setUseIn(List<ClassNode> useIn) { this.useIn = useIn; } public List<MethodNode> getUseInMth() { return useInMth; } public void setUseInMth(List<MethodNode> useInMth) { this.useInMth = useInMth; } @Override public String getInputFileName() { return inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public JavaClass getJavaNode() { return javaNode; } public void setJavaNode(JavaClass javaNode) { this.javaNode = javaNode; } @Override public AnnType getAnnType() { return AnnType.CLASS; } @Override public int hashCode() { return clsInfo.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof ClassNode) { ClassNode other = (ClassNode) o; return clsInfo.equals(other.clsInfo); } return false; } @Override public int compareTo(@NotNull ClassNode o) { return this.clsInfo.compareTo(o.clsInfo); } @Override public String toString() { return clsInfo.getFullName(); } }
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/nodes/IFieldInfoRef.java
jadx-core/src/main/java/jadx/core/dex/nodes/IFieldInfoRef.java
package jadx.core.dex.nodes; import jadx.core.dex.info.FieldInfo; /** * Common interface for FieldInfo and FieldNode */ public interface IFieldInfoRef { FieldInfo getFieldInfo(); }
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/nodes/utils/SelectFromDuplicates.java
jadx-core/src/main/java/jadx/core/dex/nodes/utils/SelectFromDuplicates.java
package jadx.core.dex.nodes.utils; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.dex.nodes.ClassNode; /** * Select best class from list of classes with same full name * Current implementation: use class with source file as 'classesN.dex' where N is minimal */ public class SelectFromDuplicates { private static final Logger LOG = LoggerFactory.getLogger(SelectFromDuplicates.class); private static final Pattern CLASSES_DEX_PATTERN = Pattern.compile("classes([1-9]\\d*)\\.dex"); public static ClassNode process(List<ClassNode> dupClsList) { ClassNode bestCls = null; int bestClsIndex = -1; for (ClassNode clsNode : dupClsList) { boolean selectCurrent = false; if (bestCls == null) { selectCurrent = true; } else { int clsIndex = getClassesIndex(clsNode.getInputFileName()); if (clsIndex != -1) { if (bestClsIndex != -1) { // if both are valid, the lower index has precedence if (clsIndex < bestClsIndex) { selectCurrent = true; } } else { // valid dex names have precedence selectCurrent = true; } } } if (selectCurrent) { bestCls = clsNode; bestClsIndex = getClassesIndex(clsNode.getInputFileName()); } } return bestCls; } /** * Get N from classesN.dex * * @return -1 if source is not valid dex name */ private static int getClassesIndex(String source) { if ("classes.dex".equals(source)) { return 1; } try { Matcher matcher = CLASSES_DEX_PATTERN.matcher(source); if (!matcher.matches()) { return -1; } String num = matcher.group(1); if (num.equals("1")) { return -1; } return Integer.parseInt(num); } catch (Exception e) { LOG.debug("Failed to parse source classes index", e); return -1; } } }
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/nodes/utils/MethodUtils.java
jadx-core/src/main/java/jadx/core/dex/nodes/utils/MethodUtils.java
package jadx.core.dex.nodes.utils; import java.util.ArrayList; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.core.clsp.ClspClass; import jadx.core.clsp.ClspMethod; 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.SkipMethodArgsAttr; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.BaseInvokeNode; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.InsnArg; 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.utils.Utils; public class MethodUtils { private final RootNode root; public MethodUtils(RootNode rootNode) { this.root = rootNode; } @Nullable public IMethodDetails getMethodDetails(BaseInvokeNode invokeNode) { IMethodDetails methodDetails = invokeNode.get(AType.METHOD_DETAILS); if (methodDetails != null) { return methodDetails; } return getMethodDetails(invokeNode.getCallMth()); } @Nullable public IMethodDetails getMethodDetails(MethodInfo callMth) { MethodNode mthNode = root.resolveMethod(callMth); if (mthNode != null) { return mthNode; } return root.getClsp().getMethodDetails(callMth); } @Nullable public MethodNode resolveMethod(BaseInvokeNode invokeNode) { IMethodDetails methodDetails = getMethodDetails(invokeNode); if (methodDetails instanceof MethodNode) { return (MethodNode) methodDetails; } return null; } public boolean isSkipArg(BaseInvokeNode invokeNode, InsnArg arg) { MethodNode mth = resolveMethod(invokeNode); if (mth == null) { return false; } SkipMethodArgsAttr skipArgsAttr = mth.get(AType.SKIP_MTH_ARGS); if (skipArgsAttr == null) { return false; } int argIndex = invokeNode.getArgIndex(arg); return skipArgsAttr.isSkip(argIndex); } /** * Search methods with same name and args count in class hierarchy starting from {@code startCls} * Beware {@code startCls} can be different from {@code mthInfo.getDeclClass()} */ public boolean isMethodArgsOverloaded(ArgType startCls, MethodInfo mthInfo) { return processMethodArgsOverloaded(startCls, mthInfo, null); } public List<IMethodDetails> collectOverloadedMethods(ArgType startCls, MethodInfo mthInfo) { List<IMethodDetails> list = new ArrayList<>(); processMethodArgsOverloaded(startCls, mthInfo, list); return list; } @Nullable public ArgType getMethodGenericReturnType(BaseInvokeNode invokeNode) { IMethodDetails methodDetails = getMethodDetails(invokeNode); if (methodDetails != null) { ArgType returnType = methodDetails.getReturnType(); if (returnType != null && returnType.containsGeneric()) { return returnType; } } return null; } private boolean processMethodArgsOverloaded(ArgType startCls, MethodInfo mthInfo, @Nullable List<IMethodDetails> collectedMths) { if (startCls == null || !startCls.isObject()) { return false; } boolean isMthConstructor = mthInfo.isConstructor() || mthInfo.isClassInit(); ClassNode classNode = root.resolveClass(startCls); if (classNode != null) { for (MethodNode mth : classNode.getMethods()) { if (mthInfo.isOverloadedBy(mth.getMethodInfo())) { if (collectedMths == null) { return true; } collectedMths.add(mth); } } if (!isMthConstructor) { if (processMethodArgsOverloaded(classNode.getSuperClass(), mthInfo, collectedMths)) { if (collectedMths == null) { return true; } } for (ArgType parentInterface : classNode.getInterfaces()) { if (processMethodArgsOverloaded(parentInterface, mthInfo, collectedMths)) { if (collectedMths == null) { return true; } } } } } else { ClspClass clsDetails = root.getClsp().getClsDetails(startCls); if (clsDetails == null) { // class info not available return false; } for (ClspMethod clspMth : clsDetails.getMethodsMap().values()) { if (mthInfo.isOverloadedBy(clspMth.getMethodInfo())) { if (collectedMths == null) { return true; } collectedMths.add(clspMth); } } if (!isMthConstructor) { for (ArgType parent : clsDetails.getParents()) { if (processMethodArgsOverloaded(parent, mthInfo, collectedMths)) { if (collectedMths == null) { return true; } } } } } return false; } @Nullable public IMethodDetails getOverrideBaseMth(MethodNode mth) { MethodOverrideAttr overrideAttr = mth.get(AType.METHOD_OVERRIDE); if (overrideAttr == null) { return null; } return Utils.getOne(overrideAttr.getBaseMethods()); } public ClassInfo getMethodOriginDeclClass(MethodNode mth) { IMethodDetails baseMth = getOverrideBaseMth(mth); if (baseMth != null) { return baseMth.getMethodInfo().getDeclClass(); } MethodBridgeAttr bridgeAttr = mth.get(AType.BRIDGED_BY); if (bridgeAttr != null) { return getMethodOriginDeclClass(bridgeAttr.getBridgeMth()); } return mth.getMethodInfo().getDeclClass(); } }
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/nodes/utils/TypeUtils.java
jadx-core/src/main/java/jadx/core/dex/nodes/utils/TypeUtils.java
package jadx.core.dex.nodes.utils; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import org.jetbrains.annotations.Nullable; import jadx.core.clsp.ClspClass; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.ClassTypeVarsAttr; import jadx.core.dex.attributes.nodes.MethodTypeVarsAttr; import jadx.core.dex.attributes.nodes.NotificationAttrNode; import jadx.core.dex.instructions.BaseInvokeNode; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.InsnArg; 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.utils.Utils; import static jadx.core.utils.Utils.isEmpty; import static jadx.core.utils.Utils.notEmpty; public class TypeUtils { private final RootNode root; public TypeUtils(RootNode rootNode) { this.root = rootNode; } public List<ArgType> getClassGenerics(ArgType type) { ClassNode classNode = root.resolveClass(type); if (classNode != null) { return classNode.getGenericTypeParameters(); } ClspClass clsDetails = root.getClsp().getClsDetails(type); if (clsDetails == null || clsDetails.getTypeParameters().isEmpty()) { return Collections.emptyList(); } List<ArgType> generics = clsDetails.getTypeParameters(); return generics == null ? Collections.emptyList() : generics; } @Nullable public ClassTypeVarsAttr getClassTypeVars(ArgType type) { ClassNode classNode = root.resolveClass(type); if (classNode == null) { return null; } ClassTypeVarsAttr typeVarsAttr = classNode.get(AType.CLASS_TYPE_VARS); if (typeVarsAttr != null) { return typeVarsAttr; } return buildClassTypeVarsAttr(classNode); } public ArgType expandTypeVariables(ClassNode cls, ArgType type) { if (type.containsTypeVariable()) { expandTypeVar(cls, type, getKnownTypeVarsAtClass(cls)); } return type; } public ArgType expandTypeVariables(MethodNode mth, ArgType type) { if (type.containsTypeVariable()) { expandTypeVar(mth, type, getKnownTypeVarsAtMethod(mth)); } return type; } private void expandTypeVar(NotificationAttrNode node, ArgType type, Collection<ArgType> typeVars) { if (typeVars.isEmpty()) { return; } boolean allExtendsEmpty = true; for (ArgType argType : typeVars) { if (notEmpty(argType.getExtendTypes())) { allExtendsEmpty = false; break; } } if (allExtendsEmpty) { return; } type.visitTypes(t -> { if (t.isGenericType()) { String typeVarName = t.getObject(); for (ArgType typeVar : typeVars) { if (typeVar.getObject().equals(typeVarName)) { t.setExtendTypes(typeVar.getExtendTypes()); return null; } } node.addWarnComment("Unknown type variable: " + typeVarName + " in type: " + type); } return null; }); } public Set<ArgType> getKnownTypeVarsAtMethod(MethodNode mth) { MethodTypeVarsAttr typeVarsAttr = mth.get(AType.METHOD_TYPE_VARS); if (typeVarsAttr != null) { return typeVarsAttr.getTypeVars(); } Set<ArgType> typeVars = collectKnownTypeVarsAtMethod(mth); MethodTypeVarsAttr varsAttr = MethodTypeVarsAttr.build(typeVars); mth.addAttr(varsAttr); return varsAttr.getTypeVars(); } private static Collection<ArgType> getKnownTypeVarsAtClass(ClassNode cls) { if (cls.isInner()) { Set<ArgType> typeVars = new HashSet<>(cls.getGenericTypeParameters()); cls.visitParentClasses(parent -> typeVars.addAll(parent.getGenericTypeParameters())); return typeVars; } return cls.getGenericTypeParameters(); } private static Set<ArgType> collectKnownTypeVarsAtMethod(MethodNode mth) { Set<ArgType> typeVars = new HashSet<>(); typeVars.addAll(getKnownTypeVarsAtClass(mth.getParentClass())); typeVars.addAll(mth.getTypeParameters()); return typeVars.isEmpty() ? Collections.emptySet() : typeVars; } /** * Search for unknown type vars at current method. Return only first. * * @return unknown type var, null if not found */ @Nullable public ArgType checkForUnknownTypeVars(MethodNode mth, ArgType checkType) { Set<ArgType> knownTypeVars = getKnownTypeVarsAtMethod(mth); return checkType.visitTypes(type -> { if (type.isGenericType() && !knownTypeVars.contains(type)) { return type; } return null; }); } public boolean containsUnknownTypeVar(MethodNode mth, ArgType type) { return checkForUnknownTypeVars(mth, type) != null; } /** * Replace generic types in {@code typeWithGeneric} using instance types * <br> * Example: * <ul> * <li>{@code instanceType: Set<String>} * <li>{@code typeWithGeneric: Iterator<E>} * <li>{@code return: Iterator<String>} * </ul> */ @Nullable public ArgType replaceClassGenerics(ArgType instanceType, ArgType typeWithGeneric) { return replaceClassGenerics(instanceType, instanceType, typeWithGeneric); } @Nullable public ArgType replaceClassGenerics(ArgType instanceType, ArgType genericSourceType, ArgType typeWithGeneric) { if (typeWithGeneric == null || genericSourceType == null) { return null; } Map<ArgType, ArgType> typeVarsMap = Collections.emptyMap(); ClassTypeVarsAttr typeVars = getClassTypeVars(instanceType); if (typeVars != null) { typeVarsMap = mergeTypeMaps(typeVarsMap, typeVars.getTypeVarsMapFor(genericSourceType)); } typeVarsMap = mergeTypeMaps(typeVarsMap, getTypeVariablesMapping(instanceType)); ArgType outerType = instanceType.getOuterType(); while (outerType != null) { typeVarsMap = mergeTypeMaps(typeVarsMap, getTypeVariablesMapping(outerType)); outerType = outerType.getOuterType(); } return replaceTypeVariablesUsingMap(typeWithGeneric, typeVarsMap); } private static Map<ArgType, ArgType> mergeTypeMaps(Map<ArgType, ArgType> base, Map<ArgType, ArgType> addition) { if (base.isEmpty()) { return addition; } if (addition.isEmpty()) { return base; } Map<ArgType, ArgType> map = new HashMap<>(base.size() + addition.size()); for (Map.Entry<ArgType, ArgType> entry : base.entrySet()) { ArgType value = entry.getValue(); ArgType type = addition.remove(value); if (type != null) { map.put(entry.getKey(), type); } else { map.put(entry.getKey(), entry.getValue()); } } map.putAll(addition); return map; } public Map<ArgType, ArgType> getTypeVariablesMapping(ArgType clsType) { if (!clsType.isGeneric()) { return Collections.emptyMap(); } List<ArgType> typeParameters = root.getTypeUtils().getClassGenerics(clsType); if (typeParameters.isEmpty()) { return Collections.emptyMap(); } List<ArgType> actualTypes = clsType.getGenericTypes(); if (isEmpty(actualTypes)) { return Collections.emptyMap(); } int genericParamsCount = actualTypes.size(); if (genericParamsCount != typeParameters.size()) { return Collections.emptyMap(); } Map<ArgType, ArgType> replaceMap = new HashMap<>(genericParamsCount); for (int i = 0; i < genericParamsCount; i++) { ArgType actualType = actualTypes.get(i); ArgType typeVar = typeParameters.get(i); if (typeVar.getExtendTypes() != null) { // force short form (only type var name) typeVar = ArgType.genericType(typeVar.getObject()); } replaceMap.put(typeVar, actualType); } return replaceMap; } public Map<ArgType, ArgType> getTypeVarMappingForInvoke(BaseInvokeNode invokeInsn) { IMethodDetails mthDetails = root.getMethodUtils().getMethodDetails(invokeInsn); if (mthDetails == null) { return Collections.emptyMap(); } Map<ArgType, ArgType> map = new HashMap<>(1 + invokeInsn.getArgsCount()); addTypeVarMapping(map, mthDetails.getReturnType(), invokeInsn.getResult()); int argCount = Math.min(mthDetails.getArgTypes().size(), invokeInsn.getArgsCount() - invokeInsn.getFirstArgOffset()); for (int i = 0; i < argCount; i++) { addTypeVarMapping(map, mthDetails.getArgTypes().get(i), invokeInsn.getArg(i + invokeInsn.getFirstArgOffset())); } return map; } private static void addTypeVarMapping(Map<ArgType, ArgType> map, ArgType typeVar, InsnArg arg) { if (arg == null || typeVar == null || !typeVar.isTypeKnown()) { return; } if (typeVar.isGenericType()) { map.put(typeVar, arg.getType()); } // TODO: resolve inner type vars: 'List<T> -> List<String>' to 'T -> String' } @Nullable public ArgType replaceMethodGenerics(BaseInvokeNode invokeInsn, IMethodDetails details, ArgType typeWithGeneric) { if (typeWithGeneric == null) { return null; } List<ArgType> methodArgTypes = details.getArgTypes(); if (methodArgTypes.isEmpty()) { return null; } int firstArgOffset = invokeInsn.getFirstArgOffset(); int argsCount = methodArgTypes.size(); for (int i = 0; i < argsCount; i++) { ArgType methodArgType = methodArgTypes.get(i); InsnArg insnArg = invokeInsn.getArg(i + firstArgOffset); ArgType insnType = insnArg.getType(); if (methodArgType.equals(typeWithGeneric)) { return insnType; } } // TODO build complete map for type variables return null; } @Nullable public ArgType replaceTypeVariablesUsingMap(ArgType replaceType, Map<ArgType, ArgType> replaceMap) { if (replaceMap.isEmpty()) { return null; } if (replaceType.isGenericType()) { return replaceMap.get(replaceType); } if (replaceType.isArray()) { ArgType replaced = replaceTypeVariablesUsingMap(replaceType.getArrayElement(), replaceMap); if (replaced == null) { return null; } return ArgType.array(replaced); } ArgType wildcardType = replaceType.getWildcardType(); if (wildcardType != null && wildcardType.containsTypeVariable()) { ArgType newWildcardType = replaceTypeVariablesUsingMap(wildcardType, replaceMap); if (newWildcardType == null) { return null; } return ArgType.wildcard(newWildcardType, replaceType.getWildcardBound()); } if (replaceType.isGeneric()) { ArgType outerType = replaceType.getOuterType(); if (outerType != null) { ArgType replacedOuter = replaceTypeVariablesUsingMap(outerType, replaceMap); if (replacedOuter == null) { return null; } ArgType innerType = replaceType.getInnerType(); ArgType replacedInner = replaceTypeVariablesUsingMap(innerType, replaceMap); return ArgType.outerGeneric(replacedOuter, replacedInner == null ? innerType : replacedInner); } List<ArgType> genericTypes = replaceType.getGenericTypes(); if (notEmpty(genericTypes)) { List<ArgType> newTypes = Utils.collectionMap(genericTypes, t -> { ArgType type = replaceTypeVariablesUsingMap(t, replaceMap); return type == null ? t : type; }); return ArgType.generic(replaceType, newTypes); } } return null; } private ClassTypeVarsAttr buildClassTypeVarsAttr(ClassNode cls) { Map<String, Map<ArgType, ArgType>> map = new HashMap<>(); ArgType currentClsType = cls.getClassInfo().getType(); map.put(currentClsType.getObject(), getTypeVariablesMapping(currentClsType)); cls.visitSuperTypes((parent, type) -> { List<ArgType> currentVars = type.getGenericTypes(); if (Utils.isEmpty(currentVars)) { return; } int varsCount = currentVars.size(); List<ArgType> sourceTypeVars = getClassGenerics(type); if (varsCount == sourceTypeVars.size()) { Map<ArgType, ArgType> parentTypeMap = map.get(parent.getObject()); Map<ArgType, ArgType> varsMap = new HashMap<>(varsCount); for (int i = 0; i < varsCount; i++) { ArgType currentTypeVar = currentVars.get(i); ArgType resultType = parentTypeMap != null ? parentTypeMap.get(currentTypeVar) : null; varsMap.put(sourceTypeVars.get(i), resultType != null ? resultType : currentTypeVar); } map.put(type.getObject(), varsMap); } }); List<ArgType> currentTypeVars = cls.getGenericTypeParameters(); ClassTypeVarsAttr typeVarsAttr = new ClassTypeVarsAttr(currentTypeVars, map); cls.addAttr(typeVarsAttr); return typeVarsAttr; } public void visitSuperTypes(ArgType type, BiConsumer<ArgType, ArgType> consumer) { ClassNode cls = root.resolveClass(type); if (cls != null) { cls.visitSuperTypes(consumer); } else { ClspClass clspClass = root.getClsp().getClsDetails(type); if (clspClass != null) { for (ArgType superType : clspClass.getParents()) { if (!superType.equals(ArgType.OBJECT)) { consumer.accept(type, superType); visitSuperTypes(superType, consumer); } } } } } }
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/nodes/parser/SignatureParser.java
jadx-core/src/main/java/jadx/core/dex/nodes/parser/SignatureParser.java
package jadx.core.dex.nodes.parser; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.plugins.input.data.attributes.JadxAttrType; import jadx.api.plugins.input.data.attributes.types.SignatureAttr; import jadx.core.dex.attributes.IAttributeNode; import jadx.core.dex.instructions.args.ArgType; import jadx.core.utils.exceptions.JadxRuntimeException; public class SignatureParser { private static final Logger LOG = LoggerFactory.getLogger(SignatureParser.class); private static final char STOP_CHAR = 0; private final String sign; private final int end; private int pos; private int mark; public SignatureParser(String signature) { sign = signature; end = sign.length(); pos = -1; mark = 0; } @Nullable public static SignatureParser fromNode(IAttributeNode node) { String signature = getSignature(node); if (signature == null) { return null; } return new SignatureParser(signature); } @Nullable public static String getSignature(IAttributeNode node) { SignatureAttr attr = node.get(JadxAttrType.SIGNATURE); if (attr == null) { return null; } return attr.getSignature(); } private char next() { pos++; if (pos >= end) { return STOP_CHAR; } return sign.charAt(pos); } private boolean lookAhead(char ch) { int next = pos + 1; return next < end && sign.charAt(next) == ch; } private void mark() { mark = pos; } /** * Exclusive slice. * * @return string from 'mark' to current position (not including current character) */ private String slice() { int start = mark == -1 ? 0 : mark; if (start >= pos) { return ""; } return sign.substring(start, pos); } /** * Inclusive slice (includes current character) */ private String inclusiveSlice() { int start = mark; if (start == -1) { start = 0; } int last = pos + 1; if (start >= last) { return ""; } return sign.substring(start, last); } private boolean skipUntil(char untilChar) { int startPos = pos; while (true) { if (lookAhead(untilChar)) { return true; } char ch = next(); if (ch == STOP_CHAR) { pos = startPos; return false; } } } private void consume(char exp) { char c = next(); if (exp != c) { throw new JadxRuntimeException("Consume wrong char: '" + c + "' != '" + exp + "', sign: " + debugString()); } } private boolean tryConsume(char exp) { if (lookAhead(exp)) { next(); return true; } return false; } @Nullable public String consumeUntil(char lastChar) { mark(); return skipUntil(lastChar) ? inclusiveSlice() : null; } public ArgType consumeType() { char ch = next(); switch (ch) { case 'L': ArgType obj = consumeObjectType(false); if (obj != null) { return obj; } break; case 'T': next(); mark(); String typeVarName = consumeUntil(';'); if (typeVarName != null) { consume(';'); if (typeVarName.contains(")")) { throw new JadxRuntimeException("Bad name for type variable: " + typeVarName); } return ArgType.genericType(typeVarName); } break; case '[': return ArgType.array(consumeType()); case STOP_CHAR: return null; default: // primitive type (one char) ArgType type = ArgType.parse(ch); if (type != null) { return type; } break; } throw new JadxRuntimeException("Can't parse type: " + debugString() + ", unexpected: " + ch); } public List<ArgType> consumeTypeList() { List<ArgType> list = null; while (true) { ArgType type = consumeType(); if (type == null) { break; } if (list == null) { list = new ArrayList<>(); } list.add(type); } if (list == null) { return Collections.emptyList(); } return list; } private ArgType consumeObjectType(boolean innerType) { mark(); int ch; do { if (innerType && lookAhead('.')) { // stop before next nested inner class return ArgType.object(inclusiveSlice()); } ch = next(); if (ch == STOP_CHAR) { return null; } } while (ch != '<' && ch != ';'); if (ch == ';') { String obj; if (innerType) { obj = slice().replace('/', '.'); } else { obj = inclusiveSlice(); } return ArgType.object(obj); } // generic type start ('<') String obj = slice(); if (!innerType) { obj += ';'; } else { obj = obj.replace('/', '.'); } List<ArgType> typeVars = consumeGenericArgs(); consume('>'); ArgType genericType = ArgType.generic(obj, typeVars); if (!lookAhead('.')) { consume(';'); return genericType; } consume('.'); next(); // type parsing not completed, proceed to inner class ArgType inner = consumeObjectType(true); if (inner == null) { throw new JadxRuntimeException("No inner type found: " + debugString()); } // for every nested inner type create nested type object while (lookAhead('.')) { genericType = ArgType.outerGeneric(genericType, inner); consume('.'); next(); inner = consumeObjectType(true); if (inner == null) { throw new JadxRuntimeException("Unexpected inner type found: " + debugString()); } } return ArgType.outerGeneric(genericType, inner); } private List<ArgType> consumeGenericArgs() { List<ArgType> list = new ArrayList<>(); ArgType type; do { if (lookAhead('*')) { next(); type = ArgType.wildcard(); } else if (lookAhead('+')) { next(); type = ArgType.wildcard(consumeType(), ArgType.WildcardBound.EXTENDS); } else if (lookAhead('-')) { next(); type = ArgType.wildcard(consumeType(), ArgType.WildcardBound.SUPER); } else { type = consumeType(); } if (type != null) { list.add(type); } } while (type != null && !lookAhead('>')); return list; } /** * Map of generic types names to extends classes. * <p> * Example: "&lt;T:Ljava/lang/Exception;:Ljava/lang/Object;&gt;" */ @SuppressWarnings("ConditionalBreakInInfiniteLoop") public List<ArgType> consumeGenericTypeParameters() { if (!lookAhead('<')) { return Collections.emptyList(); } List<ArgType> list = new ArrayList<>(); consume('<'); while (true) { if (lookAhead('>') || next() == STOP_CHAR) { break; } String id = consumeUntil(':'); if (id == null) { throw new JadxRuntimeException("Failed to parse generic types map"); } consume(':'); tryConsume(':'); List<ArgType> types = consumeExtendsTypesList(); list.add(ArgType.genericType(id, types)); } consume('>'); return list; } /** * List of types separated by ':' last type is 'java.lang.Object'. * <p/> * Example: "Ljava/lang/Exception;:Ljava/lang/Object;" */ private List<ArgType> consumeExtendsTypesList() { List<ArgType> types = Collections.emptyList(); boolean next; do { ArgType argType = consumeType(); if (argType == null) { throw new JadxRuntimeException("Unexpected end of signature"); } if (!argType.equals(ArgType.OBJECT)) { if (types.isEmpty()) { types = new ArrayList<>(); } types.add(argType); } next = lookAhead(':'); if (next) { consume(':'); } } while (next); return types; } public List<ArgType> consumeMethodArgs(int argsCount) { consume('('); if (lookAhead(')')) { consume(')'); return Collections.emptyList(); } List<ArgType> args = new ArrayList<>(argsCount); int limit = argsCount + 10; // just prevent endless loop, args count can be different for synthetic methods do { ArgType type = consumeType(); if (type == null) { throw new JadxRuntimeException("Unexpected end of signature"); } args.add(type); if (args.size() > limit) { throw new JadxRuntimeException("Arguments count limit reached: " + args.size()); } } while (!lookAhead(')')); consume(')'); return args; } private static String mergeSignature(List<String> list) { if (list.size() == 1) { return list.get(0); } StringBuilder sb = new StringBuilder(); for (String s : list) { sb.append(s); } return sb.toString(); } public String getSignature() { return sign; } private String debugString() { if (pos >= sign.length()) { return sign; } return sign + " at position " + pos + " ('" + sign.charAt(pos) + "')"; } @Override public String toString() { if (pos == -1) { return sign; } return sign.substring(0, mark) + '{' + sign.substring(mark, pos) + '}' + sign.substring(pos); } }
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/regions/SwitchRegion.java
jadx-core/src/main/java/jadx/core/dex/regions/SwitchRegion.java
package jadx.core.dex.regions; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jadx.api.ICodeWriter; import jadx.core.codegen.RegionGen; 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.utils.Utils; import jadx.core.utils.exceptions.CodegenException; public final class SwitchRegion extends AbstractRegion implements IBranchRegion { public static final Object DEFAULT_CASE_KEY = new Object() { @Override public String toString() { return "default"; } }; private final BlockNode header; private final List<CaseInfo> cases; public SwitchRegion(IRegion parent, BlockNode header) { super(parent); this.header = header; this.cases = new ArrayList<>(); } public static final class CaseInfo { private final List<Object> keys; private final IContainer container; public CaseInfo(List<Object> keys, IContainer container) { this.keys = keys; this.container = container; } public List<Object> getKeys() { return keys; } public IContainer getContainer() { return container; } } public BlockNode getHeader() { return header; } public void addCase(List<Object> keysList, IContainer c) { cases.add(new CaseInfo(keysList, c)); } public List<CaseInfo> getCases() { return cases; } public List<IContainer> getCaseContainers() { return Utils.collectionMap(cases, caseInfo -> caseInfo.container); } @Override public List<IContainer> getSubBlocks() { List<IContainer> all = new ArrayList<>(cases.size() + 1); all.add(header); all.addAll(getCaseContainers()); return Collections.unmodifiableList(all); } @Override public List<IContainer> getBranches() { return Collections.unmodifiableList(getCaseContainers()); } @Override public void generate(RegionGen regionGen, ICodeWriter code) throws CodegenException { regionGen.makeSwitch(this, code); } @Override public String baseString() { return "SW:" + header.baseString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Switch: ").append(header.baseString()); for (CaseInfo caseInfo : cases) { List<String> keyStrings = Utils.collectionMap(caseInfo.getKeys(), k -> k == DEFAULT_CASE_KEY ? "default" : k.toString()); sb.append("\n case ") .append(Utils.listToString(keyStrings)) .append(" -> ").append(caseInfo.getContainer()); } 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/regions/Region.java
jadx-core/src/main/java/jadx/core/dex/regions/Region.java
package jadx.core.dex.regions; import java.util.ArrayList; import java.util.List; import jadx.api.ICodeWriter; import jadx.core.codegen.RegionGen; import jadx.core.dex.nodes.IContainer; import jadx.core.dex.nodes.IRegion; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.CodegenException; public final class Region extends AbstractRegion { private final List<IContainer> blocks; public Region(IRegion parent) { super(parent); this.blocks = new ArrayList<>(1); } @Override public List<IContainer> getSubBlocks() { return blocks; } public void add(IContainer region) { updateParent(region, this); blocks.add(region); } @Override public void generate(RegionGen regionGen, ICodeWriter code) throws CodegenException { for (IContainer c : blocks) { regionGen.makeRegion(code, c); } } @Override public boolean replaceSubBlock(IContainer oldBlock, IContainer newBlock) { int i = blocks.indexOf(oldBlock); if (i != -1) { blocks.set(i, newBlock); updateParent(newBlock, this); return true; } return false; } @Override public String baseString() { StringBuilder sb = new StringBuilder(); int size = blocks.size(); sb.append('('); sb.append(size); if (size > 0) { sb.append(':'); Utils.listToString(sb, blocks, "|", IContainer::baseString); } sb.append(')'); return sb.toString(); } @Override public String toString() { return 'R' + baseString(); } }
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/regions/TryCatchRegion.java
jadx-core/src/main/java/jadx/core/dex/regions/TryCatchRegion.java
package jadx.core.dex.regions; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jadx.api.ICodeWriter; import jadx.core.codegen.RegionGen; import jadx.core.dex.nodes.IBranchRegion; import jadx.core.dex.nodes.IContainer; import jadx.core.dex.nodes.IRegion; import jadx.core.dex.trycatch.ExceptionHandler; import jadx.core.dex.trycatch.TryCatchBlockAttr; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.CodegenException; public final class TryCatchRegion extends AbstractRegion implements IBranchRegion { private final IContainer tryRegion; private Map<ExceptionHandler, IContainer> catchRegions = Collections.emptyMap(); private IContainer finallyRegion; private TryCatchBlockAttr tryCatchBlock; public TryCatchRegion(IRegion parent, IContainer tryRegion) { super(parent); this.tryRegion = tryRegion; } public void setTryCatchBlock(TryCatchBlockAttr tryCatchBlock) { this.tryCatchBlock = tryCatchBlock; int count = tryCatchBlock.getHandlersCount(); this.catchRegions = new LinkedHashMap<>(count); for (ExceptionHandler handler : tryCatchBlock.getHandlers()) { IContainer handlerRegion = handler.getHandlerRegion(); if (handlerRegion != null) { if (handler.isFinally()) { finallyRegion = handlerRegion; } else { catchRegions.put(handler, handlerRegion); } } } } public IContainer getTryRegion() { return tryRegion; } public Map<ExceptionHandler, IContainer> getCatchRegions() { return catchRegions; } public TryCatchBlockAttr getTryCatchBlock() { return tryCatchBlock; } public IContainer getFinallyRegion() { return finallyRegion; } public void setFinallyRegion(IContainer finallyRegion) { this.finallyRegion = finallyRegion; } @Override public List<IContainer> getSubBlocks() { List<IContainer> all = new ArrayList<>(2 + catchRegions.size()); all.add(tryRegion); all.addAll(catchRegions.values()); if (finallyRegion != null) { all.add(finallyRegion); } return Collections.unmodifiableList(all); } @Override public List<IContainer> getBranches() { return getSubBlocks(); } @Override public void generate(RegionGen regionGen, ICodeWriter code) throws CodegenException { regionGen.makeTryCatch(this, code); } @Override public String baseString() { return tryRegion.baseString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Try: ").append(tryRegion); if (!catchRegions.isEmpty()) { sb.append(" catches: ").append(Utils.listToString(catchRegions.values())); } if (finallyRegion != null) { sb.append(" finally: ").append(finallyRegion); } 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/regions/AbstractRegion.java
jadx-core/src/main/java/jadx/core/dex/regions/AbstractRegion.java
package jadx.core.dex.regions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.dex.attributes.AttrNode; import jadx.core.dex.nodes.IContainer; import jadx.core.dex.nodes.IRegion; public abstract class AbstractRegion extends AttrNode implements IRegion { private static final Logger LOG = LoggerFactory.getLogger(AbstractRegion.class); private IRegion parent; public AbstractRegion(IRegion parent) { this.parent = parent; } @Override public IRegion getParent() { return parent; } @Override public void setParent(IRegion parent) { this.parent = parent; } @Override public boolean replaceSubBlock(IContainer oldBlock, IContainer newBlock) { LOG.warn("Replace sub block not supported for class \"{}\"", this.getClass()); return false; } public void updateParent(IContainer container, IRegion newParent) { if (container instanceof IRegion) { ((IRegion) container).setParent(newParent); } } }
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/regions/SynchronizedRegion.java
jadx-core/src/main/java/jadx/core/dex/regions/SynchronizedRegion.java
package jadx.core.dex.regions; import java.util.ArrayList; import java.util.List; import jadx.api.ICodeWriter; import jadx.core.codegen.RegionGen; import jadx.core.dex.nodes.IContainer; import jadx.core.dex.nodes.IRegion; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.exceptions.CodegenException; public final class SynchronizedRegion extends AbstractRegion { private final InsnNode enterInsn; private final List<InsnNode> exitInsns = new ArrayList<>(); private final Region region; public SynchronizedRegion(IRegion parent, InsnNode insn) { super(parent); this.enterInsn = insn; this.region = new Region(this); } public InsnNode getEnterInsn() { return enterInsn; } public List<InsnNode> getExitInsns() { return exitInsns; } public Region getRegion() { return region; } @Override public List<IContainer> getSubBlocks() { return region.getSubBlocks(); } @Override public void generate(RegionGen regionGen, ICodeWriter code) throws CodegenException { regionGen.makeSynchronizedRegion(this, code); } @Override public String baseString() { return Integer.toHexString(enterInsn.getOffset()); } @Override public String toString() { return "Synchronized:" + 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/regions/conditions/ConditionRegion.java
jadx-core/src/main/java/jadx/core/dex/regions/conditions/ConditionRegion.java
package jadx.core.dex.regions.conditions; import java.util.Collections; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.IConditionRegion; import jadx.core.dex.nodes.IRegion; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.regions.AbstractRegion; import jadx.core.utils.BlockUtils; public abstract class ConditionRegion extends AbstractRegion implements IConditionRegion { @Nullable private IfCondition condition; private List<BlockNode> conditionBlocks = Collections.emptyList(); public ConditionRegion(IRegion parent) { super(parent); } @Override @Nullable public IfCondition getCondition() { return condition; } @Override public List<BlockNode> getConditionBlocks() { return conditionBlocks; } @Override public void invertCondition() { if (condition != null) { condition = IfCondition.invert(condition); } } @Override public boolean simplifyCondition() { if (condition == null) { return false; } IfCondition updated = IfCondition.simplify(condition); if (updated != condition) { condition = updated; return true; } return false; } @Override public int getConditionSourceLine() { for (BlockNode block : conditionBlocks) { InsnNode lastInsn = BlockUtils.getLastInsn(block); if (lastInsn != null) { int sourceLine = lastInsn.getSourceLine(); if (sourceLine != 0) { return sourceLine; } } } return 0; } /** * Preferred way to update condition info */ public void updateCondition(IfInfo info) { this.condition = info.getCondition(); this.conditionBlocks = info.getMergedBlocks().toList(); } public void updateCondition(IfCondition condition, List<BlockNode> conditionBlocks) { this.condition = condition; this.conditionBlocks = conditionBlocks; } public void updateCondition(BlockNode block) { this.condition = IfCondition.fromIfBlock(block); this.conditionBlocks = Collections.singletonList(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/regions/conditions/IfCondition.java
jadx-core/src/main/java/jadx/core/dex/regions/conditions/IfCondition.java
package jadx.core.dex.regions.conditions; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import jadx.core.dex.attributes.AttrNode; import jadx.core.dex.instructions.ArithNode; import jadx.core.dex.instructions.ArithOp; import jadx.core.dex.instructions.IfNode; import jadx.core.dex.instructions.IfOp; 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.nodes.BlockNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.BlockUtils; import jadx.core.utils.exceptions.JadxRuntimeException; public final class IfCondition extends AttrNode { public enum Mode { COMPARE, TERNARY, NOT, AND, OR } private final Mode mode; private final List<IfCondition> args; private final Compare compare; private IfCondition(Compare compare) { this.mode = Mode.COMPARE; this.compare = compare; this.args = Collections.emptyList(); } private IfCondition(Mode mode, List<IfCondition> args) { this.mode = mode; this.args = args; this.compare = null; } private IfCondition(IfCondition c) { this.mode = c.mode; this.compare = c.compare; if (c.mode == Mode.COMPARE) { this.args = Collections.emptyList(); } else { this.args = new ArrayList<>(c.args); } } public static IfCondition fromIfBlock(BlockNode header) { InsnNode lastInsn = BlockUtils.getLastInsn(header); if (lastInsn == null) { return null; } return fromIfNode((IfNode) lastInsn); } public static IfCondition fromIfNode(IfNode insn) { return new IfCondition(new Compare(insn)); } public static IfCondition ternary(IfCondition a, IfCondition b, IfCondition c) { return new IfCondition(Mode.TERNARY, Arrays.asList(a, b, c)); } public static IfCondition merge(Mode mode, IfCondition a, IfCondition b) { if (a.getMode() == mode) { IfCondition n = new IfCondition(a); n.addArg(b); return n; } return new IfCondition(mode, Arrays.asList(a, b)); } public Mode getMode() { return mode; } public List<IfCondition> getArgs() { return args; } public IfCondition first() { return args.get(0); } public IfCondition second() { return args.get(1); } public IfCondition third() { return args.get(2); } public void addArg(IfCondition c) { args.add(c); } public boolean isCompare() { return mode == Mode.COMPARE; } public Compare getCompare() { return compare; } public static IfCondition invert(IfCondition cond) { Mode mode = cond.getMode(); switch (mode) { case COMPARE: return new IfCondition(cond.getCompare().invert()); case TERNARY: return ternary(cond.first(), not(cond.second()), not(cond.third())); case NOT: return cond.first(); case AND: case OR: List<IfCondition> args = cond.getArgs(); List<IfCondition> newArgs = new ArrayList<>(args.size()); for (IfCondition arg : args) { newArgs.add(invert(arg)); } return new IfCondition(mode == Mode.AND ? Mode.OR : Mode.AND, newArgs); } throw new JadxRuntimeException("Unknown mode for invert: " + mode); } public static IfCondition not(IfCondition cond) { if (cond.getMode() == Mode.NOT) { return cond.first(); } if (cond.getCompare() != null) { return new IfCondition(cond.compare.invert()); } return new IfCondition(Mode.NOT, Collections.singletonList(cond)); } public static IfCondition simplify(IfCondition cond) { if (cond.isCompare()) { Compare c = cond.getCompare(); IfCondition i = simplifyCmpOp(c); if (i != null) { return i; } if (c.getOp() == IfOp.EQ && c.getB().isFalse()) { cond = new IfCondition(Mode.NOT, Collections.singletonList(new IfCondition(c.invert()))); } else { c.normalize(); } } List<IfCondition> args = null; for (int i = 0; i < cond.getArgs().size(); i++) { IfCondition arg = cond.getArgs().get(i); IfCondition simpl = simplify(arg); if (simpl != arg) { if (args == null) { args = new ArrayList<>(cond.getArgs()); } args.set(i, simpl); } } if (args != null) { // arguments was changed cond = new IfCondition(cond.getMode(), args); } if (cond.getMode() == Mode.NOT && cond.first().getMode() == Mode.NOT) { cond = invert(cond.first()); } if (cond.getMode() == Mode.TERNARY && cond.first().getMode() == Mode.NOT) { cond = invert(cond); } // for condition with a lot of negations => make invert if (cond.getMode() == Mode.OR || cond.getMode() == Mode.AND) { int count = cond.getArgs().size(); if (count > 1) { int negCount = 0; for (IfCondition arg : cond.getArgs()) { if (arg.getMode() == Mode.NOT || (arg.isCompare() && arg.getCompare().getOp() == IfOp.NE)) { negCount++; } } if (negCount > count / 2) { return not(invert(cond)); } } } return cond; } private static IfCondition simplifyCmpOp(Compare c) { if (!c.getA().isInsnWrap()) { return null; } if (!c.getB().isLiteral()) { return null; } long lit = ((LiteralArg) c.getB()).getLiteral(); if (lit != 0 && lit != 1) { return null; } InsnNode wrapInsn = ((InsnWrapArg) c.getA()).getWrapInsn(); switch (wrapInsn.getType()) { case CMP_L: case CMP_G: if (lit == 0) { IfNode insn = c.getInsn(); insn.changeCondition(insn.getOp(), wrapInsn.getArg(0), wrapInsn.getArg(1)); } break; case ARITH: if (c.getB().getType() == ArgType.BOOLEAN) { ArithOp arithOp = ((ArithNode) wrapInsn).getOp(); if (arithOp == ArithOp.OR || arithOp == ArithOp.AND) { IfOp ifOp = c.getInsn().getOp(); boolean isTrue = ifOp == IfOp.NE && lit == 0 || ifOp == IfOp.EQ && lit == 1; IfOp op = isTrue ? IfOp.NE : IfOp.EQ; Mode mode = isTrue && arithOp == ArithOp.OR || !isTrue && arithOp == ArithOp.AND ? Mode.OR : Mode.AND; IfNode if1 = new IfNode(op, -1, wrapInsn.getArg(0), LiteralArg.litFalse()); IfNode if2 = new IfNode(op, -1, wrapInsn.getArg(1), LiteralArg.litFalse()); return new IfCondition(mode, Arrays.asList(new IfCondition(new Compare(if1)), new IfCondition(new Compare(if2)))); } } break; default: break; } return null; } public List<RegisterArg> getRegisterArgs() { List<RegisterArg> list = new ArrayList<>(); if (mode == Mode.COMPARE) { compare.getInsn().getRegisterArgs(list); } else { for (IfCondition arg : args) { list.addAll(arg.getRegisterArgs()); } } return list; } public boolean replaceArg(InsnArg from, InsnArg to) { if (mode == Mode.COMPARE) { return compare.getInsn().replaceArg(from, to); } for (IfCondition arg : args) { if (arg.replaceArg(from, to)) { return true; } } return false; } public void visitInsns(Consumer<InsnNode> visitor) { if (mode == Mode.COMPARE) { compare.getInsn().visitInsns(visitor); } else { args.forEach(arg -> arg.visitInsns(visitor)); } } public List<InsnNode> collectInsns() { List<InsnNode> list = new ArrayList<>(); visitInsns(list::add); return list; } public int getSourceLine() { for (InsnNode insn : collectInsns()) { int line = insn.getSourceLine(); if (line != 0) { return line; } } return 0; } @Nullable public InsnNode getFirstInsn() { if (mode == Mode.COMPARE) { return compare.getInsn(); } return args.get(0).getFirstInsn(); } @Override public String toString() { switch (mode) { case COMPARE: return compare.toString(); case TERNARY: return first() + " ? " + second() + " : " + third(); case NOT: return "!(" + first() + ')'; case AND: case OR: String op = mode == Mode.OR ? " || " : " && "; StringBuilder sb = new StringBuilder(); sb.append('('); for (Iterator<IfCondition> it = args.iterator(); it.hasNext();) { IfCondition arg = it.next(); sb.append(arg); if (it.hasNext()) { sb.append(op); } } sb.append(')'); return sb.toString(); } return "??"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof IfCondition)) { return false; } IfCondition other = (IfCondition) obj; if (mode != other.mode) { return false; } return Objects.equals(args, other.args) && Objects.equals(compare, other.compare); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + mode.hashCode(); result = 31 * result + args.hashCode(); result = 31 * result + (compare != null ? compare.hashCode() : 0); return result; } }
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/regions/conditions/Compare.java
jadx-core/src/main/java/jadx/core/dex/regions/conditions/Compare.java
package jadx.core.dex.regions.conditions; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.instructions.IfNode; import jadx.core.dex.instructions.IfOp; import jadx.core.dex.instructions.args.InsnArg; public final class Compare { private final IfNode insn; public Compare(IfNode insn) { insn.add(AFlag.HIDDEN); this.insn = insn; } public IfOp getOp() { return insn.getOp(); } public InsnArg getA() { return insn.getArg(0); } public InsnArg getB() { return insn.getArg(1); } public IfNode getInsn() { return insn; } public Compare invert() { insn.invertCondition(); return this; } public void normalize() { insn.normalize(); } @Override public String toString() { return getA() + " " + getOp().getSymbol() + ' ' + getB(); } }
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/regions/conditions/IfInfo.java
jadx-core/src/main/java/jadx/core/dex/regions/conditions/IfInfo.java
package jadx.core.dex.regions.conditions; 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.utils.blocks.BlockSet; public final class IfInfo { private final MethodNode mth; private final IfCondition condition; private final BlockSet mergedBlocks; private final BlockNode thenBlock; private final BlockNode elseBlock; private final Set<BlockNode> skipBlocks; private final List<InsnNode> forceInlineInsns; private BlockNode outBlock; public IfInfo(MethodNode mth, IfCondition condition, BlockNode thenBlock, BlockNode elseBlock) { this(mth, condition, thenBlock, elseBlock, BlockSet.empty(mth), new HashSet<>(), new ArrayList<>()); } public IfInfo(IfInfo info, BlockNode thenBlock, BlockNode elseBlock) { this(info.getMth(), info.getCondition(), thenBlock, elseBlock, info.getMergedBlocks(), info.getSkipBlocks(), info.getForceInlineInsns()); } private IfInfo(MethodNode mth, IfCondition condition, BlockNode thenBlock, BlockNode elseBlock, BlockSet mergedBlocks, Set<BlockNode> skipBlocks, List<InsnNode> forceInlineInsns) { this.mth = mth; this.condition = condition; this.thenBlock = thenBlock; this.elseBlock = elseBlock; this.mergedBlocks = mergedBlocks; this.skipBlocks = skipBlocks; this.forceInlineInsns = forceInlineInsns; } public static IfInfo invert(IfInfo info) { return new IfInfo(info.getMth(), IfCondition.invert(info.getCondition()), info.getElseBlock(), info.getThenBlock(), info.getMergedBlocks(), info.getSkipBlocks(), info.getForceInlineInsns()); } public void merge(IfInfo... arr) { for (IfInfo info : arr) { mergedBlocks.addAll(info.getMergedBlocks()); skipBlocks.addAll(info.getSkipBlocks()); addInsnsForForcedInline(info.getForceInlineInsns()); } } @Deprecated public BlockNode getFirstIfBlock() { return mergedBlocks.getFirst(); } public BlockSet getMergedBlocks() { return mergedBlocks; } public MethodNode getMth() { return mth; } public IfCondition getCondition() { return condition; } public Set<BlockNode> getSkipBlocks() { return skipBlocks; } public BlockNode getThenBlock() { return thenBlock; } public BlockNode getElseBlock() { return elseBlock; } public BlockNode getOutBlock() { return outBlock; } public void setOutBlock(BlockNode outBlock) { this.outBlock = outBlock; } public List<InsnNode> getForceInlineInsns() { return forceInlineInsns; } public void resetForceInlineInsns() { forceInlineInsns.clear(); } public void addInsnsForForcedInline(List<InsnNode> insns) { forceInlineInsns.addAll(insns); } @Override public String toString() { return "IfInfo: then: " + thenBlock + ", else: " + elseBlock; } }
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/regions/conditions/IfRegion.java
jadx-core/src/main/java/jadx/core/dex/regions/conditions/IfRegion.java
package jadx.core.dex.regions.conditions; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jadx.api.ICodeWriter; import jadx.core.codegen.RegionGen; 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.utils.exceptions.CodegenException; public final class IfRegion extends ConditionRegion implements IBranchRegion { private IContainer thenRegion; private IContainer elseRegion; public IfRegion(IRegion parent) { super(parent); } public IContainer getThenRegion() { return thenRegion; } public void setThenRegion(IContainer thenRegion) { this.thenRegion = thenRegion; } public IContainer getElseRegion() { return elseRegion; } public void setElseRegion(IContainer elseRegion) { this.elseRegion = elseRegion; } public void invert() { invertCondition(); // swap regions IContainer tmp = thenRegion; thenRegion = elseRegion; elseRegion = tmp; } public int getSourceLine() { return getConditionSourceLine(); } @Override public List<IContainer> getSubBlocks() { List<BlockNode> conditionBlocks = getConditionBlocks(); List<IContainer> all = new ArrayList<>(conditionBlocks.size() + 2); all.addAll(conditionBlocks); if (thenRegion != null) { all.add(thenRegion); } if (elseRegion != null) { all.add(elseRegion); } return Collections.unmodifiableList(all); } @Override public List<IContainer> getBranches() { List<IContainer> branches = new ArrayList<>(2); branches.add(thenRegion); branches.add(elseRegion); return Collections.unmodifiableList(branches); } @Override public boolean replaceSubBlock(IContainer oldBlock, IContainer newBlock) { if (oldBlock == thenRegion) { thenRegion = newBlock; updateParent(thenRegion, this); return true; } if (oldBlock == elseRegion) { elseRegion = newBlock; updateParent(elseRegion, this); return true; } return false; } @Override public void generate(RegionGen regionGen, ICodeWriter code) throws CodegenException { regionGen.makeIf(this, code, true); } @Override public String baseString() { StringBuilder sb = new StringBuilder(); if (thenRegion != null) { sb.append(thenRegion.baseString()); } if (elseRegion != null) { sb.append(elseRegion.baseString()); } return sb.toString(); } @Override public String toString() { return "IF " + getConditionBlocks() + " THEN: " + thenRegion + " ELSE: " + elseRegion; } }
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/regions/loops/LoopType.java
jadx-core/src/main/java/jadx/core/dex/regions/loops/LoopType.java
package jadx.core.dex.regions.loops; public abstract class LoopType { }
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/regions/loops/ForEachLoop.java
jadx-core/src/main/java/jadx/core/dex/regions/loops/ForEachLoop.java
package jadx.core.dex.regions.loops; import jadx.core.dex.attributes.AFlag; 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.InsnNode; public final class ForEachLoop extends LoopType { private final InsnNode varArgInsn; private final InsnNode iterableArgInsn; public ForEachLoop(RegisterArg varArg, InsnArg iterableArg) { // store for-each args in fake instructions to // save code semantics and allow args manipulations like args inlining varArgInsn = new InsnNode(InsnType.REGION_ARG, 0); varArgInsn.add(AFlag.DONT_INLINE); varArgInsn.setResult(varArg.duplicate()); iterableArgInsn = new InsnNode(InsnType.REGION_ARG, 1); iterableArgInsn.add(AFlag.DONT_INLINE); iterableArgInsn.addArg(iterableArg.duplicate()); // will be declared at codegen getVarArg().getSVar().getCodeVar().setDeclared(true); } public void injectFakeInsns(LoopRegion loopRegion) { loopRegion.getInfo().getPreHeader().getInstructions().add(iterableArgInsn); loopRegion.getHeader().getInstructions().add(0, varArgInsn); } public RegisterArg getVarArg() { return varArgInsn.getResult(); } public InsnArg getIterableArg() { return iterableArgInsn.getArg(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/regions/loops/ForLoop.java
jadx-core/src/main/java/jadx/core/dex/regions/loops/ForLoop.java
package jadx.core.dex.regions.loops; import jadx.core.dex.nodes.InsnNode; public final class ForLoop extends LoopType { private final InsnNode initInsn; private final InsnNode incrInsn; public ForLoop(InsnNode initInsn, InsnNode incrInsn) { this.initInsn = initInsn; this.incrInsn = incrInsn; } public InsnNode getInitInsn() { return initInsn; } public InsnNode getIncrInsn() { return incrInsn; } }
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/regions/loops/LoopRegion.java
jadx-core/src/main/java/jadx/core/dex/regions/loops/LoopRegion.java
package jadx.core.dex.regions.loops; import java.util.ArrayList; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.api.ICodeWriter; import jadx.core.codegen.RegionGen; import jadx.core.dex.attributes.nodes.LoopInfo; 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.InsnNode; import jadx.core.dex.regions.conditions.ConditionRegion; import jadx.core.dex.regions.conditions.IfCondition; import jadx.core.utils.BlockUtils; import jadx.core.utils.InsnUtils; import jadx.core.utils.exceptions.CodegenException; public final class LoopRegion extends ConditionRegion { private final LoopInfo info; private final boolean conditionAtEnd; private final @Nullable BlockNode header; // instruction which must be executed before condition in every loop private @Nullable BlockNode preCondition; private IRegion body; private LoopType type; public LoopRegion(IRegion parent, LoopInfo info, @Nullable BlockNode header, boolean reversed) { super(parent); this.info = info; this.header = header; this.conditionAtEnd = reversed; if (header != null) { updateCondition(header); } } public LoopInfo getInfo() { return info; } @Nullable public BlockNode getHeader() { return header; } public boolean isEndless() { return header == null; } public IRegion getBody() { return body; } public void setBody(IRegion body) { this.body = body; } public boolean isConditionAtEnd() { return conditionAtEnd; } /** * Set instructions which must be executed before condition in every loop */ public void setPreCondition(BlockNode preCondition) { this.preCondition = preCondition; } /** * Check if pre-conditions can be inlined into loop condition */ public boolean checkPreCondition() { List<InsnNode> insns = preCondition.getInstructions(); if (insns.isEmpty()) { return true; } IfCondition condition = getCondition(); if (condition == null) { return false; } List<RegisterArg> conditionArgs = condition.getRegisterArgs(); if (conditionArgs.isEmpty()) { return false; } int size = insns.size(); for (int i = 0; i < size; i++) { InsnNode insn = insns.get(i); if (insn.getResult() == null) { return false; } RegisterArg res = insn.getResult(); if (res.getSVar().getUseCount() > 1) { return false; } boolean found = false; // search result arg in other insns for (int j = i + 1; j < size; j++) { if (insns.get(i).containsVar(res)) { found = true; } } // or in if insn if (!found && InsnUtils.containsVar(conditionArgs, res)) { found = true; } if (!found) { return false; } } return true; } /** * Move all preCondition block instructions before conditionBlock instructions */ public void mergePreCondition() { if (preCondition != null && header != null) { List<InsnNode> condInsns = header.getInstructions(); List<InsnNode> preCondInsns = preCondition.getInstructions(); preCondInsns.addAll(condInsns); condInsns.clear(); condInsns.addAll(preCondInsns); preCondInsns.clear(); preCondition = null; } } public int getSourceLine() { InsnNode lastInsn = BlockUtils.getLastInsn(header); int headerLine = lastInsn == null ? 0 : lastInsn.getSourceLine(); if (headerLine != 0) { return headerLine; } return getConditionSourceLine(); } public LoopType getType() { return type; } public void setType(LoopType type) { this.type = type; } @Override public List<IContainer> getSubBlocks() { List<IContainer> all = new ArrayList<>(2 + getConditionBlocks().size()); if (preCondition != null) { all.add(preCondition); } all.addAll(getConditionBlocks()); if (body != null) { all.add(body); } return all; } @Override public boolean replaceSubBlock(IContainer oldBlock, IContainer newBlock) { return false; } @Override public void generate(RegionGen regionGen, ICodeWriter code) throws CodegenException { regionGen.makeLoop(this, code); } @Override public String baseString() { return body == null ? "-" : body.baseString(); } @Override public String toString() { return "LOOP:" + info.getId() + ": " + baseString(); } }
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/attributes/EmptyAttrStorage.java
jadx-core/src/main/java/jadx/core/dex/attributes/EmptyAttrStorage.java
package jadx.core.dex.attributes; import java.util.Collections; import java.util.List; import jadx.api.plugins.input.data.annotations.IAnnotation; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; public final class EmptyAttrStorage extends AttributeStorage { public static final AttributeStorage INSTANCE = new EmptyAttrStorage(); private EmptyAttrStorage() { // singleton } @Override public boolean contains(AFlag flag) { return false; } @Override public <T extends IJadxAttribute> boolean contains(IJadxAttrType<T> type) { return false; } @Override public <T extends IJadxAttribute> T get(IJadxAttrType<T> type) { return null; } @Override public IAnnotation getAnnotation(String cls) { return null; } @Override public <T> List<T> getAll(IJadxAttrType<AttrList<T>> type) { return Collections.emptyList(); } @Override public void remove(AFlag flag) { // ignore } @Override public <T extends IJadxAttribute> void remove(IJadxAttrType<T> type) { // ignore } @Override public void remove(IJadxAttribute attr) { // ignore } @Override public List<String> getAttributeStrings() { return Collections.emptyList(); } @Override public boolean isEmpty() { return true; } @Override public String toString() { 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/attributes/ILineAttributeNode.java
jadx-core/src/main/java/jadx/core/dex/attributes/ILineAttributeNode.java
package jadx.core.dex.attributes; public interface ILineAttributeNode { int getSourceLine(); void setSourceLine(int sourceLine); int getDefPosition(); void setDefPosition(int pos); }
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/attributes/FieldInitInsnAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/FieldInitInsnAttr.java
package jadx.core.dex.attributes; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.api.plugins.input.data.attributes.PinnedAttribute; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import static java.util.Objects.requireNonNull; public final class FieldInitInsnAttr extends PinnedAttribute { private final MethodNode mth; private final InsnNode insn; public FieldInitInsnAttr(MethodNode mth, InsnNode insn) { this.mth = requireNonNull(mth); this.insn = requireNonNull(insn); } public InsnNode getInsn() { return insn; } public MethodNode getInsnMth() { return mth; } @Override public IJadxAttrType<? extends IJadxAttribute> getAttrType() { return AType.FIELD_INIT_INSN; } @Override public String toString() { return "INIT{" + 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/attributes/AType.java
jadx-core/src/main/java/jadx/core/dex/attributes/AType.java
package jadx.core.dex.attributes; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.codegen.utils.CodeComment; import jadx.core.dex.attributes.nodes.AnonymousClassAttr; import jadx.core.dex.attributes.nodes.ClassTypeVarsAttr; import jadx.core.dex.attributes.nodes.CodeFeaturesAttr; import jadx.core.dex.attributes.nodes.DeclareVariablesAttr; import jadx.core.dex.attributes.nodes.EdgeInsnAttr; import jadx.core.dex.attributes.nodes.EnumClassAttr; import jadx.core.dex.attributes.nodes.EnumMapAttr; import jadx.core.dex.attributes.nodes.FieldReplaceAttr; import jadx.core.dex.attributes.nodes.ForceReturnAttr; import jadx.core.dex.attributes.nodes.GenericInfoAttr; import jadx.core.dex.attributes.nodes.InlinedAttr; import jadx.core.dex.attributes.nodes.JadxCommentsAttr; import jadx.core.dex.attributes.nodes.JadxError; import jadx.core.dex.attributes.nodes.JumpInfo; import jadx.core.dex.attributes.nodes.LocalVarsDebugInfoAttr; import jadx.core.dex.attributes.nodes.LoopInfo; import jadx.core.dex.attributes.nodes.LoopLabelAttr; import jadx.core.dex.attributes.nodes.MethodBridgeAttr; import jadx.core.dex.attributes.nodes.MethodInlineAttr; import jadx.core.dex.attributes.nodes.MethodOverrideAttr; import jadx.core.dex.attributes.nodes.MethodReplaceAttr; import jadx.core.dex.attributes.nodes.MethodThrowsAttr; import jadx.core.dex.attributes.nodes.MethodTypeVarsAttr; import jadx.core.dex.attributes.nodes.PhiListAttr; import jadx.core.dex.attributes.nodes.RegDebugInfoAttr; import jadx.core.dex.attributes.nodes.RegionRefAttr; import jadx.core.dex.attributes.nodes.RenameReasonAttr; import jadx.core.dex.attributes.nodes.SkipMethodArgsAttr; import jadx.core.dex.attributes.nodes.SpecialEdgeAttr; import jadx.core.dex.attributes.nodes.TmpEdgeAttr; import jadx.core.dex.nodes.IMethodDetails; import jadx.core.dex.trycatch.CatchAttr; import jadx.core.dex.trycatch.ExcHandlerAttr; import jadx.core.dex.trycatch.TryCatchBlockAttr; /** * Attribute types enumeration, * uses generic type for omit cast after 'AttributeStorage.get' method * * @param <T> attribute class implementation */ public final class AType<T extends IJadxAttribute> implements IJadxAttrType<T> { // class, method, field, insn public static final AType<AttrList<CodeComment>> CODE_COMMENTS = new AType<>(); // class, method, field public static final AType<RenameReasonAttr> RENAME_REASON = new AType<>(); // class, method public static final AType<AttrList<JadxError>> JADX_ERROR = new AType<>(); // code failed to decompile public static final AType<JadxCommentsAttr> JADX_COMMENTS = new AType<>(); // additional info about decompilation // class public static final AType<EnumClassAttr> ENUM_CLASS = new AType<>(); public static final AType<EnumMapAttr> ENUM_MAP = new AType<>(); public static final AType<ClassTypeVarsAttr> CLASS_TYPE_VARS = new AType<>(); public static final AType<AnonymousClassAttr> ANONYMOUS_CLASS = new AType<>(); public static final AType<InlinedAttr> INLINED = new AType<>(); // field public static final AType<FieldInitInsnAttr> FIELD_INIT_INSN = new AType<>(); public static final AType<FieldReplaceAttr> FIELD_REPLACE = new AType<>(); // method public static final AType<LocalVarsDebugInfoAttr> LOCAL_VARS_DEBUG_INFO = new AType<>(); public static final AType<MethodInlineAttr> METHOD_INLINE = new AType<>(); public static final AType<MethodReplaceAttr> METHOD_REPLACE = new AType<>(); public static final AType<MethodBridgeAttr> BRIDGED_BY = new AType<>(); public static final AType<SkipMethodArgsAttr> SKIP_MTH_ARGS = new AType<>(); public static final AType<MethodOverrideAttr> METHOD_OVERRIDE = new AType<>(); public static final AType<MethodTypeVarsAttr> METHOD_TYPE_VARS = new AType<>(); public static final AType<AttrList<TryCatchBlockAttr>> TRY_BLOCKS_LIST = new AType<>(); public static final AType<CodeFeaturesAttr> METHOD_CODE_FEATURES = new AType<>(); public static final AType<MethodThrowsAttr> METHOD_THROWS = new AType<>(); // region public static final AType<DeclareVariablesAttr> DECLARE_VARIABLES = new AType<>(); // block public static final AType<PhiListAttr> PHI_LIST = new AType<>(); public static final AType<ForceReturnAttr> FORCE_RETURN = new AType<>(); public static final AType<AttrList<LoopInfo>> LOOP = new AType<>(); public static final AType<AttrList<EdgeInsnAttr>> EDGE_INSN = new AType<>(); public static final AType<AttrList<SpecialEdgeAttr>> SPECIAL_EDGE = new AType<>(); public static final AType<TmpEdgeAttr> TMP_EDGE = new AType<>(); public static final AType<TryCatchBlockAttr> TRY_BLOCK = new AType<>(); // block or insn public static final AType<ExcHandlerAttr> EXC_HANDLER = new AType<>(); public static final AType<CatchAttr> EXC_CATCH = new AType<>(); // instruction public static final AType<LoopLabelAttr> LOOP_LABEL = new AType<>(); public static final AType<AttrList<JumpInfo>> JUMP = new AType<>(); public static final AType<IMethodDetails> METHOD_DETAILS = new AType<>(); public static final AType<GenericInfoAttr> GENERIC_INFO = new AType<>(); public static final AType<RegionRefAttr> REGION_REF = new AType<>(); // register public static final AType<RegDebugInfoAttr> REG_DEBUG_INFO = new AType<>(); }
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/attributes/AttributeStorage.java
jadx-core/src/main/java/jadx/core/dex/attributes/AttributeStorage.java
package jadx.core.dex.attributes; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import jadx.api.plugins.input.data.annotations.IAnnotation; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.api.plugins.input.data.attributes.JadxAttrType; import jadx.api.plugins.input.data.attributes.types.AnnotationsAttr; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; /** * Storage for different attribute types:<br> * 1. Flags - boolean attribute (set or not)<br> * 2. Attributes - class instance ({@link IJadxAttribute}) associated with an attribute type * ({@link IJadxAttrType})<br> */ public class AttributeStorage { public static AttributeStorage fromList(List<IJadxAttribute> list) { AttributeStorage storage = new AttributeStorage(); storage.add(list); return storage; } static { int flagsCount = AFlag.values().length; if (flagsCount >= 64) { throw new JadxRuntimeException("Try to reduce flags count to 64 for use one long in EnumSet, now " + flagsCount); } } private static final Map<IJadxAttrType<?>, IJadxAttribute> EMPTY_ATTRIBUTES = Collections.emptyMap(); private final Set<AFlag> flags; private Map<IJadxAttrType<?>, IJadxAttribute> attributes; public AttributeStorage() { flags = EnumSet.noneOf(AFlag.class); attributes = EMPTY_ATTRIBUTES; } public void add(AFlag flag) { flags.add(flag); } public void add(IJadxAttribute attr) { writeAttributes(map -> map.put(attr.getAttrType(), attr)); } public void add(List<IJadxAttribute> list) { writeAttributes(map -> list.forEach(attr -> map.put(attr.getAttrType(), attr))); } public <T> void add(IJadxAttrType<AttrList<T>> type, T obj) { AttrList<T> list = get(type); if (list == null) { list = new AttrList<>(type); add(list); } list.getList().add(obj); } public void addAll(AttributeStorage otherList) { flags.addAll(otherList.flags); if (!otherList.attributes.isEmpty()) { writeAttributes(m -> m.putAll(otherList.attributes)); } } public boolean contains(AFlag flag) { return flags.contains(flag); } public <T extends IJadxAttribute> boolean contains(IJadxAttrType<T> type) { return attributes.containsKey(type); } @SuppressWarnings("unchecked") public <T extends IJadxAttribute> T get(IJadxAttrType<T> type) { return (T) attributes.get(type); } public IAnnotation getAnnotation(String cls) { AnnotationsAttr aList = get(JadxAttrType.ANNOTATION_LIST); return aList == null ? null : aList.get(cls); } public <T> List<T> getAll(IJadxAttrType<AttrList<T>> type) { AttrList<T> attrList = get(type); if (attrList == null) { return Collections.emptyList(); } return Collections.unmodifiableList(attrList.getList()); } public void remove(AFlag flag) { flags.remove(flag); } public void clearFlags() { flags.clear(); } public <T extends IJadxAttribute> void remove(IJadxAttrType<T> type) { if (!attributes.isEmpty()) { writeAttributes(map -> map.remove(type)); } } public void remove(IJadxAttribute attr) { if (!attributes.isEmpty()) { writeAttributes(map -> { IJadxAttrType<? extends IJadxAttribute> type = attr.getAttrType(); IJadxAttribute a = map.get(type); if (a == attr) { map.remove(type); } }); } } private void writeAttributes(Consumer<Map<IJadxAttrType<?>, IJadxAttribute>> mapConsumer) { synchronized (this) { if (attributes == EMPTY_ATTRIBUTES) { attributes = new IdentityHashMap<>(2); // only 1 or 2 attributes added in most cases } mapConsumer.accept(attributes); if (attributes.isEmpty()) { attributes = EMPTY_ATTRIBUTES; } } } public void unloadAttributes() { if (attributes.isEmpty()) { return; } writeAttributes(map -> map.entrySet().removeIf(entry -> !entry.getValue().keepLoaded())); } public List<String> getAttributeStrings() { int size = flags.size() + attributes.size(); if (size == 0) { return Collections.emptyList(); } List<String> list = new ArrayList<>(size); for (AFlag a : flags) { list.add(a.toString()); } for (IJadxAttribute a : attributes.values()) { list.add(a.toAttrString()); } return list; } public boolean isEmpty() { return flags.isEmpty() && attributes.isEmpty(); } @Override public String toString() { List<String> list = getAttributeStrings(); if (list.isEmpty()) { return ""; } list.sort(String::compareTo); return "A[" + Utils.listToString(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/attributes/IAttributeNode.java
jadx-core/src/main/java/jadx/core/dex/attributes/IAttributeNode.java
package jadx.core.dex.attributes; import java.util.List; import jadx.api.plugins.input.data.annotations.IAnnotation; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; public interface IAttributeNode { void add(AFlag flag); void addAttr(IJadxAttribute attr); void addAttrs(List<IJadxAttribute> list); <T> void addAttr(IJadxAttrType<AttrList<T>> type, T obj); void copyAttributesFrom(AttrNode attrNode); <T extends IJadxAttribute> void copyAttributeFrom(AttrNode attrNode, AType<T> attrType); <T extends IJadxAttribute> void rewriteAttributeFrom(AttrNode attrNode, AType<T> attrType); boolean contains(AFlag flag); <T extends IJadxAttribute> boolean contains(IJadxAttrType<T> type); <T extends IJadxAttribute> T get(IJadxAttrType<T> type); IAnnotation getAnnotation(String cls); <T> List<T> getAll(IJadxAttrType<AttrList<T>> type); void remove(AFlag flag); <T extends IJadxAttribute> void remove(IJadxAttrType<T> type); void removeAttr(IJadxAttribute attr); void clearAttributes(); List<String> getAttributesStringsList(); String getAttributesString(); boolean isAttrStorageEmpty(); }
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/attributes/AFlag.java
jadx-core/src/main/java/jadx/core/dex/attributes/AFlag.java
package jadx.core.dex.attributes; public enum AFlag { MTH_ENTER_BLOCK, MTH_EXIT_BLOCK, TRY_ENTER, TRY_LEAVE, LOOP_START, LOOP_END, SYNTHETIC, RETURN, // block contains only return instruction ORIG_RETURN, DONT_WRAP, DONT_INLINE, DONT_INLINE_CONST, DONT_GENERATE, // process as usual, but don't output to generated code COMMENT_OUT, // process as usual, but comment insn in generated code REMOVE, // can be completely removed REMOVE_SUPER_CLASS, // don't add super class HIDDEN, // instruction used inside other instruction but not listed in args DONT_RENAME, // do not rename during deobfuscation FORCE_RAW_NAME, // force use of raw name instead alias ADDED_TO_REGION, EXC_TOP_SPLITTER, EXC_BOTTOM_SPLITTER, FINALLY_INSNS, IGNORE_THROW_SPLIT, SKIP_FIRST_ARG, SKIP_ARG, // skip argument in invoke call NO_SKIP_ARGS, ANONYMOUS_CONSTRUCTOR, INLINE_INSTANCE_FIELD, THIS, SUPER, PACKAGE_INFO, /** * Mark Android resources class */ ANDROID_R_CLASS, /** * RegisterArg attribute for method arguments */ METHOD_ARGUMENT, /** * Type of RegisterArg or SSAVar can't be changed */ IMMUTABLE_TYPE, /** * Force inline instruction with inline assign */ FORCE_ASSIGN_INLINE, CUSTOM_DECLARE, // variable for this register don't need declaration DECLARE_VAR, ELSE_IF_CHAIN, WRAPPED, ARITH_ONEARG, FALL_THROUGH, VARARG_CALL, /** * Use constants with explicit type: cast '(byte) 1' or type letter '7L' */ EXPLICIT_PRIMITIVE_TYPE, EXPLICIT_CAST, SOFT_CAST, // synthetic cast to help type inference (allow unchecked casts for generics) INCONSISTENT_CODE, // warning about incorrect decompilation REQUEST_IF_REGION_OPTIMIZE, // run if region visitor again REQUEST_CODE_SHRINK, METHOD_CANDIDATE_FOR_INLINE, USE_LINES_HINTS, // source lines info in methods can be trusted DISABLE_BLOCKS_LOCK, // Class processing flags RESTART_CODEGEN, // codegen must be executed again RELOAD_AT_CODEGEN_STAGE, // class can't be analyzed at 'process' stage => unload before 'codegen' stage CLASS_DEEP_RELOAD, // perform deep class unload (reload) before process CLASS_UNLOADED, // class was completely unloaded DONT_UNLOAD_CLASS, // don't unload class after code generation (only for tests and debug!) RESOLVE_JAVA_JSR, COMPUTE_POST_DOM, }
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/attributes/AttrList.java
jadx-core/src/main/java/jadx/core/dex/attributes/AttrList.java
package jadx.core.dex.attributes; import java.util.ArrayList; import java.util.List; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.utils.Utils; public class AttrList<T> implements IJadxAttribute { private final IJadxAttrType<AttrList<T>> type; private final List<T> list = new ArrayList<>(); public AttrList(IJadxAttrType<AttrList<T>> type) { this.type = type; } public List<T> getList() { return list; } @Override public IJadxAttrType<AttrList<T>> getAttrType() { return type; } @Override public String toString() { return Utils.listToString(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/attributes/AttrNode.java
jadx-core/src/main/java/jadx/core/dex/attributes/AttrNode.java
package jadx.core.dex.attributes; import java.util.List; import jadx.api.CommentsLevel; import jadx.api.plugins.input.data.annotations.IAnnotation; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.Consts; import jadx.core.dex.attributes.nodes.JadxCommentsAttr; import jadx.core.utils.Utils; public abstract class AttrNode implements IAttributeNode { private static final AttributeStorage EMPTY_ATTR_STORAGE = EmptyAttrStorage.INSTANCE; private AttributeStorage storage = EMPTY_ATTR_STORAGE; @Override public void add(AFlag flag) { initStorage().add(flag); if (Consts.DEBUG_ATTRIBUTES) { addDebugComment("Add flag " + flag + " at " + Utils.currentStackTrace(2)); } } @Override public void addAttr(IJadxAttribute attr) { initStorage().add(attr); if (Consts.DEBUG_ATTRIBUTES) { addDebugComment("Add attribute " + attr.getClass().getSimpleName() + ": " + attr + " at " + Utils.currentStackTrace(2)); } } @Override public void addAttrs(List<IJadxAttribute> list) { if (list.isEmpty()) { return; } initStorage().add(list); } @Override public <T> void addAttr(IJadxAttrType<AttrList<T>> type, T obj) { initStorage().add(type, obj); if (Consts.DEBUG_ATTRIBUTES) { addDebugComment("Add attribute " + obj + " at " + Utils.currentStackTrace(2)); } } public <T> void addAttr(IJadxAttrType<AttrList<T>> type, List<T> list) { AttributeStorage strg = initStorage(); list.forEach(attr -> strg.add(type, attr)); } @Override public void copyAttributesFrom(AttrNode attrNode) { AttributeStorage copyFrom = attrNode.storage; if (!copyFrom.isEmpty()) { initStorage().addAll(copyFrom); } } @Override public <T extends IJadxAttribute> void copyAttributeFrom(AttrNode attrNode, AType<T> attrType) { IJadxAttribute attr = attrNode.get(attrType); if (attr != null) { this.addAttr(attr); } } /** * Remove attribute in this node, add copy from other if exists */ @Override public <T extends IJadxAttribute> void rewriteAttributeFrom(AttrNode attrNode, AType<T> attrType) { remove(attrType); copyAttributeFrom(attrNode, attrType); } private AttributeStorage initStorage() { AttributeStorage store = storage; if (store == EMPTY_ATTR_STORAGE) { store = new AttributeStorage(); storage = store; } return store; } private void unloadIfEmpty() { if (storage.isEmpty() && storage != EMPTY_ATTR_STORAGE) { storage = EMPTY_ATTR_STORAGE; } } @Override public boolean contains(AFlag flag) { return storage.contains(flag); } @Override public <T extends IJadxAttribute> boolean contains(IJadxAttrType<T> type) { return storage.contains(type); } @Override public <T extends IJadxAttribute> T get(IJadxAttrType<T> type) { return storage.get(type); } @Override public IAnnotation getAnnotation(String cls) { return storage.getAnnotation(cls); } @Override public <T> List<T> getAll(IJadxAttrType<AttrList<T>> type) { return storage.getAll(type); } @Override public void remove(AFlag flag) { storage.remove(flag); unloadIfEmpty(); } @Override public <T extends IJadxAttribute> void remove(IJadxAttrType<T> type) { storage.remove(type); unloadIfEmpty(); } @Override public void removeAttr(IJadxAttribute attr) { storage.remove(attr); unloadIfEmpty(); } @Override public void clearAttributes() { storage = EMPTY_ATTR_STORAGE; } public void unloadAttributes() { if (storage == EMPTY_ATTR_STORAGE) { return; } storage.unloadAttributes(); storage.clearFlags(); unloadIfEmpty(); } @Override public List<String> getAttributesStringsList() { return storage.getAttributeStrings(); } @Override public String getAttributesString() { return storage.toString(); } @Override public boolean isAttrStorageEmpty() { return storage.isEmpty(); } private void addDebugComment(String msg) { JadxCommentsAttr commentsAttr = get(AType.JADX_COMMENTS); if (commentsAttr == null) { commentsAttr = new JadxCommentsAttr(); initStorage().add(commentsAttr); } commentsAttr.add(CommentsLevel.DEBUG, msg); } }
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/attributes/nodes/InlinedAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/InlinedAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.ClassNode; public class InlinedAttr implements IJadxAttribute { private final ClassNode inlineCls; public InlinedAttr(ClassNode inlineCls) { this.inlineCls = inlineCls; } public ClassNode getInlineCls() { return inlineCls; } @Override public IJadxAttrType<InlinedAttr> getAttrType() { return AType.INLINED; } @Override public String toString() { return "INLINED: " + inlineCls; } }
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/attributes/nodes/LocalVarsDebugInfoAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/LocalVarsDebugInfoAttr.java
package jadx.core.dex.attributes.nodes; import java.util.List; import jadx.api.plugins.input.data.ILocalVar; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.utils.Utils; public class LocalVarsDebugInfoAttr implements IJadxAttribute { private final List<ILocalVar> localVars; public LocalVarsDebugInfoAttr(List<ILocalVar> localVars) { this.localVars = localVars; } public List<ILocalVar> getLocalVars() { return localVars; } @Override public AType<LocalVarsDebugInfoAttr> getAttrType() { return AType.LOCAL_VARS_DEBUG_INFO; } @Override public String toString() { return "Debug Info:\n " + Utils.listToString(localVars, "\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/attributes/nodes/RenameReasonAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/RenameReasonAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.AttrNode; public class RenameReasonAttr implements IJadxAttribute { public static RenameReasonAttr forNode(AttrNode node) { RenameReasonAttr renameReasonAttr = node.get(AType.RENAME_REASON); if (renameReasonAttr != null) { return renameReasonAttr; } RenameReasonAttr newAttr = new RenameReasonAttr(); node.addAttr(newAttr); return newAttr; } private String description; public RenameReasonAttr() { this.description = ""; } public RenameReasonAttr(String description) { this.description = description; } public RenameReasonAttr(AttrNode node) { RenameReasonAttr renameReasonAttr = node.get(AType.RENAME_REASON); if (renameReasonAttr != null) { this.description = renameReasonAttr.description; } else { this.description = ""; } } public RenameReasonAttr(AttrNode node, boolean notValid, boolean notPrintable) { this(node); if (notValid) { notValid(); } if (notPrintable) { notPrintable(); } } public RenameReasonAttr notValid() { return append("not valid java name"); } public RenameReasonAttr notPrintable() { return append("contains not printable characters"); } public RenameReasonAttr append(String reason) { if (description.isEmpty()) { description += reason; } else { description += " and " + reason; } return this; } public String getDescription() { return description; } @Override public AType<RenameReasonAttr> getAttrType() { return AType.RENAME_REASON; } @Override public String toString() { return "RENAME_REASON:" + description; } }
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/attributes/nodes/EnumMapAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/EnumMapAttr.java
package jadx.core.dex.attributes.nodes; import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.FieldNode; public class EnumMapAttr implements IJadxAttribute { public static class KeyValueMap { private final Map<Object, Object> map = new HashMap<>(); public Object get(Object key) { return map.get(key); } void put(Object key, Object value) { map.put(key, value); } } @Nullable private Map<FieldNode, KeyValueMap> fieldsMap; @Nullable public KeyValueMap getMap(FieldNode field) { if (fieldsMap == null) { return null; } return fieldsMap.get(field); } public void add(FieldNode field, Object key, Object value) { KeyValueMap map = getMap(field); if (map == null) { map = new KeyValueMap(); if (fieldsMap == null) { fieldsMap = new HashMap<>(); } fieldsMap.put(field, map); } map.put(key, value); } public boolean isEmpty() { return fieldsMap == null || fieldsMap.isEmpty(); } @Override public AType<EnumMapAttr> getAttrType() { return AType.ENUM_MAP; } @Override public String toString() { return "Enum fields map: " + fieldsMap; } }
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/attributes/nodes/RegDebugInfoAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/RegDebugInfoAttr.java
package jadx.core.dex.attributes.nodes; import java.util.Objects; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.args.ArgType; public class RegDebugInfoAttr implements IJadxAttribute { private final ArgType type; private final String name; public RegDebugInfoAttr(ArgType type, String name) { this.type = type; this.name = name; } public String getName() { return name; } public ArgType getRegType() { return type; } @Override public AType<RegDebugInfoAttr> getAttrType() { return AType.REG_DEBUG_INFO; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RegDebugInfoAttr that = (RegDebugInfoAttr) o; return Objects.equals(type, that.type) && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(type, name); } @Override public String toString() { return "D('" + name + "' " + 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/attributes/nodes/MethodTypeVarsAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/MethodTypeVarsAttr.java
package jadx.core.dex.attributes.nodes; import java.util.Collections; import java.util.Set; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.args.ArgType; import static jadx.core.utils.Utils.isEmpty; /** * Set of known type variables at current method */ public class MethodTypeVarsAttr implements IJadxAttribute { private static final MethodTypeVarsAttr EMPTY = new MethodTypeVarsAttr(Collections.emptySet()); public static MethodTypeVarsAttr build(Set<ArgType> typeVars) { if (isEmpty(typeVars)) { return EMPTY; } return new MethodTypeVarsAttr(typeVars); } private final Set<ArgType> typeVars; private MethodTypeVarsAttr(Set<ArgType> typeVars) { this.typeVars = typeVars; } public Set<ArgType> getTypeVars() { return typeVars; } @Override public AType<MethodTypeVarsAttr> getAttrType() { return AType.METHOD_TYPE_VARS; } @Override public String toString() { if (this == EMPTY) { return "TYPE_VARS: EMPTY"; } return "TYPE_VARS: " + typeVars; } }
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/attributes/nodes/CodeFeaturesAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/CodeFeaturesAttr.java
package jadx.core.dex.attributes.nodes; import java.util.EnumSet; import java.util.Set; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.MethodNode; public class CodeFeaturesAttr implements IJadxAttribute { public enum CodeFeature { /** * Code contains switch instruction */ SWITCH, /** * Code contains new-array instruction */ NEW_ARRAY, } public static boolean contains(MethodNode mth, CodeFeature feature) { CodeFeaturesAttr codeFeaturesAttr = mth.get(AType.METHOD_CODE_FEATURES); if (codeFeaturesAttr == null) { return false; } return codeFeaturesAttr.getCodeFeatures().contains(feature); } public static void add(MethodNode mth, CodeFeature feature) { CodeFeaturesAttr codeFeaturesAttr = mth.get(AType.METHOD_CODE_FEATURES); if (codeFeaturesAttr == null) { codeFeaturesAttr = new CodeFeaturesAttr(); mth.addAttr(codeFeaturesAttr); } codeFeaturesAttr.getCodeFeatures().add(feature); } private final Set<CodeFeature> codeFeatures = EnumSet.noneOf(CodeFeature.class); public Set<CodeFeature> getCodeFeatures() { return codeFeatures; } @Override public AType<CodeFeaturesAttr> getAttrType() { return AType.METHOD_CODE_FEATURES; } @Override public String toAttrString() { return "CodeFeatures{" + codeFeatures + '}'; } }
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/attributes/nodes/MethodBridgeAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/MethodBridgeAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.PinnedAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.MethodNode; public class MethodBridgeAttr extends PinnedAttribute { private final MethodNode bridgeMth; public MethodBridgeAttr(MethodNode bridgeMth) { this.bridgeMth = bridgeMth; } public MethodNode getBridgeMth() { return bridgeMth; } @Override public AType<MethodBridgeAttr> getAttrType() { return AType.BRIDGED_BY; } @Override public String toString() { return "BRIDGED_BY: " + bridgeMth; } }
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/attributes/nodes/PhiListAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/PhiListAttr.java
package jadx.core.dex.attributes.nodes; import java.util.ArrayList; import java.util.List; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.PhiInsn; import jadx.core.dex.instructions.args.RegisterArg; public class PhiListAttr implements IJadxAttribute { private final List<PhiInsn> list = new ArrayList<>(); @Override public AType<PhiListAttr> getAttrType() { return AType.PHI_LIST; } public List<PhiInsn> getList() { return list; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("PHI:"); for (PhiInsn phiInsn : list) { RegisterArg resArg = phiInsn.getResult(); if (resArg != null) { sb.append(" r").append(resArg.getRegNum()); } } for (PhiInsn phiInsn : list) { sb.append('\n').append(" ").append(phiInsn); } 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/attributes/nodes/SkipMethodArgsAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/SkipMethodArgsAttr.java
package jadx.core.dex.attributes.nodes; import java.util.BitSet; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.attributes.PinnedAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; public class SkipMethodArgsAttr extends PinnedAttribute { public static void skipArg(MethodNode mth, RegisterArg arg) { int argNum = Utils.indexInListByRef(mth.getArgRegs(), arg); if (argNum == -1) { throw new JadxRuntimeException("Arg not found: " + arg); } skipArg(mth, argNum); } public static void skipArg(MethodNode mth, int argNum) { SkipMethodArgsAttr attr = mth.get(AType.SKIP_MTH_ARGS); if (attr == null) { attr = new SkipMethodArgsAttr(mth); mth.addAttr(attr); } attr.skip(argNum); } public static boolean isSkip(@Nullable MethodNode mth, int argNum) { if (mth == null) { return false; } SkipMethodArgsAttr attr = mth.get(AType.SKIP_MTH_ARGS); if (attr == null) { return false; } return attr.isSkip(argNum); } private final BitSet skipArgs; private SkipMethodArgsAttr(MethodNode mth) { this.skipArgs = new BitSet(mth.getMethodInfo().getArgsCount()); } public void skip(int argNum) { skipArgs.set(argNum); } public boolean isSkip(int argNum) { return skipArgs.get(argNum); } public int getSkipCount() { return skipArgs.cardinality(); } @Override public AType<SkipMethodArgsAttr> getAttrType() { return AType.SKIP_MTH_ARGS; } @Override public String toString() { return "SKIP_MTH_ARGS: " + skipArgs; } }
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/attributes/nodes/EnumClassAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/EnumClassAttr.java
package jadx.core.dex.attributes.nodes; import java.util.List; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.mods.ConstructorInsn; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; public class EnumClassAttr implements IJadxAttribute { public static class EnumField { private final FieldNode field; private final ConstructorInsn constrInsn; private ClassNode cls; public EnumField(FieldNode field, ConstructorInsn co) { this.field = field; this.constrInsn = co; } public FieldNode getField() { return field; } public ConstructorInsn getConstrInsn() { return constrInsn; } public ClassNode getCls() { return cls; } public void setCls(ClassNode cls) { this.cls = cls; } @Override public String toString() { return field + "(" + constrInsn + ") " + cls; } } private final List<EnumField> fields; private MethodNode staticMethod; public EnumClassAttr(List<EnumField> fields) { this.fields = fields; } public List<EnumField> getFields() { return fields; } public MethodNode getStaticMethod() { return staticMethod; } public void setStaticMethod(MethodNode staticMethod) { this.staticMethod = staticMethod; } @Override public AType<EnumClassAttr> getAttrType() { return AType.ENUM_CLASS; } @Override public String toString() { return "Enum fields: " + fields; } }
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/attributes/nodes/FieldReplaceAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/FieldReplaceAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.PinnedAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.instructions.args.InsnArg; public class FieldReplaceAttr extends PinnedAttribute { public enum ReplaceWith { CLASS_INSTANCE, VAR } private final ReplaceWith replaceType; private final Object replaceObj; public FieldReplaceAttr(ClassInfo cls) { this.replaceType = ReplaceWith.CLASS_INSTANCE; this.replaceObj = cls; } public FieldReplaceAttr(InsnArg reg) { this.replaceType = ReplaceWith.VAR; this.replaceObj = reg; } public ReplaceWith getReplaceType() { return replaceType; } public ClassInfo getClsRef() { return (ClassInfo) replaceObj; } public InsnArg getVarRef() { return (InsnArg) replaceObj; } @Override public AType<FieldReplaceAttr> getAttrType() { return AType.FIELD_REPLACE; } @Override public String toString() { return "REPLACE: " + replaceType + ' ' + replaceObj; } }
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/attributes/nodes/TmpEdgeAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/TmpEdgeAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.BlockNode; public class TmpEdgeAttr implements IJadxAttribute { private final BlockNode block; public TmpEdgeAttr(BlockNode block) { this.block = block; } public BlockNode getBlock() { return block; } @Override public IJadxAttrType<? extends IJadxAttribute> getAttrType() { return AType.TMP_EDGE; } @Override public String toString() { return "TMP_EDGE: " + 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/attributes/nodes/JumpInfo.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/JumpInfo.java
package jadx.core.dex.attributes.nodes; import jadx.core.utils.InsnUtils; public class JumpInfo { private final int src; private final int dest; public JumpInfo(int src, int dest) { this.src = src; this.dest = dest; } public int getSrc() { return src; } public int getDest() { return dest; } @Override public int hashCode() { return 31 * dest + src; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } JumpInfo other = (JumpInfo) obj; return dest == other.dest && src == other.src; } @Override public String toString() { return "JUMP: " + InsnUtils.formatOffset(src) + " -> " + InsnUtils.formatOffset(dest); } }
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/attributes/nodes/MethodOverrideAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/MethodOverrideAttr.java
package jadx.core.dex.attributes.nodes; import java.util.List; import java.util.Set; import java.util.SortedSet; import jadx.api.plugins.input.data.attributes.PinnedAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.IMethodDetails; import jadx.core.dex.nodes.MethodNode; public class MethodOverrideAttr extends PinnedAttribute { /** * All methods overridden by current method. Current method excluded, empty for base method. */ private final List<IMethodDetails> overrideList; /** * All method nodes from override hierarchy. Current method included. */ private SortedSet<MethodNode> relatedMthNodes; private final Set<IMethodDetails> baseMethods; public MethodOverrideAttr(List<IMethodDetails> overrideList, SortedSet<MethodNode> relatedMthNodes, Set<IMethodDetails> baseMethods) { this.overrideList = overrideList; this.relatedMthNodes = relatedMthNodes; this.baseMethods = baseMethods; } public List<IMethodDetails> getOverrideList() { return overrideList; } public SortedSet<MethodNode> getRelatedMthNodes() { return relatedMthNodes; } public Set<IMethodDetails> getBaseMethods() { return baseMethods; } public void setRelatedMthNodes(SortedSet<MethodNode> relatedMthNodes) { this.relatedMthNodes = relatedMthNodes; } @Override public AType<MethodOverrideAttr> getAttrType() { return AType.METHOD_OVERRIDE; } @Override public String toString() { return "METHOD_OVERRIDE: " + getBaseMethods(); } }
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/attributes/nodes/SpecialEdgeAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/SpecialEdgeAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.AttrList; import jadx.core.dex.nodes.BlockNode; public class SpecialEdgeAttr implements IJadxAttribute { public enum SpecialEdgeType { BACK_EDGE, CROSS_EDGE } private final SpecialEdgeType type; private final BlockNode start; private final BlockNode end; public SpecialEdgeAttr(SpecialEdgeType type, BlockNode start, BlockNode end) { this.type = type; this.start = start; this.end = end; } public SpecialEdgeType getType() { return type; } public BlockNode getStart() { return start; } public BlockNode getEnd() { return end; } @Override public AType<AttrList<SpecialEdgeAttr>> getAttrType() { return AType.SPECIAL_EDGE; } @Override public String toString() { return type + ": " + start + " -> " + end; } }
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/attributes/nodes/LoopInfo.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/LoopInfo.java
package jadx.core.dex.attributes.nodes; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.Edge; import jadx.core.utils.BlockUtils; public class LoopInfo { private final BlockNode start; private final BlockNode end; private final Set<BlockNode> loopBlocks; private int id; private LoopInfo parentLoop; public LoopInfo(BlockNode start, BlockNode end, Set<BlockNode> loopBlocks) { this.start = start; this.end = end; this.loopBlocks = loopBlocks; } public BlockNode getStart() { return start; } public BlockNode getEnd() { return end; } public Set<BlockNode> getLoopBlocks() { return loopBlocks; } /** * Return source blocks of exit edges. <br> * Exit nodes belongs to loop (contains in {@code loopBlocks}) */ public Set<BlockNode> getExitNodes() { Set<BlockNode> nodes = new HashSet<>(); Set<BlockNode> blocks = getLoopBlocks(); for (BlockNode block : blocks) { // exit: successor node not from this loop, (don't change to getCleanSuccessors) for (BlockNode s : block.getSuccessors()) { if (!blocks.contains(s) && !s.contains(AType.EXC_HANDLER)) { nodes.add(block); } } } return nodes; } /** * Return loop exit edges. */ public List<Edge> getExitEdges() { List<Edge> edges = new ArrayList<>(); Set<BlockNode> blocks = getLoopBlocks(); for (BlockNode block : blocks) { for (BlockNode s : block.getSuccessors()) { // don't use clean successors to include loop back edges if (!blocks.contains(s) && !BlockUtils.isExceptionHandlerPath(s)) { edges.add(new Edge(block, s)); } } } return edges; } public BlockNode getPreHeader() { return BlockUtils.selectOther(end, start.getPredecessors()); } public int getId() { return id; } public void setId(int id) { this.id = id; } public LoopInfo getParentLoop() { return parentLoop; } public void setParentLoop(LoopInfo parentLoop) { this.parentLoop = parentLoop; } public boolean hasParent(LoopInfo searchLoop) { LoopInfo parent = parentLoop; while (true) { if (parent == null) { return false; } if (parent == searchLoop) { return true; } parent = parent.getParentLoop(); } } @Override public String toString() { return "LOOP:" + id + ": " + start + "->" + end; } }
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/attributes/nodes/AnonymousClassAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/AnonymousClassAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.PinnedAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.ClassNode; public class AnonymousClassAttr extends PinnedAttribute { public enum InlineType { CONSTRUCTOR, INSTANCE_FIELD, } private final ClassNode outerCls; private final ArgType baseType; private final InlineType inlineType; public AnonymousClassAttr(ClassNode outerCls, ArgType baseType, InlineType inlineType) { this.outerCls = outerCls; this.baseType = baseType; this.inlineType = inlineType; } public ClassNode getOuterCls() { return outerCls; } public ArgType getBaseType() { return baseType; } public InlineType getInlineType() { return inlineType; } @Override public AType<AnonymousClassAttr> getAttrType() { return AType.ANONYMOUS_CLASS; } @Override public String toString() { return "AnonymousClass{" + outerCls + ", base: " + baseType + ", inline type: " + inlineType + '}'; } }
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/attributes/nodes/NotificationAttrNode.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/NotificationAttrNode.java
package jadx.core.dex.attributes.nodes; import jadx.api.CommentsLevel; import jadx.api.data.CommentStyle; import jadx.core.codegen.utils.CodeComment; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.ICodeNode; import jadx.core.utils.ErrorsCounter; import jadx.core.utils.Utils; public abstract class NotificationAttrNode extends LineAttrNode implements ICodeNode { public boolean checkCommentsLevel(CommentsLevel required) { return required.filter(this.root().getArgs().getCommentsLevel()); } public void addError(String errStr, Throwable e) { ErrorsCounter.error(this, errStr, e); } public void addWarn(String warn) { ErrorsCounter.warning(this, warn); JadxCommentsAttr.add(this, CommentsLevel.WARN, warn); this.add(AFlag.INCONSISTENT_CODE); } public void addCodeComment(String comment) { addAttr(AType.CODE_COMMENTS, new CodeComment(comment, CommentStyle.LINE)); } public void addCodeComment(String comment, CommentStyle style) { addAttr(AType.CODE_COMMENTS, new CodeComment(comment, style)); } public void addWarnComment(String warn) { JadxCommentsAttr.add(this, CommentsLevel.WARN, warn); } public void addWarnComment(String warn, Throwable exc) { String commentStr = warn + root().getArgs().getCodeNewLineStr() + Utils.getStackTrace(exc); JadxCommentsAttr.add(this, CommentsLevel.WARN, commentStr); } public void addInfoComment(String commentStr) { JadxCommentsAttr.add(this, CommentsLevel.INFO, commentStr); } public void addDebugComment(String commentStr) { JadxCommentsAttr.add(this, CommentsLevel.DEBUG, commentStr); } public CommentsLevel getCommentsLevel() { return this.root().getArgs().getCommentsLevel(); } }
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/attributes/nodes/MethodReplaceAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/MethodReplaceAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.PinnedAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.MethodNode; /** * Calls of method should be replaced by provided method (used for synthetic methods redirect) */ public class MethodReplaceAttr extends PinnedAttribute { private final MethodNode replaceMth; public MethodReplaceAttr(MethodNode replaceMth) { this.replaceMth = replaceMth; } public MethodNode getReplaceMth() { return replaceMth; } @Override public AType<MethodReplaceAttr> getAttrType() { return AType.METHOD_REPLACE; } @Override public String toString() { return "REPLACED_BY: " + replaceMth; } }
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/attributes/nodes/JadxCommentsAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/JadxCommentsAttr.java
package jadx.core.dex.attributes.nodes; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import jadx.api.CommentsLevel; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.IAttributeNode; import jadx.core.utils.Utils; public class JadxCommentsAttr implements IJadxAttribute { public static void add(IAttributeNode node, CommentsLevel level, String comment) { initFor(node).add(level, comment); } private static JadxCommentsAttr initFor(IAttributeNode node) { JadxCommentsAttr currentAttr = node.get(AType.JADX_COMMENTS); if (currentAttr != null) { return currentAttr; } JadxCommentsAttr newAttr = new JadxCommentsAttr(); node.addAttr(newAttr); return newAttr; } private final Map<CommentsLevel, Set<String>> comments = new EnumMap<>(CommentsLevel.class); public void add(CommentsLevel level, String comment) { comments.computeIfAbsent(level, l -> new HashSet<>()).add(comment); } public List<String> formatAndFilter(CommentsLevel level) { if (level == CommentsLevel.NONE || level == CommentsLevel.USER_ONLY) { return Collections.emptyList(); } return comments.entrySet().stream() .filter(e -> e.getKey().filter(level)) .flatMap(e -> { String levelName = e.getKey().name(); return e.getValue().stream() .map(v -> "JADX " + levelName + ": " + v); }) .sorted() .collect(Collectors.toList()); } public Map<CommentsLevel, Set<String>> getComments() { return comments; } @Override public IJadxAttrType<JadxCommentsAttr> getAttrType() { return AType.JADX_COMMENTS; } @Override public String toString() { return "JadxCommentsAttr{\n " + Utils.listToString(comments.entrySet(), "\n ", e -> e.getKey() + ": \n -> " + Utils.listToString(e.getValue(), "\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/attributes/nodes/ClassTypeVarsAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/ClassTypeVarsAttr.java
package jadx.core.dex.attributes.nodes; import java.util.Collections; import java.util.List; import java.util.Map; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.args.ArgType; public class ClassTypeVarsAttr implements IJadxAttribute { public static final ClassTypeVarsAttr EMPTY = new ClassTypeVarsAttr(Collections.emptyList(), Collections.emptyMap()); /** * Type vars defined in current class */ private final List<ArgType> typeVars; /** * Type vars mapping in current and super types: * TypeRawObj -> (TypeVarInSuperType -> TypeVarFromThisClass) */ private final Map<String, Map<ArgType, ArgType>> superTypeMaps; public ClassTypeVarsAttr(List<ArgType> typeVars, Map<String, Map<ArgType, ArgType>> superTypeMaps) { this.typeVars = typeVars; this.superTypeMaps = superTypeMaps; } public List<ArgType> getTypeVars() { return typeVars; } public Map<ArgType, ArgType> getTypeVarsMapFor(ArgType type) { Map<ArgType, ArgType> typeMap = superTypeMaps.get(type.getObject()); if (typeMap == null) { return Collections.emptyMap(); } return typeMap; } @Override public AType<ClassTypeVarsAttr> getAttrType() { return AType.CLASS_TYPE_VARS; } @Override public String toString() { return "ClassTypeVarsAttr{" + typeVars + ", super maps: " + superTypeMaps + '}'; } }
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/attributes/nodes/JadxError.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/JadxError.java
package jadx.core.dex.attributes.nodes; import java.util.Objects; import org.jetbrains.annotations.NotNull; import jadx.core.utils.Utils; public class JadxError implements Comparable<JadxError> { private final String error; private final Throwable cause; public JadxError(String error, Throwable cause) { this.error = Objects.requireNonNull(error); this.cause = cause; } public String getError() { return error; } public Throwable getCause() { return cause; } @Override public int compareTo(@NotNull JadxError o) { return this.error.compareTo(o.getError()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JadxError other = (JadxError) o; return error.equals(other.error); } @Override public int hashCode() { return error.hashCode(); } @Override public String toString() { StringBuilder str = new StringBuilder(); str.append("JadxError: ").append(error).append(' '); if (cause != null) { str.append(cause.getClass()); str.append(':'); str.append(cause.getMessage()); str.append('\n'); str.append(Utils.getStackTrace(cause)); } return str.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/attributes/nodes/EdgeInsnAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/EdgeInsnAttr.java
package jadx.core.dex.attributes.nodes; import java.util.Objects; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.AttrList; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.Edge; import jadx.core.dex.nodes.InsnNode; public class EdgeInsnAttr implements IJadxAttribute { private final BlockNode start; private final BlockNode end; private final InsnNode insn; public static void addEdgeInsn(Edge edge, InsnNode insn) { addEdgeInsn(edge.getSource(), edge.getTarget(), insn); } public static void addEdgeInsn(BlockNode start, BlockNode end, InsnNode insn) { EdgeInsnAttr edgeInsnAttr = new EdgeInsnAttr(start, end, insn); if (!start.getAll(AType.EDGE_INSN).contains(edgeInsnAttr)) { start.addAttr(AType.EDGE_INSN, edgeInsnAttr); } if (!end.getAll(AType.EDGE_INSN).contains(edgeInsnAttr)) { end.addAttr(AType.EDGE_INSN, edgeInsnAttr); } } private EdgeInsnAttr(BlockNode start, BlockNode end, InsnNode insn) { this.start = start; this.end = end; this.insn = insn; } @Override public AType<AttrList<EdgeInsnAttr>> getAttrType() { return AType.EDGE_INSN; } public BlockNode getStart() { return start; } public BlockNode getEnd() { return end; } public InsnNode getInsn() { return insn; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EdgeInsnAttr that = (EdgeInsnAttr) o; return start.equals(that.start) && end.equals(that.end) && insn.isDeepEquals(that.insn); } @Override public int hashCode() { return Objects.hash(start, end, insn); } @Override public String toString() { return "EDGE_INSN: " + start + "->" + end + ' ' + 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/attributes/nodes/MethodInlineAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/MethodInlineAttr.java
package jadx.core.dex.attributes.nodes; import java.util.List; import java.util.Objects; import jadx.api.plugins.input.data.attributes.PinnedAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; public class MethodInlineAttr extends PinnedAttribute { private static final MethodInlineAttr INLINE_NOT_NEEDED = new MethodInlineAttr(null, null); public static MethodInlineAttr markForInline(MethodNode mth, InsnNode replaceInsn) { Objects.requireNonNull(replaceInsn); List<RegisterArg> allArgRegs = mth.getAllArgRegs(); int argsCount = allArgRegs.size(); int[] regNums = new int[argsCount]; for (int i = 0; i < argsCount; i++) { RegisterArg reg = allArgRegs.get(i); regNums[i] = reg.getRegNum(); } MethodInlineAttr mia = new MethodInlineAttr(replaceInsn, regNums); mth.addAttr(mia); mth.addDebugComment("Marked for inline"); return mia; } public static MethodInlineAttr inlineNotNeeded(MethodNode mth) { mth.addAttr(INLINE_NOT_NEEDED); return INLINE_NOT_NEEDED; } private final InsnNode insn; /** * Store method arguments register numbers to allow remap registers */ private final int[] argsRegNums; private MethodInlineAttr(InsnNode insn, int[] argsRegNums) { this.insn = insn; this.argsRegNums = argsRegNums; } public boolean notNeeded() { return insn == null; } public InsnNode getInsn() { return insn; } public int[] getArgsRegNums() { return argsRegNums; } @Override public AType<MethodInlineAttr> getAttrType() { return AType.METHOD_INLINE; } @Override public String toString() { if (notNeeded()) { return "INLINE_NOT_NEEDED"; } return "INLINE: " + 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/attributes/nodes/ForceReturnAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/ForceReturnAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.Utils; public class ForceReturnAttr implements IJadxAttribute { private final InsnNode returnInsn; public ForceReturnAttr(InsnNode retInsn) { this.returnInsn = retInsn; } public InsnNode getReturnInsn() { return returnInsn; } @Override public AType<ForceReturnAttr> getAttrType() { return AType.FORCE_RETURN; } @Override public String toString() { return "FORCE_RETURN " + Utils.listToString(returnInsn.getArguments()); } }
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/attributes/nodes/MethodThrowsAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/MethodThrowsAttr.java
package jadx.core.dex.attributes.nodes; import java.util.Set; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.PinnedAttribute; import jadx.core.dex.attributes.AType; public class MethodThrowsAttr extends PinnedAttribute { private final Set<String> list; private boolean visited; public MethodThrowsAttr(Set<String> list) { this.list = list; } public boolean isVisited() { return visited; } public void setVisited(boolean visited) { this.visited = visited; } public Set<String> getList() { return list; } @Override public IJadxAttrType<MethodThrowsAttr> getAttrType() { return AType.METHOD_THROWS; } @Override public String toString() { return "THROWS:" + 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/attributes/nodes/RegionRefAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/RegionRefAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.IRegion; /** * Region created based on parent instruction */ public class RegionRefAttr implements IJadxAttribute { private final IRegion region; public RegionRefAttr(IRegion region) { this.region = region; } public IRegion getRegion() { return region; } @Override public AType<RegionRefAttr> getAttrType() { return AType.REGION_REF; } @Override public String toString() { return "RegionRef:" + region.baseString(); } }
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/attributes/nodes/DeclareVariablesAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/DeclareVariablesAttr.java
package jadx.core.dex.attributes.nodes; import java.util.ArrayList; import java.util.List; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.args.CodeVar; import jadx.core.utils.Utils; /** * List of variables to be declared at region start. */ public class DeclareVariablesAttr implements IJadxAttribute { private final List<CodeVar> vars = new ArrayList<>(); public Iterable<CodeVar> getVars() { return vars; } public void addVar(CodeVar arg) { vars.add(arg); } @Override public AType<DeclareVariablesAttr> getAttrType() { return AType.DECLARE_VARIABLES; } @Override public String toString() { return "DECL_VAR: " + Utils.listToString(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/attributes/nodes/GenericInfoAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/GenericInfoAttr.java
package jadx.core.dex.attributes.nodes; import java.util.List; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.args.ArgType; public class GenericInfoAttr implements IJadxAttribute { private final List<ArgType> genericTypes; private boolean explicit; public GenericInfoAttr(List<ArgType> genericTypes) { this.genericTypes = genericTypes; } public List<ArgType> getGenericTypes() { return genericTypes; } public boolean isExplicit() { return explicit; } public void setExplicit(boolean explicit) { this.explicit = explicit; } @Override public AType<GenericInfoAttr> getAttrType() { return AType.GENERIC_INFO; } @Override public String toString() { return "GenericInfoAttr{" + genericTypes + ", explicit=" + explicit + '}'; } }
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/attributes/nodes/LoopLabelAttr.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/LoopLabelAttr.java
package jadx.core.dex.attributes.nodes; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; public class LoopLabelAttr implements IJadxAttribute { private final LoopInfo loop; public LoopLabelAttr(LoopInfo loop) { this.loop = loop; } public LoopInfo getLoop() { return loop; } @Override public AType<LoopLabelAttr> getAttrType() { return AType.LOOP_LABEL; } @Override public String toString() { return "LOOP_LABEL: " + loop; } }
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/attributes/nodes/LineAttrNode.java
jadx-core/src/main/java/jadx/core/dex/attributes/nodes/LineAttrNode.java
package jadx.core.dex.attributes.nodes; import jadx.core.dex.attributes.AttrNode; import jadx.core.dex.attributes.ILineAttributeNode; public abstract class LineAttrNode extends AttrNode implements ILineAttributeNode { private int sourceLine; /** * Position where a node declared at in decompiled code */ private int defPosition; @Override public int getSourceLine() { return sourceLine; } @Override public void setSourceLine(int sourceLine) { this.sourceLine = sourceLine; } @Override public int getDefPosition() { return this.defPosition; } @Override public void setDefPosition(int defPosition) { this.defPosition = defPosition; } public void addSourceLineFrom(LineAttrNode lineAttrNode) { if (this.getSourceLine() == 0) { this.setSourceLine(lineAttrNode.getSourceLine()); } } public void copyLines(LineAttrNode lineAttrNode) { setSourceLine(lineAttrNode.getSourceLine()); setDefPosition(lineAttrNode.getDefPosition()); } }
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/IDexTreeVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/IDexTreeVisitor.java
package jadx.core.dex.visitors; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.exceptions.JadxException; /** * Visitor interface for traverse dex tree */ public interface IDexTreeVisitor { /** * Visitor short id */ String getName(); /** * Called after loading dex tree, but before visitor traversal. */ void init(RootNode root) throws JadxException; /** * Visit class * * @return false for disable child methods and inner classes traversal */ boolean visit(ClassNode cls) throws JadxException; /** * Visit method */ void visit(MethodNode mth) throws JadxException; }
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/DepthTraversal.java
jadx-core/src/main/java/jadx/core/dex/visitors/DepthTraversal.java
package jadx.core.dex.visitors; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; public class DepthTraversal { public static void visit(IDexTreeVisitor visitor, ClassNode cls) { try { if (visitor.visit(cls)) { cls.getInnerClasses().forEach(inCls -> visit(visitor, inCls)); cls.getMethods().forEach(mth -> visit(visitor, mth)); } } catch (StackOverflowError | Exception e) { cls.addError(e.getClass().getSimpleName() + " in pass: " + visitor.getClass().getSimpleName(), e); } } public static void visit(IDexTreeVisitor visitor, MethodNode mth) { try { if (mth.contains(AType.JADX_ERROR)) { return; } visitor.visit(mth); } catch (StackOverflowError | Exception e) { mth.addError(e.getClass().getSimpleName() + " in pass: " + visitor.getClass().getSimpleName(), e); } } private DepthTraversal() { } }
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/EnumVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/EnumVisitor.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.AccessFlags; import jadx.core.codegen.TypeGen; import jadx.core.deobf.NameMapper; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.EnumClassAttr; import jadx.core.dex.attributes.nodes.EnumClassAttr.EnumField; 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.IContainer; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.regions.Region; import jadx.core.dex.visitors.regions.CheckRegions; import jadx.core.dex.visitors.regions.IfRegionVisitor; import jadx.core.dex.visitors.shrink.CodeShrinkVisitor; import jadx.core.utils.BlockInsnPair; import jadx.core.utils.BlockUtils; import jadx.core.utils.InsnRemover; import jadx.core.utils.InsnUtils; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxException; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.utils.InsnUtils.checkInsnType; import static jadx.core.utils.InsnUtils.getSingleArg; import static jadx.core.utils.InsnUtils.getWrappedInsn; @JadxVisitor( name = "EnumVisitor", desc = "Restore enum classes", runAfter = { CodeShrinkVisitor.class, // all possible instructions already inlined ModVisitor.class, ReplaceNewArray.class, // values array normalized IfRegionVisitor.class, // ternary operator inlined CheckRegions.class // regions processing finished }, runBefore = { ExtractFieldInit.class } ) public class EnumVisitor extends AbstractVisitor { private MethodInfo enumValueOfMth; private MethodInfo cloneMth; @Override public void init(RootNode root) { enumValueOfMth = MethodInfo.fromDetails( root, ClassInfo.fromType(root, ArgType.ENUM), "valueOf", Arrays.asList(ArgType.CLASS, ArgType.STRING), ArgType.ENUM); cloneMth = MethodInfo.fromDetails(root, ClassInfo.fromType(root, ArgType.OBJECT), "clone", Collections.emptyList(), ArgType.OBJECT); } @Override public boolean visit(ClassNode cls) throws JadxException { if (cls.isEnum()) { boolean converted; try { converted = convertToEnum(cls); } catch (Exception e) { cls.addWarnComment("Enum visitor error", e); converted = false; } if (!converted) { AccessInfo accessFlags = cls.getAccessFlags(); if (accessFlags.isEnum()) { cls.setAccessFlags(accessFlags.remove(AccessFlags.ENUM)); cls.addWarnComment("Failed to restore enum class, 'enum' modifier and super class removed"); } } } return true; } private boolean convertToEnum(ClassNode cls) { ArgType superType = cls.getSuperClass(); if (superType != null && superType.getObject().equals(ArgType.ENUM.getObject())) { cls.add(AFlag.REMOVE_SUPER_CLASS); } MethodNode classInitMth = cls.getClassInitMth(); if (classInitMth == null) { cls.addWarnComment("Enum class init method not found"); return false; } Region staticRegion = classInitMth.getRegion(); if (staticRegion == null || classInitMth.getBasicBlocks().isEmpty()) { return false; } // collect blocks on linear part of static method (ignore branching on method end) List<BlockNode> staticBlocks = new ArrayList<>(); for (IContainer subBlock : staticRegion.getSubBlocks()) { if (subBlock instanceof BlockNode) { staticBlocks.add((BlockNode) subBlock); } else { break; } } if (staticBlocks.isEmpty()) { cls.addWarnComment("Unexpected branching in enum static init block"); return false; } EnumData data = new EnumData(cls, classInitMth, staticBlocks); if (!searchValuesField(data)) { return false; } List<EnumField> enumFields = null; InsnArg arrArg = data.valuesInitInsn.getArg(0); if (arrArg.isInsnWrap()) { InsnNode wrappedInsn = ((InsnWrapArg) arrArg).getWrapInsn(); enumFields = extractEnumFieldsFromInsn(data, wrappedInsn); } if (enumFields == null) { cls.addWarnComment("Unknown enum class pattern. Please report as an issue!"); return false; } data.toRemove.add(data.valuesInitInsn); // all checks complete, perform transform EnumClassAttr attr = new EnumClassAttr(enumFields); attr.setStaticMethod(classInitMth); cls.addAttr(attr); for (EnumField enumField : attr.getFields()) { ConstructorInsn co = enumField.getConstrInsn(); FieldNode fieldNode = enumField.getField(); // use string arg from the constructor as enum field name String name = getConstString(cls.root(), co.getArg(0)); if (name != null && !fieldNode.getAlias().equals(name) && NameMapper.isValidAndPrintable(name) && cls.root().getArgs().isRenameValid()) { fieldNode.getFieldInfo().setAlias(name); } fieldNode.add(AFlag.DONT_GENERATE); processConstructorInsn(data, enumField, classInitMth); } data.valuesField.add(AFlag.DONT_GENERATE); InsnRemover.removeAllAndUnbind(classInitMth, data.toRemove); if (classInitMth.countInsns() == 0) { classInitMth.add(AFlag.DONT_GENERATE); } else if (!data.toRemove.isEmpty()) { CodeShrinkVisitor.shrinkMethod(classInitMth); } removeEnumMethods(cls, data.valuesField); return true; } /** * Search "$VALUES" field (holds all enum values) */ private boolean searchValuesField(EnumData data) { ArgType clsType = data.cls.getClassInfo().getType(); List<FieldNode> valuesCandidates = data.cls.getFields().stream() .filter(f -> f.getAccessFlags().isStatic()) .filter(f -> f.getType().isArray()) .filter(f -> Objects.equals(f.getType().getArrayRootElement(), clsType)) .collect(Collectors.toList()); if (valuesCandidates.isEmpty()) { data.cls.addWarnComment("$VALUES field not found"); return false; } if (valuesCandidates.size() > 1) { valuesCandidates.removeIf(f -> !f.getAccessFlags().isSynthetic()); } if (valuesCandidates.size() > 1) { Optional<FieldNode> valuesOpt = valuesCandidates.stream().filter(f -> f.getName().equals("$VALUES")).findAny(); if (valuesOpt.isPresent()) { valuesCandidates.clear(); valuesCandidates.add(valuesOpt.get()); } } if (valuesCandidates.size() != 1) { data.cls.addWarnComment("Found several \"values\" enum fields: " + valuesCandidates); return false; } data.valuesField = valuesCandidates.get(0); // search "$VALUES" array init and collect enum fields BlockInsnPair valuesInitPair = getValuesInitInsn(data); if (valuesInitPair == null) { return false; } data.valuesInitInsn = valuesInitPair.getInsn(); return true; } private void processConstructorInsn(EnumData data, EnumField enumField, MethodNode classInitMth) { ConstructorInsn co = enumField.getConstrInsn(); ClassInfo enumClsInfo = co.getClassType(); if (!enumClsInfo.equals(data.cls.getClassInfo())) { ClassNode enumCls = data.cls.root().resolveClass(enumClsInfo); if (enumCls != null) { processEnumCls(data.cls, enumField, enumCls); } } MethodNode ctrMth = data.cls.root().resolveMethod(co.getCallMth()); if (ctrMth != null) { markArgsForSkip(ctrMth); } RegisterArg coResArg = co.getResult(); if (coResArg == null || coResArg.getSVar().getUseList().size() <= 2) { data.toRemove.add(co); } else { boolean varUseFound = coResArg.getSVar().getUseList().stream() .anyMatch(useArg -> !data.toRemove.contains(useArg.getParentInsn())); if (varUseFound) { // constructor result used in other places -> replace constructor with enum field get (SGET) IndexInsnNode enumGet = new IndexInsnNode(InsnType.SGET, enumField.getField().getFieldInfo(), 0); enumGet.setResult(coResArg.duplicate()); BlockUtils.replaceInsn(classInitMth, co, enumGet); } } } @Nullable private List<EnumField> extractEnumFieldsFromInsn(EnumData enumData, InsnNode wrappedInsn) { switch (wrappedInsn.getType()) { case FILLED_NEW_ARRAY: return extractEnumFieldsFromFilledArray(enumData, wrappedInsn); case INVOKE: // handle redirection of values array fill (added in java 15) return extractEnumFieldsFromInvoke(enumData, (InvokeNode) wrappedInsn); case NEW_ARRAY: InsnArg arg = wrappedInsn.getArg(0); if (arg.isZeroLiteral()) { // empty enum return Collections.emptyList(); } return null; default: return null; } } private List<EnumField> extractEnumFieldsFromInvoke(EnumData enumData, InvokeNode invokeNode) { MethodInfo callMth = invokeNode.getCallMth(); MethodNode valuesMth = enumData.cls.root().resolveMethod(callMth); if (valuesMth == null || valuesMth.isVoidReturn()) { return null; } BlockNode returnBlock = Utils.getOne(valuesMth.getPreExitBlocks()); InsnNode returnInsn = BlockUtils.getLastInsn(returnBlock); InsnNode wrappedInsn = getWrappedInsn(getSingleArg(returnInsn)); if (wrappedInsn == null) { return null; } List<EnumField> enumFields = extractEnumFieldsFromInsn(enumData, wrappedInsn); if (enumFields != null) { valuesMth.add(AFlag.DONT_GENERATE); } return enumFields; } private BlockInsnPair getValuesInitInsn(EnumData data) { FieldInfo searchField = data.valuesField.getFieldInfo(); for (BlockNode blockNode : data.staticBlocks) { for (InsnNode insn : blockNode.getInstructions()) { if (insn.getType() == InsnType.SPUT) { IndexInsnNode indexInsnNode = (IndexInsnNode) insn; FieldInfo f = (FieldInfo) indexInsnNode.getIndex(); if (f.equals(searchField)) { return new BlockInsnPair(blockNode, indexInsnNode); } } } } return null; } private List<EnumField> extractEnumFieldsFromFilledArray(EnumData enumData, InsnNode arrFillInsn) { List<EnumField> enumFields = new ArrayList<>(); for (InsnArg arg : arrFillInsn.getArguments()) { EnumField field = null; if (arg.isInsnWrap()) { InsnNode wrappedInsn = ((InsnWrapArg) arg).getWrapInsn(); field = processEnumFieldByWrappedInsn(enumData, wrappedInsn); } else if (arg.isRegister()) { field = processEnumFieldByRegister(enumData, (RegisterArg) arg); } if (field == null) { return null; } enumFields.add(field); } enumData.toRemove.add(arrFillInsn); return enumFields; } private EnumField processEnumFieldByWrappedInsn(EnumData data, InsnNode wrappedInsn) { if (wrappedInsn.getType() == InsnType.SGET) { return processEnumFieldByField(data, wrappedInsn); } ConstructorInsn constructorInsn = castConstructorInsn(wrappedInsn); if (constructorInsn != null) { FieldNode enumFieldNode = createFakeField(data.cls, "EF" + constructorInsn.getOffset()); data.cls.addField(enumFieldNode); return createEnumFieldByConstructor(data, enumFieldNode, constructorInsn); } return null; } @Nullable private EnumField processEnumFieldByField(EnumData data, InsnNode sgetInsn) { if (sgetInsn.getType() != InsnType.SGET) { return null; } FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) sgetInsn).getIndex(); FieldNode enumFieldNode = data.cls.searchField(fieldInfo); if (enumFieldNode == null) { return null; } InsnNode sputInsn = searchFieldPutInsn(data, enumFieldNode); if (sputInsn == null) { return null; } ConstructorInsn co = getConstructorInsn(sputInsn); if (co == null) { return null; } RegisterArg sgetResult = sgetInsn.getResult(); if (sgetResult == null || sgetResult.getSVar().getUseCount() == 1) { data.toRemove.add(sgetInsn); } data.toRemove.add(sputInsn); return createEnumFieldByConstructor(data, enumFieldNode, co); } @Nullable private EnumField processEnumFieldByRegister(EnumData data, RegisterArg arg) { InsnNode assignInsn = arg.getAssignInsn(); if (assignInsn != null && assignInsn.getType() == InsnType.SGET) { return processEnumFieldByField(data, assignInsn); } SSAVar ssaVar = arg.getSVar(); if (ssaVar.getUseCount() == 0) { return null; } InsnNode constrInsn = ssaVar.getAssign().getParentInsn(); if (constrInsn == null || constrInsn.getType() != InsnType.CONSTRUCTOR) { return null; } FieldNode enumFieldNode = searchEnumField(data, ssaVar); if (enumFieldNode == null) { enumFieldNode = createFakeField(data.cls, "EF" + arg.getRegNum()); data.cls.addField(enumFieldNode); } return createEnumFieldByConstructor(data, enumFieldNode, (ConstructorInsn) constrInsn); } private FieldNode createFakeField(ClassNode cls, String name) { FieldNode enumFieldNode; FieldInfo fldInfo = FieldInfo.from(cls.root(), cls.getClassInfo(), name, cls.getType()); enumFieldNode = new FieldNode(cls, fldInfo, 0); enumFieldNode.add(AFlag.SYNTHETIC); enumFieldNode.addInfoComment("Fake field, exist only in values array"); return enumFieldNode; } @Nullable private FieldNode searchEnumField(EnumData data, SSAVar ssaVar) { InsnNode sputInsn = ssaVar.getUseList().get(0).getParentInsn(); if (sputInsn == null || sputInsn.getType() != InsnType.SPUT) { return null; } FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) sputInsn).getIndex(); FieldNode enumFieldNode = data.cls.searchField(fieldInfo); if (enumFieldNode == null) { return null; } data.toRemove.add(sputInsn); return enumFieldNode; } @SuppressWarnings("StatementWithEmptyBody") private EnumField createEnumFieldByConstructor(EnumData data, FieldNode enumFieldNode, ConstructorInsn co) { // usually constructor signature is '<init>(Ljava/lang/String;I)V'. // sometimes for one field enum second arg can be omitted if (co.getArgsCount() < 1) { return null; } ClassNode cls = data.cls; ClassInfo clsInfo = co.getClassType(); ClassNode constrCls = cls.root().resolveClass(clsInfo); if (constrCls == null) { return null; } if (constrCls.equals(cls)) { // allow same class } else if (constrCls.contains(AType.ANONYMOUS_CLASS)) { // allow external class already marked as anonymous } else { return null; } MethodNode ctrMth = cls.root().resolveMethod(co.getCallMth()); if (ctrMth == null) { return null; } List<RegisterArg> regs = new ArrayList<>(); co.getRegisterArgs(regs); if (!regs.isEmpty()) { ConstructorInsn replacedCo = inlineExternalRegs(data, co); if (replacedCo == null) { throw new JadxRuntimeException("Init of enum field '" + enumFieldNode.getName() + "' uses external variables"); } data.toRemove.add(co); co = replacedCo; } return new EnumField(enumFieldNode, co); } private ConstructorInsn inlineExternalRegs(EnumData data, ConstructorInsn co) { ConstructorInsn resCo = co.copyWithoutResult(); List<RegisterArg> regs = new ArrayList<>(); resCo.getRegisterArgs(regs); for (RegisterArg reg : regs) { FieldInfo enumField = checkExternalRegUsage(data, reg); if (enumField == null) { return null; } InsnNode enumUse = new IndexInsnNode(InsnType.SGET, enumField, 0); boolean replaced = resCo.replaceArg(reg, InsnArg.wrapArg(enumUse)); if (!replaced) { return null; } } return resCo; } private static FieldInfo checkExternalRegUsage(EnumData data, RegisterArg reg) { ClassNode cls = data.cls; SSAVar ssaVar = reg.getSVar(); InsnNode assignInsn = checkInsnType(ssaVar.getAssignInsn(), InsnType.CONSTRUCTOR); if (assignInsn == null || !((ConstructorInsn) assignInsn).getClassType().equals(cls.getClassInfo())) { return null; } FieldInfo enumField = null; for (RegisterArg useArg : ssaVar.getUseList()) { InsnNode useInsn = useArg.getParentInsn(); if (useInsn == null) { return null; } switch (useInsn.getType()) { case SPUT: { FieldInfo field = (FieldInfo) ((IndexInsnNode) useInsn).getIndex(); if (!field.getDeclClass().equals(cls.getClassInfo()) || !field.getType().equals(cls.getType())) { return null; } enumField = field; break; } case CONSTRUCTOR: { ConstructorInsn useCo = (ConstructorInsn) useInsn; if (!useCo.getClassType().equals(cls.getClassInfo())) { return null; } break; } case FILLED_NEW_ARRAY: { // allow usage in values init instruction if (!data.valuesInitInsn.getArg(0).unwrap().equals(useInsn)) { return null; } break; } default: return null; } } if (enumField != null) { data.toRemove.add(assignInsn); } return enumField; } @Nullable private InsnNode searchFieldPutInsn(EnumData data, FieldNode enumFieldNode) { for (BlockNode block : data.staticBlocks) { for (InsnNode sputInsn : block.getInstructions()) { if (sputInsn != null && sputInsn.getType() == InsnType.SPUT) { FieldInfo f = (FieldInfo) ((IndexInsnNode) sputInsn).getIndex(); FieldNode fieldNode = data.cls.searchField(f); if (Objects.equals(fieldNode, enumFieldNode)) { return sputInsn; } } } } return null; } private void removeEnumMethods(ClassNode cls, FieldNode valuesField) { ArgType clsType = cls.getClassInfo().getType(); String valuesMethodShortId = "values()" + TypeGen.signature(ArgType.array(clsType)); MethodNode valuesMethod = null; // remove compiler generated methods for (MethodNode mth : cls.getMethods()) { MethodInfo mi = mth.getMethodInfo(); if (mi.isClassInit() || mth.isNoCode()) { continue; } String shortId = mi.getShortId(); if (mi.isConstructor()) { if (isDefaultConstructor(mth, shortId)) { mth.add(AFlag.DONT_GENERATE); } markArgsForSkip(mth); } else if (mi.getShortId().equals(valuesMethodShortId)) { if (isValuesMethod(mth, clsType)) { valuesMethod = mth; mth.add(AFlag.DONT_GENERATE); } else { // custom values method => rename to resolve conflict with enum method mth.getMethodInfo().setAlias("valuesCustom"); mth.addAttr(new RenameReasonAttr(mth).append("to resolve conflict with enum method")); } } else if (isValuesMethod(mth, clsType)) { if (!mth.getMethodInfo().getAlias().equals("values") && !mth.getUseIn().isEmpty()) { // rename to use default values method mth.getMethodInfo().setAlias("values"); mth.addAttr(new RenameReasonAttr(mth).append("to match enum method name")); mth.add(AFlag.DONT_RENAME); } valuesMethod = mth; mth.add(AFlag.DONT_GENERATE); } else if (simpleValueOfMth(mth, clsType)) { mth.add(AFlag.DONT_GENERATE); } } FieldInfo valuesFieldInfo = valuesField.getFieldInfo(); for (MethodNode mth : cls.getMethods()) { // fix access to 'values' field and 'values()' method fixValuesAccess(mth, valuesFieldInfo, clsType, valuesMethod); } } private void markArgsForSkip(MethodNode mth) { // skip first and second args SkipMethodArgsAttr.skipArg(mth, 0); if (mth.getMethodInfo().getArgsCount() > 1) { SkipMethodArgsAttr.skipArg(mth, 1); } } private boolean isDefaultConstructor(MethodNode mth, String shortId) { boolean defaultId = shortId.equals("<init>(Ljava/lang/String;I)V") || shortId.equals("<init>(Ljava/lang/String;)V"); if (defaultId) { // check content return mth.countInsns() == 0; } return false; } // TODO: support other method patterns ??? private boolean isValuesMethod(MethodNode mth, ArgType clsType) { ArgType retType = mth.getReturnType(); if (!retType.isArray() || !retType.getArrayElement().equals(clsType)) { return false; } InsnNode returnInsn = BlockUtils.getOnlyOneInsnFromMth(mth); if (returnInsn == null || returnInsn.getType() != InsnType.RETURN || returnInsn.getArgsCount() != 1) { return false; } InsnNode wrappedInsn = getWrappedInsn(getSingleArg(returnInsn)); IndexInsnNode castInsn = (IndexInsnNode) checkInsnType(wrappedInsn, InsnType.CHECK_CAST); if (castInsn != null && Objects.equals(castInsn.getIndex(), ArgType.array(clsType))) { InvokeNode invokeInsn = (InvokeNode) checkInsnType(getWrappedInsn(getSingleArg(castInsn)), InsnType.INVOKE); return invokeInsn != null && invokeInsn.getCallMth().equals(cloneMth); } return false; } private boolean simpleValueOfMth(MethodNode mth, ArgType clsType) { InsnNode returnInsn = InsnUtils.searchSingleReturnInsn(mth, insn -> insn.getArgsCount() == 1); if (returnInsn == null) { return false; } InsnNode wrappedInsn = getWrappedInsn(getSingleArg(returnInsn)); IndexInsnNode castInsn = (IndexInsnNode) checkInsnType(wrappedInsn, InsnType.CHECK_CAST); if (castInsn != null && Objects.equals(castInsn.getIndex(), clsType)) { InvokeNode invokeInsn = (InvokeNode) checkInsnType(getWrappedInsn(getSingleArg(castInsn)), InsnType.INVOKE); return invokeInsn != null && invokeInsn.getCallMth().equals(enumValueOfMth); } return false; } private void fixValuesAccess(MethodNode mth, FieldInfo valuesFieldInfo, ArgType clsType, @Nullable MethodNode valuesMethod) { MethodInfo mi = mth.getMethodInfo(); if (mi.isConstructor() || mi.isClassInit() || mth.isNoCode() || mth == valuesMethod) { return; } // search value field usage Predicate<InsnNode> insnTest = insn -> Objects.equals(((IndexInsnNode) insn).getIndex(), valuesFieldInfo); InsnNode useInsn = InsnUtils.searchInsn(mth, InsnType.SGET, insnTest); if (useInsn == null) { return; } // replace 'values' field with 'values()' method InsnUtils.replaceInsns(mth, insn -> { if (insn.getType() == InsnType.SGET && insnTest.test(insn)) { MethodInfo valueMth = valuesMethod == null ? getValueMthInfo(mth.root(), clsType) : valuesMethod.getMethodInfo(); InvokeNode invokeNode = new InvokeNode(valueMth, InvokeType.STATIC, 0); invokeNode.setResult(insn.getResult()); if (valuesMethod == null) { // forcing enum method (can overlap and get renamed by custom method) invokeNode.add(AFlag.FORCE_RAW_NAME); } mth.addDebugComment("Replace access to removed values field (" + valuesFieldInfo.getName() + ") with 'values()' method"); return invokeNode; } return null; }); } private MethodInfo getValueMthInfo(RootNode root, ArgType clsType) { return MethodInfo.fromDetails(root, ClassInfo.fromType(root, clsType), "values", Collections.emptyList(), ArgType.array(clsType)); } private static void processEnumCls(ClassNode cls, EnumField field, ClassNode innerCls) { // remove constructor, because it is anonymous class for (MethodNode innerMth : innerCls.getMethods()) { if (innerMth.getAccessFlags().isConstructor()) { innerMth.add(AFlag.DONT_GENERATE); } } field.setCls(innerCls); if (!innerCls.getParentClass().equals(cls)) { // not inner cls.addInlinedClass(innerCls); innerCls.add(AFlag.DONT_GENERATE); } } private ConstructorInsn getConstructorInsn(InsnNode insn) { if (insn.getArgsCount() != 1) { return null; } InsnArg arg = insn.getArg(0); if (arg.isInsnWrap()) { return castConstructorInsn(((InsnWrapArg) arg).getWrapInsn()); } if (arg.isRegister()) { return castConstructorInsn(((RegisterArg) arg).getAssignInsn()); } return null; } @Nullable private ConstructorInsn castConstructorInsn(InsnNode coCandidate) { if (coCandidate != null && coCandidate.getType() == InsnType.CONSTRUCTOR) { return (ConstructorInsn) coCandidate; } return null; } private String getConstString(RootNode root, InsnArg arg) { if (arg.isInsnWrap()) { InsnNode constInsn = ((InsnWrapArg) arg).getWrapInsn(); Object constValue = InsnUtils.getConstValueByInsn(root, constInsn); if (constValue instanceof String) { return (String) constValue; } } return null; } private static class EnumData { final ClassNode cls; final MethodNode classInitMth; final List<BlockNode> staticBlocks; final List<InsnNode> toRemove = new ArrayList<>(); FieldNode valuesField; InsnNode valuesInitInsn; public EnumData(ClassNode cls, MethodNode classInitMth, List<BlockNode> staticBlocks) { this.cls = cls; this.classInitMth = classInitMth; this.staticBlocks = staticBlocks; } } }
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/ApplyVariableNames.java
jadx-core/src/main/java/jadx/core/dex/visitors/ApplyVariableNames.java
package jadx.core.dex.visitors; import java.util.List; import java.util.Map; import java.util.Set; import org.jetbrains.annotations.Nullable; import jadx.core.Consts; import jadx.core.deobf.NameMapper; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.InvokeNode; 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.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.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.visitors.regions.variables.ProcessVariables; import jadx.core.utils.StringUtils; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxException; @JadxVisitor( name = "ApplyVariableNames", desc = "Try to guess variable name from usage", runAfter = { ProcessVariables.class } ) public class ApplyVariableNames extends AbstractVisitor { private static final Map<String, String> OBJ_ALIAS = Utils.newConstStringMap( Consts.CLASS_STRING, "str", Consts.CLASS_CLASS, "cls", Consts.CLASS_THROWABLE, "th", Consts.CLASS_OBJECT, "obj", "java.util.Iterator", "it", "java.util.HashMap", "map", "java.lang.Boolean", "bool", "java.lang.Short", "sh", "java.lang.Integer", "num", "java.lang.Character", "ch", "java.lang.Byte", "b", "java.lang.Float", "f", "java.lang.Long", "l", "java.lang.Double", "d", "java.lang.StringBuilder", "sb", "java.lang.Exception", "exc"); private static final Set<String> GOOD_VAR_NAMES = Set.of( "size", "length", "list", "map", "next"); private static final List<String> INVOKE_PREFIXES = List.of( "get", "set", "to", "parse", "read", "format"); private RootNode root; @Override public void init(RootNode root) throws JadxException { this.root = root; } @Override public void visit(MethodNode mth) throws JadxException { for (SSAVar ssaVar : mth.getSVars()) { CodeVar codeVar = ssaVar.getCodeVar(); String newName = guessName(codeVar); if (newName != null) { codeVar.setName(newName); } } } private @Nullable String guessName(CodeVar var) { if (var.isThis()) { return RegisterArg.THIS_ARG_NAME; } if (!var.isDeclared()) { // name is not used in code return null; } if (NameMapper.isValidAndPrintable(var.getName())) { // the current name is valid, keep it return null; } List<SSAVar> ssaVars = var.getSsaVars(); if (Utils.notEmpty(ssaVars)) { boolean mthArg = ssaVars.stream().anyMatch(ssaVar -> ssaVar.getAssign().contains(AFlag.METHOD_ARGUMENT)); if (mthArg) { // for method args use defined type and ignore usage return makeNameForType(var.getType()); } for (SSAVar ssaVar : ssaVars) { String name = makeNameForSSAVar(ssaVar); if (name != null) { return name; } } } return makeNameForType(var.getType()); } private @Nullable String makeNameForSSAVar(SSAVar ssaVar) { String ssaVarName = ssaVar.getName(); if (ssaVarName != null) { return ssaVarName; } InsnNode assignInsn = ssaVar.getAssignInsn(); if (assignInsn != null) { String name = makeNameFromInsn(ssaVar, assignInsn); if (NameMapper.isValidAndPrintable(name)) { return name; } } return null; } private String makeNameFromInsn(SSAVar ssaVar, InsnNode insn) { switch (insn.getType()) { case INVOKE: return makeNameFromInvoke(ssaVar, (InvokeNode) insn); case CONSTRUCTOR: ConstructorInsn co = (ConstructorInsn) insn; MethodNode callMth = root.getMethodUtils().resolveMethod(co); if (callMth != null && callMth.contains(AFlag.ANONYMOUS_CONSTRUCTOR)) { // don't use name of anonymous class return null; } return makeNameForClass(co.getClassType()); case ARRAY_LENGTH: return "length"; case ARITH: case TERNARY: case CAST: for (InsnArg arg : insn.getArguments()) { if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); String wName = makeNameFromInsn(ssaVar, wrapInsn); if (wName != null) { return wName; } } } break; default: break; } return null; } private String makeNameForType(ArgType type) { if (type.isPrimitive()) { return type.getPrimitiveType().getShortName().toLowerCase(); } if (type.isArray()) { return makeNameForType(type.getArrayRootElement()) + "Arr"; } return makeNameForObject(type); } private String makeNameForObject(ArgType type) { if (type.isGenericType()) { return StringUtils.escape(type.getObject().toLowerCase()); } if (type.isObject()) { String alias = getAliasForObject(type.getObject()); if (alias != null) { return alias; } return makeNameForCheckedClass(ClassInfo.fromType(root, type)); } return StringUtils.escape(type.toString()); } private String makeNameForCheckedClass(ClassInfo classInfo) { String shortName = classInfo.getAliasShortName(); String vName = fromName(shortName); if (vName != null) { return vName; } String lower = StringUtils.escape(shortName.toLowerCase()); if (shortName.equals(lower)) { return lower + "Var"; } return lower; } private String makeNameForClass(ClassInfo classInfo) { String alias = getAliasForObject(classInfo.getFullName()); if (alias != null) { return alias; } return makeNameForCheckedClass(classInfo); } private static String fromName(String name) { if (name == null || name.isEmpty()) { return null; } if (name.toUpperCase().equals(name)) { // all characters are upper case return name.toLowerCase(); } String v1 = Character.toLowerCase(name.charAt(0)) + name.substring(1); if (!v1.equals(name)) { return v1; } if (name.length() < 3) { return name + "Var"; } return null; } private static String getAliasForObject(String name) { return OBJ_ALIAS.get(name); } private String makeNameFromInvoke(SSAVar ssaVar, InvokeNode inv) { MethodInfo callMth = inv.getCallMth(); String name = callMth.getAlias(); ClassInfo declClass = callMth.getDeclClass(); if ("getInstance".equals(name)) { // e.g. Cipher.getInstance return makeNameForClass(declClass); } String shortName = cutPrefix(name); if (shortName != null) { return fromName(shortName); } if ("iterator".equals(name)) { return "it"; } if ("toString".equals(name)) { return makeNameForClass(declClass); } if ("forName".equals(name) && declClass.getType().equals(ArgType.CLASS)) { return OBJ_ALIAS.get(Consts.CLASS_CLASS); } // use method name as a variable name not the best idea in most cases if (!GOOD_VAR_NAMES.contains(name)) { String typeName = makeNameForType(ssaVar.getCodeVar().getType()); if (!typeName.equalsIgnoreCase(name)) { return typeName + StringUtils.capitalizeFirstChar(name); } } return name; } private @Nullable String cutPrefix(String name) { for (String prefix : INVOKE_PREFIXES) { if (name.startsWith(prefix)) { return name.substring(prefix.length()); } } return null; } @Override public String getName() { return "ApplyVariableNames"; } }
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/AttachMethodDetails.java
jadx-core/src/main/java/jadx/core/dex/visitors/AttachMethodDetails.java
package jadx.core.dex.visitors; import jadx.core.dex.instructions.BaseInvokeNode; 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.visitors.blocks.BlockSplitter; import jadx.core.utils.exceptions.JadxException; @JadxVisitor( name = "Attach Method Details", desc = "Attach method details for invoke instructions", runBefore = { BlockSplitter.class, MethodInvokeVisitor.class } ) public class AttachMethodDetails extends AbstractVisitor { private MethodUtils methodUtils; @Override public void init(RootNode root) { methodUtils = root.getMethodUtils(); } @Override public void visit(MethodNode mth) throws JadxException { if (mth.isNoCode()) { return; } for (InsnNode insn : mth.getInstructions()) { if (insn instanceof BaseInvokeNode) { attachMethodDetails((BaseInvokeNode) insn); } } } private void attachMethodDetails(BaseInvokeNode insn) { IMethodDetails methodDetails = methodUtils.getMethodDetails(insn.getCallMth()); if (methodDetails != null) { insn.addAttr(methodDetails); } } }
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/ProcessMethodsForInline.java
jadx-core/src/main/java/jadx/core/dex/visitors/ProcessMethodsForInline.java
package jadx.core.dex.visitors; import jadx.core.Consts; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.visitors.usage.UsageInfoVisitor; import jadx.core.utils.exceptions.JadxException; @JadxVisitor( name = "ProcessMethodsForInline", desc = "Mark methods for future inline", runAfter = { UsageInfoVisitor.class } ) public class ProcessMethodsForInline extends AbstractVisitor { private boolean inlineMethods; @Override public void init(RootNode root) { inlineMethods = root.getArgs().isInlineMethods(); } @Override public boolean visit(ClassNode cls) throws JadxException { if (!inlineMethods) { return false; } for (MethodNode mth : cls.getMethods()) { if (canInline(mth)) { mth.add(AFlag.METHOD_CANDIDATE_FOR_INLINE); fixClassDependencies(mth); } } return true; } private static boolean canInline(MethodNode mth) { if (mth.isNoCode() || mth.contains(AFlag.DONT_GENERATE)) { return false; } AccessInfo accessFlags = mth.getAccessFlags(); boolean isSynthetic = accessFlags.isSynthetic() || mth.getName().contains("$"); return isSynthetic && canInlineMethod(mth, accessFlags); } private static boolean canInlineMethod(MethodNode mth, AccessInfo accessFlags) { if (accessFlags.isStatic()) { return true; } return mth.isConstructor() && mth.root().getArgs().isInlineAnonymousClasses(); } private static void fixClassDependencies(MethodNode mth) { ClassNode parentClass = mth.getTopParentClass(); for (MethodNode useInMth : mth.getUseIn()) { // remove possible cross dependency // to force class with inline method to be processed before its usage ClassNode useTopCls = useInMth.getTopParentClass(); if (useTopCls != parentClass) { parentClass.removeDependency(useTopCls); useTopCls.addCodegenDep(parentClass); if (Consts.DEBUG_USAGE) { parentClass.addDebugComment("Remove dependency: " + useTopCls + " to inline " + mth); useTopCls.addDebugComment("Add dependency: " + parentClass + " to inline " + mth); } } } } @Override public String getName() { return "ProcessMethodsForInline"; } }
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/MethodThrowsVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/MethodThrowsVisitor.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.Collection; 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.attributes.JadxAttrType; import jadx.api.plugins.input.data.attributes.types.ExceptionsAttr; import jadx.core.Consts; 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.MethodThrowsAttr; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.InsnType; 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.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.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.trycatch.CatchAttr; import jadx.core.dex.trycatch.ExceptionHandler; import jadx.core.dex.visitors.regions.RegionMakerVisitor; import jadx.core.dex.visitors.typeinference.TypeCompare; import jadx.core.dex.visitors.typeinference.TypeCompareEnum; import jadx.core.utils.exceptions.JadxException; @JadxVisitor( name = "MethodThrowsVisitor", desc = "Scan methods to collect thrown exceptions", runAfter = { RegionMakerVisitor.class // Run after RegionMakerVisitor to ignore throw instructions of synchronized regions } ) public class MethodThrowsVisitor extends AbstractVisitor { private enum ExceptionType { THROWS_REQUIRED, RUNTIME, UNKNOWN_TYPE, NO_EXCEPTION } private RootNode root; @Override public void init(RootNode root) throws JadxException { this.root = root; } @Override public void visit(MethodNode mth) throws JadxException { MethodThrowsAttr attr = mth.get(AType.METHOD_THROWS); if (attr == null) { attr = new MethodThrowsAttr(new HashSet<>()); mth.addAttr(attr); } if (!attr.isVisited()) { attr.setVisited(true); processInstructions(mth); } List<ArgType> invalid = new ArrayList<>(); ExceptionsAttr exceptions = mth.get(JadxAttrType.EXCEPTIONS); if (exceptions != null && !exceptions.getList().isEmpty()) { for (String throwsTypeStr : exceptions.getList()) { ArgType excType = ArgType.object(throwsTypeStr); if (validateException(excType) == ExceptionType.NO_EXCEPTION) { invalid.add(excType); } else { attr.getList().add(excType.getObject()); } } } if (!invalid.isEmpty()) { mth.addWarnComment("Byte code manipulation detected: skipped illegal throws declarations: " + invalid); } mergeExceptions(attr.getList()); } private void mergeExceptions(Set<String> excSet) { if (excSet.contains(Consts.CLASS_EXCEPTION)) { excSet.removeIf(e -> !e.equals(Consts.CLASS_EXCEPTION)); return; } if (excSet.contains(Consts.CLASS_THROWABLE)) { excSet.removeIf(e -> !e.equals(Consts.CLASS_THROWABLE)); return; } List<String> toRemove = new ArrayList<>(); for (String ex1 : excSet) { for (String ex2 : excSet) { if (ex1.equals(ex2)) { continue; } if (isBaseException(ex1, ex2)) { toRemove.add(ex1); } } } toRemove.forEach(excSet::remove); } private void processInstructions(MethodNode mth) { if (mth.isNoCode() || mth.getBasicBlocks() == null) { return; } try { blocks: for (final BlockNode block : mth.getBasicBlocks()) { // Skip e.g. throw instructions of synchronized regions boolean skipExceptions = block.contains(AFlag.REMOVE) || block.contains(AFlag.DONT_GENERATE); Set<String> excludedExceptions = new HashSet<>(); CatchAttr catchAttr = block.get(AType.EXC_CATCH); if (catchAttr != null) { for (ExceptionHandler handler : catchAttr.getHandlers()) { if (handler.isCatchAll()) { continue blocks; } excludedExceptions.add(handler.getArgType().toString()); } } for (final InsnNode insn : block.getInstructions()) { checkInsn(mth, insn, excludedExceptions, skipExceptions); } } } catch (Exception e) { mth.addWarnComment("Failed to analyze thrown exceptions", e); } } private void checkInsn(MethodNode mth, InsnNode insn, Set<String> excludedExceptions, boolean skipExceptions) throws JadxException { if (!skipExceptions && insn.getType() == InsnType.THROW && !insn.contains(AFlag.DONT_GENERATE)) { InsnArg throwArg = insn.getArg(0); if (throwArg instanceof RegisterArg) { RegisterArg regArg = (RegisterArg) throwArg; ArgType exceptionType = regArg.getType(); if (exceptionType.equals(ArgType.THROWABLE)) { InsnNode assignInsn = regArg.getAssignInsn(); if (assignInsn != null && assignInsn.getType() == InsnType.MOVE_EXCEPTION && assignInsn.getResult().contains(AFlag.CUSTOM_DECLARE)) { // arg variable is from catch statement, ignore Throwable rethrow return; } } visitThrows(mth, exceptionType, excludedExceptions); } else { if (throwArg instanceof InsnWrapArg) { InsnWrapArg insnWrapArg = (InsnWrapArg) throwArg; ArgType exceptionType = insnWrapArg.getType(); visitThrows(mth, exceptionType, excludedExceptions); } } return; } if (insn.getType() == InsnType.INVOKE) { InvokeNode invokeNode = (InvokeNode) insn; MethodInfo callMth = invokeNode.getCallMth(); String signature = callMth.makeSignature(true); ClassInfo classInfo = callMth.getDeclClass(); ClassNode classNode = root.resolveClass(classInfo); if (classNode != null) { MethodNode cMth = searchOverriddenMethod(classNode, callMth, signature); if (cMth == null) { return; } visit(cMth); MethodThrowsAttr cAttr = cMth.get(AType.METHOD_THROWS); MethodThrowsAttr attr = mth.get(AType.METHOD_THROWS); if (attr != null && cAttr != null && !cAttr.getList().isEmpty()) { attr.getList().addAll(filterExceptions(cAttr.getList(), excludedExceptions)); } } else { ClspClass clsDetails = root.getClsp().getClsDetails(classInfo.getType()); if (clsDetails != null) { ClspMethod cMth = searchOverriddenMethod(clsDetails, signature); if (cMth != null && cMth.getThrows() != null && !cMth.getThrows().isEmpty()) { MethodThrowsAttr attr = mth.get(AType.METHOD_THROWS); if (attr != null) { attr.getList().addAll(filterExceptions(cMth.getThrows(), excludedExceptions)); } } } } } } private void visitThrows(MethodNode mth, ArgType excType, Set<String> excludedExceptions) { if (excType.isTypeKnown() && isThrowsRequired(mth, excType)) { for (String excludedException : excludedExceptions) { if (isBaseException(excType.getObject(), excludedException)) { return; } } mth.get(AType.METHOD_THROWS).getList().add(excType.getObject()); } } private boolean isThrowsRequired(MethodNode mth, ArgType type) { ExceptionType result = validateException(type); if (result == ExceptionType.UNKNOWN_TYPE) { mth.addInfoComment("Thrown type has an unknown type hierarchy: " + type); return true; // assume an exception } return result == ExceptionType.THROWS_REQUIRED; } private ExceptionType validateException(ArgType clsType) { if (clsType == null || clsType.equals(ArgType.OBJECT)) { return ExceptionType.NO_EXCEPTION; } if (!clsType.isTypeKnown() || !root.getClsp().isClsKnown(clsType.getObject())) { return ExceptionType.UNKNOWN_TYPE; } if (isImplements(clsType, ArgType.RUNTIME_EXCEPTION) || isImplements(clsType, ArgType.ERROR)) { return ExceptionType.RUNTIME; } if (isImplements(clsType, ArgType.THROWABLE) || isImplements(clsType, ArgType.EXCEPTION)) { return ExceptionType.THROWS_REQUIRED; } return ExceptionType.NO_EXCEPTION; } /** * @return is 'possibleParent' an exception class of 'exception' */ private boolean isBaseException(String exception, String possibleParent) { if (exception.equals(possibleParent)) { return true; } return root.getClsp().isImplements(exception, possibleParent); } private boolean isImplements(ArgType type, ArgType baseType) { if (type.equals(baseType)) { return true; } return root.getClsp().isImplements(type.getObject(), baseType.getObject()); } private Collection<String> filterExceptions(Set<String> exceptions, Set<String> excludedExceptions) { Set<String> filteredExceptions = new HashSet<>(); for (String exception : exceptions) { boolean filtered = false; for (String excluded : excludedExceptions) { filtered = isBaseException(exception, excluded); if (filtered) { break; } } if (!filtered) { filteredExceptions.add(exception); } } return filteredExceptions; } private Collection<String> filterExceptions(Collection<ArgType> exceptionArgTypes, Set<String> excludedExceptions) { Set<String> filteredExceptions = new HashSet<>(); for (ArgType exceptionArgType : exceptionArgTypes) { boolean filtered = false; String exception = exceptionArgType.getObject(); for (String excluded : excludedExceptions) { filtered = isBaseException(exception, excluded); if (filtered) { break; } } if (!filtered) { filteredExceptions.add(exception); } } return filteredExceptions; } private @Nullable MethodNode searchOverriddenMethod(ClassNode cls, MethodInfo mth, String signature) { // search by exact full signature (with return value) to fight obfuscation (see test // 'TestOverrideWithSameName') String shortId = mth.getShortId(); for (MethodNode supMth : cls.getMethods()) { if (supMth.getMethodInfo().getShortId().equals(shortId)) { 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.getReturnType(); TypeCompareEnum res = typeCompare.compareTypes(supRetType, mthRetType); if (res.isWider()) { return supMth; } } } return null; } private ClspMethod searchOverriddenMethod(ClspClass clsDetails, String signature) { 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)) { return entry.getValue(); } } 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/InlineMethods.java
jadx-core/src/main/java/jadx/core/dex/visitors/InlineMethods.java
package jadx.core.dex.visitors; 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.attributes.AType; import jadx.core.dex.attributes.nodes.MethodInlineAttr; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.info.MethodInfo; 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.args.InsnArg; 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.IMethodDetails; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.visitors.typeinference.TypeInferenceVisitor; import jadx.core.utils.BlockUtils; import jadx.core.utils.InsnRemover; import jadx.core.utils.ListUtils; import jadx.core.utils.exceptions.JadxException; import jadx.core.utils.exceptions.JadxRuntimeException; @JadxVisitor( name = "InlineMethods", desc = "Inline methods (previously marked in MarkMethodsForInline)", runAfter = TypeInferenceVisitor.class, runBefore = ModVisitor.class ) public class InlineMethods extends AbstractVisitor { private static final Logger LOG = LoggerFactory.getLogger(InlineMethods.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.INVOKE) { processInvokeInsn(mth, block, (InvokeNode) insn); } } } } private void processInvokeInsn(MethodNode mth, BlockNode block, InvokeNode insn) { IMethodDetails callMthDetails = insn.get(AType.METHOD_DETAILS); if (!(callMthDetails instanceof MethodNode)) { return; } MethodNode callMth = (MethodNode) callMthDetails; try { MethodInlineAttr mia = MarkMethodsForInline.process(callMth); if (mia == null) { // method is not yet loaded => force process mth.addDebugComment("Class process forced to load method for inline: " + callMth); mth.root().getProcessClasses().forceProcess(callMth.getParentClass()); // run check again mia = MarkMethodsForInline.process(callMth); if (mia == null) { mth.addWarnComment("Failed to check method for inline after forced process" + callMth); return; } } if (mia.notNeeded()) { return; } inlineMethod(mth, callMth, mia, block, insn); } catch (Exception e) { throw new JadxRuntimeException("Failed to process method for inline: " + callMth, e); } } private void inlineMethod(MethodNode mth, MethodNode callMth, MethodInlineAttr mia, BlockNode block, InvokeNode insn) { InsnNode inlCopy = mia.getInsn().copyWithoutResult(); if (replaceRegs(mth, callMth, mia, insn, inlCopy)) { IMethodDetails methodDetailsAttr = inlCopy.get(AType.METHOD_DETAILS); // replaceInsn replaces the attributes as well, make sure to preserve METHOD_DETAILS if (BlockUtils.replaceInsn(mth, block, insn, inlCopy)) { if (methodDetailsAttr != null) { inlCopy.addAttr(methodDetailsAttr); } updateUsageInfo(mth, callMth, mia.getInsn()); return; } } mth.addWarnComment("Failed to inline method: " + callMth); // undo changes to insn InsnRemover.unbindInsn(mth, inlCopy); insn.rebindArgs(); } private boolean replaceRegs(MethodNode mth, MethodNode callMth, MethodInlineAttr mia, InvokeNode insn, InsnNode inlCopy) { try { if (!callMth.getMethodInfo().getArgumentsTypes().isEmpty()) { // remap args InsnArg[] regs = new InsnArg[callMth.getRegsCount()]; int[] regNums = mia.getArgsRegNums(); for (int i = 0; i < regNums.length; i++) { InsnArg arg = insn.getArg(i); regs[regNums[i]] = arg; } // replace args List<RegisterArg> inlArgs = new ArrayList<>(); inlCopy.getRegisterArgs(inlArgs); for (RegisterArg r : inlArgs) { int regNum = r.getRegNum(); if (regNum >= regs.length) { mth.addWarnComment("Unknown register number '" + r + "' in method call: " + callMth); return false; } InsnArg repl = regs[regNum]; if (repl == null) { mth.addWarnComment("Not passed register '" + r + "' in method call: " + callMth); return false; } if (!inlCopy.replaceArg(r, repl.duplicate())) { mth.addWarnComment("Failed to replace arg " + r + " for method inline: " + callMth); return false; } } } RegisterArg resultArg = insn.getResult(); if (resultArg != null) { inlCopy.setResult(resultArg.duplicate()); } else if (isAssignNeeded(mia.getInsn(), insn, callMth)) { // add a fake result to make correct java expression (see test TestGetterInlineNegative) inlCopy.setResult(mth.makeSyntheticRegArg(callMth.getReturnType(), "unused")); } return true; } catch (Exception e) { mth.addWarnComment("Method inline failed with exception", e); return false; } } private boolean isAssignNeeded(InsnNode inlineInsn, InvokeNode parentInsn, MethodNode callMthNode) { if (parentInsn.getResult() != null) { return false; } if (parentInsn.contains(AFlag.WRAPPED)) { return false; } if (inlineInsn.getType() == InsnType.IPUT) { return false; } return !callMthNode.isVoidReturn(); } private void updateUsageInfo(MethodNode mth, MethodNode inlinedMth, InsnNode insn) { inlinedMth.getUseIn().remove(mth); insn.visitInsns(innerInsn -> { // TODO: share code with UsageInfoVisitor switch (innerInsn.getType()) { case INVOKE: case CONSTRUCTOR: MethodInfo callMth = ((BaseInvokeNode) innerInsn).getCallMth(); MethodNode callMthNode = mth.root().resolveMethod(callMth); if (callMthNode != null) { callMthNode.setUseIn(ListUtils.safeReplace(callMthNode.getUseIn(), inlinedMth, mth)); replaceClsUsage(mth, inlinedMth, callMthNode.getParentClass()); } break; case IGET: case IPUT: case SPUT: case SGET: FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) innerInsn).getIndex(); FieldNode fieldNode = mth.root().resolveField(fieldInfo); if (fieldNode != null) { fieldNode.setUseIn(ListUtils.safeReplace(fieldNode.getUseIn(), inlinedMth, mth)); replaceClsUsage(mth, inlinedMth, fieldNode.getParentClass()); } break; } }); } private void replaceClsUsage(MethodNode mth, MethodNode inlinedMth, ClassNode parentClass) { parentClass.setUseInMth(ListUtils.safeReplace(parentClass.getUseInMth(), inlinedMth, mth)); parentClass.setUseIn(ListUtils.safeReplace(parentClass.getUseIn(), inlinedMth.getParentClass(), mth.getParentClass())); } }
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/FallbackModeVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/FallbackModeVisitor.java
package jadx.core.dex.visitors; import jadx.core.codegen.json.JsonMappingGen; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.trycatch.CatchAttr; import jadx.core.utils.exceptions.JadxException; public class FallbackModeVisitor extends AbstractVisitor { @Override public void init(RootNode root) { if (root.getArgs().isJsonOutput()) { JsonMappingGen.dump(root); } } @Override public void visit(MethodNode mth) throws JadxException { if (mth.isNoCode()) { return; } for (InsnNode insn : mth.getInstructions()) { if (insn == null) { continue; } // remove 'exception catch' for instruction which don't throw any exceptions CatchAttr catchAttr = insn.get(AType.EXC_CATCH); if (catchAttr != null) { switch (insn.getType()) { case RETURN: case IF: case GOTO: case JAVA_JSR: case MOVE: case MOVE_EXCEPTION: case ARITH: // ?? case NEG: case CONST: case CONST_STR: case CONST_CLASS: case CMP_L: case CMP_G: insn.remove(AType.EXC_CATCH); break; default: break; } } } } }
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/SimplifyVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/SimplifyVisitor.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.Consts; import jadx.core.codegen.TypeGen; import jadx.core.deobf.NameMapper; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.ArithNode; import jadx.core.dex.instructions.ArithOp; import jadx.core.dex.instructions.ConstStringNode; import jadx.core.dex.instructions.FilledNewArrayNode; import jadx.core.dex.instructions.IfNode; 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.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.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.regions.conditions.IfCondition; import jadx.core.dex.visitors.shrink.CodeShrinkVisitor; import jadx.core.dex.visitors.typeinference.TypeCompareEnum; import jadx.core.utils.BlockUtils; import jadx.core.utils.InsnList; import jadx.core.utils.InsnRemover; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; public class SimplifyVisitor extends AbstractVisitor { private static final Logger LOG = LoggerFactory.getLogger(SimplifyVisitor.class); private MethodInfo stringGetBytesMth; @Override public void init(RootNode root) { stringGetBytesMth = MethodInfo.fromDetails( root, ClassInfo.fromType(root, ArgType.STRING), "getBytes", Collections.emptyList(), ArgType.array(ArgType.BYTE)); } @Override public void visit(MethodNode mth) { if (mth.isNoCode()) { return; } boolean changed = false; for (BlockNode block : mth.getBasicBlocks()) { if (simplifyBlock(mth, block)) { changed = true; } } if (changed || mth.contains(AFlag.REQUEST_CODE_SHRINK)) { CodeShrinkVisitor.shrinkMethod(mth); } } private boolean simplifyBlock(MethodNode mth, BlockNode block) { boolean changed = false; List<InsnNode> list = block.getInstructions(); for (int i = 0; i < list.size(); i++) { InsnNode insn = list.get(i); int insnCount = list.size(); InsnNode modInsn = simplifyInsn(mth, insn, null); if (modInsn != null) { modInsn.rebindArgs(); if (i < list.size() && list.get(i) == insn) { list.set(i, modInsn); } else { int idx = InsnList.getIndex(list, insn); if (idx == -1) { throw new JadxRuntimeException("Failed to replace insn"); } list.set(idx, modInsn); } if (list.size() < insnCount) { // some insns removed => restart block processing simplifyBlock(mth, block); return true; } changed = true; } } return changed; } private void simplifyArgs(MethodNode mth, InsnNode insn) { boolean changed = false; for (InsnArg arg : insn.getArguments()) { if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); InsnNode replaceInsn = simplifyInsn(mth, wrapInsn, insn); if (replaceInsn != null) { arg.wrapInstruction(mth, replaceInsn, false); InsnRemover.unbindInsn(mth, wrapInsn); changed = true; } } } if (changed) { insn.rebindArgs(); mth.add(AFlag.REQUEST_CODE_SHRINK); } } private InsnNode simplifyInsn(MethodNode mth, InsnNode insn, @Nullable InsnNode parentInsn) { if (insn.contains(AFlag.DONT_GENERATE)) { return null; } simplifyArgs(mth, insn); switch (insn.getType()) { case ARITH: return simplifyArith((ArithNode) insn); case IF: simplifyIf(mth, (IfNode) insn); break; case TERNARY: simplifyTernary(mth, (TernaryInsn) insn); break; case INVOKE: return convertInvoke(mth, (InvokeNode) insn); case IPUT: case SPUT: return convertFieldArith(mth, insn); case CAST: case CHECK_CAST: return processCast(mth, (IndexInsnNode) insn, parentInsn); case MOVE: InsnArg firstArg = insn.getArg(0); if (firstArg.isLiteral()) { InsnNode constInsn = new InsnNode(InsnType.CONST, 1); constInsn.setResult(insn.getResult()); constInsn.addArg(firstArg); constInsn.copyAttributesFrom(insn); return constInsn; } break; case CONSTRUCTOR: return simplifyStringConstructor(mth, (ConstructorInsn) insn); default: break; } return null; } private InsnNode simplifyStringConstructor(MethodNode mth, ConstructorInsn insn) { if (insn.getCallMth().getDeclClass().getType().equals(ArgType.STRING) && insn.getArgsCount() != 0 && insn.getArg(0).isInsnWrap()) { InsnNode arrInsn = ((InsnWrapArg) insn.getArg(0)).getWrapInsn(); if (arrInsn.getType() == InsnType.FILLED_NEW_ARRAY && arrInsn.getArgsCount() != 0) { ArgType elemType = ((FilledNewArrayNode) arrInsn).getElemType(); if (elemType == ArgType.BYTE || elemType == ArgType.CHAR) { int printable = 0; byte[] arr = new byte[arrInsn.getArgsCount()]; for (int i = 0; i < arr.length; i++) { InsnArg arrArg = arrInsn.getArg(i); if (!arrArg.isLiteral()) { return null; } arr[i] = (byte) ((LiteralArg) arrArg).getLiteral(); if (NameMapper.isPrintableChar((char) arr[i])) { printable++; } } if (printable >= arr.length - printable) { InsnNode constStr = new ConstStringNode(new String(arr)); if (insn.getArgsCount() == 1) { constStr.setResult(insn.getResult()); constStr.copyAttributesFrom(insn); InsnRemover.unbindArgUsage(mth, insn.getArg(0)); return constStr; } else { InvokeNode in = new InvokeNode(stringGetBytesMth, InvokeType.VIRTUAL, 1); in.addArg(InsnArg.wrapArg(constStr)); InsnArg bytesArg = InsnArg.wrapArg(in); bytesArg.setType(stringGetBytesMth.getReturnType()); insn.setArg(0, bytesArg); return null; } } } } } return null; } private static InsnNode processCast(MethodNode mth, IndexInsnNode castInsn, @Nullable InsnNode parentInsn) { if (castInsn.contains(AFlag.EXPLICIT_CAST)) { return null; } InsnArg castArg = castInsn.getArg(0); ArgType argType = castArg.getType(); // Don't removes CHECK_CAST for wrapped INVOKE if invoked method returns different type if (castArg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) castArg).getWrapInsn(); if (wrapInsn.getType() == InsnType.INVOKE) { argType = ((InvokeNode) wrapInsn).getCallMth().getReturnType(); } } ArgType castToType = (ArgType) castInsn.getIndex(); if (!ArgType.isCastNeeded(mth.root(), argType, castToType) || isCastDuplicate(castInsn) || shadowedByOuterCast(mth.root(), castToType, parentInsn)) { InsnNode insnNode = new InsnNode(InsnType.MOVE, 1); insnNode.setOffset(castInsn.getOffset()); insnNode.setResult(castInsn.getResult()); insnNode.addArg(castArg); return insnNode; } return null; } private static boolean isCastDuplicate(IndexInsnNode castInsn) { InsnArg arg = castInsn.getArg(0); if (arg.isRegister()) { SSAVar sVar = ((RegisterArg) arg).getSVar(); if (sVar != null && sVar.getUseCount() == 1 && !sVar.isUsedInPhi()) { InsnNode assignInsn = sVar.getAssign().getParentInsn(); if (assignInsn != null && assignInsn.getType() == InsnType.CHECK_CAST) { ArgType assignCastType = (ArgType) ((IndexInsnNode) assignInsn).getIndex(); return assignCastType.equals(castInsn.getIndex()); } } } return false; } private static boolean shadowedByOuterCast(RootNode root, ArgType castType, @Nullable InsnNode parentInsn) { if (parentInsn != null && parentInsn.getType() == InsnType.CAST) { ArgType parentCastType = (ArgType) ((IndexInsnNode) parentInsn).getIndex(); TypeCompareEnum result = root.getTypeCompare().compareTypes(parentCastType, castType); return result.isNarrow(); } return false; } /** * Simplify 'cmp' instruction in if condition */ private static void simplifyIf(MethodNode mth, IfNode insn) { InsnArg f = insn.getArg(0); if (f.isInsnWrap()) { InsnNode wi = ((InsnWrapArg) f).getWrapInsn(); if (wi.getType() == InsnType.CMP_L || wi.getType() == InsnType.CMP_G) { if (insn.getArg(1).isZeroLiteral()) { insn.changeCondition(insn.getOp(), wi.getArg(0).duplicate(), wi.getArg(1).duplicate()); InsnRemover.unbindInsn(mth, wi); } else { LOG.warn("TODO: cmp {}", insn); } } } } /** * Simplify condition in ternary operation */ private static void simplifyTernary(MethodNode mth, TernaryInsn insn) { IfCondition condition = insn.getCondition(); if (condition.isCompare()) { simplifyIf(mth, condition.getCompare().getInsn()); } else { insn.simplifyCondition(); } } /** * Simplify chains of calls to StringBuilder#append() plus constructor of StringBuilder. * Those chains are usually automatically generated by the Java compiler when you create String * concatenations like <code>"text " + 1 + " text"</code>. */ private static InsnNode convertInvoke(MethodNode mth, InvokeNode insn) { MethodInfo callMth = insn.getCallMth(); if (callMth.getDeclClass().getFullName().equals(Consts.CLASS_STRING_BUILDER) && callMth.getShortId().equals(Consts.MTH_TOSTRING_SIGNATURE)) { InsnArg instanceArg = insn.getArg(0); if (instanceArg.isInsnWrap()) { // Convert 'new StringBuilder(xxx).append(yyy).append(zzz).toString() to STRING_CONCAT insn List<InsnNode> callChain = flattenInsnChainUntil(insn, InsnType.CONSTRUCTOR); return convertStringBuilderChain(mth, insn, callChain); } if (instanceArg.isRegister()) { // Convert 'StringBuilder sb = new StringBuilder(xxx); sb.append(yyy); String str = sb.toString();' List<InsnNode> useChain = collectUseChain(mth, insn, (RegisterArg) instanceArg); return convertStringBuilderChain(mth, insn, useChain); } } return null; } private static List<InsnNode> collectUseChain(MethodNode mth, InvokeNode insn, RegisterArg instanceArg) { SSAVar sVar = instanceArg.getSVar(); if (sVar.isUsedInPhi() || sVar.getUseCount() == 0) { return Collections.emptyList(); } List<InsnNode> useChain = new ArrayList<>(sVar.getUseCount() + 1); InsnNode assignInsn = sVar.getAssign().getParentInsn(); if (assignInsn == null) { return Collections.emptyList(); } useChain.add(assignInsn); for (RegisterArg reg : sVar.getUseList()) { InsnNode parentInsn = reg.getParentInsn(); if (parentInsn == null) { return Collections.emptyList(); } useChain.add(parentInsn); } int toStrIdx = InsnList.getIndex(useChain, insn); if (useChain.size() - 1 != toStrIdx) { return Collections.emptyList(); } useChain.remove(toStrIdx); // all insns must be in one block and sequential BlockNode assignBlock = BlockUtils.getBlockByInsn(mth, assignInsn); if (assignBlock == null) { return Collections.emptyList(); } List<InsnNode> blockInsns = assignBlock.getInstructions(); int assignIdx = InsnList.getIndex(blockInsns, assignInsn); int chainSize = useChain.size(); int lastInsn = blockInsns.size() - assignIdx; if (lastInsn < chainSize) { return Collections.emptyList(); } for (int i = 1; i < chainSize; i++) { if (blockInsns.get(assignIdx + i) != useChain.get(i)) { return Collections.emptyList(); } } return useChain; } private static InsnNode convertStringBuilderChain(MethodNode mth, InvokeNode toStrInsn, List<InsnNode> chain) { try { int chainSize = chain.size(); if (chainSize < 2) { return null; } List<InsnArg> args = new ArrayList<>(chainSize); InsnNode firstInsn = chain.get(0); if (firstInsn.getType() != InsnType.CONSTRUCTOR) { return null; } ConstructorInsn constrInsn = (ConstructorInsn) firstInsn; if (constrInsn.getArgsCount() == 1) { ArgType argType = constrInsn.getCallMth().getArgumentsTypes().get(0); if (!argType.isObject()) { return null; } args.add(constrInsn.getArg(0)); } for (int i = 1; i < chainSize; i++) { InsnNode chainInsn = chain.get(i); InsnArg arg = getArgFromAppend(chainInsn); if (arg == null) { return null; } args.add(arg); } boolean stringArgFound = false; for (InsnArg arg : args) { if (arg.getType().equals(ArgType.STRING)) { stringArgFound = true; break; } } if (!stringArgFound) { String argStr = Utils.listToString(args, InsnArg::toShortString); mth.addDebugComment("TODO: convert one arg to string using `String.valueOf()`, args: " + argStr); return null; } // all check passed List<InsnArg> dupArgs = Utils.collectionMap(args, InsnArg::duplicate); List<InsnArg> simplifiedArgs = concatConstArgs(dupArgs); InsnNode concatInsn = new InsnNode(InsnType.STR_CONCAT, simplifiedArgs); concatInsn.add(AFlag.SYNTHETIC); if (toStrInsn.getResult() == null && !toStrInsn.contains(AFlag.WRAPPED)) { // string concat without assign to variable will cause compilation error concatInsn.setResult(mth.makeSyntheticRegArg(ArgType.STRING)); } else { concatInsn.setResult(toStrInsn.getResult()); } concatInsn.copyAttributesFrom(toStrInsn); removeStringBuilderInsns(mth, toStrInsn, chain); return concatInsn; } catch (Exception e) { mth.addWarnComment("String concatenation convert failed", e); } return null; } private static boolean isConstConcatNeeded(List<InsnArg> args) { boolean prevConst = false; for (InsnArg arg : args) { boolean curConst = arg.isConst(); if (curConst && prevConst) { // found 2 consecutive constants return true; } prevConst = curConst; } return false; } private static List<InsnArg> concatConstArgs(List<InsnArg> args) { if (!isConstConcatNeeded(args)) { return args; } int size = args.size(); List<InsnArg> newArgs = new ArrayList<>(size); List<String> concatList = new ArrayList<>(size); for (int i = 0; i < size; i++) { InsnArg arg = args.get(i); String constStr = getConstString(arg); if (constStr != null) { concatList.add(constStr); } else { if (!concatList.isEmpty()) { newArgs.add(getConcatArg(concatList, args, i)); concatList.clear(); } newArgs.add(arg); } } if (!concatList.isEmpty()) { newArgs.add(getConcatArg(concatList, args, size)); } return newArgs; } private static InsnArg getConcatArg(List<String> concatList, List<InsnArg> args, int idx) { if (concatList.size() == 1) { return args.get(idx - 1); } String str = Utils.concatStrings(concatList); return InsnArg.wrapArg(new ConstStringNode(str)); } @Nullable private static String getConstString(InsnArg arg) { if (arg.isLiteral()) { return TypeGen.literalToRawString((LiteralArg) arg); } if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); if (wrapInsn instanceof ConstStringNode) { return ((ConstStringNode) wrapInsn).getString(); } } return null; } /** * Remove and unbind all instructions with StringBuilder */ private static void removeStringBuilderInsns(MethodNode mth, InvokeNode toStrInsn, List<InsnNode> chain) { InsnRemover.unbindAllArgs(mth, toStrInsn); for (InsnNode insnNode : chain) { InsnRemover.unbindAllArgs(mth, insnNode); } InsnRemover insnRemover = new InsnRemover(mth); for (InsnNode insnNode : chain) { if (insnNode != toStrInsn) { insnRemover.addAndUnbind(insnNode); } } insnRemover.perform(); } private static List<InsnNode> flattenInsnChainUntil(InsnNode insn, InsnType insnType) { List<InsnNode> chain = new ArrayList<>(); InsnArg arg = insn.getArg(0); while (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); chain.add(wrapInsn); if (wrapInsn.getType() == insnType || wrapInsn.getArgsCount() == 0) { break; } arg = wrapInsn.getArg(0); } Collections.reverse(chain); return chain; } private static InsnArg getArgFromAppend(InsnNode chainInsn) { if (chainInsn.getType() == InsnType.INVOKE && chainInsn.getArgsCount() == 2) { MethodInfo callMth = ((InvokeNode) chainInsn).getCallMth(); if (callMth.getDeclClass().getFullName().equals(Consts.CLASS_STRING_BUILDER) && callMth.getName().equals("append")) { return chainInsn.getArg(1); } } return null; } private static InsnNode simplifyArith(ArithNode arith) { if (arith.getArgsCount() != 2) { return null; } LiteralArg litArg = null; InsnArg secondArg = arith.getArg(1); if (secondArg.isInsnWrap()) { InsnNode wr = ((InsnWrapArg) secondArg).getWrapInsn(); if (wr.getType() == InsnType.CONST) { InsnArg arg = wr.getArg(0); if (arg.isLiteral()) { litArg = (LiteralArg) arg; } } } else if (secondArg.isLiteral()) { litArg = (LiteralArg) secondArg; } if (litArg == null) { return null; } switch (arith.getOp()) { case ADD: // fix 'c + (-1)' to 'c - (1)' if (litArg.isNegative()) { LiteralArg negLitArg = litArg.negate(); if (negLitArg != null) { return new ArithNode(ArithOp.SUB, arith.getResult(), arith.getArg(0), negLitArg); } } break; case XOR: // simplify xor on boolean InsnArg firstArg = arith.getArg(0); long lit = litArg.getLiteral(); if (firstArg.getType() == ArgType.BOOLEAN && (lit == 0 || lit == 1)) { InsnNode node = new InsnNode(lit == 0 ? InsnType.MOVE : InsnType.NOT, 1); node.setResult(arith.getResult()); node.addArg(firstArg); return node; } break; } return null; } /** * Convert field arith operation to arith instruction * (IPUT (ARITH (IGET, lit)) -> ARITH ((IGET)) <op>= lit)) */ private static ArithNode convertFieldArith(MethodNode mth, InsnNode insn) { InsnArg arg = insn.getArg(0); if (!arg.isInsnWrap()) { return null; } InsnNode wrap = ((InsnWrapArg) arg).getWrapInsn(); InsnType wrapType = wrap.getType(); if (wrapType != InsnType.ARITH && wrapType != InsnType.STR_CONCAT || !wrap.getArg(0).isInsnWrap()) { return null; } InsnArg getWrap = wrap.getArg(0); InsnNode get = ((InsnWrapArg) getWrap).getWrapInsn(); InsnType getType = get.getType(); if (getType != InsnType.IGET && getType != InsnType.SGET) { return null; } FieldInfo field = (FieldInfo) ((IndexInsnNode) insn).getIndex(); FieldInfo innerField = (FieldInfo) ((IndexInsnNode) get).getIndex(); if (!field.equals(innerField)) { return null; } try { if (getType == InsnType.IGET && insn.getType() == InsnType.IPUT) { InsnArg reg = get.getArg(0); InsnArg putReg = insn.getArg(1); if (!reg.equals(putReg)) { return null; } } InsnArg fArg = getWrap.duplicate(); InsnRemover.unbindInsn(mth, get); if (insn.getType() == InsnType.IPUT) { InsnRemover.unbindArgUsage(mth, insn.getArg(1)); } if (wrapType == InsnType.ARITH) { ArithNode ar = (ArithNode) wrap; return ArithNode.oneArgOp(ar.getOp(), fArg, ar.getArg(1)); } int argsCount = wrap.getArgsCount(); InsnNode concat = new InsnNode(InsnType.STR_CONCAT, argsCount - 1); for (int i = 1; i < argsCount; i++) { concat.addArg(wrap.getArg(i)); } InsnArg concatArg = InsnArg.wrapArg(concat); concatArg.setType(ArgType.STRING); return ArithNode.oneArgOp(ArithOp.ADD, fArg, concatArg); } catch (Exception e) { LOG.debug("Can't convert field arith insn: {}, mth: {}", insn, mth, e); } 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/AbstractVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/AbstractVisitor.java
package jadx.core.dex.visitors; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.exceptions.JadxException; public abstract class AbstractVisitor implements IDexTreeVisitor { @Override public void init(RootNode root) throws JadxException { // no op implementation } @Override public boolean visit(ClassNode cls) throws JadxException { // no op implementation return true; } @Override public void visit(MethodNode mth) throws JadxException { // no op implementation } @Override public String getName() { return this.getClass().getSimpleName(); } @Override public String toString() { return getName(); } }
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/ConstInlineVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/ConstInlineVisitor.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.List; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.BaseInvokeNode; 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.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.ConstructorInsn; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.IFieldInfoRef; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.visitors.finaly.MarkFinallyVisitor; import jadx.core.dex.visitors.ssa.SSATransform; import jadx.core.dex.visitors.typeinference.TypeInferenceVisitor; import jadx.core.utils.InsnRemover; import jadx.core.utils.exceptions.JadxException; import jadx.core.utils.exceptions.JadxRuntimeException; @JadxVisitor( name = "Constants Inline", desc = "Inline constant registers into instructions", runAfter = { SSATransform.class, MarkFinallyVisitor.class }, runBefore = TypeInferenceVisitor.class ) public class ConstInlineVisitor extends AbstractVisitor { @Override public void visit(MethodNode mth) throws JadxException { if (mth.isNoCode()) { return; } process(mth); } public static void process(MethodNode mth) { List<InsnNode> toRemove = new ArrayList<>(); for (BlockNode block : mth.getBasicBlocks()) { toRemove.clear(); for (InsnNode insn : block.getInstructions()) { checkInsn(mth, insn, toRemove); } InsnRemover.removeAllAndUnbind(mth, block, toRemove); } } private static void checkInsn(MethodNode mth, InsnNode insn, List<InsnNode> toRemove) { if (insn.contains(AFlag.DONT_INLINE) || insn.contains(AFlag.DONT_GENERATE) || insn.getResult() == null) { return; } SSAVar sVar = insn.getResult().getSVar(); InsnArg constArg; Runnable onSuccess = null; switch (insn.getType()) { case CONST: case MOVE: { constArg = insn.getArg(0); if (!constArg.isLiteral()) { return; } if (constArg.isZeroLiteral() && forbidNullInlines(sVar)) { // all usages forbids inlining return; } break; } case CONST_STR: { String s = ((ConstStringNode) insn).getString(); IFieldInfoRef f = mth.getParentClass().getConstField(s); if (f == null) { InsnNode copy = insn.copyWithoutResult(); constArg = InsnArg.wrapArg(copy); } else { InsnNode constGet = new IndexInsnNode(InsnType.SGET, f.getFieldInfo(), 0); constArg = InsnArg.wrapArg(constGet); constArg.setType(ArgType.STRING); onSuccess = () -> ModVisitor.addFieldUsage(f, mth); } break; } case CONST_CLASS: { if (sVar.isUsedInPhi()) { return; } constArg = InsnArg.wrapArg(insn.copyWithoutResult()); constArg.setType(ArgType.CLASS); break; } default: return; } // all check passed, run replace if (replaceConst(mth, insn, constArg)) { toRemove.add(insn); if (onSuccess != null) { onSuccess.run(); } } } /** * Don't inline null object */ private static boolean forbidNullInlines(SSAVar sVar) { List<RegisterArg> useList = sVar.getUseList(); if (useList.isEmpty()) { return false; } int k = 0; for (RegisterArg useArg : useList) { InsnNode insn = useArg.getParentInsn(); if (insn != null && forbidNullArgInline(insn, useArg)) { k++; } } return k == useList.size(); } private static boolean forbidNullArgInline(InsnNode insn, RegisterArg useArg) { if (insn.getType() == InsnType.MOVE) { // result is null, chain checks return forbidNullInlines(insn.getResult().getSVar()); } if (!canUseNull(insn, useArg)) { useArg.add(AFlag.DONT_INLINE_CONST); return true; } return false; } private static boolean canUseNull(InsnNode insn, RegisterArg useArg) { switch (insn.getType()) { case INVOKE: return ((InvokeNode) insn).getInstanceArg() != useArg; case ARRAY_LENGTH: case AGET: case APUT: case IGET: case SWITCH: case MONITOR_ENTER: case MONITOR_EXIT: case INSTANCE_OF: return insn.getArg(0) != useArg; case IPUT: return insn.getArg(1) != useArg; } return true; } private static boolean replaceConst(MethodNode mth, InsnNode constInsn, InsnArg constArg) { SSAVar ssaVar = constInsn.getResult().getSVar(); if (ssaVar.getUseCount() == 0) { return true; } List<RegisterArg> useList = new ArrayList<>(ssaVar.getUseList()); int replaceCount = 0; for (RegisterArg arg : useList) { if (canInline(mth, arg) && replaceArg(mth, arg, constArg, constInsn)) { replaceCount++; } } if (replaceCount == useList.size()) { return true; } // hide insn if used only in not generated insns if (ssaVar.getUseList().stream().allMatch(ConstInlineVisitor::canIgnoreInsn)) { constInsn.add(AFlag.DONT_GENERATE); } return false; } private static boolean canIgnoreInsn(RegisterArg reg) { InsnNode parentInsn = reg.getParentInsn(); if (parentInsn == null || parentInsn.getType() == InsnType.PHI) { return false; } if (reg.isLinkedToOtherSsaVars()) { return false; } return parentInsn.contains(AFlag.DONT_GENERATE); } @SuppressWarnings("RedundantIfStatement") private static boolean canInline(MethodNode mth, RegisterArg arg) { if (arg.contains(AFlag.DONT_INLINE_CONST) || arg.contains(AFlag.DONT_INLINE)) { return false; } InsnNode parentInsn = arg.getParentInsn(); if (parentInsn == null) { return false; } if (parentInsn.contains(AFlag.DONT_GENERATE)) { return false; } if (arg.isLinkedToOtherSsaVars() && !arg.getSVar().isUsedInPhi()) { // don't inline vars used in finally block return false; } if (parentInsn.getType() == InsnType.CONSTRUCTOR) { // don't inline into anonymous call if it can be inlined later MethodNode ctrMth = mth.root().getMethodUtils().resolveMethod((ConstructorInsn) parentInsn); if (ctrMth != null && (ctrMth.contains(AFlag.METHOD_CANDIDATE_FOR_INLINE) || ctrMth.contains(AFlag.ANONYMOUS_CONSTRUCTOR))) { return false; } } return true; } private static boolean replaceArg(MethodNode mth, RegisterArg arg, InsnArg constArg, InsnNode constInsn) { InsnNode useInsn = arg.getParentInsn(); if (useInsn == null) { return false; } InsnType insnType = useInsn.getType(); if (insnType == InsnType.PHI) { return false; } if (constArg.isLiteral()) { long literal = ((LiteralArg) constArg).getLiteral(); ArgType argType = arg.getType(); if (argType == ArgType.UNKNOWN) { argType = arg.getInitType(); } if (argType.isObject() && literal != 0) { argType = ArgType.NARROW_NUMBERS; } LiteralArg litArg = InsnArg.lit(literal, argType); litArg.copyAttributesFrom(constArg); if (!useInsn.replaceArg(arg, litArg)) { return false; } // arg replaced, made some optimizations IFieldInfoRef fieldNode = null; ArgType litArgType = litArg.getType(); if (litArgType.isTypeKnown()) { fieldNode = mth.getParentClass().getConstFieldByLiteralArg(litArg); } else if (litArgType.contains(PrimitiveType.INT)) { fieldNode = mth.getParentClass().getConstField((int) literal, false); } if (fieldNode != null) { IndexInsnNode sgetInsn = new IndexInsnNode(InsnType.SGET, fieldNode.getFieldInfo(), 0); if (litArg.wrapInstruction(mth, sgetInsn) != null) { ModVisitor.addFieldUsage(fieldNode, mth); } } else { addExplicitCast(useInsn, litArg); } } else { if (!useInsn.replaceArg(arg, constArg.duplicate())) { return false; } } useInsn.inheritMetadata(constInsn); return true; } private static void addExplicitCast(InsnNode insn, LiteralArg arg) { if (insn instanceof BaseInvokeNode) { BaseInvokeNode callInsn = (BaseInvokeNode) insn; MethodInfo callMth = callInsn.getCallMth(); if (callInsn.getInstanceArg() == arg) { // instance arg is null, force cast if (!arg.isZeroLiteral()) { throw new JadxRuntimeException("Unexpected instance arg in invoke"); } ArgType castType = callMth.getDeclClass().getType(); InsnNode castInsn = new IndexInsnNode(InsnType.CAST, castType, 1); castInsn.addArg(arg); castInsn.add(AFlag.EXPLICIT_CAST); InsnArg wrapCast = InsnArg.wrapArg(castInsn); wrapCast.setType(castType); insn.replaceArg(arg, wrapCast); } else { int offset = callInsn.getFirstArgOffset(); int argIndex = insn.getArgIndex(arg); ArgType argType = callMth.getArgumentsTypes().get(argIndex - offset); if (argType.isPrimitive()) { arg.setType(argType); if (argType.equals(ArgType.BYTE)) { arg.add(AFlag.EXPLICIT_PRIMITIVE_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/PrepareForCodeGen.java
jadx-core/src/main/java/jadx/core/dex/visitors/PrepareForCodeGen.java
package jadx.core.dex.visitors; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.IFieldRef; 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.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.AttrNode; import jadx.core.dex.attributes.nodes.DeclareVariablesAttr; import jadx.core.dex.attributes.nodes.LineAttrNode; import jadx.core.dex.info.FieldInfo; 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.InvokeNode; 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.mods.ConstructorInsn; import jadx.core.dex.instructions.mods.TernaryInsn; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.InsnContainer; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.regions.conditions.IfCondition; import jadx.core.dex.regions.conditions.IfCondition.Mode; import jadx.core.dex.visitors.regions.variables.ProcessVariables; import jadx.core.dex.visitors.shrink.CodeShrinkVisitor; import jadx.core.utils.BlockUtils; import jadx.core.utils.InsnList; import jadx.core.utils.exceptions.JadxException; /** * Prepare instructions for code generation pass, * most of this modification breaks register dependencies, * so this pass must be just before CodeGen. */ @JadxVisitor( name = "PrepareForCodeGen", desc = "Prepare instructions for code generation pass", runAfter = { CodeShrinkVisitor.class, ClassModifier.class, ProcessVariables.class } ) public class PrepareForCodeGen extends AbstractVisitor { @Override public String getName() { return "PrepareForCodeGen"; } @Override public boolean visit(ClassNode cls) throws JadxException { if (cls.root().getArgs().isDebugInfo()) { setClassSourceLine(cls); } collectFieldsUsageInAnnotations(cls); return true; } @Override public void visit(MethodNode mth) throws JadxException { if (mth.isNoCode()) { return; } for (BlockNode block : mth.getBasicBlocks()) { if (block.contains(AFlag.DONT_GENERATE)) { continue; } removeInstructions(block); checkInline(block); removeParenthesis(block); modifyArith(block); checkConstUsage(block); addNullCasts(mth, block); } moveConstructorInConstructor(mth); collectFieldsUsageInAnnotations(mth, mth); } private static void removeInstructions(BlockNode block) { Iterator<InsnNode> it = block.getInstructions().iterator(); while (it.hasNext()) { InsnNode insn = it.next(); switch (insn.getType()) { case NOP: case MONITOR_ENTER: case MONITOR_EXIT: case MOVE_EXCEPTION: it.remove(); break; case CONSTRUCTOR: ConstructorInsn co = (ConstructorInsn) insn; if (co.isSelf()) { it.remove(); } break; case MOVE: // remove redundant moves: unused result and same args names (a = a;) RegisterArg result = insn.getResult(); if (result.getSVar().getUseCount() == 0 && result.isNameEquals(insn.getArg(0))) { it.remove(); } break; default: break; } } } private static void checkInline(BlockNode block) { List<InsnNode> list = block.getInstructions(); for (int i = 0; i < list.size(); i++) { InsnNode insn = list.get(i); // replace 'move' with inner wrapped instruction if (insn.getType() == InsnType.MOVE && insn.getArg(0).isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) insn.getArg(0)).getWrapInsn(); wrapInsn.setResult(insn.getResult()); wrapInsn.copyAttributesFrom(insn); list.set(i, wrapInsn); } } } /** * Add explicit type for non int constants */ private static void checkConstUsage(BlockNode block) { for (InsnNode blockInsn : block.getInstructions()) { blockInsn.visitInsns(insn -> { if (forbidExplicitType(insn.getType())) { return; } for (InsnArg arg : insn.getArguments()) { if (arg.isLiteral() && arg.getType() != ArgType.INT) { arg.add(AFlag.EXPLICIT_PRIMITIVE_TYPE); } } }); } } private static boolean forbidExplicitType(InsnType type) { switch (type) { case CONST: case CAST: case IF: case FILLED_NEW_ARRAY: case APUT: case ARITH: return true; default: return false; } } private static void removeParenthesis(BlockNode block) { for (InsnNode insn : block.getInstructions()) { removeParenthesis(insn); } } /** * Remove parenthesis for wrapped insn in arith '+' or '-' * ('(a + b) +c' => 'a + b + c') */ private static void removeParenthesis(InsnNode insn) { if (insn.getType() == InsnType.ARITH) { ArithNode arith = (ArithNode) insn; ArithOp op = arith.getOp(); if (op == ArithOp.ADD || op == ArithOp.MUL || op == ArithOp.AND || op == ArithOp.OR) { for (int i = 0; i < 2; i++) { InsnArg arg = arith.getArg(i); if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); if (wrapInsn.getType() == InsnType.ARITH && ((ArithNode) wrapInsn).getOp() == op) { wrapInsn.add(AFlag.DONT_WRAP); } removeParenthesis(wrapInsn); } } } } else { if (insn.getType() == InsnType.TERNARY) { removeParenthesis(((TernaryInsn) insn).getCondition()); } for (InsnArg arg : insn.getArguments()) { if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); removeParenthesis(wrapInsn); } } } } private static void removeParenthesis(IfCondition cond) { Mode mode = cond.getMode(); for (IfCondition c : cond.getArgs()) { if (c.getMode() == mode) { c.add(AFlag.DONT_WRAP); } } } /** * Replace arithmetic operation with short form * ('a = a + 2' => 'a += 2') */ private static void modifyArith(BlockNode block) { List<InsnNode> list = block.getInstructions(); for (InsnNode insn : list) { if (insn.getType() == InsnType.ARITH && !insn.contains(AFlag.ARITH_ONEARG) && !insn.contains(AFlag.DECLARE_VAR)) { RegisterArg res = insn.getResult(); InsnArg arg = insn.getArg(0); boolean replace = false; if (res.equals(arg)) { replace = true; } else if (arg.isRegister()) { RegisterArg regArg = (RegisterArg) arg; replace = res.sameCodeVar(regArg); } if (replace) { insn.setResult(null); insn.add(AFlag.ARITH_ONEARG); } } } } /** * Check that 'super' or 'this' call in constructor is a first instruction. * Otherwise, move to the top and add a warning. */ private void moveConstructorInConstructor(MethodNode mth) { if (!mth.isConstructor()) { return; } ConstructorInsn ctrInsn = searchConstructorCall(mth); if (ctrInsn == null || ctrInsn.contains(AFlag.DONT_GENERATE)) { return; } boolean firstInsn = BlockUtils.isFirstInsn(mth, ctrInsn); DeclareVariablesAttr declVarsAttr = mth.getRegion().get(AType.DECLARE_VARIABLES); if (firstInsn && declVarsAttr == null) { // move not needed return; } String callType = ctrInsn.getCallType().toString().toLowerCase(); BlockNode blockByInsn = BlockUtils.getBlockByInsn(mth, ctrInsn); if (blockByInsn == null) { mth.addWarn("Failed to move " + callType + " instruction to top"); return; } if (!firstInsn) { Set<RegisterArg> regArgs = new HashSet<>(); ctrInsn.getRegisterArgs(regArgs); regArgs.remove(mth.getThisArg()); mth.getArgRegs().forEach(regArgs::remove); if (!regArgs.isEmpty()) { mth.addWarnComment("Illegal instructions before constructor call"); return; } mth.addWarnComment("'" + callType + "' call moved to the top of the method (can break code semantics)"); } // move confirmed InsnList.remove(blockByInsn, ctrInsn); mth.getRegion().getSubBlocks().add(0, new InsnContainer(ctrInsn)); } private @Nullable ConstructorInsn searchConstructorCall(MethodNode mth) { for (BlockNode block : mth.getBasicBlocks()) { for (InsnNode insn : block.getInstructions()) { if (insn.getType() == InsnType.CONSTRUCTOR) { ConstructorInsn ctrInsn = (ConstructorInsn) insn; if (ctrInsn.isSuper() || ctrInsn.isThis()) { return ctrInsn; } return null; } } } return null; } /** * Use source line from top method */ private void setClassSourceLine(ClassNode cls) { for (ClassNode innerClass : cls.getInnerClasses()) { setClassSourceLine(innerClass); } int minLine = Stream.of(cls.getMethods(), cls.getInnerClasses(), cls.getFields()) .flatMap(Collection::stream) .filter(mth -> !mth.contains(AFlag.DONT_GENERATE)) .filter(mth -> mth.getSourceLine() != 0) .mapToInt(LineAttrNode::getSourceLine) .min() .orElse(0); if (minLine != 0) { cls.setSourceLine(minLine - 1); } } private void collectFieldsUsageInAnnotations(ClassNode cls) { MethodNode useMth = cls.getDefaultConstructor(); if (useMth == null && !cls.getMethods().isEmpty()) { useMth = cls.getMethods().get(0); } if (useMth == null) { return; } collectFieldsUsageInAnnotations(useMth, cls); MethodNode finalUseMth = useMth; cls.getFields().forEach(f -> collectFieldsUsageInAnnotations(finalUseMth, f)); } private void collectFieldsUsageInAnnotations(MethodNode mth, AttrNode attrNode) { AnnotationsAttr annotationsList = attrNode.get(JadxAttrType.ANNOTATION_LIST); if (annotationsList == null) { return; } for (IAnnotation annotation : annotationsList.getAll()) { if (annotation.getVisibility() == AnnotationVisibility.SYSTEM) { continue; } for (Map.Entry<String, EncodedValue> entry : annotation.getValues().entrySet()) { checkEncodedValue(mth, entry.getValue()); } } } @SuppressWarnings("unchecked") private void checkEncodedValue(MethodNode mth, EncodedValue encodedValue) { switch (encodedValue.getType()) { case ENCODED_FIELD: Object fieldData = encodedValue.getValue(); FieldInfo fieldInfo; if (fieldData instanceof IFieldRef) { fieldInfo = FieldInfo.fromRef(mth.root(), (IFieldRef) fieldData); } else { fieldInfo = (FieldInfo) fieldData; } FieldNode fieldNode = mth.root().resolveField(fieldInfo); if (fieldNode != null) { fieldNode.addUseIn(mth); } break; case ENCODED_ANNOTATION: IAnnotation annotation = (IAnnotation) encodedValue.getValue(); annotation.getValues().forEach((k, v) -> checkEncodedValue(mth, v)); break; case ENCODED_ARRAY: List<EncodedValue> valueList = (List<EncodedValue>) encodedValue.getValue(); valueList.forEach(v -> checkEncodedValue(mth, v)); break; } } private void addNullCasts(MethodNode mth, BlockNode block) { for (InsnNode insn : block.getInstructions()) { switch (insn.getType()) { case INVOKE: verifyNullCast(mth, ((InvokeNode) insn).getInstanceArg()); break; case ARRAY_LENGTH: verifyNullCast(mth, insn.getArg(0)); break; } } } private void verifyNullCast(MethodNode mth, InsnArg arg) { if (arg != null && arg.isZeroConst()) { ArgType castType = arg.getType(); IndexInsnNode castInsn = new IndexInsnNode(InsnType.CAST, castType, 1); castInsn.addArg(InsnArg.lit(0, castType)); arg.wrapInstruction(mth, castInsn); } } }
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/JadxVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/JadxVisitor.java
package jadx.core.dex.visitors; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation for describe dependencies of jadx visitors */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface JadxVisitor { /** * Visitor short name (identifier) */ String name(); /** * Detailed visitor description */ String desc() default ""; /** * This visitor must be run <b>after</b> listed visitors */ Class<? extends IDexTreeVisitor>[] runAfter() default {}; /** * This visitor must be run <b>before</b> listed visitors */ Class<? extends IDexTreeVisitor>[] runBefore() default {}; }
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/AnonymousClassVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/AnonymousClassVisitor.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; 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.SkipMethodArgsAttr; 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.args.InsnArg; 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.FieldNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.visitors.shrink.CodeShrinkVisitor; import jadx.core.utils.exceptions.JadxException; @JadxVisitor( name = "AnonymousClassVisitor", desc = "Prepare anonymous class for inline", runBefore = { ModVisitor.class, CodeShrinkVisitor.class } ) public class AnonymousClassVisitor extends AbstractVisitor { @Override public boolean visit(ClassNode cls) throws JadxException { if (cls.contains(AType.ANONYMOUS_CLASS)) { for (MethodNode mth : cls.getMethods()) { if (mth.contains(AFlag.ANONYMOUS_CONSTRUCTOR)) { processAnonymousConstructor(mth); break; } } } return true; } private static void processAnonymousConstructor(MethodNode mth) { List<InsnNode> usedInsns = new ArrayList<>(); Map<InsnArg, FieldNode> argsMap = getArgsToFieldsMapping(mth, usedInsns); if (argsMap.isEmpty()) { mth.add(AFlag.NO_SKIP_ARGS); } else { for (Map.Entry<InsnArg, FieldNode> entry : argsMap.entrySet()) { FieldNode field = entry.getValue(); if (field == null) { continue; } InsnArg arg = entry.getKey(); field.addAttr(new FieldReplaceAttr(arg)); field.add(AFlag.DONT_GENERATE); if (arg.isRegister()) { arg.add(AFlag.SKIP_ARG); SkipMethodArgsAttr.skipArg(mth, ((RegisterArg) arg)); } } } for (InsnNode usedInsn : usedInsns) { usedInsn.add(AFlag.DONT_GENERATE); } } private static Map<InsnArg, FieldNode> getArgsToFieldsMapping(MethodNode mth, List<InsnNode> usedInsns) { MethodInfo callMth = mth.getMethodInfo(); ClassNode cls = mth.getParentClass(); List<RegisterArg> argList = mth.getArgRegs(); ClassNode outerCls = mth.getUseIn().get(0).getParentClass(); int startArg = 0; if (callMth.getArgsCount() != 0 && callMth.getArgumentsTypes().get(0).equals(outerCls.getClassInfo().getType())) { startArg = 1; } Map<InsnArg, FieldNode> map = new LinkedHashMap<>(); int argsCount = argList.size(); for (int i = startArg; i < argsCount; i++) { RegisterArg arg = argList.get(i); InsnNode useInsn = getParentInsnSkipMove(arg); if (useInsn == null) { return Collections.emptyMap(); } switch (useInsn.getType()) { case IPUT: FieldNode fieldNode = cls.searchField((FieldInfo) ((IndexInsnNode) useInsn).getIndex()); if (fieldNode == null || !fieldNode.getAccessFlags().isSynthetic()) { return Collections.emptyMap(); } map.put(arg, fieldNode); usedInsns.add(useInsn); break; case CONSTRUCTOR: ConstructorInsn superConstr = (ConstructorInsn) useInsn; if (!superConstr.isSuper()) { return Collections.emptyMap(); } usedInsns.add(useInsn); break; default: return Collections.emptyMap(); } } return map; } private static InsnNode getParentInsnSkipMove(RegisterArg arg) { SSAVar sVar = arg.getSVar(); if (sVar.getUseCount() != 1) { return null; } RegisterArg useArg = sVar.getUseList().get(0); InsnNode parentInsn = useArg.getParentInsn(); if (parentInsn == null) { return null; } if (parentInsn.getType() == InsnType.MOVE) { return getParentInsnSkipMove(parentInsn.getResult()); } return parentInsn; } }
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/DotGraphVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/DotGraphVisitor.java
package jadx.core.dex.visitors; import java.io.File; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import jadx.api.ICodeWriter; import jadx.api.impl.SimpleCodeWriter; import jadx.core.codegen.MethodGen; import jadx.core.dex.attributes.IAttributeNode; import jadx.core.dex.instructions.IfNode; import jadx.core.dex.instructions.InsnType; 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.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.trycatch.ExceptionHandler; import jadx.core.utils.BlockUtils; import jadx.core.utils.InsnUtils; import jadx.core.utils.RegionUtils; import jadx.core.utils.StringUtils; import jadx.core.utils.Utils; import static jadx.core.codegen.MethodGen.FallbackOption.BLOCK_DUMP; public class DotGraphVisitor extends AbstractVisitor { private static final String NL = "\\l"; private static final String NLQR = Matcher.quoteReplacement(NL); private static final boolean PRINT_DOMINATORS = false; private static final boolean PRINT_DOMINATORS_INFO = false; private final boolean useRegions; private final boolean rawInsn; public static DotGraphVisitor dump() { return new DotGraphVisitor(false, false); } public static DotGraphVisitor dumpRaw() { return new DotGraphVisitor(false, true); } public static DotGraphVisitor dumpRegions() { return new DotGraphVisitor(true, false); } public static DotGraphVisitor dumpRawRegions() { return new DotGraphVisitor(true, true); } private DotGraphVisitor(boolean useRegions, boolean rawInsn) { this.useRegions = useRegions; this.rawInsn = rawInsn; } @Override public String getName() { return "DotGraphVisitor"; } @Override public void visit(MethodNode mth) { if (mth.isNoCode()) { return; } File outRootDir = mth.root().getArgs().getOutDir(); new DumpDotGraph(outRootDir).process(mth); } public void save(File dir, MethodNode mth) { if (mth.isNoCode()) { return; } new DumpDotGraph(dir).process(mth); } private class DumpDotGraph { private final ICodeWriter dot = new SimpleCodeWriter(); private final ICodeWriter conn = new SimpleCodeWriter(); private final File dir; public DumpDotGraph(File dir) { this.dir = dir; } public void process(MethodNode mth) { dot.startLine("digraph \"CFG for"); dot.add(escape(mth.getMethodInfo().getFullId())); dot.add("\" {"); BlockNode enterBlock = mth.getEnterBlock(); if (useRegions) { if (mth.getRegion() == null) { return; } processMethodRegion(mth); } else { List<BlockNode> blocks = mth.getBasicBlocks(); if (blocks == null) { InsnNode[] insnArr = mth.getInstructions(); if (insnArr == null) { return; } BlockNode block = new BlockNode(0, 0, 0); List<InsnNode> insnList = block.getInstructions(); for (InsnNode insn : insnArr) { if (insn != null) { insnList.add(insn); } } enterBlock = block; blocks = Collections.singletonList(block); } for (BlockNode block : blocks) { processBlock(mth, block, false); } } dot.startLine("MethodNode[shape=record,label=\"{"); dot.add(escape(mth.getAccessFlags().makeString(true))); dot.add(escape(mth.getReturnType() + " " + mth.getParentClass() + '.' + mth.getName() + '(' + Utils.listToString(mth.getAllArgRegs()) + ") ")); String attrs = attributesString(mth); if (!attrs.isEmpty()) { dot.add(" | ").add(attrs); } dot.add("}\"];"); dot.startLine("MethodNode -> ").add(makeName(enterBlock)).add(';'); dot.add(conn.toString()); dot.startLine('}'); dot.startLine(); String fileName = StringUtils.escape(mth.getMethodInfo().getShortId()) + (useRegions ? ".regions" : "") + (rawInsn ? ".raw" : "") + ".dot"; File file = dir.toPath() .resolve(mth.getParentClass().getClassInfo().getAliasFullPath() + "_graphs") .resolve(fileName) .toFile(); SaveCode.save(dot.finish(), file); } private void processMethodRegion(MethodNode mth) { processRegion(mth, mth.getRegion()); for (ExceptionHandler h : mth.getExceptionHandlers()) { if (h.getHandlerRegion() != null) { processRegion(mth, h.getHandlerRegion()); } } Set<IBlock> regionsBlocks = new HashSet<>(mth.getBasicBlocks().size()); RegionUtils.getAllRegionBlocks(mth.getRegion(), regionsBlocks); for (ExceptionHandler handler : mth.getExceptionHandlers()) { IContainer handlerRegion = handler.getHandlerRegion(); if (handlerRegion != null) { RegionUtils.getAllRegionBlocks(handlerRegion, regionsBlocks); } } for (BlockNode block : mth.getBasicBlocks()) { if (!regionsBlocks.contains(block)) { processBlock(mth, block, true); } } } private void processRegion(MethodNode mth, IContainer region) { if (region instanceof IRegion) { IRegion r = (IRegion) region; dot.startLine("subgraph " + makeName(region) + " {"); dot.startLine("label = \"").add(r.toString()); String attrs = attributesString(r); if (!attrs.isEmpty()) { dot.add(" | ").add(attrs); } dot.add("\";"); dot.startLine("node [shape=record,color=blue];"); for (IContainer c : r.getSubBlocks()) { processRegion(mth, c); } dot.startLine('}'); } else if (region instanceof BlockNode) { processBlock(mth, (BlockNode) region, false); } else if (region instanceof IBlock) { processIBlock(mth, (IBlock) region, false); } } private void processBlock(MethodNode mth, BlockNode block, boolean error) { String attrs = attributesString(block); dot.startLine(makeName(block)); dot.add(" [shape=record,"); if (error) { dot.add("color=red,"); } dot.add("label=\"{"); dot.add(String.valueOf(block.getCId())).add("\\:\\ "); dot.add(InsnUtils.formatOffset(block.getStartOffset())); if (!attrs.isEmpty()) { dot.add('|').add(attrs); } if (PRINT_DOMINATORS_INFO) { dot.add('|'); dot.startLine("doms: ").add(escape(block.getDoms())); dot.startLine("\\lidom: ").add(escape(block.getIDom())); dot.startLine("\\lpost-doms: ").add(escape(block.getPostDoms())); dot.startLine("\\lpost-idom: ").add(escape(block.getIPostDom())); dot.startLine("\\ldom-f: ").add(escape(block.getDomFrontier())); dot.startLine("\\ldoms-on: ").add(escape(Utils.listToString(block.getDominatesOn()))); dot.startLine("\\l"); } String insns = insertInsns(mth, block); if (!insns.isEmpty()) { dot.add('|').add(insns); } dot.add("}\"];"); BlockNode falsePath = null; InsnNode lastInsn = BlockUtils.getLastInsn(block); if (lastInsn != null && lastInsn.getType() == InsnType.IF) { falsePath = ((IfNode) lastInsn).getElseBlock(); } for (BlockNode next : block.getSuccessors()) { String style = next == falsePath ? "[style=dashed]" : ""; addEdge(block, next, style); } if (PRINT_DOMINATORS) { for (BlockNode c : block.getDominatesOn()) { conn.startLine(block.getCId() + " -> " + c.getCId() + "[color=green];"); } for (BlockNode dom : BlockUtils.bitSetToBlocks(mth, block.getDomFrontier())) { conn.startLine("f_" + block.getCId() + " -> f_" + dom.getCId() + "[color=blue];"); } } } private void processIBlock(MethodNode mth, IBlock block, boolean error) { String attrs = attributesString(block); dot.startLine(makeName(block)); dot.add(" [shape=record,"); if (error) { dot.add("color=red,"); } dot.add("label=\"{"); if (!attrs.isEmpty()) { dot.add(attrs); } String insns = insertInsns(mth, block); if (!insns.isEmpty()) { dot.add('|').add(insns); } dot.add("}\"];"); } private void addEdge(BlockNode from, BlockNode to, String style) { conn.startLine(makeName(from)).add(" -> ").add(makeName(to)); conn.add(style); conn.add(';'); } private String attributesString(IAttributeNode block) { StringBuilder attrs = new StringBuilder(); for (String attr : block.getAttributesStringsList()) { attrs.append(escape(attr)).append(NL); } return attrs.toString(); } private String makeName(IContainer c) { String name; if (c instanceof BlockNode) { name = "Node_" + ((BlockNode) c).getCId(); } else if (c instanceof IBlock) { name = "Node_" + c.getClass().getSimpleName() + '_' + c.hashCode(); } else { name = "cluster_" + c.getClass().getSimpleName() + '_' + c.hashCode(); } return name; } private String insertInsns(MethodNode mth, IBlock block) { if (rawInsn) { StringBuilder sb = new StringBuilder(); for (InsnNode insn : block.getInstructions()) { sb.append(escape(insn)).append(NL); } return sb.toString(); } else { ICodeWriter code = new SimpleCodeWriter(); List<InsnNode> instructions = block.getInstructions(); MethodGen.addFallbackInsns(code, mth, instructions.toArray(new InsnNode[0]), BLOCK_DUMP); String str = escape(code.newLine().toString()); if (str.startsWith(NL)) { str = str.substring(NL.length()); } return str; } } private String escape(Object obj) { if (obj == null) { return "null"; } return escape(obj.toString()); } private String escape(String string) { return string .replace("\\", "") // TODO replace \" .replace("/", "\\/") .replace(">", "\\>").replace("<", "\\<") .replace("{", "\\{").replace("}", "\\}") .replace("\"", "\\\"") .replace("-", "\\-") .replace("|", "\\|") .replaceAll("\\R", NLQR); } } }
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/SignatureProcessor.java
jadx-core/src/main/java/jadx/core/dex/visitors/SignatureProcessor.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import org.jetbrains.annotations.Nullable; import jadx.core.deobf.NameMapper; 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.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.nodes.parser.SignatureParser; import jadx.core.dex.nodes.utils.TypeUtils; import jadx.core.dex.visitors.typeinference.TypeCompareEnum; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxException; public class SignatureProcessor extends AbstractVisitor { private RootNode root; @Override public void init(RootNode root) { this.root = root; } @Override public boolean visit(ClassNode cls) throws JadxException { parseClassSignature(cls); for (FieldNode field : cls.getFields()) { parseFieldSignature(field); } for (MethodNode mth : cls.getMethods()) { parseMethodSignature(mth); } return true; } private void parseClassSignature(ClassNode cls) { SignatureParser sp = SignatureParser.fromNode(cls); if (sp == null) { return; } try { List<ArgType> generics = sp.consumeGenericTypeParameters(); ArgType superClass = processSuperType(cls, sp.consumeType()); List<ArgType> interfaces = processInterfaces(cls, sp.consumeTypeList()); List<ArgType> resultGenerics = fixTypeParamDeclarations(cls, generics, superClass, interfaces); cls.updateGenericClsData(resultGenerics, superClass, interfaces); } catch (Exception e) { cls.addWarnComment("Failed to parse class signature: " + sp.getSignature(), e); } } private ArgType processSuperType(ClassNode cls, ArgType parsedType) { ArgType superType = cls.getSuperClass(); if (Objects.equals(parsedType.getObject(), cls.getClassInfo().getType().getObject())) { cls.addWarnComment("Incorrect class signature: super class is equals to this class"); return superType; } return bestClsType(cls, parsedType, superType); } /** * Parse, validate and update class interfaces types. */ private List<ArgType> processInterfaces(ClassNode cls, List<ArgType> parsedTypes) { List<ArgType> interfaces = cls.getInterfaces(); if (parsedTypes.isEmpty()) { return interfaces; } int parsedCount = parsedTypes.size(); int interfacesCount = interfaces.size(); List<ArgType> result = new ArrayList<>(interfacesCount); int count = Math.min(interfacesCount, parsedCount); for (int i = 0; i < interfacesCount; i++) { if (i < count) { result.add(bestClsType(cls, parsedTypes.get(i), interfaces.get(i))); } else { result.add(interfaces.get(i)); } } if (interfacesCount < parsedCount) { cls.addWarnComment("Unexpected interfaces in signature: " + parsedTypes.subList(interfacesCount, parsedCount)); } return result; } /** * Add missing type parameters from super type and interfaces to make code compilable */ private static List<ArgType> fixTypeParamDeclarations(ClassNode cls, List<ArgType> generics, ArgType superClass, List<ArgType> interfaces) { if (interfaces.isEmpty() && superClass.equals(ArgType.OBJECT)) { return generics; } Set<String> typeParams = new HashSet<>(); superClass.visitTypes(t -> addGenericType(typeParams, t)); interfaces.forEach(i -> i.visitTypes(t -> addGenericType(typeParams, t))); if (typeParams.isEmpty()) { return generics; } List<ArgType> knownTypeParams; if (cls.isInner()) { knownTypeParams = new ArrayList<>(generics); cls.visitParentClasses(p -> knownTypeParams.addAll(p.getGenericTypeParameters())); } else { knownTypeParams = generics; } for (ArgType declTypeParam : knownTypeParams) { typeParams.remove(declTypeParam.getObject()); } if (typeParams.isEmpty()) { return generics; } cls.addInfoComment("Add missing generic type declarations: " + typeParams); List<ArgType> fixedGenerics = new ArrayList<>(generics.size() + typeParams.size()); fixedGenerics.addAll(generics); typeParams.stream().sorted().map(ArgType::genericType).forEach(fixedGenerics::add); return fixedGenerics; } private static @Nullable Object addGenericType(Set<String> usedTypeParameters, ArgType t) { if (t.isGenericType()) { usedTypeParameters.add(t.getObject()); } return null; } private ArgType bestClsType(ClassNode cls, ArgType candidateType, ArgType currentType) { if (validateClsType(cls, candidateType)) { return candidateType; } return currentType; } private boolean validateClsType(ClassNode cls, ArgType candidateType) { if (candidateType == null) { return false; } if (!candidateType.isObject()) { cls.addWarnComment("Incorrect class signature, class is not an object: " + candidateType); return false; } return true; } private void parseFieldSignature(FieldNode field) { SignatureParser sp = SignatureParser.fromNode(field); if (sp == null) { return; } ClassNode cls = field.getParentClass(); try { ArgType signatureType = sp.consumeType(); if (signatureType == null) { return; } if (!validateInnerType(signatureType)) { field.addWarnComment("Incorrect inner types in field signature: " + sp.getSignature()); return; } ArgType type = root.getTypeUtils().expandTypeVariables(cls, signatureType); if (!validateParsedType(type, field.getType())) { field.addInfoComment("Incorrect field signature: " + sp.getSignature()); return; } field.updateType(type); } catch (Exception e) { cls.addWarnComment("Field signature parse error: " + field.getName(), e); } } private void parseMethodSignature(MethodNode mth) { SignatureParser sp = SignatureParser.fromNode(mth); if (sp == null) { return; } try { List<ArgType> typeParameters = sp.consumeGenericTypeParameters(); List<ArgType> parsedArgTypes = sp.consumeMethodArgs(mth.getMethodInfo().getArgsCount()); ArgType parsedRetType = sp.consumeType(); if (!validateInnerType(parsedRetType) || !validateInnerType(parsedArgTypes)) { mth.addWarnComment("Incorrect inner types in method signature: " + sp.getSignature()); return; } mth.updateTypeParameters(typeParameters); // apply before expand args TypeUtils typeUtils = root.getTypeUtils(); ArgType retType = typeUtils.expandTypeVariables(mth, parsedRetType); List<ArgType> argTypes = Utils.collectionMap(parsedArgTypes, t -> typeUtils.expandTypeVariables(mth, t)); if (!validateAndApplyTypes(mth, sp, retType, argTypes)) { // bad types -> reset typed parameters mth.updateTypeParameters(Collections.emptyList()); } } catch (Exception e) { mth.addWarnComment("Failed to parse method signature: " + sp.getSignature(), e); } } private boolean validateAndApplyTypes(MethodNode mth, SignatureParser sp, ArgType retType, List<ArgType> argTypes) { try { if (!validateParsedType(retType, mth.getMethodInfo().getReturnType())) { mth.addWarnComment("Incorrect return type in method signature: " + sp.getSignature()); return false; } List<ArgType> checkedArgTypes = checkArgTypes(mth, sp, argTypes); if (checkedArgTypes == null) { return false; } mth.updateTypes(Collections.unmodifiableList(checkedArgTypes), retType); return true; } catch (Exception e) { mth.addWarnComment("Type validation failed for signature: " + sp.getSignature(), e); return false; } } private List<ArgType> checkArgTypes(MethodNode mth, SignatureParser sp, List<ArgType> parsedArgTypes) { MethodInfo mthInfo = mth.getMethodInfo(); List<ArgType> mthArgTypes = mthInfo.getArgumentsTypes(); int len = parsedArgTypes.size(); if (len != mthArgTypes.size()) { if (mth.getParentClass().getAccessFlags().isEnum()) { // ignore for enums return null; } if (mthInfo.isConstructor() && !mthArgTypes.isEmpty() && !parsedArgTypes.isEmpty()) { // add synthetic arg for outer class (see test TestGeneric8) List<ArgType> newArgTypes = new ArrayList<>(parsedArgTypes); newArgTypes.add(0, mthArgTypes.get(0)); if (newArgTypes.size() == mthArgTypes.size()) { return newArgTypes; } } mth.addDebugComment("Incorrect args count in method signature: " + sp.getSignature()); return null; } for (int i = 0; i < len; i++) { ArgType parsedType = parsedArgTypes.get(i); ArgType mthArgType = mthArgTypes.get(i); if (!validateParsedType(parsedType, mthArgType)) { mth.addWarnComment("Incorrect types in method signature: " + sp.getSignature()); return null; } } return parsedArgTypes; } private boolean validateParsedType(ArgType parsedType, ArgType currentType) { TypeCompareEnum result = root.getTypeCompare().compareTypes(parsedType, currentType); if (result == TypeCompareEnum.UNKNOWN && parsedType.isObject() && !validateFullClsName(parsedType.getObject())) { // ignore external invalid class names: may be a reserved words or garbage return false; } return result != TypeCompareEnum.CONFLICT; } private boolean validateFullClsName(String fullClsName) { if (!NameMapper.isValidFullIdentifier(fullClsName)) { return false; } if (fullClsName.indexOf('.') > 0) { for (String namePart : fullClsName.split("\\.")) { if (!NameMapper.isValidIdentifier(namePart)) { return false; } } } return true; } private boolean validateInnerType(List<ArgType> types) { for (ArgType type : types) { if (!validateInnerType(type)) { return false; } } return true; } private boolean validateInnerType(ArgType type) { ArgType innerType = type.getInnerType(); if (innerType == null) { return true; } // check in outer type has inner type as inner class ArgType outerType = type.getOuterType(); ClassNode outerCls = root.resolveClass(outerType); if (outerCls == null) { // can't check class not found return true; } String innerObj; if (innerType.getOuterType() != null) { innerObj = innerType.getOuterType().getObject(); // "next" inner type will be processed at end of method } else { innerObj = innerType.getObject(); } if (!innerObj.contains(".")) { // short reference for (ClassNode innerClass : outerCls.getInnerClasses()) { if (innerClass.getShortName().equals(innerObj)) { return true; } } return false; } // full name ClassNode innerCls = root.resolveClass(innerObj); if (innerCls == null) { return false; } if (!innerCls.getParentClass().equals(outerCls)) { // not inner => fixing outerCls.addInnerClass(innerCls); innerCls.getClassInfo().convertToInner(outerCls); } return validateInnerType(innerType); } @Override public String getName() { return "SignatureProcessor"; } }
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/FixSwitchOverEnum.java
jadx-core/src/main/java/jadx/core/dex/visitors/FixSwitchOverEnum.java
package jadx.core.dex.visitors; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.IntFunction; import org.jetbrains.annotations.Nullable; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.EnumClassAttr; import jadx.core.dex.attributes.nodes.EnumMapAttr; import jadx.core.dex.attributes.nodes.RegionRefAttr; import jadx.core.dex.info.AccessInfo; 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.SwitchInsn; 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.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.regions.SwitchRegion; import jadx.core.dex.visitors.shrink.CodeShrinkVisitor; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxException; @JadxVisitor( name = "FixSwitchOverEnum", desc = "Simplify synthetic code in switch over enum", runAfter = { CodeShrinkVisitor.class, EnumVisitor.class } ) public class FixSwitchOverEnum extends AbstractVisitor { @Override public boolean visit(ClassNode cls) throws JadxException { initClsEnumMap(cls); return true; } @Override public void visit(MethodNode mth) throws JadxException { if (mth.isNoCode()) { return; } boolean changed = false; for (BlockNode block : mth.getBasicBlocks()) { for (InsnNode insn : block.getInstructions()) { if (insn.getType() == InsnType.SWITCH && !insn.contains(AFlag.REMOVE)) { changed |= processEnumSwitch(mth, (SwitchInsn) insn); } } } if (changed) { CodeShrinkVisitor.shrinkMethod(mth); } } private static boolean processEnumSwitch(MethodNode mth, SwitchInsn insn) { InsnArg arg = insn.getArg(0); if (!arg.isInsnWrap()) { return false; } InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); switch (wrapInsn.getType()) { case AGET: return processRemappedEnumSwitch(mth, insn, wrapInsn, arg); case INVOKE: return processDirectEnumSwitch(mth, insn, (InvokeNode) wrapInsn, arg); } return false; } private static boolean executeReplace(SwitchInsn swInsn, InsnArg arg, InsnArg invVar, IntFunction<Object> caseReplace) { RegionRefAttr regionRefAttr = swInsn.get(AType.REGION_REF); if (regionRefAttr == null) { return false; } if (!swInsn.replaceArg(arg, invVar)) { return false; } Map<Object, Object> replaceMap = new HashMap<>(); int caseCount = swInsn.getKeys().length; for (int i = 0; i < caseCount; i++) { Object key = swInsn.getKey(i); Object replaceObj = caseReplace.apply(i); swInsn.modifyKey(i, replaceObj); replaceMap.put(key, replaceObj); } SwitchRegion region = (SwitchRegion) regionRefAttr.getRegion(); for (SwitchRegion.CaseInfo caseInfo : region.getCases()) { caseInfo.getKeys().replaceAll(key -> Utils.getOrElse(replaceMap.get(key), key)); } return true; } private static boolean processDirectEnumSwitch(MethodNode mth, SwitchInsn swInsn, InvokeNode invInsn, InsnArg arg) { MethodInfo callMth = invInsn.getCallMth(); if (!callMth.getShortId().equals("ordinal()I")) { return false; } InsnArg invVar = invInsn.getArg(0); ClassNode enumCls = mth.root().resolveClass(invVar.getType()); if (enumCls == null) { return false; } EnumClassAttr enumClassAttr = enumCls.get(AType.ENUM_CLASS); if (enumClassAttr == null) { return false; } FieldNode[] casesReplaceArr = mapToCases(swInsn, enumClassAttr.getFields()); if (casesReplaceArr == null) { return false; } return executeReplace(swInsn, arg, invVar, i -> casesReplaceArr[i]); } private static @Nullable FieldNode[] mapToCases(SwitchInsn swInsn, List<EnumClassAttr.EnumField> fields) { int caseCount = swInsn.getKeys().length; if (fields.size() < caseCount) { return null; } FieldNode[] casesMap = new FieldNode[caseCount]; for (int i = 0; i < caseCount; i++) { Object key = swInsn.getKey(i); if (key instanceof Integer) { int ordinal = (Integer) key; try { casesMap[ordinal] = fields.get(ordinal).getField(); } catch (Exception e) { return null; } } else { return null; } } return casesMap; } private static boolean processRemappedEnumSwitch(MethodNode mth, SwitchInsn insn, InsnNode wrapInsn, InsnArg arg) { EnumMapInfo enumMapInfo = checkEnumMapAccess(mth.root(), wrapInsn); if (enumMapInfo == null) { return false; } FieldNode enumMapField = enumMapInfo.getMapField(); InsnArg invArg = enumMapInfo.getArg(); EnumMapAttr.KeyValueMap valueMap = getEnumMap(enumMapField); if (valueMap == null) { return false; } int caseCount = insn.getKeys().length; for (int i = 0; i < caseCount; i++) { Object key = insn.getKey(i); Object newKey = valueMap.get(key); if (newKey == null) { return false; } } if (executeReplace(insn, arg, invArg, i -> valueMap.get(insn.getKey(i)))) { enumMapField.add(AFlag.DONT_GENERATE); checkAndHideClass(enumMapField.getParentClass()); return true; } return false; } private static void initClsEnumMap(ClassNode enumCls) { MethodNode clsInitMth = enumCls.getClassInitMth(); if (clsInitMth == null || clsInitMth.isNoCode() || clsInitMth.getBasicBlocks() == null) { return; } EnumMapAttr mapAttr = new EnumMapAttr(); for (BlockNode block : clsInitMth.getBasicBlocks()) { for (InsnNode insn : block.getInstructions()) { if (insn.getType() == InsnType.APUT) { addToEnumMap(enumCls.root(), mapAttr, insn); } } } if (!mapAttr.isEmpty()) { enumCls.addAttr(mapAttr); } } private static @Nullable EnumMapAttr.KeyValueMap getEnumMap(FieldNode field) { ClassNode syntheticClass = field.getParentClass(); EnumMapAttr mapAttr = syntheticClass.get(AType.ENUM_MAP); if (mapAttr == null) { return null; } return mapAttr.getMap(field); } private static void addToEnumMap(RootNode root, EnumMapAttr mapAttr, InsnNode aputInsn) { InsnArg litArg = aputInsn.getArg(2); if (!litArg.isLiteral()) { return; } EnumMapInfo mapInfo = checkEnumMapAccess(root, aputInsn); if (mapInfo == null) { return; } InsnArg enumArg = mapInfo.getArg(); FieldNode field = mapInfo.getMapField(); if (field == null || !enumArg.isInsnWrap()) { return; } InsnNode sget = ((InsnWrapArg) enumArg).getWrapInsn(); if (!(sget instanceof IndexInsnNode)) { return; } Object index = ((IndexInsnNode) sget).getIndex(); if (!(index instanceof FieldInfo)) { return; } FieldNode fieldNode = root.resolveField((FieldInfo) index); if (fieldNode == null) { return; } int literal = (int) ((LiteralArg) litArg).getLiteral(); mapAttr.add(field, literal, fieldNode); } private static @Nullable EnumMapInfo checkEnumMapAccess(RootNode root, InsnNode checkInsn) { InsnArg sgetArg = checkInsn.getArg(0); InsnArg invArg = checkInsn.getArg(1); if (!sgetArg.isInsnWrap() || !invArg.isInsnWrap()) { return null; } InsnNode invInsn = ((InsnWrapArg) invArg).getWrapInsn(); InsnNode sgetInsn = ((InsnWrapArg) sgetArg).getWrapInsn(); if (invInsn.getType() != InsnType.INVOKE || sgetInsn.getType() != InsnType.SGET) { return null; } InvokeNode inv = (InvokeNode) invInsn; if (!inv.getCallMth().getShortId().equals("ordinal()I")) { return null; } ClassNode enumCls = root.resolveClass(inv.getCallMth().getDeclClass()); if (enumCls == null || !enumCls.isEnum()) { return null; } Object index = ((IndexInsnNode) sgetInsn).getIndex(); if (!(index instanceof FieldInfo)) { return null; } FieldNode enumMapField = root.resolveField((FieldInfo) index); if (enumMapField == null || !enumMapField.getAccessFlags().isSynthetic()) { return null; } return new EnumMapInfo(inv.getArg(0), enumMapField); } /** * If all static final synthetic fields have DONT_GENERATE => hide whole class */ private static void checkAndHideClass(ClassNode cls) { for (FieldNode field : cls.getFields()) { AccessInfo af = field.getAccessFlags(); if (af.isSynthetic() && af.isStatic() && af.isFinal() && !field.contains(AFlag.DONT_GENERATE)) { return; } } cls.add(AFlag.DONT_GENERATE); } private static class EnumMapInfo { private final InsnArg arg; private final FieldNode mapField; public EnumMapInfo(InsnArg arg, FieldNode mapField) { this.arg = arg; this.mapField = mapField; } public InsnArg getArg() { return arg; } public FieldNode getMapField() { return mapField; } } }
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/MarkMethodsForInline.java
jadx-core/src/main/java/jadx/core/dex/visitors/MarkMethodsForInline.java
package jadx.core.dex.visitors; import java.util.List; 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.MethodInlineAttr; import jadx.core.dex.info.FieldInfo; 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.instructions.args.SSAVar; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.visitors.fixaccessmodifiers.FixAccessModifiers; import jadx.core.utils.BlockUtils; import jadx.core.utils.ListUtils; import jadx.core.utils.exceptions.JadxException; @JadxVisitor( name = "MarkMethodsForInline", desc = "Mark synthetic static methods for inline", runAfter = { FixAccessModifiers.class, ClassModifier.class } ) public class MarkMethodsForInline extends AbstractVisitor { @Override public void visit(MethodNode mth) throws JadxException { process(mth); } /** * @return null if method can't be analyzed (not loaded) */ @Nullable public static MethodInlineAttr process(MethodNode mth) { try { MethodInlineAttr mia = mth.get(AType.METHOD_INLINE); if (mia != null) { return mia; } if (mth.contains(AFlag.METHOD_CANDIDATE_FOR_INLINE)) { if (mth.getBasicBlocks() == null) { return null; } MethodInlineAttr inlined = inlineMth(mth); if (inlined != null) { return inlined; } } } catch (Exception e) { mth.addWarnComment("Method inline analysis failed", e); } return MethodInlineAttr.inlineNotNeeded(mth); } @Nullable private static MethodInlineAttr inlineMth(MethodNode mth) { List<InsnNode> insns = BlockUtils.collectInsnsWithLimit(mth.getBasicBlocks(), 2); int insnsCount = insns.size(); if (insnsCount == 0) { return null; } if (insnsCount == 1) { InsnNode insn = insns.get(0); if (insn.getType() == InsnType.RETURN && insn.getArgsCount() == 1) { // synthetic field getter // set arg from 'return' instruction InsnArg arg = insn.getArg(0); if (!arg.isInsnWrap()) { return null; } return addInlineAttr(mth, ((InsnWrapArg) arg).unWrapWithCopy(), true); } // method invoke return addInlineAttr(mth, insn, false); } if (insnsCount == 2 && insns.get(1).getType() == InsnType.RETURN) { InsnNode firstInsn = insns.get(0); InsnNode retInsn = insns.get(1); if (retInsn.getArgsCount() == 0 || isSyntheticAccessPattern(mth, firstInsn, retInsn)) { return addInlineAttr(mth, firstInsn, false); } } // TODO: inline field arithmetics. Disabled tests: TestAnonymousClass3a and TestAnonymousClass5 return null; } private static boolean isSyntheticAccessPattern(MethodNode mth, InsnNode firstInsn, InsnNode retInsn) { List<RegisterArg> mthRegs = mth.getArgRegs(); switch (firstInsn.getType()) { case IGET: return mthRegs.size() == 1 && retInsn.getArg(0).isSameVar(firstInsn.getResult()) && firstInsn.getArg(0).isSameVar(mthRegs.get(0)); case SGET: return mthRegs.isEmpty() && retInsn.getArg(0).isSameVar(firstInsn.getResult()); case IPUT: return mthRegs.size() == 2 && retInsn.getArg(0).isSameVar(mthRegs.get(1)) && firstInsn.getArg(0).isSameVar(mthRegs.get(1)) && firstInsn.getArg(1).isSameVar(mthRegs.get(0)); case SPUT: return mthRegs.size() == 1 && retInsn.getArg(0).isSameVar(mthRegs.get(0)) && firstInsn.getArg(0).isSameVar(mthRegs.get(0)); case INVOKE: if (!retInsn.getArg(0).isSameVar(firstInsn.getResult())) { return false; } return ListUtils.orderedEquals( mth.getArgRegs(), firstInsn.getArgList(), (mthArg, insnArg) -> insnArg.isSameVar(mthArg)); default: return false; } } private static @Nullable MethodInlineAttr addInlineAttr(MethodNode mth, InsnNode insn, boolean isCopy) { if (!fixVisibilityOfInlineCode(mth, insn)) { if (isCopy) { unbindSsaVars(insn); } return null; } InsnNode inlInsn = isCopy ? insn : insn.copyWithoutResult(); unbindSsaVars(inlInsn); return MethodInlineAttr.markForInline(mth, inlInsn); } private static void unbindSsaVars(InsnNode insn) { insn.visitArgs(arg -> { if (arg.isRegister()) { RegisterArg reg = (RegisterArg) arg; SSAVar ssaVar = reg.getSVar(); if (ssaVar != null) { ssaVar.removeUse(reg); reg.resetSSAVar(); } } }); } private static boolean fixVisibilityOfInlineCode(MethodNode mth, InsnNode insn) { int newVisFlag = AccessFlags.PUBLIC; // TODO: calculate more precisely InsnType insnType = insn.getType(); if (insnType == InsnType.INVOKE) { InvokeNode invoke = (InvokeNode) insn; MethodNode callMthNode = mth.root().resolveMethod(invoke.getCallMth()); if (callMthNode != null && !callMthNode.root().getArgs().isRespectBytecodeAccModifiers()) { FixAccessModifiers.changeVisibility(callMthNode, newVisFlag); } return true; } if (insnType == InsnType.ONE_ARG) { InsnArg arg = insn.getArg(0); if (!arg.isInsnWrap()) { return false; } return fixVisibilityOfInlineCode(mth, ((InsnWrapArg) arg).getWrapInsn()); } if (insn instanceof IndexInsnNode) { Object indexObj = ((IndexInsnNode) insn).getIndex(); if (indexObj instanceof FieldInfo) { // field access must be already fixed in ModVisitor.fixFieldUsage method return true; } } mth.addDebugComment("Can't inline method, not implemented redirect type for insn: " + insn); 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/ReplaceNewArray.java
jadx-core/src/main/java/jadx/core/dex/visitors/ReplaceNewArray.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.nodes.CodeFeaturesAttr; import jadx.core.dex.attributes.nodes.CodeFeaturesAttr.CodeFeature; import jadx.core.dex.instructions.FilledNewArrayNode; import jadx.core.dex.instructions.IndexInsnNode; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.NewArrayNode; 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.nodes.BlockNode; import jadx.core.dex.nodes.IFieldInfoRef; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.visitors.shrink.CodeShrinkVisitor; import jadx.core.utils.InsnList; import jadx.core.utils.InsnRemover; import jadx.core.utils.InsnUtils; import jadx.core.utils.exceptions.JadxException; @JadxVisitor( name = "ReplaceNewArray", desc = "Replace new-array and sequence of array-put to new filled-array instruction", runAfter = CodeShrinkVisitor.class ) public class ReplaceNewArray extends AbstractVisitor { @Override public void visit(MethodNode mth) throws JadxException { if (!CodeFeaturesAttr.contains(mth, CodeFeature.NEW_ARRAY)) { return; } InsnRemover remover = new InsnRemover(mth); int k = 0; while (true) { boolean changed = false; for (BlockNode block : mth.getBasicBlocks()) { List<InsnNode> insnList = block.getInstructions(); int size = insnList.size(); for (int i = 0; i < size; i++) { changed |= processInsn(mth, insnList, i, remover); } remover.performForBlock(block); } if (changed) { CodeShrinkVisitor.shrinkMethod(mth); } else { break; } if (k++ > 100) { mth.addWarnComment("Reached limit for ReplaceNewArray iterations"); break; } } } private static boolean processInsn(MethodNode mth, List<InsnNode> instructions, int i, InsnRemover remover) { InsnNode insn = instructions.get(i); if (insn.getType() == InsnType.NEW_ARRAY && !insn.contains(AFlag.REMOVE)) { return processNewArray(mth, (NewArrayNode) insn, instructions, remover); } return false; } private static boolean processNewArray(MethodNode mth, NewArrayNode newArrayInsn, List<InsnNode> instructions, InsnRemover remover) { Object arrayLenConst = InsnUtils.getConstValueByArg(mth.root(), newArrayInsn.getArg(0)); if (!(arrayLenConst instanceof LiteralArg)) { return false; } int len = (int) ((LiteralArg) arrayLenConst).getLiteral(); if (len == 0) { return false; } ArgType arrType = newArrayInsn.getArrayType(); ArgType elemType = arrType.getArrayElement(); boolean allowMissingKeys = arrType.getArrayDimension() == 1 && elemType.isPrimitive(); int minLen = allowMissingKeys ? len / 2 : len; RegisterArg arrArg = newArrayInsn.getResult(); List<RegisterArg> useList = arrArg.getSVar().getUseList(); if (useList.size() < minLen) { return false; } // quick check if APUT is used boolean foundPut = false; for (RegisterArg registerArg : useList) { InsnNode parentInsn = registerArg.getParentInsn(); if (parentInsn != null && parentInsn.getType() == InsnType.APUT) { foundPut = true; break; } } if (!foundPut) { return false; } // collect put instructions sorted by array index SortedMap<Long, InsnNode> arrPuts = new TreeMap<>(); InsnNode firstNotAPutUsage = null; for (RegisterArg registerArg : useList) { InsnNode parentInsn = registerArg.getParentInsn(); if (parentInsn == null || parentInsn.getType() != InsnType.APUT || !arrArg.sameRegAndSVar(parentInsn.getArg(0))) { if (firstNotAPutUsage == null) { firstNotAPutUsage = parentInsn; } continue; } Object constVal = InsnUtils.getConstValueByArg(mth.root(), parentInsn.getArg(1)); if (!(constVal instanceof LiteralArg)) { return false; } long index = ((LiteralArg) constVal).getLiteral(); if (index >= len) { return false; } if (arrPuts.containsKey(index)) { // stop on index rewrite break; } arrPuts.put(index, parentInsn); } if (arrPuts.size() < minLen) { return false; } if (!verifyPutInsns(arrArg, instructions, arrPuts)) { return false; } // checks complete, apply InsnNode filledArr = new FilledNewArrayNode(elemType, len); filledArr.setResult(arrArg.duplicate()); filledArr.copyAttributesFrom(newArrayInsn); filledArr.inheritMetadata(newArrayInsn); filledArr.setOffset(newArrayInsn.getOffset()); long prevIndex = -1; for (Map.Entry<Long, InsnNode> entry : arrPuts.entrySet()) { long index = entry.getKey(); if (index != prevIndex) { // use zero for missing keys for (long i = prevIndex + 1; i < index; i++) { filledArr.addArg(InsnArg.lit(0, elemType)); } } InsnNode put = entry.getValue(); filledArr.addArg(replaceConstInArg(mth, put.getArg(2))); remover.addAndUnbind(put); prevIndex = index; } // add missing trailing zeros for (long i = prevIndex + 1; i < len; i++) { filledArr.addArg(InsnArg.lit(0, elemType)); } remover.addAndUnbind(newArrayInsn); // place new insn at last array put or before first usage InsnNode lastPut = arrPuts.get(arrPuts.lastKey()); int newInsnPos = InsnList.getIndex(instructions, lastPut); if (firstNotAPutUsage != null) { int idx = InsnList.getIndex(instructions, firstNotAPutUsage); if (idx != -1) { // TODO: check that all args already assigned newInsnPos = Math.min(idx, newInsnPos); } } instructions.add(newInsnPos, filledArr); return true; } private static boolean verifyPutInsns(RegisterArg arrReg, List<InsnNode> insnList, SortedMap<Long, InsnNode> arrPuts) { List<InsnNode> puts = new ArrayList<>(arrPuts.values()); int putsCount = puts.size(); // expect all puts to be in the same block if (insnList.size() < putsCount) { return false; } Set<InsnNode> insnSet = Collections.newSetFromMap(new IdentityHashMap<>()); insnSet.addAll(insnList); if (!insnSet.containsAll(puts)) { return false; } // array arg shouldn't be used in puts insns for (InsnNode put : puts) { InsnArg putArg = put.getArg(2); if (putArg.isUseVar(arrReg)) { return false; } } return true; } private static InsnArg replaceConstInArg(MethodNode mth, InsnArg valueArg) { if (valueArg.isLiteral()) { IFieldInfoRef f = mth.getParentClass().getConstFieldByLiteralArg((LiteralArg) valueArg); if (f != null) { InsnNode fGet = new IndexInsnNode(InsnType.SGET, f.getFieldInfo(), 0); InsnArg arg = InsnArg.wrapArg(fGet); ModVisitor.addFieldUsage(f, mth); return arg; } } return valueArg.duplicate(); } }
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/MethodVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/MethodVisitor.java
package jadx.core.dex.visitors; import java.util.function.Consumer; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.exceptions.JadxException; public class MethodVisitor extends AbstractVisitor { private final String name; private final Consumer<MethodNode> visitor; public MethodVisitor(String name, Consumer<MethodNode> visitor) { this.name = name; this.visitor = visitor; } @Override public void visit(MethodNode mth) throws JadxException { visitor.accept(mth); } @Override public String getName() { return name; } }
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/ProcessInstructionsVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/ProcessInstructionsVisitor.java
package jadx.core.dex.visitors; import org.jetbrains.annotations.Nullable; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.JumpInfo; import jadx.core.dex.instructions.BaseInvokeNode; import jadx.core.dex.instructions.FillArrayData; import jadx.core.dex.instructions.FillArrayInsn; import jadx.core.dex.instructions.FilledNewArrayNode; import jadx.core.dex.instructions.GotoNode; import jadx.core.dex.instructions.IfNode; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.SwitchData; import jadx.core.dex.instructions.SwitchInsn; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.instructions.java.JsrNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.visitors.blocks.BlockSplitter; import jadx.core.utils.InsnUtils; import jadx.core.utils.exceptions.JadxException; import jadx.core.utils.exceptions.JadxRuntimeException; @JadxVisitor( name = "Process Instructions Visitor", desc = "Init instructions info", runBefore = { BlockSplitter.class } ) public class ProcessInstructionsVisitor extends AbstractVisitor { @Override public void visit(MethodNode mth) throws JadxException { if (mth.isNoCode()) { return; } initJumps(mth, mth.getInstructions()); } private static void initJumps(MethodNode mth, InsnNode[] insnByOffset) { for (int offset = 0; offset < insnByOffset.length; offset++) { InsnNode insn = insnByOffset[offset]; if (insn == null) { continue; } switch (insn.getType()) { case SWITCH: SwitchInsn sw = (SwitchInsn) insn; if (sw.needData()) { attachSwitchData(insnByOffset, offset, sw); } int defCaseOffset = sw.getDefaultCaseOffset(); if (defCaseOffset != -1) { addJump(mth, insnByOffset, offset, defCaseOffset); } for (int target : sw.getTargets()) { addJump(mth, insnByOffset, offset, target); } break; case IF: int next = getNextInsnOffset(insnByOffset, offset); if (next != -1) { addJump(mth, insnByOffset, offset, next); } addJump(mth, insnByOffset, offset, ((IfNode) insn).getTarget()); break; case GOTO: addJump(mth, insnByOffset, offset, ((GotoNode) insn).getTarget()); break; case JAVA_JSR: addJump(mth, insnByOffset, offset, ((JsrNode) insn).getTarget()); int onRet = getNextInsnOffset(insnByOffset, offset); if (onRet != -1) { addJump(mth, insnByOffset, offset, onRet); } break; case INVOKE: if (insn.getResult() == null) { ArgType retType = ((BaseInvokeNode) insn).getCallMth().getReturnType(); mergeMoveResult(insnByOffset, offset, insn, retType); } break; case STR_CONCAT: // invoke-custom with string concatenation translated directly to STR_CONCAT, merge next move-result if (insn.getResult() == null) { mergeMoveResult(insnByOffset, offset, insn, ArgType.STRING); } break; case FILLED_NEW_ARRAY: ArgType arrType = ((FilledNewArrayNode) insn).getArrayType(); mergeMoveResult(insnByOffset, offset, insn, arrType); break; case FILL_ARRAY: FillArrayInsn fillArrayInsn = (FillArrayInsn) insn; int target = fillArrayInsn.getTarget(); InsnNode arrDataInsn = getInsnAtOffset(insnByOffset, target); if (arrDataInsn != null && arrDataInsn.getType() == InsnType.FILL_ARRAY_DATA) { fillArrayInsn.setArrayData((FillArrayData) arrDataInsn); removeInsn(insnByOffset, arrDataInsn); } else { throw new JadxRuntimeException("Payload for fill-array not found at " + InsnUtils.formatOffset(target)); } break; default: break; } } } private static void attachSwitchData(InsnNode[] insnByOffset, int offset, SwitchInsn sw) { int nextInsnOffset = getNextInsnOffset(insnByOffset, offset); int dataTarget = sw.getDataTarget(); InsnNode switchDataInsn = getInsnAtOffset(insnByOffset, dataTarget); if (switchDataInsn != null && switchDataInsn.getType() == InsnType.SWITCH_DATA) { SwitchData data = (SwitchData) switchDataInsn; data.fixTargets(offset); sw.attachSwitchData(data, nextInsnOffset); removeInsn(insnByOffset, switchDataInsn); } else { throw new JadxRuntimeException("Payload for switch not found at " + InsnUtils.formatOffset(dataTarget)); } } private static void mergeMoveResult(InsnNode[] insnByOffset, int offset, InsnNode insn, ArgType resType) { int nextInsnOffset = getNextInsnOffset(insnByOffset, offset); if (nextInsnOffset == -1) { return; } InsnNode nextInsn = insnByOffset[nextInsnOffset]; if (nextInsn.getType() != InsnType.MOVE_RESULT) { return; } RegisterArg moveRes = nextInsn.getResult(); insn.setResult(moveRes.duplicate(resType)); insn.copyAttributesFrom(nextInsn); removeInsn(insnByOffset, nextInsn); } private static void addJump(MethodNode mth, InsnNode[] insnByOffset, int offset, int target) { try { insnByOffset[target].addAttr(AType.JUMP, new JumpInfo(offset, target)); } catch (Exception e) { mth.addError("Failed to set jump: " + InsnUtils.formatOffset(offset) + " -> " + InsnUtils.formatOffset(target), e); } } public static int getNextInsnOffset(InsnNode[] insnByOffset, int offset) { int len = insnByOffset.length; for (int i = offset + 1; i < len; i++) { InsnNode insnNode = insnByOffset[i]; if (insnNode != null && insnNode.getType() != InsnType.NOP) { return i; } } return -1; } @Nullable private static InsnNode getInsnAtOffset(InsnNode[] insnByOffset, int offset) { int len = insnByOffset.length; for (int i = offset; i < len; i++) { InsnNode insnNode = insnByOffset[i]; if (insnNode != null && insnNode.getType() != InsnType.NOP) { return insnNode; } } return null; } private static void removeInsn(InsnNode[] insnByOffset, InsnNode insn) { insnByOffset[insn.getOffset()] = 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/DeboxingVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/DeboxingVisitor.java
package jadx.core.dex.visitors; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.MethodInfo; 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.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.nodes.RootNode; import jadx.core.dex.visitors.regions.variables.ProcessVariables; import jadx.core.dex.visitors.shrink.CodeShrinkVisitor; import jadx.core.utils.BlockUtils; import jadx.core.utils.exceptions.JadxException; /** * Remove primitives boxing * i.e convert 'Integer.valueOf(1)' to '1' */ @JadxVisitor( name = "DeboxingVisitor", desc = "Remove primitives boxing", runBefore = { CodeShrinkVisitor.class, ProcessVariables.class } ) public class DeboxingVisitor extends AbstractVisitor { private Set<MethodInfo> valueOfMths; @Override public void init(RootNode root) { valueOfMths = new HashSet<>(); valueOfMths.add(valueOfMth(root, ArgType.INT, "java.lang.Integer")); valueOfMths.add(valueOfMth(root, ArgType.BOOLEAN, "java.lang.Boolean")); valueOfMths.add(valueOfMth(root, ArgType.BYTE, "java.lang.Byte")); valueOfMths.add(valueOfMth(root, ArgType.SHORT, "java.lang.Short")); valueOfMths.add(valueOfMth(root, ArgType.CHAR, "java.lang.Character")); valueOfMths.add(valueOfMth(root, ArgType.LONG, "java.lang.Long")); } private static MethodInfo valueOfMth(RootNode root, ArgType argType, String clsName) { ArgType boxType = ArgType.object(clsName); ClassInfo boxCls = ClassInfo.fromType(root, boxType); return MethodInfo.fromDetails(root, boxCls, "valueOf", Collections.singletonList(argType), boxType); } @Override public void visit(MethodNode mth) throws JadxException { if (mth.isNoCode()) { return; } boolean replaced = false; for (BlockNode blockNode : mth.getBasicBlocks()) { List<InsnNode> insnList = blockNode.getInstructions(); int count = insnList.size(); for (int i = 0; i < count; i++) { InsnNode insnNode = insnList.get(i); if (insnNode.getType() == InsnType.INVOKE) { InsnNode replaceInsn = checkForReplace(((InvokeNode) insnNode)); if (replaceInsn != null) { BlockUtils.replaceInsn(mth, blockNode, i, replaceInsn); replaced = true; } } } } if (replaced) { ConstInlineVisitor.process(mth); } } private InsnNode checkForReplace(InvokeNode insnNode) { if (insnNode.getInvokeType() != InvokeType.STATIC || insnNode.getResult() == null) { return null; } MethodInfo callMth = insnNode.getCallMth(); if (valueOfMths.contains(callMth)) { RegisterArg resArg = insnNode.getResult(); InsnArg arg = insnNode.getArg(0); if (arg.isLiteral()) { ArgType primitiveType = callMth.getArgumentsTypes().get(0); ArgType boxType = callMth.getReturnType(); if (isNeedExplicitCast(resArg, primitiveType, boxType)) { arg.add(AFlag.EXPLICIT_PRIMITIVE_TYPE); } arg.setType(primitiveType); boolean forbidInline; if (canChangeTypeToPrimitive(resArg, boxType)) { resArg.setType(primitiveType); forbidInline = false; } else { forbidInline = true; } InsnNode constInsn = new InsnNode(InsnType.CONST, 1); constInsn.addArg(arg); constInsn.setResult(resArg); if (forbidInline) { constInsn.add(AFlag.DONT_INLINE); } return constInsn; } } return null; } private boolean isNeedExplicitCast(RegisterArg resArg, ArgType primitiveType, ArgType boxType) { if (primitiveType == ArgType.LONG) { return true; } if (primitiveType != ArgType.INT) { Set<ArgType> useTypes = collectUseTypes(resArg); useTypes.add(resArg.getType()); useTypes.remove(boxType); useTypes.remove(primitiveType); return !useTypes.isEmpty(); } return false; } private boolean canChangeTypeToPrimitive(RegisterArg arg, ArgType boxType) { for (SSAVar ssaVar : arg.getSVar().getCodeVar().getSsaVars()) { if (ssaVar.isTypeImmutable()) { return false; } InsnNode assignInsn = ssaVar.getAssignInsn(); if (assignInsn == null) { // method arg return false; } InsnType assignInsnType = assignInsn.getType(); if (assignInsnType == InsnType.CONST || assignInsnType == InsnType.MOVE) { if (assignInsn.getArg(0).getType().isObject()) { return false; } } ArgType initType = assignInsn.getResult().getInitType(); if (initType.isObject() && !initType.equals(boxType)) { // some of related vars have another object type return false; } for (RegisterArg useArg : ssaVar.getUseList()) { InsnNode parentInsn = useArg.getParentInsn(); if (parentInsn == null) { return false; } if (parentInsn.getType() == InsnType.INVOKE) { InvokeNode invokeNode = (InvokeNode) parentInsn; if (useArg.equals(invokeNode.getInstanceArg())) { return false; } } } } return true; } private Set<ArgType> collectUseTypes(RegisterArg arg) { Set<ArgType> types = new HashSet<>(); for (RegisterArg useArg : arg.getSVar().getUseList()) { types.add(useArg.getType()); types.add(useArg.getInitType()); } return types; } }
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/CheckCode.java
jadx-core/src/main/java/jadx/core/dex/visitors/CheckCode.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.List; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.exceptions.JadxException; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.utils.Utils.isEmpty; @JadxVisitor( name = "CheckCode", desc = "Check and remove bad or incorrect code" ) public class CheckCode extends AbstractVisitor { @Override public void visit(MethodNode mth) throws JadxException { MethodInfo mthInfo = mth.getMethodInfo(); if (mthInfo.getArgumentsTypes().size() > 255) { // java spec don't allow more than 255 args if (canRemoveMethod(mth)) { mth.ignoreMethod(); } else { // TODO: convert args to array } } checkInstructions(mth); } private boolean canRemoveMethod(MethodNode mth) { if (mth.getUseIn().isEmpty()) { return true; } InsnNode[] insns = mth.getInstructions(); if (insns.length == 0) { return true; } for (InsnNode insn : insns) { if (insn != null && insn.getType() != InsnType.NOP) { if (insn.getType() == InsnType.RETURN && insn.getArgsCount() == 0) { // ignore void return } else { // found useful instruction return false; } } } return true; } public void checkInstructions(MethodNode mth) { if (isEmpty(mth.getInstructions())) { return; } int regsCount = mth.getRegsCount(); List<RegisterArg> list = new ArrayList<>(); for (InsnNode insnNode : mth.getInstructions()) { if (insnNode == null) { continue; } list.clear(); RegisterArg resultArg = insnNode.getResult(); if (resultArg != null) { list.add(resultArg); } insnNode.getRegisterArgs(list); for (RegisterArg arg : list) { int regNum = arg.getRegNum(); if (regNum < 0) { throw new JadxRuntimeException("Incorrect negative register number in instruction: " + insnNode); } if (regNum >= regsCount) { throw new JadxRuntimeException("Incorrect register number in instruction: " + insnNode + ", expected to be less than " + regsCount); } } } } }
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/MethodInvokeVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/MethodInvokeVisitor.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.Consts; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.MethodInfo; 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.InsnWrapArg; 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.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.dex.visitors.methods.MutableMethodDetails; import jadx.core.dex.visitors.shrink.CodeShrinkVisitor; import jadx.core.dex.visitors.typeinference.TypeCompare; import jadx.core.dex.visitors.typeinference.TypeCompareEnum; import jadx.core.utils.InsnUtils; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; @JadxVisitor( name = "MethodInvokeVisitor", desc = "Process additional info for method invocation (overload, vararg)", runAfter = { CodeShrinkVisitor.class, ModVisitor.class }, runBefore = { SimplifyVisitor.class // run before cast remove and StringBuilder replace } ) public class MethodInvokeVisitor extends AbstractVisitor { private static final Logger LOG = LoggerFactory.getLogger(MethodInvokeVisitor.class); private RootNode root; @Override public void init(RootNode root) { this.root = root; } @Override public void visit(MethodNode mth) { if (mth.isNoCode()) { return; } for (BlockNode block : mth.getBasicBlocks()) { if (block.contains(AFlag.DONT_GENERATE)) { continue; } for (InsnNode insn : block.getInstructions()) { if (insn.contains(AFlag.DONT_GENERATE)) { continue; } insn.visitInsns(in -> { if (in instanceof BaseInvokeNode) { processInvoke(mth, ((BaseInvokeNode) in)); } }); } } } private void processInvoke(MethodNode parentMth, BaseInvokeNode invokeInsn) { MethodInfo callMth = invokeInsn.getCallMth(); if (callMth.getArgsCount() == 0) { return; } IMethodDetails mthDetails = root.getMethodUtils().getMethodDetails(invokeInsn); if (mthDetails == null) { if (Consts.DEBUG) { parentMth.addDebugComment("Method info not found: " + callMth); } processUnknown(invokeInsn); } else { if (mthDetails.isVarArg()) { ArgType last = Utils.last(mthDetails.getArgTypes()); if (last != null && last.isArray()) { invokeInsn.add(AFlag.VARARG_CALL); } } processOverloaded(parentMth, invokeInsn, mthDetails); } } private void processOverloaded(MethodNode parentMth, BaseInvokeNode invokeInsn, IMethodDetails mthDetails) { MethodInfo callMth = invokeInsn.getCallMth(); ArgType callCls = getCallClassFromInvoke(parentMth, invokeInsn, callMth); List<IMethodDetails> overloadMethods = root.getMethodUtils().collectOverloadedMethods(callCls, callMth); if (overloadMethods.isEmpty()) { // not overloaded return; } // resolve generic type variables Map<ArgType, ArgType> typeVarsMapping = getTypeVarsMapping(invokeInsn); IMethodDetails effectiveMthDetails = resolveTypeVars(mthDetails, typeVarsMapping); List<IMethodDetails> effectiveOverloadMethods = new ArrayList<>(overloadMethods.size() + 1); for (IMethodDetails overloadMethod : overloadMethods) { effectiveOverloadMethods.add(resolveTypeVars(overloadMethod, typeVarsMapping)); } effectiveOverloadMethods.add(effectiveMthDetails); // search cast types to resolve overloading int argsOffset = invokeInsn.getFirstArgOffset(); List<ArgType> compilerVarTypes = collectCompilerVarTypes(invokeInsn, argsOffset); List<ArgType> castTypes = searchCastTypes(parentMth, effectiveMthDetails, effectiveOverloadMethods, compilerVarTypes); List<ArgType> resultCastTypes = expandTypes(parentMth, effectiveMthDetails, castTypes); applyArgsCast(invokeInsn, argsOffset, compilerVarTypes, resultCastTypes); } /** * Method details not found => add cast for 'null' args */ private void processUnknown(BaseInvokeNode invokeInsn) { int argsOffset = invokeInsn.getFirstArgOffset(); List<ArgType> compilerVarTypes = collectCompilerVarTypes(invokeInsn, argsOffset); List<ArgType> castTypes = new ArrayList<>(compilerVarTypes); if (replaceUnknownTypes(castTypes, invokeInsn.getCallMth().getArgumentsTypes())) { applyArgsCast(invokeInsn, argsOffset, compilerVarTypes, castTypes); } } private ArgType getCallClassFromInvoke(MethodNode parentMth, BaseInvokeNode invokeInsn, MethodInfo callMth) { if (invokeInsn instanceof ConstructorInsn) { ConstructorInsn constrInsn = (ConstructorInsn) invokeInsn; if (constrInsn.isSuper()) { return parentMth.getParentClass().getSuperClass(); } } InsnArg instanceArg = invokeInsn.getInstanceArg(); if (instanceArg != null) { return instanceArg.getType(); } // static call return callMth.getDeclClass().getType(); } private Map<ArgType, ArgType> getTypeVarsMapping(BaseInvokeNode invokeInsn) { MethodInfo callMthInfo = invokeInsn.getCallMth(); ArgType declClsType = callMthInfo.getDeclClass().getType(); ArgType callClsType = getClsCallType(invokeInsn, declClsType); TypeUtils typeUtils = root.getTypeUtils(); Map<ArgType, ArgType> clsTypeVars = typeUtils.getTypeVariablesMapping(callClsType); Map<ArgType, ArgType> mthTypeVars = typeUtils.getTypeVarMappingForInvoke(invokeInsn); return Utils.mergeMaps(clsTypeVars, mthTypeVars); } private ArgType getClsCallType(BaseInvokeNode invokeInsn, ArgType declClsType) { InsnArg instanceArg = invokeInsn.getInstanceArg(); if (instanceArg != null) { return instanceArg.getType(); } if (invokeInsn.getType() == InsnType.CONSTRUCTOR && invokeInsn.getResult() != null) { return invokeInsn.getResult().getType(); } return declClsType; } private void applyArgsCast(BaseInvokeNode invokeInsn, int argsOffset, List<ArgType> compilerVarTypes, List<ArgType> castTypes) { int argsCount = invokeInsn.getArgsCount(); for (int i = argsOffset; i < argsCount; i++) { InsnArg arg = invokeInsn.getArg(i); int origPos = i - argsOffset; ArgType compilerType = compilerVarTypes.get(origPos); ArgType castType = castTypes.get(origPos); if (castType != null) { if (!castType.equals(compilerType)) { if (arg.isLiteral() && compilerType.isPrimitive() && castType.isPrimitive()) { arg.setType(castType); arg.add(AFlag.EXPLICIT_PRIMITIVE_TYPE); } else if (InsnUtils.isWrapped(arg, InsnType.CHECK_CAST)) { IndexInsnNode wrapInsn = (IndexInsnNode) ((InsnWrapArg) arg).getWrapInsn(); wrapInsn.updateIndex(castType); } else { if (Consts.DEBUG_TYPE_INFERENCE) { LOG.info("Insert cast for invoke insn arg: {}, insn: {}", arg, invokeInsn); } InsnNode castInsn = new IndexInsnNode(InsnType.CAST, castType, 1); castInsn.addArg(arg); castInsn.add(AFlag.EXPLICIT_CAST); InsnArg wrapCast = InsnArg.wrapArg(castInsn); wrapCast.setType(castType); invokeInsn.setArg(i, wrapCast); } } else { // protect already existed cast if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); if (wrapInsn.getType() == InsnType.CHECK_CAST) { wrapInsn.add(AFlag.EXPLICIT_CAST); } } } } } } private IMethodDetails resolveTypeVars(IMethodDetails mthDetails, Map<ArgType, ArgType> typeVarsMapping) { List<ArgType> argTypes = mthDetails.getArgTypes(); int argsCount = argTypes.size(); boolean fixed = false; List<ArgType> fixedArgTypes = new ArrayList<>(argsCount); for (int argNum = 0; argNum < argsCount; argNum++) { ArgType argType = argTypes.get(argNum); if (argType == null) { throw new JadxRuntimeException("Null arg type in " + mthDetails + " at: " + argNum + " in: " + argTypes); } if (argType.containsTypeVariable()) { ArgType resolvedType = root.getTypeUtils().replaceTypeVariablesUsingMap(argType, typeVarsMapping); if (resolvedType == null || resolvedType.equals(argType)) { // type variables erased from method info by compiler resolvedType = mthDetails.getMethodInfo().getArgumentsTypes().get(argNum); } fixedArgTypes.add(resolvedType); fixed = true; } else { fixedArgTypes.add(argType); } } ArgType returnType = mthDetails.getReturnType(); if (returnType.containsTypeVariable()) { ArgType resolvedType = root.getTypeUtils().replaceTypeVariablesUsingMap(returnType, typeVarsMapping); if (resolvedType == null || resolvedType.containsTypeVariable()) { returnType = mthDetails.getMethodInfo().getReturnType(); fixed = true; } } if (!fixed) { return mthDetails; } MutableMethodDetails mutableMethodDetails = new MutableMethodDetails(mthDetails); mutableMethodDetails.setArgTypes(fixedArgTypes); mutableMethodDetails.setRetType(returnType); return mutableMethodDetails; } private List<ArgType> searchCastTypes(MethodNode parentMth, IMethodDetails mthDetails, List<IMethodDetails> overloadedMethods, List<ArgType> compilerVarTypes) { // try compiler types if (isOverloadResolved(mthDetails, overloadedMethods, compilerVarTypes)) { return compilerVarTypes; } int argsCount = compilerVarTypes.size(); List<ArgType> castTypes = new ArrayList<>(compilerVarTypes); // replace unknown types boolean changed = replaceUnknownTypes(castTypes, mthDetails.getArgTypes()); if (changed && isOverloadResolved(mthDetails, overloadedMethods, castTypes)) { return castTypes; } // replace generic types changed = false; for (int i = 0; i < argsCount; i++) { ArgType castType = castTypes.get(i); ArgType mthType = mthDetails.getArgTypes().get(i); if (!castType.isGeneric() && mthType.isGeneric()) { castTypes.set(i, mthType); changed = true; } } if (changed && isOverloadResolved(mthDetails, overloadedMethods, castTypes)) { return castTypes; } // if just one arg => cast will resolve if (argsCount == 1) { return mthDetails.getArgTypes(); } if (Consts.DEBUG_OVERLOADED_CASTS) { // TODO: try to minimize casts count parentMth.addDebugComment("Failed to find minimal casts for resolve overloaded methods, cast all args instead" + "\n method: " + mthDetails + "\n arg types: " + compilerVarTypes + "\n candidates:" + "\n " + Utils.listToString(overloadedMethods, "\n ")); } // not resolved -> cast all args return mthDetails.getArgTypes(); } private boolean replaceUnknownTypes(List<ArgType> castTypes, List<ArgType> mthArgTypes) { int argsCount = castTypes.size(); boolean changed = false; for (int i = 0; i < argsCount; i++) { ArgType castType = castTypes.get(i); if (!castType.isTypeKnown()) { ArgType mthType = mthArgTypes.get(i); castTypes.set(i, mthType); changed = true; } } return changed; } /** * Use generified types if available */ private List<ArgType> expandTypes(MethodNode parentMth, IMethodDetails methodDetails, List<ArgType> castTypes) { TypeCompare typeCompare = parentMth.root().getTypeCompare(); List<ArgType> mthArgTypes = methodDetails.getArgTypes(); int argsCount = castTypes.size(); List<ArgType> list = new ArrayList<>(argsCount); for (int i = 0; i < argsCount; i++) { ArgType mthType = mthArgTypes.get(i); ArgType castType = castTypes.get(i); TypeCompareEnum result = typeCompare.compareTypes(mthType, castType); if (result == TypeCompareEnum.NARROW_BY_GENERIC) { list.add(mthType); } else { list.add(castType); } } return list; } private boolean isOverloadResolved(IMethodDetails expectedMthDetails, List<IMethodDetails> overloadedMethods, List<ArgType> castTypes) { if (overloadedMethods.isEmpty()) { return false; } // TODO: search closest method, instead filtering List<IMethodDetails> strictMethods = filterApplicableMethods(overloadedMethods, castTypes, MethodInvokeVisitor::isStrictTypes); if (strictMethods.size() == 1) { return strictMethods.get(0).equals(expectedMthDetails); } List<IMethodDetails> resolvedMethods = filterApplicableMethods(overloadedMethods, castTypes, MethodInvokeVisitor::isTypeApplicable); if (resolvedMethods.size() == 1) { return resolvedMethods.get(0).equals(expectedMthDetails); } return false; } private static boolean isStrictTypes(TypeCompareEnum result) { return result.isEqual(); } private static boolean isTypeApplicable(TypeCompareEnum result) { return result.isNarrowOrEqual() || result == TypeCompareEnum.WIDER_BY_GENERIC; } private List<IMethodDetails> filterApplicableMethods(List<IMethodDetails> methods, List<ArgType> types, Function<TypeCompareEnum, Boolean> acceptFunction) { List<IMethodDetails> list = new ArrayList<>(methods.size()); for (IMethodDetails m : methods) { if (isMethodAcceptable(m, types, acceptFunction)) { list.add(m); } } return list; } private boolean isMethodAcceptable(IMethodDetails methodDetails, List<ArgType> types, Function<TypeCompareEnum, Boolean> acceptFunction) { List<ArgType> mthTypes = methodDetails.getArgTypes(); int argCount = mthTypes.size(); if (argCount != types.size()) { return false; } TypeCompare typeCompare = root.getTypeUpdate().getTypeCompare(); for (int i = 0; i < argCount; i++) { ArgType mthType = mthTypes.get(i); ArgType argType = types.get(i); TypeCompareEnum result = typeCompare.compareTypes(argType, mthType); if (!acceptFunction.apply(result)) { return false; } } return true; } private List<ArgType> collectCompilerVarTypes(BaseInvokeNode insn, int argOffset) { int argsCount = insn.getArgsCount(); List<ArgType> result = new ArrayList<>(argsCount); for (int i = argOffset; i < argsCount; i++) { InsnArg arg = insn.getArg(i); result.add(getCompilerVarType(arg)); } return result; } /** * Return type as seen by compiler */ private ArgType getCompilerVarType(InsnArg arg) { if (arg instanceof LiteralArg) { LiteralArg literalArg = (LiteralArg) arg; ArgType type = literalArg.getType(); if (literalArg.getLiteral() == 0) { if (type.isObject() || type.isArray()) { // null return ArgType.UNKNOWN_OBJECT; } } if (type.isPrimitive() && !arg.contains(AFlag.EXPLICIT_PRIMITIVE_TYPE)) { return ArgType.INT; } return arg.getType(); } if (arg instanceof RegisterArg) { return arg.getType(); } if (arg instanceof InsnWrapArg) { InsnWrapArg wrapArg = (InsnWrapArg) arg; return getInsnCompilerType(arg, wrapArg.getWrapInsn()); } throw new JadxRuntimeException("Unknown var type for: " + arg); } private static ArgType getInsnCompilerType(InsnArg arg, InsnNode insn) { switch (insn.getType()) { case CAST: case CHECK_CAST: return ((IndexInsnNode) insn).getIndexAsType(); default: if (insn.getResult() != null) { return insn.getResult().getType(); } return arg.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/ModVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/ModVisitor.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.plugins.input.data.annotations.AnnotationVisibility; import jadx.api.plugins.input.data.annotations.EncodedType; 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.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.AttrNode; import jadx.core.dex.attributes.nodes.SkipMethodArgsAttr; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.instructions.ArithNode; import jadx.core.dex.instructions.ConstClassNode; import jadx.core.dex.instructions.ConstStringNode; import jadx.core.dex.instructions.FillArrayInsn; import jadx.core.dex.instructions.FilledNewArrayNode; import jadx.core.dex.instructions.IfNode; import jadx.core.dex.instructions.IfOp; import jadx.core.dex.instructions.IndexInsnNode; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.NewArrayNode; 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.InsnWrapArg; import jadx.core.dex.instructions.args.LiteralArg; import jadx.core.dex.instructions.args.NamedArg; 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.instructions.mods.TernaryInsn; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.IFieldInfoRef; import jadx.core.dex.nodes.IMethodDetails; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.regions.conditions.IfCondition; import jadx.core.dex.trycatch.ExcHandlerAttr; import jadx.core.dex.trycatch.ExceptionHandler; import jadx.core.dex.visitors.regions.variables.ProcessVariables; import jadx.core.dex.visitors.shrink.CodeShrinkVisitor; import jadx.core.dex.visitors.typeinference.TypeCompareEnum; import jadx.core.utils.InsnRemover; import jadx.core.utils.InsnUtils; import jadx.core.utils.exceptions.JadxException; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.utils.BlockUtils.replaceInsn; import static jadx.core.utils.ListUtils.allMatch; /** * Visitor for modify method instructions * (remove, replace, process exception handlers) */ @JadxVisitor( name = "ModVisitor", desc = "Modify method instructions", runBefore = { CodeShrinkVisitor.class, ProcessVariables.class } ) public class ModVisitor extends AbstractVisitor { private static final Logger LOG = LoggerFactory.getLogger(ModVisitor.class); private static final long DOUBLE_TO_BITS = Double.doubleToLongBits(1); private static final long FLOAT_TO_BITS = Float.floatToIntBits(1); @Override public boolean visit(ClassNode cls) throws JadxException { replaceConstInAnnotations(cls); return true; } @Override public void visit(MethodNode mth) { if (mth.isNoCode()) { return; } InsnRemover remover = new InsnRemover(mth); replaceStep(mth, remover); removeStep(mth, remover); iterativeRemoveStep(mth); } private static void replaceStep(MethodNode mth, InsnRemover remover) { ClassNode parentClass = mth.getParentClass(); for (BlockNode block : mth.getBasicBlocks()) { remover.setBlock(block); List<InsnNode> insnsList = block.getInstructions(); int size = insnsList.size(); for (int i = 0; i < size; i++) { InsnNode insn = insnsList.get(i); switch (insn.getType()) { case CONSTRUCTOR: processAnonymousConstructor(mth, ((ConstructorInsn) insn)); break; case CONST: case CONST_STR: case CONST_CLASS: replaceConst(mth, parentClass, block, i, insn); break; case SWITCH: replaceConstKeys(mth, parentClass, (SwitchInsn) insn); break; case NEW_ARRAY: // replace with filled array if 'fill-array' is next instruction NewArrayNode newArrInsn = (NewArrayNode) insn; InsnNode nextInsn = getFirstUseSkipMove(insn.getResult()); if (nextInsn != null && nextInsn.getType() == InsnType.FILL_ARRAY) { FillArrayInsn fillArrInsn = (FillArrayInsn) nextInsn; if (checkArrSizes(mth, newArrInsn, fillArrInsn)) { InsnNode filledArr = makeFilledArrayInsn(mth, newArrInsn, fillArrInsn); replaceInsn(mth, block, i, filledArr); remover.addAndUnbind(nextInsn); } } break; case MOVE_EXCEPTION: processMoveException(mth, block, insn, remover); break; case ARITH: processArith(mth, parentClass, (ArithNode) insn); break; case CMP_L: case CMP_G: inlineCMPInsns(mth, block, i, insn, remover); break; case CHECK_CAST: removeCheckCast(mth, block, i, (IndexInsnNode) insn); break; case CAST: fixPrimitiveCast(mth, block, i, insn); break; case IPUT: case IGET: fixFieldUsage(mth, (IndexInsnNode) insn); break; default: break; } } remover.perform(); } } /** * If field is not visible from use site => cast to origin class */ private static void fixFieldUsage(MethodNode mth, IndexInsnNode insn) { InsnArg instanceArg = insn.getArg(insn.getType() == InsnType.IGET ? 0 : 1); if (instanceArg.contains(AFlag.SUPER)) { return; } if (instanceArg.isInsnWrap() && ((InsnWrapArg) instanceArg).getWrapInsn().getType() == InsnType.CAST) { return; } FieldInfo fieldInfo = (FieldInfo) insn.getIndex(); ArgType clsType = fieldInfo.getDeclClass().getType(); ArgType instanceType = instanceArg.getType(); if (Objects.equals(clsType, instanceType)) { // cast not needed return; } FieldNode fieldNode = mth.root().resolveField(fieldInfo); if (fieldNode == null) { // unknown field TypeCompareEnum result = mth.root().getTypeCompare().compareTypes(instanceType, clsType); if (result.isEqual() || (result == TypeCompareEnum.NARROW_BY_GENERIC && !instanceType.isGenericType())) { return; } } else if (isFieldVisibleInMethod(fieldNode, mth)) { return; } // insert cast IndexInsnNode castInsn = new IndexInsnNode(InsnType.CAST, clsType, 1); castInsn.addArg(instanceArg.duplicate()); castInsn.add(AFlag.SYNTHETIC); castInsn.add(AFlag.EXPLICIT_CAST); InsnArg castArg = InsnArg.wrapInsnIntoArg(castInsn); castArg.setType(clsType); insn.replaceArg(instanceArg, castArg); InsnRemover.unbindArgUsage(mth, instanceArg); } private static boolean isFieldVisibleInMethod(FieldNode field, MethodNode mth) { AccessInfo accessFlags = field.getAccessFlags(); if (accessFlags.isPublic()) { return true; } ClassNode useCls = mth.getParentClass(); ClassNode fieldCls = field.getParentClass(); boolean sameScope = Objects.equals(useCls, fieldCls) && !mth.getAccessFlags().isStatic(); if (sameScope) { return true; } if (accessFlags.isPrivate()) { return false; } // package-private or protected if (Objects.equals(useCls.getClassInfo().getPackage(), fieldCls.getClassInfo().getPackage())) { // same package return true; } if (accessFlags.isPackagePrivate()) { return false; } // protected TypeCompareEnum result = mth.root().getTypeCompare().compareTypes(useCls, fieldCls); return result == TypeCompareEnum.NARROW; // true if use class is subclass of field class } private static void replaceConstKeys(MethodNode mth, ClassNode parentClass, SwitchInsn insn) { int[] keys = insn.getKeys(); int len = keys.length; for (int k = 0; k < len; k++) { IFieldInfoRef f = parentClass.getConstField(keys[k]); if (f != null) { insn.modifyKey(k, f); addFieldUsage(f, mth); } } } private static void fixPrimitiveCast(MethodNode mth, BlockNode block, int i, InsnNode insn) { // replace boolean to (byte/char/short/long/double/float) cast with ternary InsnArg castArg = insn.getArg(0); if (castArg.getType() == ArgType.BOOLEAN) { ArgType type = insn.getResult().getType(); if (type.isPrimitive()) { TernaryInsn ternary = makeBooleanConvertInsn(insn.getResult(), castArg, type); replaceInsn(mth, block, i, ternary); } } } public static TernaryInsn makeBooleanConvertInsn(RegisterArg result, InsnArg castArg, ArgType type) { InsnArg zero = LiteralArg.make(0, type); long litVal = 1; if (type == ArgType.DOUBLE) { litVal = DOUBLE_TO_BITS; } else if (type == ArgType.FLOAT) { litVal = FLOAT_TO_BITS; } InsnArg one = LiteralArg.make(litVal, type); IfNode ifNode = new IfNode(IfOp.EQ, -1, castArg, LiteralArg.litTrue()); IfCondition condition = IfCondition.fromIfNode(ifNode); return new TernaryInsn(condition, result, one, zero); } private void replaceConstInAnnotations(ClassNode cls) { if (cls.root().getArgs().isReplaceConsts()) { replaceConstsInAnnotationForAttrNode(cls, cls); cls.getFields().forEach(f -> replaceConstsInAnnotationForAttrNode(cls, f)); cls.getMethods().forEach((m) -> { replaceConstsInAnnotationForAttrNode(cls, m); replaceConstsInAnnotationForMethodParamsAttr(cls, m); }); } } private void replaceConstsInAnnotationForMethodParamsAttr(ClassNode cls, MethodNode m) { AnnotationMethodParamsAttr paramsAnnotation = m.get(JadxAttrType.ANNOTATION_MTH_PARAMETERS); if (paramsAnnotation == null) { return; } paramsAnnotation.getParamList().forEach(annotationsList -> replaceConstsInAnnotationsAttr(cls, annotationsList)); } private void replaceConstsInAnnotationForAttrNode(ClassNode parentCls, AttrNode attrNode) { AnnotationsAttr annotationsList = attrNode.get(JadxAttrType.ANNOTATION_LIST); replaceConstsInAnnotationsAttr(parentCls, annotationsList); } private void replaceConstsInAnnotationsAttr(ClassNode parentCls, AnnotationsAttr annotationsList) { if (annotationsList == null) { return; } for (IAnnotation annotation : annotationsList.getAll()) { if (annotation.getVisibility() == AnnotationVisibility.SYSTEM) { continue; } for (Map.Entry<String, EncodedValue> entry : annotation.getValues().entrySet()) { entry.setValue(replaceConstValue(parentCls, entry.getValue())); } } } @SuppressWarnings("unchecked") private EncodedValue replaceConstValue(ClassNode parentCls, EncodedValue encodedValue) { if (encodedValue.getType() == EncodedType.ENCODED_ANNOTATION) { IAnnotation annotation = (IAnnotation) encodedValue.getValue(); for (Map.Entry<String, EncodedValue> entry : annotation.getValues().entrySet()) { entry.setValue(replaceConstValue(parentCls, entry.getValue())); } return encodedValue; } if (encodedValue.getType() == EncodedType.ENCODED_ARRAY) { List<EncodedValue> listVal = (List<EncodedValue>) encodedValue.getValue(); if (!listVal.isEmpty()) { listVal.replaceAll(v -> replaceConstValue(parentCls, v)); } return new EncodedValue(EncodedType.ENCODED_ARRAY, listVal); } IFieldInfoRef constField = parentCls.getConstField(encodedValue.getValue()); if (constField != null) { return new EncodedValue(EncodedType.ENCODED_FIELD, constField.getFieldInfo()); } return encodedValue; } private static void replaceConst(MethodNode mth, ClassNode parentClass, BlockNode block, int i, InsnNode insn) { IFieldInfoRef f; if (insn.getType() == InsnType.CONST_STR) { String s = ((ConstStringNode) insn).getString(); f = parentClass.getConstField(s); } else if (insn.getType() == InsnType.CONST_CLASS) { ArgType t = ((ConstClassNode) insn).getClsType(); f = parentClass.getConstField(t); } else { f = parentClass.getConstFieldByLiteralArg((LiteralArg) insn.getArg(0)); } if (f != null) { InsnNode inode = new IndexInsnNode(InsnType.SGET, f.getFieldInfo(), 0); inode.setResult(insn.getResult()); replaceInsn(mth, block, i, inode); addFieldUsage(f, mth); } } private static void processArith(MethodNode mth, ClassNode parentClass, ArithNode arithNode) { if (arithNode.getArgsCount() != 2) { throw new JadxRuntimeException("Invalid args count in insn: " + arithNode); } InsnArg litArg = arithNode.getArg(1); if (litArg.isLiteral()) { IFieldInfoRef f = parentClass.getConstFieldByLiteralArg((LiteralArg) litArg); if (f != null) { InsnNode fGet = new IndexInsnNode(InsnType.SGET, f.getFieldInfo(), 0); if (arithNode.replaceArg(litArg, InsnArg.wrapArg(fGet))) { addFieldUsage(f, mth); } } } } /** * Inline CMP instructions into 'if' to help conditions merging */ private static void inlineCMPInsns(MethodNode mth, BlockNode block, int i, InsnNode insn, InsnRemover remover) { RegisterArg resArg = insn.getResult(); List<RegisterArg> useList = resArg.getSVar().getUseList(); if (allMatch(useList, use -> InsnUtils.isInsnType(use.getParentInsn(), InsnType.IF))) { for (RegisterArg useArg : new ArrayList<>(useList)) { InsnNode useInsn = useArg.getParentInsn(); if (useInsn != null) { InsnArg wrapArg = InsnArg.wrapInsnIntoArg(insn.copyWithoutResult()); if (!useInsn.replaceArg(useArg, wrapArg)) { mth.addWarnComment("Failed to inline CMP insn: " + insn + " into " + useInsn); return; } } } remover.addAndUnbind(insn); } } private static boolean checkArrSizes(MethodNode mth, NewArrayNode newArrInsn, FillArrayInsn fillArrInsn) { int dataSize = fillArrInsn.getSize(); InsnArg arrSizeArg = newArrInsn.getArg(0); Object value = InsnUtils.getConstValueByArg(mth.root(), arrSizeArg); if (value instanceof LiteralArg) { long literal = ((LiteralArg) value).getLiteral(); return dataSize == (int) literal; } return false; } private static void removeCheckCast(MethodNode mth, BlockNode block, int i, IndexInsnNode insn) { InsnArg castArg = insn.getArg(0); if (castArg.isZeroLiteral()) { // always keep cast for 'null' insn.add(AFlag.EXPLICIT_CAST); return; } ArgType castType = (ArgType) insn.getIndex(); if (!ArgType.isCastNeeded(mth.root(), castArg.getType(), castType)) { RegisterArg result = insn.getResult(); result.setType(castArg.getType()); InsnNode move = new InsnNode(InsnType.MOVE, 1); move.setResult(result); move.addArg(castArg); replaceInsn(mth, block, i, move); return; } InsnNode prevCast = isCastDuplicate(insn); if (prevCast != null) { // replace previous cast with move InsnNode move = new InsnNode(InsnType.MOVE, 1); move.setResult(prevCast.getResult()); move.addArg(prevCast.getArg(0)); replaceInsn(mth, block, prevCast, move); } } private static @Nullable InsnNode isCastDuplicate(IndexInsnNode castInsn) { InsnArg arg = castInsn.getArg(0); if (arg.isRegister()) { SSAVar sVar = ((RegisterArg) arg).getSVar(); if (sVar != null && sVar.getUseCount() == 1 && !sVar.isUsedInPhi()) { InsnNode assignInsn = sVar.getAssign().getParentInsn(); if (assignInsn != null && assignInsn.getType() == InsnType.CHECK_CAST) { ArgType assignCastType = (ArgType) ((IndexInsnNode) assignInsn).getIndex(); if (assignCastType.equals(castInsn.getIndex())) { return assignInsn; } } } } return null; } /** * Remove unnecessary instructions */ private static void removeStep(MethodNode mth, InsnRemover remover) { for (BlockNode block : mth.getBasicBlocks()) { remover.setBlock(block); for (InsnNode insn : block.getInstructions()) { switch (insn.getType()) { case NOP: case GOTO: case NEW_INSTANCE: remover.addAndUnbind(insn); break; default: if (insn.contains(AFlag.REMOVE)) { remover.addAndUnbind(insn); } break; } } remover.perform(); } } private static void iterativeRemoveStep(MethodNode mth) { boolean changed; do { changed = false; for (BlockNode block : mth.getBasicBlocks()) { for (InsnNode insn : block.getInstructions()) { if (insn.getType() == InsnType.MOVE && insn.isAttrStorageEmpty() && isResultArgNotUsed(insn)) { InsnRemover.remove(mth, block, insn); changed = true; break; } } } } while (changed); } private static boolean isResultArgNotUsed(InsnNode insn) { RegisterArg result = insn.getResult(); if (result != null) { SSAVar ssaVar = result.getSVar(); return ssaVar.getUseCount() == 0; } return false; } /** * For args in anonymous constructor invoke apply: * - forbid inline into constructor call * - make variables final (compiler require this implicitly) */ private static void processAnonymousConstructor(MethodNode mth, ConstructorInsn co) { IMethodDetails callMthDetails = mth.root().getMethodUtils().getMethodDetails(co); if (!(callMthDetails instanceof MethodNode)) { return; } MethodNode callMth = (MethodNode) callMthDetails; if (!callMth.contains(AFlag.ANONYMOUS_CONSTRUCTOR) || callMth.contains(AFlag.NO_SKIP_ARGS)) { return; } SkipMethodArgsAttr attr = callMth.get(AType.SKIP_MTH_ARGS); if (attr != null) { int argsCount = Math.min(callMth.getMethodInfo().getArgsCount(), co.getArgsCount()); for (int i = 0; i < argsCount; i++) { if (attr.isSkip(i)) { anonymousCallArgMod(co.getArg(i)); } } } else { // additional info not available apply mods to all args (the safest solution) co.getArguments().forEach(ModVisitor::anonymousCallArgMod); } } private static void anonymousCallArgMod(InsnArg arg) { arg.add(AFlag.DONT_INLINE); if (arg.isRegister()) { ((RegisterArg) arg).getSVar().getCodeVar().setFinal(true); } } /** * Return first usage instruction for arg. * If used only once try to follow move chain */ @Nullable private static InsnNode getFirstUseSkipMove(RegisterArg arg) { SSAVar sVar = arg.getSVar(); int useCount = sVar.getUseCount(); if (useCount == 0) { return null; } RegisterArg useArg = sVar.getUseList().get(0); InsnNode parentInsn = useArg.getParentInsn(); if (parentInsn == null) { return null; } if (useCount == 1 && parentInsn.getType() == InsnType.MOVE) { return getFirstUseSkipMove(parentInsn.getResult()); } return parentInsn; } private static InsnNode makeFilledArrayInsn(MethodNode mth, NewArrayNode newArrayNode, FillArrayInsn insn) { ArgType insnArrayType = newArrayNode.getArrayType(); ArgType insnElementType = insnArrayType.getArrayElement(); ArgType elType = insn.getElementType(); if (!elType.isTypeKnown() && insnElementType.isPrimitive() && elType.contains(insnElementType.getPrimitiveType())) { elType = insnElementType; } if (!elType.equals(insnElementType) && !insnArrayType.equals(ArgType.OBJECT)) { mth.addWarn("Incorrect type for fill-array insn " + InsnUtils.formatOffset(insn.getOffset()) + ", element type: " + elType + ", insn element type: " + insnElementType); } if (!elType.isTypeKnown()) { LOG.warn("Unknown array element type: {} in mth: {}", elType, mth); elType = insnElementType.isTypeKnown() ? insnElementType : elType.selectFirst(); if (elType == null) { throw new JadxRuntimeException("Null array element type"); } } List<LiteralArg> list = insn.getLiteralArgs(elType); InsnNode filledArr = new FilledNewArrayNode(elType, list.size()); filledArr.setResult(newArrayNode.getResult().duplicate()); for (LiteralArg arg : list) { IFieldInfoRef f = mth.getParentClass().getConstFieldByLiteralArg(arg); if (f != null) { InsnNode fGet = new IndexInsnNode(InsnType.SGET, f.getFieldInfo(), 0); filledArr.addArg(InsnArg.wrapArg(fGet)); addFieldUsage(f, mth); } else { filledArr.addArg(arg.duplicate()); } } return filledArr; } private static void processMoveException(MethodNode mth, BlockNode block, InsnNode insn, InsnRemover remover) { ExcHandlerAttr excHandlerAttr = block.get(AType.EXC_HANDLER); if (excHandlerAttr == null) { return; } ExceptionHandler excHandler = excHandlerAttr.getHandler(); // result arg used both in this insn and exception handler, RegisterArg resArg = insn.getResult(); ArgType type = excHandler.getArgType(); String name = excHandler.isCatchAll() ? "th" : "e"; if (resArg.getName() == null) { resArg.setName(name); } SSAVar sVar = insn.getResult().getSVar(); if (sVar.getUseCount() == 0) { excHandler.setArg(new NamedArg(name, type)); remover.addAndUnbind(insn); } else if (sVar.isUsedInPhi()) { // exception var moved to external variable => replace with 'move' insn InsnNode moveInsn = new InsnNode(InsnType.MOVE, 1); moveInsn.setResult(insn.getResult()); NamedArg namedArg = new NamedArg(name, type); moveInsn.addArg(namedArg); excHandler.setArg(namedArg); replaceInsn(mth, block, 0, moveInsn); } block.copyAttributeFrom(insn, AType.CODE_COMMENTS); // save comment } public static void addFieldUsage(IFieldInfoRef fieldData, MethodNode mth) { if (fieldData instanceof FieldNode) { ((FieldNode) fieldData).addUseIn(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/AttachTryCatchVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/AttachTryCatchVisitor.java
package jadx.core.dex.visitors; import java.util.ArrayList; import java.util.List; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.plugins.input.data.ICatch; import jadx.api.plugins.input.data.ITry; 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.info.ClassInfo; import jadx.core.dex.instructions.InsnType; 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.utils.exceptions.JadxException; import static jadx.core.dex.visitors.ProcessInstructionsVisitor.getNextInsnOffset; @JadxVisitor( name = "Attach Try/Catch Visitor", desc = "Attach try/catch info to instructions", runBefore = { ProcessInstructionsVisitor.class } ) public class AttachTryCatchVisitor extends AbstractVisitor { private static final Logger LOG = LoggerFactory.getLogger(AttachTryCatchVisitor.class); @Override public void visit(MethodNode mth) throws JadxException { if (mth.isNoCode()) { return; } initTryCatches(mth, mth.getInstructions(), mth.getCodeReader().getTries()); } private static void initTryCatches(MethodNode mth, InsnNode[] insnByOffset, List<ITry> tries) { if (tries.isEmpty()) { return; } if (Consts.DEBUG_EXC_HANDLERS) { LOG.debug("Raw try blocks in {}", mth); tries.forEach(tryData -> LOG.debug(" - {}", tryData)); } for (ITry tryData : tries) { List<ExceptionHandler> handlers = convertToHandlers(mth, tryData.getCatch(), insnByOffset); if (handlers.isEmpty()) { continue; } markTryBounds(insnByOffset, tryData, CatchAttr.build(handlers)); } } private static void markTryBounds(InsnNode[] insnByOffset, ITry aTry, CatchAttr catchAttr) { int offset = aTry.getStartOffset(); int end = aTry.getEndOffset(); boolean tryBlockStarted = false; InsnNode insn = null; while (offset <= end) { InsnNode insnAtOffset = insnByOffset[offset]; if (insnAtOffset != null) { insn = insnAtOffset; attachCatchAttr(catchAttr, insn); if (!tryBlockStarted) { insn.add(AFlag.TRY_ENTER); tryBlockStarted = true; } } offset = getNextInsnOffset(insnByOffset, offset); if (offset == -1) { break; } } if (tryBlockStarted) { insn.add(AFlag.TRY_LEAVE); } else { // no instructions found in range -> add nop at start offset InsnNode nop = insertNOP(insnByOffset, aTry.getStartOffset()); nop.add(AFlag.TRY_ENTER); nop.add(AFlag.TRY_LEAVE); nop.addAttr(catchAttr); } } private static void attachCatchAttr(CatchAttr catchAttr, InsnNode insn) { CatchAttr existAttr = insn.get(AType.EXC_CATCH); if (existAttr != null) { // merge handlers List<ExceptionHandler> handlers = Utils.concat(existAttr.getHandlers(), catchAttr.getHandlers()); insn.addAttr(CatchAttr.build(handlers)); } else { insn.addAttr(catchAttr); } } private static List<ExceptionHandler> convertToHandlers(MethodNode mth, ICatch catchBlock, InsnNode[] insnByOffset) { int[] handlerOffsetArr = catchBlock.getHandlers(); String[] handlerTypes = catchBlock.getTypes(); int handlersCount = handlerOffsetArr.length; List<ExceptionHandler> list = new ArrayList<>(handlersCount); for (int i = 0; i < handlersCount; i++) { int handlerOffset = handlerOffsetArr[i]; ClassInfo type = ClassInfo.fromName(mth.root(), handlerTypes[i]); Utils.addToList(list, createHandler(mth, insnByOffset, handlerOffset, type)); } int allHandlerOffset = catchBlock.getCatchAllHandler(); if (allHandlerOffset >= 0) { Utils.addToList(list, createHandler(mth, insnByOffset, allHandlerOffset, null)); } return list; } @Nullable private static ExceptionHandler createHandler(MethodNode mth, InsnNode[] insnByOffset, int handlerOffset, @Nullable ClassInfo type) { InsnNode insn = insnByOffset[handlerOffset]; if (insn != null) { ExcHandlerAttr excHandlerAttr = insn.get(AType.EXC_HANDLER); if (excHandlerAttr != null) { ExceptionHandler handler = excHandlerAttr.getHandler(); if (handler.addCatchType(mth, type)) { // exist handler updated (assume from same try block) - don't add again return null; } // same handler (can be used in different try blocks) return handler; } } else { insn = insertNOP(insnByOffset, handlerOffset); } ExceptionHandler handler = ExceptionHandler.build(mth, handlerOffset, type); mth.addExceptionHandler(handler); insn.addAttr(new ExcHandlerAttr(handler)); return handler; } private static InsnNode insertNOP(InsnNode[] insnByOffset, int offset) { InsnNode nop = new InsnNode(InsnType.NOP, 0); nop.setOffset(offset); nop.add(AFlag.SYNTHETIC); insnByOffset[offset] = nop; return nop; } }
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/AttachCommentsVisitor.java
jadx-core/src/main/java/jadx/core/dex/visitors/AttachCommentsVisitor.java
package jadx.core.dex.visitors; 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.CodeRefType; import jadx.api.data.ICodeComment; import jadx.api.data.ICodeData; import jadx.api.data.IJavaCodeRef; import jadx.api.data.IJavaNodeRef; import jadx.core.codegen.utils.CodeComment; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.IAttributeNode; 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.utils.exceptions.JadxException; import jadx.core.utils.exceptions.JadxRuntimeException; @JadxVisitor( name = "AttachComments", desc = "Attach user code comments", runBefore = { ProcessInstructionsVisitor.class } ) public class AttachCommentsVisitor extends AbstractVisitor { private static final Logger LOG = LoggerFactory.getLogger(AttachCommentsVisitor.class); private Map<String, List<ICodeComment>> clsCommentsMap; @Override public void init(RootNode root) throws JadxException { updateCommentsData(root.getArgs().getCodeData()); root.registerCodeDataUpdateListener(this::updateCommentsData); } @Override public boolean visit(ClassNode cls) { List<ICodeComment> clsComments = getCommentsData(cls); if (!clsComments.isEmpty()) { applyComments(cls, clsComments); } cls.getInnerClasses().forEach(this::visit); return false; } private static void applyComments(ClassNode cls, List<ICodeComment> clsComments) { for (ICodeComment comment : clsComments) { IJavaNodeRef nodeRef = comment.getNodeRef(); switch (nodeRef.getType()) { case CLASS: addComment(cls, comment); break; case FIELD: FieldNode fieldNode = cls.searchFieldByShortId(nodeRef.getShortId()); if (fieldNode == null) { LOG.warn("Field reference not found: {}", nodeRef); } else { addComment(fieldNode, comment); } break; case METHOD: MethodNode methodNode = cls.searchMethodByShortId(nodeRef.getShortId()); if (methodNode == null) { LOG.warn("Method reference not found: {}", nodeRef); } else { IJavaCodeRef codeRef = comment.getCodeRef(); if (codeRef == null) { addComment(methodNode, comment); } else { processCustomAttach(methodNode, codeRef, comment); } } break; } } } private static InsnNode getInsnByOffset(MethodNode mth, int offset) { try { return mth.getInstructions()[offset]; } catch (Exception e) { LOG.warn("Insn reference not found in: {} with offset: {}", mth, offset); return null; } } private static void processCustomAttach(MethodNode mth, IJavaCodeRef codeRef, ICodeComment comment) { CodeRefType attachType = codeRef.getAttachType(); switch (attachType) { case INSN: { InsnNode insn = getInsnByOffset(mth, codeRef.getIndex()); addComment(insn, comment); break; } default: throw new JadxRuntimeException("Unexpected attach type: " + attachType); } } private static void addComment(@Nullable IAttributeNode node, ICodeComment comment) { if (node == null) { return; } node.addAttr(AType.CODE_COMMENTS, new CodeComment(comment)); } private List<ICodeComment> getCommentsData(ClassNode cls) { if (clsCommentsMap == null) { return Collections.emptyList(); } List<ICodeComment> clsComments = clsCommentsMap.get(cls.getClassInfo().getRawName()); if (clsComments == null) { return Collections.emptyList(); } return clsComments; } private void updateCommentsData(@Nullable ICodeData data) { if (data == null) { this.clsCommentsMap = Collections.emptyMap(); } else { this.clsCommentsMap = data.getComments().stream() .collect(Collectors.groupingBy(c -> c.getNodeRef().getDeclaringClass())); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false