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-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/trycatch/JavaSingleCatch.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/trycatch/JavaSingleCatch.java
package jadx.plugins.input.java.data.code.trycatch; import org.jetbrains.annotations.Nullable; public class JavaSingleCatch { private final int handler; private final @Nullable String type; public JavaSingleCatch(int handler, @Nullable String type) { this.handler = handler; this.type = type; } public int getHandler() { return handler; } public @Nullable String getType() { return type; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/WideDecoder.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/WideDecoder.java
package jadx.plugins.input.java.data.code.decoders; import jadx.api.plugins.input.insns.Opcode; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.code.CodeDecodeState; import jadx.plugins.input.java.data.code.JavaInsnData; import jadx.plugins.input.java.utils.JavaClassParseException; public class WideDecoder implements IJavaInsnDecoder { private static final int IINC = 0x84; @Override public void decode(CodeDecodeState state) { DataReader reader = state.reader(); JavaInsnData insn = state.insn(); int opcode = reader.readU1(); if (opcode == IINC) { int varNum = reader.readU2(); int constValue = reader.readS2(); state.local(0, varNum).local(1, varNum).lit(constValue); insn.setPayloadSize(5); insn.setRegsCount(2); insn.setOpcode(Opcode.ADD_INT_LIT); return; } int index = reader.readU2(); switch (opcode) { case 0x15: // iload, case 0x17: // fload case 0x19: // aload state.local(1, index).push(0); break; case 0x16: // lload case 0x18: // dload state.local(1, index).pushWide(0); break; case 0x36: case 0x37: case 0x38: case 0x39: case 0x3a: // *store state.pop(1).local(0, index); break; default: throw new JavaClassParseException("Unexpected opcode in 'wide': 0x" + Integer.toHexString(opcode)); } insn.setPayloadSize(3); insn.setRegsCount(2); insn.setOpcode(Opcode.MOVE); } @Override public void skip(CodeDecodeState state) { DataReader reader = state.reader(); JavaInsnData insn = state.insn(); int opcode = reader.readU1(); if (opcode == IINC) { reader.skip(4); insn.setPayloadSize(5); } else { reader.skip(2); insn.setPayloadSize(3); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/LookupSwitchDecoder.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/LookupSwitchDecoder.java
package jadx.plugins.input.java.data.code.decoders; import jadx.api.plugins.input.insns.custom.impl.SwitchPayload; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.code.CodeDecodeState; import jadx.plugins.input.java.data.code.JavaInsnData; public class LookupSwitchDecoder implements IJavaInsnDecoder { @Override public void decode(CodeDecodeState state) { read(state, false); } @Override public void skip(CodeDecodeState state) { read(state, true); } private static void read(CodeDecodeState state, boolean skip) { DataReader reader = state.reader(); JavaInsnData insn = state.insn(); int dataOffset = reader.getOffset(); int insnOffset = insn.getOffset(); reader.skip(3 - insnOffset % 4); int defTarget = insnOffset + reader.readS4(); int pairs = reader.readS4(); if (skip) { reader.skip(pairs * 8); } else { state.pop(0); int[] keys = new int[pairs]; int[] targets = new int[pairs]; for (int i = 0; i < pairs; i++) { keys[i] = reader.readS4(); int target = insnOffset + reader.readS4(); targets[i] = target; state.registerJump(target); } insn.setTarget(defTarget); state.registerJump(defTarget); insn.setPayload(new SwitchPayload(pairs, keys, targets)); } insn.setPayloadSize(reader.getOffset() - dataOffset); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/TableSwitchDecoder.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/TableSwitchDecoder.java
package jadx.plugins.input.java.data.code.decoders; import jadx.api.plugins.input.insns.custom.impl.SwitchPayload; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.code.CodeDecodeState; import jadx.plugins.input.java.data.code.JavaInsnData; public class TableSwitchDecoder implements IJavaInsnDecoder { @Override public void decode(CodeDecodeState state) { read(state, false); } @Override public void skip(CodeDecodeState state) { read(state, true); } private static void read(CodeDecodeState state, boolean skip) { DataReader reader = state.reader(); JavaInsnData insn = state.insn(); int dataOffset = reader.getOffset(); int insnOffset = insn.getOffset(); reader.skip(3 - insnOffset % 4); int defTarget = insnOffset + reader.readS4(); int low = reader.readS4(); int high = reader.readS4(); int count = high - low + 1; if (skip) { reader.skip(count * 4); } else { state.pop(0); int[] keys = new int[count]; int[] targets = new int[count]; for (int i = 0; i < count; i++) { int target = insnOffset + reader.readS4(); keys[i] = low + i; targets[i] = target; state.registerJump(target); } insn.setTarget(defTarget); state.registerJump(defTarget); insn.setPayload(new SwitchPayload(count, keys, targets)); } insn.setPayloadSize(reader.getOffset() - dataOffset); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/IJavaInsnDecoder.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/IJavaInsnDecoder.java
package jadx.plugins.input.java.data.code.decoders; import jadx.plugins.input.java.data.code.CodeDecodeState; public interface IJavaInsnDecoder { void decode(CodeDecodeState state); default void skip(CodeDecodeState state) { } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/InvokeDecoder.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/InvokeDecoder.java
package jadx.plugins.input.java.data.code.decoders; import jadx.api.plugins.input.data.ICallSite; import jadx.api.plugins.input.data.IMethodProto; import jadx.api.plugins.input.data.IMethodRef; import jadx.api.plugins.input.insns.Opcode; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.code.CodeDecodeState; import jadx.plugins.input.java.data.code.JavaInsnData; public class InvokeDecoder implements IJavaInsnDecoder { private final int payloadSize; private final Opcode apiOpcode; public InvokeDecoder(int payloadSize, Opcode apiOpcode) { this.payloadSize = payloadSize; this.apiOpcode = apiOpcode; } @Override public void decode(CodeDecodeState state) { DataReader reader = state.reader(); int mthIdx = reader.readS2(); if (payloadSize == 4) { reader.skip(2); } JavaInsnData insn = state.insn(); insn.setIndex(mthIdx); boolean instanceCall; IMethodProto mthProto; if (apiOpcode == Opcode.INVOKE_CUSTOM) { ICallSite callSite = insn.getIndexAsCallSite(); insn.setPayload(callSite); mthProto = (IMethodProto) callSite.getValues().get(2).getValue(); instanceCall = false; // 'this' arg already included in proto args } else { IMethodRef mthRef = insn.getIndexAsMethod(); mthRef.load(); insn.setPayload(mthRef); mthProto = mthRef; instanceCall = apiOpcode != Opcode.INVOKE_STATIC; } int argsCount = mthProto.getArgTypes().size(); if (instanceCall) { argsCount++; } insn.setRegsCount(argsCount * 2); // allocate twice of the size for worst case int[] regs = insn.getRegsArray(); // calculate actual count of registers // set '1' in regs to be filled with stack values later, '0' for skip int regsCount = 0; if (instanceCall) { regs[regsCount++] = 1; } for (String type : mthProto.getArgTypes()) { int size = getRegsCountForType(type); regs[regsCount++] = 1; if (size == 2) { regs[regsCount++] = 0; } } insn.setRegsCount(regsCount); for (int i = regsCount - 1; i >= 0; i--) { if (regs[i] == 1) { state.pop(i); } } String returnType = mthProto.getReturnType(); if (!returnType.equals("V")) { insn.setResultReg(state.push(returnType)); } else { insn.setResultReg(-1); } } private int getRegsCountForType(String type) { char c = type.charAt(0); if (c == 'J' || c == 'D') { return 2; } return 1; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/LoadConstDecoder.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/code/decoders/LoadConstDecoder.java
package jadx.plugins.input.java.data.code.decoders; import jadx.api.plugins.input.insns.Opcode; import jadx.plugins.input.java.data.ConstPoolReader; import jadx.plugins.input.java.data.ConstantType; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.attributes.stack.StackValueType; import jadx.plugins.input.java.data.code.CodeDecodeState; import jadx.plugins.input.java.data.code.JavaInsnData; import jadx.plugins.input.java.utils.JavaClassParseException; public class LoadConstDecoder implements IJavaInsnDecoder { private final boolean wide; public LoadConstDecoder(boolean wide) { this.wide = wide; } @Override public void decode(CodeDecodeState state) { DataReader reader = state.reader(); JavaInsnData insn = state.insn(); int index; if (wide) { index = reader.readU2(); } else { index = reader.readU1(); } ConstPoolReader constPoolReader = insn.constPoolReader(); ConstantType constType = constPoolReader.jumpToConst(index); switch (constType) { case INTEGER: case FLOAT: insn.setLiteral(constPoolReader.readU4()); insn.setOpcode(Opcode.CONST); state.push(0, StackValueType.NARROW); break; case LONG: case DOUBLE: insn.setLiteral(constPoolReader.readU8()); insn.setOpcode(Opcode.CONST_WIDE); state.push(0, StackValueType.WIDE); break; case STRING: insn.setIndex(constPoolReader.readU2()); insn.setOpcode(Opcode.CONST_STRING); state.push(0, StackValueType.NARROW); break; case UTF8: insn.setIndex(index); insn.setOpcode(Opcode.CONST_STRING); state.push(0, StackValueType.NARROW); break; case CLASS: insn.setIndex(index); insn.setOpcode(Opcode.CONST_CLASS); state.push(0, StackValueType.NARROW); break; default: throw new JavaClassParseException("Unsupported constant type: " + constType); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/IJavaAttribute.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/IJavaAttribute.java
package jadx.plugins.input.java.data.attributes; public interface IJavaAttribute { }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/JavaAttrStorage.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/JavaAttrStorage.java
package jadx.plugins.input.java.data.attributes; import org.jetbrains.annotations.Nullable; public class JavaAttrStorage { public static final JavaAttrStorage EMPTY = new JavaAttrStorage(); private final IJavaAttribute[] map = new IJavaAttribute[JavaAttrType.size()]; public void add(JavaAttrType<?> type, IJavaAttribute value) { map[type.getId()] = value; } @SuppressWarnings("unchecked") @Nullable public <A extends IJavaAttribute> A get(JavaAttrType<A> type) { return (A) map[type.getId()]; } public int size() { int size = 0; for (IJavaAttribute attr : map) { if (attr != null) { size++; } } return size; } @Override public String toString() { return "AttributesStorage{size=" + size() + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/IJavaAttributeReader.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/IJavaAttributeReader.java
package jadx.plugins.input.java.data.attributes; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.JavaClassData; public interface IJavaAttributeReader { IJavaAttribute read(JavaClassData clsData, DataReader reader); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/JavaAttrType.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/JavaAttrType.java
package jadx.plugins.input.java.data.attributes; import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.annotations.AnnotationVisibility; import jadx.plugins.input.java.data.attributes.debuginfo.LineNumberTableAttr; import jadx.plugins.input.java.data.attributes.debuginfo.LocalVarTypesAttr; import jadx.plugins.input.java.data.attributes.debuginfo.LocalVarsAttr; import jadx.plugins.input.java.data.attributes.stack.StackMapTableReader; import jadx.plugins.input.java.data.attributes.types.CodeAttr; import jadx.plugins.input.java.data.attributes.types.ConstValueAttr; import jadx.plugins.input.java.data.attributes.types.IgnoredAttr; import jadx.plugins.input.java.data.attributes.types.JavaAnnotationDefaultAttr; import jadx.plugins.input.java.data.attributes.types.JavaAnnotationsAttr; import jadx.plugins.input.java.data.attributes.types.JavaBootstrapMethodsAttr; import jadx.plugins.input.java.data.attributes.types.JavaExceptionsAttr; import jadx.plugins.input.java.data.attributes.types.JavaInnerClsAttr; import jadx.plugins.input.java.data.attributes.types.JavaMethodParametersAttr; import jadx.plugins.input.java.data.attributes.types.JavaParamAnnsAttr; import jadx.plugins.input.java.data.attributes.types.JavaSignatureAttr; import jadx.plugins.input.java.data.attributes.types.JavaSourceFileAttr; import jadx.plugins.input.java.data.attributes.types.StackMapTableAttr; public final class JavaAttrType<T extends IJavaAttribute> { private static final Map<String, JavaAttrType<?>> NAME_TO_TYPE_MAP; public static final JavaAttrType<JavaInnerClsAttr> INNER_CLASSES; public static final JavaAttrType<JavaBootstrapMethodsAttr> BOOTSTRAP_METHODS; public static final JavaAttrType<ConstValueAttr> CONST_VALUE; public static final JavaAttrType<CodeAttr> CODE; public static final JavaAttrType<StackMapTableAttr> STACK_MAP_TABLE; public static final JavaAttrType<LineNumberTableAttr> LINE_NUMBER_TABLE; public static final JavaAttrType<LocalVarsAttr> LOCAL_VAR_TABLE; public static final JavaAttrType<LocalVarTypesAttr> LOCAL_VAR_TYPE_TABLE; public static final JavaAttrType<JavaAnnotationsAttr> RUNTIME_ANNOTATIONS; public static final JavaAttrType<JavaAnnotationsAttr> BUILD_ANNOTATIONS; public static final JavaAttrType<JavaParamAnnsAttr> RUNTIME_PARAMETER_ANNOTATIONS; public static final JavaAttrType<JavaParamAnnsAttr> BUILD_PARAMETER_ANNOTATIONS; public static final JavaAttrType<IgnoredAttr> RUNTIME_TYPE_ANNOTATIONS; public static final JavaAttrType<IgnoredAttr> BUILD_TYPE_ANNOTATIONS; public static final JavaAttrType<JavaAnnotationDefaultAttr> ANNOTATION_DEFAULT; public static final JavaAttrType<JavaSourceFileAttr> SOURCE_FILE; public static final JavaAttrType<JavaSignatureAttr> SIGNATURE; public static final JavaAttrType<JavaExceptionsAttr> EXCEPTIONS; public static final JavaAttrType<JavaMethodParametersAttr> METHOD_PARAMETERS; public static final JavaAttrType<IgnoredAttr> DEPRECATED; public static final JavaAttrType<IgnoredAttr> SYNTHETIC; public static final JavaAttrType<IgnoredAttr> ENCLOSING_METHOD; public static final JavaAttrType<IgnoredAttr> MODULE; public static final JavaAttrType<IgnoredAttr> SOURCE_DEBUG_EXTENSION; public static final JavaAttrType<IgnoredAttr> NEST_HOST; public static final JavaAttrType<IgnoredAttr> NEST_MEMBERS; static { NAME_TO_TYPE_MAP = new HashMap<>(); CONST_VALUE = bind("ConstantValue", ConstValueAttr.reader()); CODE = bind("Code", CodeAttr.reader()); LINE_NUMBER_TABLE = bind("LineNumberTable", LineNumberTableAttr.reader()); LOCAL_VAR_TABLE = bind("LocalVariableTable", LocalVarsAttr.reader()); LOCAL_VAR_TYPE_TABLE = bind("LocalVariableTypeTable", LocalVarTypesAttr.reader()); INNER_CLASSES = bind("InnerClasses", JavaInnerClsAttr.reader()); BOOTSTRAP_METHODS = bind("BootstrapMethods", JavaBootstrapMethodsAttr.reader()); RUNTIME_ANNOTATIONS = bind("RuntimeVisibleAnnotations", JavaAnnotationsAttr.reader(AnnotationVisibility.RUNTIME)); BUILD_ANNOTATIONS = bind("RuntimeInvisibleAnnotations", JavaAnnotationsAttr.reader(AnnotationVisibility.BUILD)); RUNTIME_PARAMETER_ANNOTATIONS = bind("RuntimeVisibleParameterAnnotations", JavaParamAnnsAttr.reader(AnnotationVisibility.RUNTIME)); BUILD_PARAMETER_ANNOTATIONS = bind("RuntimeInvisibleParameterAnnotations", JavaParamAnnsAttr.reader(AnnotationVisibility.BUILD)); ANNOTATION_DEFAULT = bind("AnnotationDefault", JavaAnnotationDefaultAttr.reader()); SOURCE_FILE = bind("SourceFile", JavaSourceFileAttr.reader()); SIGNATURE = bind("Signature", JavaSignatureAttr.reader()); EXCEPTIONS = bind("Exceptions", JavaExceptionsAttr.reader()); METHOD_PARAMETERS = bind("MethodParameters", JavaMethodParametersAttr.reader()); STACK_MAP_TABLE = bind("StackMapTable", new StackMapTableReader()); // ignored DEPRECATED = bind("Deprecated", null); // duplicated by annotation SYNTHETIC = bind("Synthetic", null); // duplicated by access flag ENCLOSING_METHOD = bind("EnclosingMethod", null); // TODO: not supported yet RUNTIME_TYPE_ANNOTATIONS = bind("RuntimeVisibleTypeAnnotations", null); BUILD_TYPE_ANNOTATIONS = bind("RuntimeInvisibleTypeAnnotations", null); MODULE = bind("Module", null); NEST_HOST = bind("NestHost", null); NEST_MEMBERS = bind("NestMembers", null); SOURCE_DEBUG_EXTENSION = bind("SourceDebugExtension", null); } private static <A extends IJavaAttribute> JavaAttrType<A> bind(String name, IJavaAttributeReader reader) { JavaAttrType<A> attrType = new JavaAttrType<>(NAME_TO_TYPE_MAP.size(), name, reader); NAME_TO_TYPE_MAP.put(name, attrType); return attrType; } @Nullable public static JavaAttrType<?> byName(String name) { return NAME_TO_TYPE_MAP.get(name); } public static int size() { return NAME_TO_TYPE_MAP.size(); } private final int id; private final String name; private final IJavaAttributeReader reader; private JavaAttrType(int id, String name, IJavaAttributeReader reader) { this.id = id; this.name = name; this.reader = reader; } public int getId() { return id; } public String getName() { return name; } public IJavaAttributeReader getReader() { return reader; } @Override public int hashCode() { return id; } @Override public boolean equals(Object o) { if (this == o) { return true; } return id == ((JavaAttrType<?>) o).id; } @Override public String toString() { return name; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/AttributesReader.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/AttributesReader.java
package jadx.plugins.input.java.data.attributes; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.plugins.input.java.data.ConstPoolReader; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.JavaClassData; public class AttributesReader { private static final Logger LOG = LoggerFactory.getLogger(AttributesReader.class); private static final Predicate<JavaAttrType<?>> LOAD_ALL = type -> true; private final JavaClassData clsData; private final ConstPoolReader constPool; private final Map<Integer, JavaAttrType<?>> attrCache = new HashMap<>(JavaAttrType.size()); public AttributesReader(JavaClassData clsData, ConstPoolReader constPoolReader) { this.clsData = clsData; this.constPool = constPoolReader; } public JavaAttrStorage loadAll(DataReader reader) { return loadAttributes(reader, LOAD_ALL); } public JavaAttrStorage loadMulti(DataReader reader, Set<JavaAttrType<?>> types) { return loadAttributes(reader, types::contains); } /** * Load attributes into storage * * @param reader - reader pos should be set to attributes section start * @param condition - check if attribute should be parsed and added to storage */ private JavaAttrStorage loadAttributes(DataReader reader, Predicate<JavaAttrType<?>> condition) { int count = reader.readU2(); if (count == 0) { return JavaAttrStorage.EMPTY; } JavaAttrStorage storage = new JavaAttrStorage(); for (int i = 0; i < count; i++) { int nameIdx = reader.readU2(); int len = reader.readU4(); int end = reader.getOffset() + len; try { JavaAttrType<?> attrType = resolveAttrReader(nameIdx); if (attrType != null && condition.test(attrType)) { IJavaAttributeReader attrReader = attrType.getReader(); if (attrReader != null) { IJavaAttribute attrValue = attrReader.read(clsData, reader); if (attrValue != null) { storage.add(attrType, attrValue); } } } } catch (Exception e) { LOG.error("Failed to parse attribute: {}", constPool.getUtf8(nameIdx), e); } finally { reader.absPos(end); } } return storage; } @SuppressWarnings("unchecked") public <T extends IJavaAttribute> @Nullable T loadOne(DataReader reader, JavaAttrType<T> type) { int count = reader.readU2(); for (int i = 0; i < count; i++) { int nameIdx = reader.readU2(); int len = reader.readU4(); int end = reader.getOffset() + len; try { JavaAttrType<?> attrType = resolveAttrReader(nameIdx); if (attrType == type) { return (T) attrType.getReader().read(clsData, reader); } } catch (Exception e) { LOG.error("Failed to parse attribute: {}", constPool.getUtf8(nameIdx), e); } finally { reader.absPos(end); } } return null; } private JavaAttrType<?> resolveAttrReader(int nameIdx) { return attrCache.computeIfAbsent(nameIdx, idx -> { String attrName = constPool.getUtf8(idx); JavaAttrType<?> attrType = JavaAttrType.byName(attrName); if (attrType == null) { LOG.warn("Unknown java class attribute type: {}", attrName); return null; } return attrType; }); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/EncodedValueReader.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/EncodedValueReader.java
package jadx.plugins.input.java.data.attributes; import java.util.ArrayList; import java.util.List; 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.impl.JadxFieldRef; import jadx.plugins.input.java.data.ConstPoolReader; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.JavaClassData; import jadx.plugins.input.java.data.attributes.types.JavaAnnotationsAttr; import jadx.plugins.input.java.utils.JavaClassParseException; public class EncodedValueReader { public static EncodedValue read(JavaClassData clsData, DataReader reader) { ConstPoolReader constPool = clsData.getConstPoolReader(); char tag = (char) reader.readU1(); switch (tag) { case 'B': return new EncodedValue(EncodedType.ENCODED_BYTE, (byte) constPool.getInt(reader.readU2())); case 'C': return new EncodedValue(EncodedType.ENCODED_CHAR, (char) constPool.getInt(reader.readU2())); case 'D': return new EncodedValue(EncodedType.ENCODED_DOUBLE, constPool.getDouble(reader.readU2())); case 'F': return new EncodedValue(EncodedType.ENCODED_FLOAT, constPool.getFloat(reader.readU2())); case 'I': return new EncodedValue(EncodedType.ENCODED_INT, constPool.getInt(reader.readU2())); case 'J': return new EncodedValue(EncodedType.ENCODED_LONG, constPool.getLong(reader.readU2())); case 'S': return new EncodedValue(EncodedType.ENCODED_SHORT, (short) constPool.getInt(reader.readU2())); case 'Z': return new EncodedValue(EncodedType.ENCODED_BOOLEAN, 1 == constPool.getInt(reader.readU2())); case 's': return new EncodedValue(EncodedType.ENCODED_STRING, constPool.getUtf8(reader.readU2())); case 'e': String cls = constPool.getUtf8(reader.readU2()); String name = constPool.getUtf8(reader.readU2()); return new EncodedValue(EncodedType.ENCODED_ENUM, new JadxFieldRef(cls, name, cls)); case 'c': return new EncodedValue(EncodedType.ENCODED_TYPE, constPool.getUtf8(reader.readU2())); case '@': return new EncodedValue(EncodedType.ENCODED_ANNOTATION, JavaAnnotationsAttr.readAnnotation(AnnotationVisibility.RUNTIME, clsData, reader)); case '[': int len = reader.readU2(); List<EncodedValue> values = new ArrayList<>(len); for (int i = 0; i < len; i++) { values.add(read(clsData, reader)); } return new EncodedValue(EncodedType.ENCODED_ARRAY, values); default: throw new JavaClassParseException("Unknown element value tag: " + tag); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/debuginfo/LocalVarsAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/debuginfo/LocalVarsAttr.java
package jadx.plugins.input.java.data.attributes.debuginfo; import java.util.ArrayList; import java.util.List; import jadx.plugins.input.java.data.ConstPoolReader; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class LocalVarsAttr implements IJavaAttribute { private final List<JavaLocalVar> vars; public LocalVarsAttr(List<JavaLocalVar> vars) { this.vars = vars; } public List<JavaLocalVar> getVars() { return vars; } public static IJavaAttributeReader reader() { return (clsData, reader) -> { ConstPoolReader constPool = clsData.getConstPoolReader(); int count = reader.readU2(); List<JavaLocalVar> varsList = new ArrayList<>(count); for (int i = 0; i < count; i++) { int startOffset = reader.readU2(); int length = reader.readU2(); int endOffset = startOffset + length - 1; int nameIdx = reader.readU2(); int typeIdx = reader.readU2(); int varNum = reader.readU2(); varsList.add(new JavaLocalVar(varNum, constPool.getUtf8(nameIdx), constPool.getUtf8(typeIdx), null, startOffset, endOffset)); } return new LocalVarsAttr(varsList); }; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/debuginfo/LineNumberTableAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/debuginfo/LineNumberTableAttr.java
package jadx.plugins.input.java.data.attributes.debuginfo; import java.util.HashMap; import java.util.Map; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class LineNumberTableAttr implements IJavaAttribute { private final Map<Integer, Integer> lineMap; public LineNumberTableAttr(Map<Integer, Integer> sourceLineMap) { this.lineMap = sourceLineMap; } public Map<Integer, Integer> getLineMap() { return lineMap; } public static IJavaAttributeReader reader() { return (clsData, reader) -> { int len = reader.readU2(); Map<Integer, Integer> map = new HashMap<>(len); for (int i = 0; i < len; i++) { int offset = reader.readU2(); int line = reader.readU2(); map.put(offset, line); } return new LineNumberTableAttr(map); }; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/debuginfo/LocalVarTypesAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/debuginfo/LocalVarTypesAttr.java
package jadx.plugins.input.java.data.attributes.debuginfo; import java.util.ArrayList; import java.util.List; import jadx.plugins.input.java.data.ConstPoolReader; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class LocalVarTypesAttr implements IJavaAttribute { private final List<JavaLocalVar> vars; public LocalVarTypesAttr(List<JavaLocalVar> vars) { this.vars = vars; } public List<JavaLocalVar> getVars() { return vars; } public static IJavaAttributeReader reader() { return (clsData, reader) -> { ConstPoolReader constPool = clsData.getConstPoolReader(); int len = reader.readU2(); List<JavaLocalVar> varsList = new ArrayList<>(len); for (int i = 0; i < len; i++) { int startOffset = reader.readU2(); int endOffset = startOffset + reader.readU2() - 1; int nameIdx = reader.readU2(); int typeIdx = reader.readU2(); int varNum = reader.readU2(); varsList.add(new JavaLocalVar( varNum, constPool.getUtf8(nameIdx), null, constPool.getUtf8(typeIdx), startOffset, endOffset)); } return new LocalVarTypesAttr(varsList); }; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/debuginfo/JavaLocalVar.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/debuginfo/JavaLocalVar.java
package jadx.plugins.input.java.data.attributes.debuginfo; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.ILocalVar; public class JavaLocalVar implements ILocalVar { private int regNum; private final String name; private final String type; @Nullable private String sign; private final int startOffset; private final int endOffset; public JavaLocalVar(int regNum, String name, @Nullable String type, @Nullable String sign, int startOffset, int endOffset) { this.regNum = regNum; this.name = name; this.type = type; this.sign = sign; this.startOffset = startOffset; this.endOffset = endOffset; } public void shiftRegNum(int maxStack) { this.regNum += maxStack; // convert local var to register } @Override public String getName() { return name; } @Override public int getRegNum() { return regNum; } @Override public String getType() { return type; } @Override public @Nullable String getSignature() { return sign; } public void setSignature(String sign) { this.sign = sign; } @Override public int getStartOffset() { return startOffset; } @Override public int getEndOffset() { return endOffset; } @Override public boolean isMarkedAsParameter() { return false; } @Override public int hashCode() { int result = regNum; result = 31 * result + name.hashCode(); result = 31 * result + startOffset; result = 31 * result + endOffset; return result; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof JavaLocalVar)) { return false; } JavaLocalVar other = (JavaLocalVar) o; return regNum == other.regNum && startOffset == other.startOffset && endOffset == other.endOffset && name.equals(other.name); } private static String formatOffset(int offset) { return String.format("0x%04x", offset); } @Override public String toString() { return formatOffset(startOffset) + '-' + formatOffset(endOffset) + ": r" + regNum + " '" + name + "' " + type + (sign != null ? ", signature: " + sign : ""); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/StackFrameType.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/StackFrameType.java
package jadx.plugins.input.java.data.attributes.stack; import org.jetbrains.annotations.Nullable; public enum StackFrameType { SAME_FRAME(0, 63), SAME_LOCALS_1_STACK(64, 127), SAME_LOCALS_1_STACK_EXTENDED(247, 247), CHOP(248, 250), SAME_FRAME_EXTENDED(251, 251), APPEND(252, 254), FULL(255, 255); private final int start; private final int end; StackFrameType(int start, int end) { this.start = start; this.end = end; } private static final StackFrameType[] MAPPING = buildMapping(); private static StackFrameType[] buildMapping() { StackFrameType[] mapping = new StackFrameType[256]; for (StackFrameType value : StackFrameType.values()) { for (int i = value.start; i <= value.end; i++) { mapping[i] = value; } } return mapping; } public static @Nullable StackFrameType getType(int data) { return MAPPING[data]; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/StackMapTableReader.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/StackMapTableReader.java
package jadx.plugins.input.java.data.attributes.stack; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.JavaClassData; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; import jadx.plugins.input.java.data.attributes.types.StackMapTableAttr; import jadx.plugins.input.java.utils.JavaClassParseException; public class StackMapTableReader implements IJavaAttributeReader { @Override public IJavaAttribute read(JavaClassData clsData, DataReader reader) { int count = reader.readU2(); Map<Integer, StackFrame> map = new HashMap<>(count, 1); StackFrame prevFrame = null; for (int i = 0; i < count; i++) { StackFrame frame = readFrame(reader, prevFrame); map.put(frame.getOffset(), frame); prevFrame = frame; } return new StackMapTableAttr(map); } private static final Map<StackFrameType, Consumer<FrameContext>> FRAME_READERS = registerReaders(); private static Map<StackFrameType, Consumer<FrameContext>> registerReaders() { EnumMap<StackFrameType, Consumer<FrameContext>> map = new EnumMap<>(StackFrameType.class); map.put(StackFrameType.SAME_FRAME, context -> readSame(context, false)); map.put(StackFrameType.SAME_FRAME_EXTENDED, context -> readSame(context, true)); map.put(StackFrameType.SAME_LOCALS_1_STACK, context -> readSL1S(context, false)); map.put(StackFrameType.SAME_LOCALS_1_STACK_EXTENDED, context -> readSL1S(context, true)); map.put(StackFrameType.CHOP, StackMapTableReader::readChop); map.put(StackFrameType.APPEND, StackMapTableReader::readAppend); map.put(StackFrameType.FULL, StackMapTableReader::readFull); return map; } private StackFrame readFrame(DataReader reader, StackFrame prevFrame) { int typeData = reader.readU1(); StackFrameType frameType = StackFrameType.getType(typeData); Consumer<FrameContext> frameReader = FRAME_READERS.get(frameType); if (frameReader == null) { throw new JavaClassParseException("Found unsupported stack frame type: " + frameType); } FrameContext frameContext = new FrameContext(reader, typeData, prevFrame); frameReader.accept(frameContext); return Objects.requireNonNull(frameContext.getFrame()); } private static void readSame(FrameContext context, boolean extended) { int offsetDelta; StackFrameType type; if (extended) { type = StackFrameType.SAME_FRAME_EXTENDED; offsetDelta = context.getDataReader().readU2(); } else { type = StackFrameType.SAME_FRAME; offsetDelta = context.getTypeData(); } StackFrame frame = new StackFrame(calcOffset(context, offsetDelta), type); frame.setStackSize(0); frame.setLocalsCount(getPrevLocalsCount(context)); context.setFrame(frame); } private static void readSL1S(FrameContext context, boolean extended) { DataReader reader = context.getDataReader(); int offsetDelta; StackFrameType type; if (extended) { type = StackFrameType.SAME_LOCALS_1_STACK_EXTENDED; offsetDelta = reader.readU2(); } else { type = StackFrameType.SAME_LOCALS_1_STACK; offsetDelta = context.getTypeData() - 64; } StackValueType[] stackTypes = TypeInfoReader.readTypeInfoList(reader, 1); StackFrame frame = new StackFrame(calcOffset(context, offsetDelta), type); frame.setStackSize(1); frame.setStackValueTypes(stackTypes); frame.setLocalsCount(getPrevLocalsCount(context)); context.setFrame(frame); } private static void readChop(FrameContext context) { int k = 251 - context.getTypeData(); int offsetDelta = context.getDataReader().readU2(); StackFrame frame = new StackFrame(calcOffset(context, offsetDelta), StackFrameType.CHOP); frame.setStackSize(0); frame.setLocalsCount(getPrevLocalsCount(context) - k); context.setFrame(frame); } private static void readAppend(FrameContext context) { DataReader reader = context.getDataReader(); int k = context.getTypeData() - 251; int offsetDelta = reader.readU2(); TypeInfoReader.skipTypeInfoList(reader, k); StackFrame frame = new StackFrame(calcOffset(context, offsetDelta), StackFrameType.APPEND); frame.setStackSize(0); frame.setLocalsCount(getPrevLocalsCount(context) - k); context.setFrame(frame); } private static void readFull(FrameContext context) { DataReader reader = context.getDataReader(); int offsetDelta = reader.readU2(); int localsCount = reader.readU2(); TypeInfoReader.skipTypeInfoList(reader, localsCount); int stackSize = reader.readU2(); StackValueType[] stackTypes = TypeInfoReader.readTypeInfoList(reader, stackSize); StackFrame frame = new StackFrame(calcOffset(context, offsetDelta), StackFrameType.FULL); frame.setLocalsCount(localsCount); frame.setStackSize(stackSize); frame.setStackValueTypes(stackTypes); context.setFrame(frame); } private static int calcOffset(FrameContext context, int offsetDelta) { StackFrame prevFrame = context.getPrevFrame(); if (prevFrame == null) { return offsetDelta; } return prevFrame.getOffset() + offsetDelta + 1; } private static int getPrevLocalsCount(FrameContext context) { StackFrame prevFrame = context.getPrevFrame(); if (prevFrame == null) { return 0; } return prevFrame.getLocalsCount(); } private static final class FrameContext { private final DataReader dataReader; private final int typeData; private final StackFrame prevFrame; private StackFrame frame; private FrameContext(DataReader dataReader, int typeData, StackFrame prevFrame) { this.dataReader = dataReader; this.typeData = typeData; this.prevFrame = prevFrame; } public DataReader getDataReader() { return dataReader; } public int getTypeData() { return typeData; } public StackFrame getPrevFrame() { return prevFrame; } public StackFrame getFrame() { return frame; } public void setFrame(StackFrame frame) { this.frame = frame; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/StackValueType.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/StackValueType.java
package jadx.plugins.input.java.data.attributes.stack; public enum StackValueType { NARROW, // int, float, etc WIDE, // long, double }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/StackFrame.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/StackFrame.java
package jadx.plugins.input.java.data.attributes.stack; public class StackFrame { private final int offset; private final StackFrameType type; private int stackSize; private StackValueType[] stackValueTypes; private int localsCount; public StackFrame(int offset, StackFrameType type) { this.offset = offset; this.type = type; } public int getOffset() { return offset; } public StackFrameType getType() { return type; } public int getLocalsCount() { return localsCount; } public void setLocalsCount(int localsCount) { this.localsCount = localsCount; } public int getStackSize() { return stackSize; } public void setStackSize(int stackSize) { this.stackSize = stackSize; } public StackValueType[] getStackValueTypes() { return stackValueTypes; } public void setStackValueTypes(StackValueType[] stackValueTypes) { this.stackValueTypes = stackValueTypes; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/TypeInfoReader.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/stack/TypeInfoReader.java
package jadx.plugins.input.java.data.attributes.stack; import jadx.plugins.input.java.data.DataReader; public class TypeInfoReader { private static final int ITEM_TOP = 0; private static final int ITEM_INT = 1; private static final int ITEM_FLOAT = 2; private static final int ITEM_DOUBLE = 3; private static final int ITEM_LONG = 4; private static final int ITEM_NULL = 5; private static final int ITEM_UNINITIALIZED_THIS = 6; private static final int ITEM_OBJECT = 7; private static final int ITEM_UNINITIALIZED = 8; static StackValueType[] readTypeInfoList(DataReader reader, int count) { StackValueType[] types = new StackValueType[count]; for (int i = 0; i < count; i++) { int tag = reader.readU1(); StackValueType type; switch (tag) { case ITEM_DOUBLE: case ITEM_LONG: type = StackValueType.WIDE; break; case ITEM_OBJECT: case ITEM_UNINITIALIZED: reader.readU2(); // ignore type = StackValueType.NARROW; break; default: type = StackValueType.NARROW; break; } types[i] = type; } return types; } static void skipTypeInfoList(DataReader reader, int count) { for (int i = 0; i < count; i++) { int tag = reader.readU1(); if (tag == ITEM_OBJECT || tag == ITEM_UNINITIALIZED) { reader.readU2(); } } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/ConstValueAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/ConstValueAttr.java
package jadx.plugins.input.java.data.attributes.types; import jadx.api.plugins.input.data.annotations.EncodedValue; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class ConstValueAttr implements IJavaAttribute { private final EncodedValue value; public ConstValueAttr(EncodedValue value) { this.value = value; } public EncodedValue getValue() { return value; } public static IJavaAttributeReader reader() { return (clsData, reader) -> new ConstValueAttr(clsData.getConstPoolReader().readAsEncodedValue(reader.readU2())); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaSignatureAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaSignatureAttr.java
package jadx.plugins.input.java.data.attributes.types; import jadx.api.plugins.input.data.attributes.types.SignatureAttr; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class JavaSignatureAttr extends SignatureAttr implements IJavaAttribute { public JavaSignatureAttr(String signature) { super(signature); } public static IJavaAttributeReader reader() { return (clsData, reader) -> new JavaSignatureAttr(clsData.getConstPoolReader().getUtf8(reader.readU2())); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaAnnotationDefaultAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaAnnotationDefaultAttr.java
package jadx.plugins.input.java.data.attributes.types; import jadx.api.plugins.input.data.annotations.EncodedValue; import jadx.api.plugins.input.data.attributes.types.AnnotationDefaultAttr; import jadx.plugins.input.java.data.attributes.EncodedValueReader; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; import jadx.plugins.input.java.data.attributes.JavaAttrStorage; import jadx.plugins.input.java.data.attributes.JavaAttrType; public class JavaAnnotationDefaultAttr extends AnnotationDefaultAttr implements IJavaAttribute { public JavaAnnotationDefaultAttr(EncodedValue value) { super(value); } public static IJavaAttributeReader reader() { return (clsData, reader) -> new JavaAnnotationDefaultAttr(EncodedValueReader.read(clsData, reader)); } public static AnnotationDefaultAttr convert(JavaAttrStorage attributes) { return attributes.get(JavaAttrType.ANNOTATION_DEFAULT); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaSourceFileAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaSourceFileAttr.java
package jadx.plugins.input.java.data.attributes.types; import jadx.api.plugins.input.data.attributes.types.SourceFileAttr; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class JavaSourceFileAttr extends SourceFileAttr implements IJavaAttribute { public JavaSourceFileAttr(String fileName) { super(fileName); } public static IJavaAttributeReader reader() { return (clsData, reader) -> new JavaSourceFileAttr(clsData.getConstPoolReader().getUtf8(reader.readU2())); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/StackMapTableAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/StackMapTableAttr.java
package jadx.plugins.input.java.data.attributes.types; import java.util.Collections; import java.util.Map; import org.jetbrains.annotations.Nullable; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.stack.StackFrame; public class StackMapTableAttr implements IJavaAttribute { public static final StackMapTableAttr EMPTY = new StackMapTableAttr(Collections.emptyMap()); private final Map<Integer, StackFrame> map; public StackMapTableAttr(Map<Integer, StackFrame> map) { this.map = map; } public @Nullable StackFrame getFor(int offset) { return map.get(offset); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/IgnoredAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/IgnoredAttr.java
package jadx.plugins.input.java.data.attributes.types; import jadx.plugins.input.java.data.attributes.IJavaAttribute; @SuppressWarnings("unused") public class IgnoredAttr implements IJavaAttribute { }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaInnerClsAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaInnerClsAttr.java
package jadx.plugins.input.java.data.attributes.types; import java.util.HashMap; import java.util.Map; import jadx.api.plugins.input.data.attributes.types.InnerClassesAttr; import jadx.api.plugins.input.data.attributes.types.InnerClsInfo; import jadx.plugins.input.java.data.ConstPoolReader; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class JavaInnerClsAttr extends InnerClassesAttr implements IJavaAttribute { public JavaInnerClsAttr(Map<String, InnerClsInfo> map) { super(map); } public static IJavaAttributeReader reader() { return (clsData, reader) -> { int len = reader.readU2(); ConstPoolReader constPool = clsData.getConstPoolReader(); Map<String, InnerClsInfo> clsMap = new HashMap<>(len); for (int i = 0; i < len; i++) { String innerCls = constPool.getClass(reader.readU2()); int outerClsIdx = reader.readU2(); String outerCls = outerClsIdx == 0 ? null : constPool.getClass(outerClsIdx); String name = constPool.getUtf8(reader.readU2()); int accFlags = reader.readU2(); clsMap.put(innerCls, new InnerClsInfo(innerCls, outerCls, name, accFlags)); } return new JavaInnerClsAttr(clsMap); }; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaExceptionsAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaExceptionsAttr.java
package jadx.plugins.input.java.data.attributes.types; import java.util.List; import jadx.api.plugins.input.data.attributes.types.ExceptionsAttr; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class JavaExceptionsAttr extends ExceptionsAttr implements IJavaAttribute { public JavaExceptionsAttr(List<String> list) { super(list); } public static IJavaAttributeReader reader() { return (clsData, reader) -> new JavaExceptionsAttr(reader.readClassesList(clsData.getConstPoolReader())); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaMethodParametersAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaMethodParametersAttr.java
package jadx.plugins.input.java.data.attributes.types; import java.util.ArrayList; import java.util.List; import jadx.api.plugins.input.data.attributes.types.MethodParametersAttr; import jadx.plugins.input.java.data.ConstPoolReader; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class JavaMethodParametersAttr extends MethodParametersAttr implements IJavaAttribute { public JavaMethodParametersAttr(List<Info> list) { super(list); } public static IJavaAttributeReader reader() { return (clsData, reader) -> { ConstPoolReader constPool = clsData.getConstPoolReader(); int count = reader.readU1(); List<Info> params = new ArrayList<>(count); for (int i = 0; i < count; i++) { String name = constPool.getUtf8(reader.readU2()); int accessFlags = reader.readU2(); params.add(new Info(accessFlags, name)); } return new JavaMethodParametersAttr(params); }; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/CodeAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/CodeAttr.java
package jadx.plugins.input.java.data.attributes.types; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; public class CodeAttr implements IJavaAttribute { private final int offset; public CodeAttr(int offset) { this.offset = offset; } public int getOffset() { return offset; } public static IJavaAttributeReader reader() { return (clsData, reader) -> new CodeAttr(reader.getOffset()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaBootstrapMethodsAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaBootstrapMethodsAttr.java
package jadx.plugins.input.java.data.attributes.types; import java.util.ArrayList; import java.util.List; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; import jadx.plugins.input.java.data.attributes.types.data.RawBootstrapMethod; public class JavaBootstrapMethodsAttr implements IJavaAttribute { private final List<RawBootstrapMethod> list; public JavaBootstrapMethodsAttr(List<RawBootstrapMethod> list) { this.list = list; } public List<RawBootstrapMethod> getList() { return list; } public static IJavaAttributeReader reader() { return (clsData, reader) -> { int len = reader.readU2(); List<RawBootstrapMethod> list = new ArrayList<>(len); for (int i = 0; i < len; i++) { int methodHandleIdx = reader.readU2(); int argsCount = reader.readU2(); int[] args = new int[argsCount]; for (int j = 0; j < argsCount; j++) { args[j] = reader.readU2(); } list.add(new RawBootstrapMethod(methodHandleIdx, args)); } return new JavaBootstrapMethodsAttr(list); }; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaAnnotationsAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaAnnotationsAttr.java
package jadx.plugins.input.java.data.attributes.types; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jadx.api.plugins.input.data.annotations.AnnotationVisibility; import jadx.api.plugins.input.data.annotations.EncodedValue; import jadx.api.plugins.input.data.annotations.IAnnotation; import jadx.api.plugins.input.data.annotations.JadxAnnotation; import jadx.api.plugins.input.data.attributes.types.AnnotationsAttr; import jadx.api.plugins.utils.Utils; import jadx.plugins.input.java.data.ConstPoolReader; import jadx.plugins.input.java.data.DataReader; import jadx.plugins.input.java.data.JavaClassData; import jadx.plugins.input.java.data.attributes.EncodedValueReader; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; import jadx.plugins.input.java.data.attributes.JavaAttrStorage; import jadx.plugins.input.java.data.attributes.JavaAttrType; public class JavaAnnotationsAttr implements IJavaAttribute { private final List<IAnnotation> list; public JavaAnnotationsAttr(List<IAnnotation> list) { this.list = list; } public List<IAnnotation> getList() { return list; } public static IJavaAttributeReader reader(AnnotationVisibility visibility) { return (clsData, reader) -> new JavaAnnotationsAttr(readAnnotationsList(visibility, clsData, reader)); } public static List<IAnnotation> readAnnotationsList(AnnotationVisibility visibility, JavaClassData clsData, DataReader reader) { int len = reader.readU2(); List<IAnnotation> list = new ArrayList<>(len); for (int i = 0; i < len; i++) { list.add(readAnnotation(visibility, clsData, reader)); } return list; } public static JadxAnnotation readAnnotation(AnnotationVisibility visibility, JavaClassData clsData, DataReader reader) { ConstPoolReader constPool = clsData.getConstPoolReader(); String type = constPool.getUtf8(reader.readU2()); int pairsCount = reader.readU2(); Map<String, EncodedValue> pairs = new LinkedHashMap<>(pairsCount); for (int j = 0; j < pairsCount; j++) { String name = constPool.getUtf8(reader.readU2()); EncodedValue value = EncodedValueReader.read(clsData, reader); pairs.put(name, value); } return new JadxAnnotation(visibility, type, pairs); } public static AnnotationsAttr merge(JavaAttrStorage storage) { JavaAnnotationsAttr runtimeAnnAttr = storage.get(JavaAttrType.RUNTIME_ANNOTATIONS); JavaAnnotationsAttr buildAnnAttr = storage.get(JavaAttrType.BUILD_ANNOTATIONS); if (runtimeAnnAttr == null && buildAnnAttr == null) { return null; } if (buildAnnAttr == null) { return AnnotationsAttr.pack(runtimeAnnAttr.getList()); } if (runtimeAnnAttr == null) { return AnnotationsAttr.pack(buildAnnAttr.getList()); } return AnnotationsAttr.pack(Utils.concat(runtimeAnnAttr.getList(), buildAnnAttr.getList())); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaParamAnnsAttr.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/JavaParamAnnsAttr.java
package jadx.plugins.input.java.data.attributes.types; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jadx.api.plugins.input.data.annotations.AnnotationVisibility; import jadx.api.plugins.input.data.annotations.IAnnotation; import jadx.api.plugins.input.data.attributes.types.AnnotationMethodParamsAttr; import jadx.api.plugins.utils.Utils; import jadx.plugins.input.java.data.attributes.IJavaAttribute; import jadx.plugins.input.java.data.attributes.IJavaAttributeReader; import jadx.plugins.input.java.data.attributes.JavaAttrStorage; import jadx.plugins.input.java.data.attributes.JavaAttrType; public class JavaParamAnnsAttr implements IJavaAttribute { private final List<List<IAnnotation>> list; public JavaParamAnnsAttr(List<List<IAnnotation>> list) { this.list = list; } public List<List<IAnnotation>> getList() { return list; } public static IJavaAttributeReader reader(AnnotationVisibility visibility) { return (clsData, reader) -> { int len = reader.readU1(); List<List<IAnnotation>> list = new ArrayList<>(len); for (int i = 0; i < len; i++) { list.add(JavaAnnotationsAttr.readAnnotationsList(visibility, clsData, reader)); } return new JavaParamAnnsAttr(list); }; } public static AnnotationMethodParamsAttr merge(JavaAttrStorage storage) { JavaParamAnnsAttr runtimeAnnAttr = storage.get(JavaAttrType.RUNTIME_PARAMETER_ANNOTATIONS); JavaParamAnnsAttr buildAnnAttr = storage.get(JavaAttrType.BUILD_PARAMETER_ANNOTATIONS); if (runtimeAnnAttr == null && buildAnnAttr == null) { return null; } if (buildAnnAttr == null) { return AnnotationMethodParamsAttr.pack(runtimeAnnAttr.getList()); } if (runtimeAnnAttr == null) { return AnnotationMethodParamsAttr.pack(buildAnnAttr.getList()); } return AnnotationMethodParamsAttr.pack(mergeParamLists(runtimeAnnAttr.getList(), buildAnnAttr.getList())); } private static List<List<IAnnotation>> mergeParamLists(List<List<IAnnotation>> first, List<List<IAnnotation>> second) { int firstSize = first.size(); int secondSize = second.size(); int size = Math.max(firstSize, secondSize); List<List<IAnnotation>> result = new ArrayList<>(size); for (int i = 0; i < size; i++) { List<IAnnotation> firstList = i < firstSize ? first.get(i) : Collections.emptyList(); List<IAnnotation> secondList = i < secondSize ? second.get(i) : Collections.emptyList(); result.add(Utils.concat(firstList, secondList)); } return result; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/data/RawBootstrapMethod.java
jadx-plugins/jadx-java-input/src/main/java/jadx/plugins/input/java/data/attributes/types/data/RawBootstrapMethod.java
package jadx.plugins.input.java.data.attributes.types.data; public class RawBootstrapMethod { private final int methodHandleIdx; private final int[] args; public RawBootstrapMethod(int methodHandleIdx, int[] args) { this.methodHandleIdx = methodHandleIdx; this.args = args; } public int getMethodHandleIdx() { return methodHandleIdx; } public int[] getArgs() { return args; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-raung-input/src/main/java/jadx/plugins/input/raung/RaungConvert.java
jadx-plugins/jadx-raung-input/src/main/java/jadx/plugins/input/raung/RaungConvert.java
package jadx.plugins.input.raung; import java.io.Closeable; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.skylot.raung.asm.RaungAsm; public class RaungConvert implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(RaungConvert.class); @Nullable private Path tmpJar; public boolean execute(List<Path> input) { List<Path> raungInputs = filterRaungFiles(input); if (raungInputs.isEmpty()) { return false; } try { this.tmpJar = Files.createTempFile("jadx-raung-", ".jar"); RaungAsm.create() .output(tmpJar) .inputs(raungInputs) .execute(); return true; } catch (Exception e) { LOG.error("Raung process error", e); } close(); return false; } private List<Path> filterRaungFiles(List<Path> input) { PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.raung"); return input.stream() .filter(matcher::matches) .collect(Collectors.toList()); } public List<Path> getFiles() { if (tmpJar == null) { return Collections.emptyList(); } return Collections.singletonList(tmpJar); } @Override public void close() { try { if (tmpJar != null) { Files.deleteIfExists(tmpJar); } } catch (Exception e) { LOG.error("Failed to remove tmp jar file: {}", tmpJar, e); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-plugins/jadx-raung-input/src/main/java/jadx/plugins/input/raung/RaungInputPlugin.java
jadx-plugins/jadx-raung-input/src/main/java/jadx/plugins/input/raung/RaungInputPlugin.java
package jadx.plugins.input.raung; import jadx.api.plugins.JadxPlugin; import jadx.api.plugins.JadxPluginContext; import jadx.api.plugins.JadxPluginInfo; import jadx.api.plugins.data.JadxPluginRuntimeData; import jadx.api.plugins.input.data.impl.EmptyCodeLoader; public class RaungInputPlugin implements JadxPlugin { @Override public JadxPluginInfo getPluginInfo() { return new JadxPluginInfo("raung-input", "Raung Input", "Load .raung files"); } @Override public void init(JadxPluginContext context) { JadxPluginRuntimeData javaInput = context.plugins().getProviding("java-input"); context.addCodeInput(inputs -> { RaungConvert convert = new RaungConvert(); if (!convert.execute(inputs)) { return EmptyCodeLoader.INSTANCE; } return javaInput.loadCodeFiles(convert.getFiles(), convert); }); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/IZipParser.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/IZipParser.java
package jadx.zip; import java.io.Closeable; import java.io.IOException; public interface IZipParser extends Closeable { ZipContent open() throws IOException; }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/ZipReaderFlags.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/ZipReaderFlags.java
package jadx.zip; import java.util.EnumSet; import java.util.Set; public enum ZipReaderFlags { /** * Search all local file headers by signature without reading * 'central directory' and 'end of central directory' entries */ IGNORE_CENTRAL_DIR_ENTRIES, /** * Enable additional checks to verify zip data and report possible tampering */ REPORT_TAMPERING, /** * Use fallback (java built-in implementation) parser as default. * Custom implementation will be used for '*.apk' files only. */ FALLBACK_AS_DEFAULT, /** * Use only jadx custom parser and do not switch to fallback on errors. */ DONT_USE_FALLBACK; public static Set<ZipReaderFlags> none() { return EnumSet.noneOf(ZipReaderFlags.class); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/ZipContent.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/ZipContent.java
package jadx.zip; import java.io.Closeable; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZipContent implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(ZipContent.class); private final IZipParser zipParser; private final List<IZipEntry> entries; private final Map<String, IZipEntry> entriesMap; public ZipContent(IZipParser zipParser, List<IZipEntry> entries) { this.zipParser = zipParser; this.entries = entries; this.entriesMap = buildNameMap(zipParser, entries); } private static Map<String, IZipEntry> buildNameMap(IZipParser zipParser, List<IZipEntry> entries) { Map<String, IZipEntry> map = new HashMap<>(entries.size()); for (IZipEntry entry : entries) { String name = entry.getName(); IZipEntry prevEntry = map.put(name, entry); if (prevEntry != null) { LOG.warn("Found duplicate entry: {} in {}", name, zipParser); } } return map; } public List<IZipEntry> getEntries() { return entries; } public @Nullable IZipEntry searchEntry(String fileName) { return entriesMap.get(fileName); } @Override public void close() throws IOException { zipParser.close(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/ZipReader.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/ZipReader.java
package jadx.zip; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; import org.jetbrains.annotations.Nullable; import jadx.zip.fallback.FallbackZipParser; import jadx.zip.parser.JadxZipParser; import jadx.zip.security.IJadxZipSecurity; import jadx.zip.security.JadxZipSecurity; /** * Jadx wrapper to provide custom zip parser ({@link JadxZipParser}) * with fallback to default Java implementation. */ public class ZipReader { private final ZipReaderOptions options; public ZipReader() { this(ZipReaderOptions.getDefault()); } public ZipReader(Set<ZipReaderFlags> flags) { this(new ZipReaderOptions(new JadxZipSecurity(), flags)); } public ZipReader(IJadxZipSecurity security) { this(new ZipReaderOptions(security, ZipReaderFlags.none())); } public ZipReader(ZipReaderOptions options) { this.options = options; } @SuppressWarnings("resource") public ZipContent open(File zipFile) throws IOException { try { JadxZipParser jadxParser = new JadxZipParser(zipFile, options); IZipParser detectedParser = detectParser(zipFile, jadxParser); if (detectedParser != jadxParser) { jadxParser.close(); } return detectedParser.open(); } catch (Exception e) { if (options.getFlags().contains(ZipReaderFlags.DONT_USE_FALLBACK)) { throw new IOException("Failed to open zip: " + zipFile, e); } // switch to fallback parser return buildFallbackParser(zipFile).open(); } } /** * Visit valid entries in a zip file. * Return not null value from visitor to stop iteration. */ public <R> @Nullable R visitEntries(File file, Function<IZipEntry, R> visitor) { try (ZipContent content = open(file)) { for (IZipEntry entry : content.getEntries()) { R result = visitor.apply(entry); if (result != null) { return result; } } } catch (Exception e) { throw new RuntimeException("Failed to process zip file: " + file.getAbsolutePath(), e); } return null; } public void readEntries(File file, BiConsumer<IZipEntry, InputStream> visitor) { visitEntries(file, entry -> { if (!entry.isDirectory()) { try (InputStream in = entry.getInputStream()) { visitor.accept(entry, in); } catch (Exception e) { throw new RuntimeException("Failed to process zip entry: " + entry, e); } } return null; }); } public ZipReaderOptions getOptions() { return options; } private IZipParser detectParser(File zipFile, JadxZipParser jadxParser) { if (zipFile.getName().endsWith(".apk") || options.getFlags().contains(ZipReaderFlags.DONT_USE_FALLBACK)) { return jadxParser; } if (!jadxParser.canOpen()) { return buildFallbackParser(zipFile); } // default if (options.getFlags().contains(ZipReaderFlags.FALLBACK_AS_DEFAULT)) { return buildFallbackParser(zipFile); } return jadxParser; } private FallbackZipParser buildFallbackParser(File zipFile) { return new FallbackZipParser(zipFile, options); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/ZipReaderOptions.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/ZipReaderOptions.java
package jadx.zip; import java.util.Set; import jadx.zip.security.IJadxZipSecurity; import jadx.zip.security.JadxZipSecurity; public class ZipReaderOptions { public static ZipReaderOptions getDefault() { return new ZipReaderOptions(new JadxZipSecurity(), ZipReaderFlags.none()); } private final IJadxZipSecurity zipSecurity; private final Set<ZipReaderFlags> flags; public ZipReaderOptions(IJadxZipSecurity zipSecurity, Set<ZipReaderFlags> flags) { this.zipSecurity = zipSecurity; this.flags = flags; } public IJadxZipSecurity getZipSecurity() { return zipSecurity; } public Set<ZipReaderFlags> getFlags() { return flags; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/IZipEntry.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/IZipEntry.java
package jadx.zip; import java.io.File; import java.io.InputStream; public interface IZipEntry { /** * Zip entry name */ String getName(); /** * Uncompressed bytes */ byte[] getBytes(); /** * Stream of uncompressed bytes. */ InputStream getInputStream(); long getCompressedSize(); long getUncompressedSize(); boolean isDirectory(); File getZipFile(); /** * Return true if {@link #getBytes()} method is more optimal to use other than * {@link #getInputStream()} */ boolean preferBytes(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/fallback/FallbackZipEntry.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/fallback/FallbackZipEntry.java
package jadx.zip.fallback; import java.io.File; import java.io.InputStream; import java.util.zip.ZipEntry; import jadx.zip.IZipEntry; public class FallbackZipEntry implements IZipEntry { private final FallbackZipParser parser; private final ZipEntry zipEntry; public FallbackZipEntry(FallbackZipParser parser, ZipEntry zipEntry) { this.parser = parser; this.zipEntry = zipEntry; } public ZipEntry getZipEntry() { return zipEntry; } @Override public String getName() { return zipEntry.getName(); } @Override public boolean preferBytes() { return false; } @Override public byte[] getBytes() { return parser.getBytes(this); } @Override public InputStream getInputStream() { return parser.getInputStream(this); } @Override public long getCompressedSize() { return zipEntry.getCompressedSize(); } @Override public long getUncompressedSize() { return zipEntry.getSize(); } @Override public boolean isDirectory() { return zipEntry.isDirectory(); } @Override public File getZipFile() { return parser.getZipFile(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/fallback/FallbackZipParser.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/fallback/FallbackZipParser.java
package jadx.zip.fallback; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.zip.IZipEntry; import jadx.zip.IZipParser; import jadx.zip.ZipContent; import jadx.zip.ZipReaderOptions; import jadx.zip.io.LimitedInputStream; import jadx.zip.security.IJadxZipSecurity; public class FallbackZipParser implements IZipParser { private static final Logger LOG = LoggerFactory.getLogger(FallbackZipParser.class); private final File file; private final IJadxZipSecurity zipSecurity; private final boolean useLimitedDataStream; private ZipFile zipFile; public FallbackZipParser(File file, ZipReaderOptions options) { this.file = file; this.zipSecurity = options.getZipSecurity(); this.useLimitedDataStream = zipSecurity.useLimitedDataStream(); } @Override public ZipContent open() throws IOException { zipFile = new ZipFile(file); int maxEntriesCount = zipSecurity.getMaxEntriesCount(); if (maxEntriesCount == -1) { maxEntriesCount = Integer.MAX_VALUE; } List<IZipEntry> list = new ArrayList<>(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { FallbackZipEntry zipEntry = new FallbackZipEntry(this, entries.nextElement()); if (isValidEntry(zipEntry)) { list.add(zipEntry); if (list.size() > maxEntriesCount) { throw new IllegalStateException("Max entries count limit exceeded: " + list.size()); } } } return new ZipContent(this, list); } private boolean isValidEntry(IZipEntry zipEntry) { boolean validEntry = zipSecurity.isValidEntry(zipEntry); if (!validEntry) { LOG.warn("Zip entry '{}' is invalid and excluded from processing", zipEntry); } return validEntry; } public byte[] getBytes(FallbackZipEntry entry) { try (InputStream is = getEntryStream(entry)) { return is.readAllBytes(); } catch (Exception e) { throw new RuntimeException("Failed to read bytes for entry: " + entry.getName(), e); } } public InputStream getInputStream(FallbackZipEntry entry) { try { return getEntryStream(entry); } catch (Exception e) { throw new RuntimeException("Failed to open input stream for entry: " + entry.getName(), e); } } private InputStream getEntryStream(FallbackZipEntry entry) throws IOException { InputStream entryStream = zipFile.getInputStream(entry.getZipEntry()); InputStream stream; if (useLimitedDataStream) { stream = new LimitedInputStream(entryStream, entry.getUncompressedSize()); } else { stream = entryStream; } return new BufferedInputStream(stream); } public File getZipFile() { return file; } @Override public void close() throws IOException { try { if (zipFile != null) { zipFile.close(); } } finally { zipFile = null; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/security/IJadxZipSecurity.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/security/IJadxZipSecurity.java
package jadx.zip.security; import java.io.File; import jadx.zip.IZipEntry; public interface IJadxZipSecurity { /** * Check if zip entry is valid and safe to process */ boolean isValidEntry(IZipEntry entry); /** * Check if the zip entry name is valid. * This check should be part of {@link #isValidEntry(IZipEntry)} method. */ boolean isValidEntryName(String entryName); /** * Use limited InputStream for entry uncompressed data */ boolean useLimitedDataStream(); /** * Max entries count expected in a zip file, fail zip open if the limit exceeds. * Return -1 to disable entries count check. */ int getMaxEntriesCount(); /** * Check if a file will be inside baseDir after a system resolves its path */ boolean isInSubDirectory(File baseDir, File file); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/security/JadxZipSecurity.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/security/JadxZipSecurity.java
package jadx.zip.security; import java.io.File; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.zip.IZipEntry; public class JadxZipSecurity implements IJadxZipSecurity { private static final Logger LOG = LoggerFactory.getLogger(JadxZipSecurity.class); private static final File CWD = getCWD(); /** * The size of uncompressed zip entry shouldn't be bigger of compressed in zipBombDetectionFactor * times */ private int zipBombDetectionFactor = 100; /** * Zip entries that have an uncompressed size of less than zipBombMinUncompressedSize are considered * safe */ private int zipBombMinUncompressedSize = 25 * 1024 * 1024; private int maxEntriesCount = 100_000; private boolean useLimitedDataStream = true; @Override public boolean isValidEntry(IZipEntry entry) { return isValidEntryName(entry.getName()) && !isZipBomb(entry); } @Override public boolean useLimitedDataStream() { return useLimitedDataStream; } @Override public int getMaxEntriesCount() { return maxEntriesCount; } /** * Checks that entry name contains no any traversals and prevents cases like "../classes.dex", * to limit output only to the specified directory */ @Override public boolean isValidEntryName(String entryName) { if (entryName.contains("..")) { // quick pre-check if (entryName.contains("../") || entryName.contains("..\\")) { LOG.error("Path traversal attack detected in entry: '{}'", entryName); return false; } } try { File currentPath = CWD; File canonical = new File(currentPath, entryName).getCanonicalFile(); if (isInSubDirectoryInternal(currentPath, canonical)) { return true; } } catch (Exception e) { // check failed } LOG.error("Invalid file name or path traversal attack detected: {}", entryName); return false; } @Override public boolean isInSubDirectory(File baseDir, File file) { try { return isInSubDirectoryInternal(baseDir.getCanonicalFile(), file.getCanonicalFile()); } catch (IOException e) { return false; } } public boolean isZipBomb(IZipEntry entry) { long compressedSize = entry.getCompressedSize(); long uncompressedSize = entry.getUncompressedSize(); boolean invalidSize = compressedSize < 0 || uncompressedSize < 0; boolean possibleZipBomb = uncompressedSize >= zipBombMinUncompressedSize && compressedSize * zipBombDetectionFactor < uncompressedSize; if (invalidSize || possibleZipBomb) { LOG.error("Potential zip bomb attack detected, invalid sizes: compressed {}, uncompressed {}, name {}", compressedSize, uncompressedSize, entry.getName()); return true; } return false; } private static boolean isInSubDirectoryInternal(File baseDir, File file) { File current = file; while (true) { if (current == null) { return false; } if (current.equals(baseDir)) { return true; } current = current.getParentFile(); } } public void setMaxEntriesCount(int maxEntriesCount) { this.maxEntriesCount = maxEntriesCount; } public void setZipBombDetectionFactor(int zipBombDetectionFactor) { this.zipBombDetectionFactor = zipBombDetectionFactor; } public void setZipBombMinUncompressedSize(int zipBombMinUncompressedSize) { this.zipBombMinUncompressedSize = zipBombMinUncompressedSize; } public void setUseLimitedDataStream(boolean useLimitedDataStream) { this.useLimitedDataStream = useLimitedDataStream; } private static File getCWD() { try { return new File(".").getCanonicalFile(); } catch (IOException e) { throw new RuntimeException("Failed to init current working dir constant", e); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/security/DisabledZipSecurity.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/security/DisabledZipSecurity.java
package jadx.zip.security; import java.io.File; import jadx.zip.IZipEntry; public class DisabledZipSecurity implements IJadxZipSecurity { public static final DisabledZipSecurity INSTANCE = new DisabledZipSecurity(); @Override public boolean isValidEntry(IZipEntry entry) { return true; } @Override public boolean isValidEntryName(String entryName) { return true; } @Override public boolean isInSubDirectory(File baseDir, File file) { return true; } @Override public boolean useLimitedDataStream() { return false; } @Override public int getMaxEntriesCount() { return -1; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/io/ByteBufferBackedInputStream.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/io/ByteBufferBackedInputStream.java
package jadx.zip.io; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; public class ByteBufferBackedInputStream extends InputStream { private final ByteBuffer buf; private int markedPosition = 0; public ByteBufferBackedInputStream(ByteBuffer buf) { this.buf = buf; } public int read() throws IOException { if (!buf.hasRemaining()) { return -1; } return buf.get() & 0xFF; } @SuppressWarnings("NullableProblems") public int read(byte[] bytes, int off, int len) throws IOException { if (!buf.hasRemaining()) { return -1; } int readLen = Math.min(len, buf.remaining()); buf.get(bytes, off, readLen); return readLen; } @Override public boolean markSupported() { return true; } @Override public synchronized void mark(int unused) { markedPosition = buf.position(); } @Override public synchronized void reset() { buf.position(markedPosition); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/io/LimitedInputStream.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/io/LimitedInputStream.java
package jadx.zip.io; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; public class LimitedInputStream extends FilterInputStream { private final long maxSize; private long currentPos; private long markPos; public LimitedInputStream(InputStream in, long maxSize) { super(in); this.maxSize = maxSize; } private void addAndCheckPos(long count) { currentPos += count; if (currentPos > maxSize) { throw new IllegalStateException("Read limit exceeded"); } } @Override public int read() throws IOException { int data = super.read(); if (data != -1) { addAndCheckPos(1); } return data; } @SuppressWarnings("NullableProblems") @Override public int read(byte[] b, int off, int len) throws IOException { int count = super.read(b, off, len); if (count > 0) { addAndCheckPos(count); } return count; } @Override public long skip(long n) throws IOException { long skipped = super.skip(n); if (skipped > 0) { addAndCheckPos(skipped); } return skipped; } @Override public void mark(int readLimit) { super.mark(readLimit); markPos = currentPos; } @Override public void reset() throws IOException { super.reset(); currentPos = markPos; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/parser/JadxZipParser.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/parser/JadxZipParser.java
package jadx.zip.parser; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.zip.IZipEntry; import jadx.zip.IZipParser; import jadx.zip.ZipContent; import jadx.zip.ZipReaderFlags; import jadx.zip.ZipReaderOptions; import jadx.zip.fallback.FallbackZipParser; import jadx.zip.io.ByteBufferBackedInputStream; import jadx.zip.io.LimitedInputStream; import jadx.zip.security.IJadxZipSecurity; /** * Custom and simple zip parser to fight tampering. * Many zip features aren't supported: * - Compression methods other than STORE or DEFLATE * - Zip64 * - Checksum verification * - Multi file archives */ public final class JadxZipParser implements IZipParser { private static final Logger LOG = LoggerFactory.getLogger(JadxZipParser.class); private static final byte LOCAL_FILE_HEADER_START = 0x50; private static final int LOCAL_FILE_HEADER_SIGN = 0x04034b50; private static final int CD_SIGN = 0x02014b50; private static final int END_OF_CD_SIGN = 0x06054b50; private final File zipFile; private final ZipReaderOptions options; private final IJadxZipSecurity zipSecurity; private final Set<ZipReaderFlags> flags; private final boolean verify; private final boolean useLimitedDataStream; private RandomAccessFile file; private FileChannel fileChannel; private ByteBuffer byteBuffer; private int endOfCDStart = -2; private @Nullable ZipContent fallbackZipContent; public JadxZipParser(File zipFile, ZipReaderOptions options) { this.zipFile = zipFile; this.options = options; this.zipSecurity = options.getZipSecurity(); this.flags = options.getFlags(); this.verify = options.getFlags().contains(ZipReaderFlags.REPORT_TAMPERING); this.useLimitedDataStream = zipSecurity.useLimitedDataStream(); } @Override public ZipContent open() throws IOException { load(); try { int maxEntriesCount = zipSecurity.getMaxEntriesCount(); if (maxEntriesCount == -1) { maxEntriesCount = Integer.MAX_VALUE; } List<IZipEntry> entries; if (flags.contains(ZipReaderFlags.IGNORE_CENTRAL_DIR_ENTRIES)) { entries = searchLocalFileHeaders(maxEntriesCount); } else { entries = loadFromCentralDirs(maxEntriesCount); } return new ZipContent(this, entries); } catch (Exception e) { if (flags.contains(ZipReaderFlags.DONT_USE_FALLBACK)) { throw new IOException("Failed to open zip: " + zipFile + ", error: " + e.getMessage(), e); } LOG.warn("Zip open failed, switching to fallback parser, zip: {}", zipFile, e); return initFallbackParser(); } } @SuppressWarnings("RedundantIfStatement") public boolean canOpen() { try { load(); int eocdStart = searchEndOfCDStart(); ByteBuffer buf = byteBuffer; buf.position(eocdStart + 4); int diskNum = readU2(buf); if (diskNum == 0xFFFF) { // Zip64 return false; } return true; } catch (Exception e) { LOG.warn("Jadx parser can't open zip file: {}", zipFile, e); return false; } } private boolean isValidEntry(JadxZipEntry zipEntry) { boolean validEntry = zipSecurity.isValidEntry(zipEntry); if (!validEntry) { LOG.warn("Zip entry '{}' is invalid and excluded from processing", zipEntry); } return validEntry; } private void load() throws IOException { if (byteBuffer != null) { // already loaded return; } file = new RandomAccessFile(zipFile, "r"); long size = file.length(); if (size >= Integer.MAX_VALUE) { throw new IOException("Zip file is too big"); } int fileLen = (int) size; if (fileLen < 100 * 1024 * 1024) { // load files smaller than 100MB directly into memory byte[] bytes = new byte[fileLen]; file.readFully(bytes); byteBuffer = ByteBuffer.wrap(bytes).asReadOnlyBuffer(); file.close(); file = null; } else { // for big files - use a memory mapped file fileChannel = file.getChannel(); byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); } byteBuffer.order(ByteOrder.LITTLE_ENDIAN); } private List<IZipEntry> searchLocalFileHeaders(int maxEntriesCount) { List<IZipEntry> entries = new ArrayList<>(); while (true) { int start = searchEntryStart(); if (start == -1) { return entries; } JadxZipEntry zipEntry = loadFileEntry(start); if (isValidEntry(zipEntry)) { entries.add(zipEntry); if (entries.size() > maxEntriesCount) { throw new IllegalStateException("Max entries count limit exceeded: " + entries.size()); } } } } private List<IZipEntry> loadFromCentralDirs(int maxEntriesCount) throws IOException { int eocdStart = searchEndOfCDStart(); if (eocdStart < 0) { throw new RuntimeException("End of central directory not found"); } ByteBuffer buf = byteBuffer; buf.position(eocdStart + 10); int entriesCount = readU2(buf); buf.position(eocdStart + 16); int cdOffset = buf.getInt(); if (entriesCount > maxEntriesCount) { throw new IllegalStateException("Max entries count limit exceeded: " + entriesCount); } List<IZipEntry> entries = new ArrayList<>(entriesCount); buf.position(cdOffset); for (int i = 0; i < entriesCount; i++) { JadxZipEntry zipEntry = loadCDEntry(); if (isValidEntry(zipEntry)) { entries.add(zipEntry); } } return entries; } private JadxZipEntry loadCDEntry() { ByteBuffer buf = byteBuffer; int start = buf.position(); buf.position(start + 28); int fileNameLen = readU2(buf); int extraFieldLen = readU2(buf); int commentLen = readU2(buf); buf.position(start + 42); int fileEntryStart = buf.getInt(); int entryEnd = start + 46 + fileNameLen + extraFieldLen + commentLen; JadxZipEntry entry = loadFileEntry(fileEntryStart); if (verify) { compareCDAndLFH(buf, start, entry); } if (!entry.isSizesValid()) { entry = fixEntryFromCD(entry, start); } buf.position(entryEnd); return entry; } private JadxZipEntry fixEntryFromCD(JadxZipEntry entry, int start) { ByteBuffer buf = byteBuffer; buf.position(start + 10); int comprMethod = readU2(buf); buf.position(start + 20); int comprSize = buf.getInt(); int unComprSize = buf.getInt(); return new JadxZipEntry(this, entry.getName(), start, entry.getDataStart(), comprMethod, comprSize, unComprSize); } private static void compareCDAndLFH(ByteBuffer buf, int start, JadxZipEntry entry) { buf.position(start + 10); int comprMethod = readU2(buf); if (comprMethod != entry.getCompressMethod()) { LOG.warn("Compression method differ in CD {} and LFH {} for {}", comprMethod, entry.getCompressMethod(), entry); } buf.position(start + 20); int comprSize = buf.getInt(); int unComprSize = buf.getInt(); if (comprSize != entry.getCompressedSize()) { LOG.warn("Compressed size differ in CD {} and LFH {} for {}", comprSize, entry.getCompressedSize(), entry); } if (unComprSize != entry.getUncompressedSize()) { LOG.warn("Uncompressed size differ in CD {} and LFH {} for {}", unComprSize, entry.getUncompressedSize(), entry); } } private JadxZipEntry loadFileEntry(int start) { ByteBuffer buf = byteBuffer; buf.position(start + 8); int comprMethod = readU2(buf); buf.position(start + 18); int comprSize = buf.getInt(); int unComprSize = buf.getInt(); int fileNameLen = readU2(buf); int extraFieldLen = readU2(buf); String fileName = readString(buf, fileNameLen); int dataStart = start + 30 + fileNameLen + extraFieldLen; buf.position(dataStart + comprSize); return new JadxZipEntry(this, fileName, start, dataStart, comprMethod, comprSize, unComprSize); } private int searchEndOfCDStart() throws IOException { if (endOfCDStart != -2) { return endOfCDStart; } ByteBuffer buf = byteBuffer; int pos = buf.limit() - 22; int minPos = Math.max(0, pos - 0xffff); while (true) { buf.position(pos); int sign = buf.getInt(); if (sign == END_OF_CD_SIGN) { endOfCDStart = pos; return pos; } pos--; if (pos < minPos) { throw new IOException("End of central directory record not found"); } } } private int searchEntryStart() { ByteBuffer buf = byteBuffer; while (true) { int start = buf.position(); if (start + 4 > buf.limit()) { return -1; } byte b = buf.get(); if (b == LOCAL_FILE_HEADER_START) { buf.position(start); int sign = buf.getInt(); if (sign == LOCAL_FILE_HEADER_SIGN) { return start; } } } } synchronized InputStream getInputStream(JadxZipEntry entry) { if (verify) { verifyEntry(entry); } InputStream stream; if (entry.getCompressMethod() == 8) { try { stream = ZipDeflate.decompressEntryToStream(byteBuffer, entry); } catch (Exception e) { entryParseFailed(entry, e); return useFallbackParser(entry).getInputStream(); } } else { // treat any other compression methods values as UNCOMPRESSED stream = bufferToStream(byteBuffer, entry.getDataStart(), (int) entry.getUncompressedSize()); } if (useLimitedDataStream) { return new LimitedInputStream(stream, entry.getUncompressedSize()); } return stream; } synchronized byte[] getBytes(JadxZipEntry entry) { if (verify) { verifyEntry(entry); } if (entry.getCompressMethod() == 8) { try { return ZipDeflate.decompressEntryToBytes(byteBuffer, entry); } catch (Exception e) { entryParseFailed(entry, e); return useFallbackParser(entry).getBytes(); } } // treat any other compression methods values as UNCOMPRESSED return bufferToBytes(byteBuffer, entry.getDataStart(), (int) entry.getUncompressedSize()); } private static void verifyEntry(JadxZipEntry entry) { int compressMethod = entry.getCompressMethod(); if (compressMethod == 0) { if (entry.getCompressedSize() != entry.getUncompressedSize()) { LOG.warn("Not equal sizes for STORE method: compressed: {}, uncompressed: {}, entry: {}", entry.getCompressedSize(), entry.getUncompressedSize(), entry); } } else if (compressMethod != 8) { LOG.warn("Unknown compress method: {} in entry: {}", compressMethod, entry); } } private void entryParseFailed(JadxZipEntry entry, Exception e) { if (isEncrypted(entry)) { throw new RuntimeException("Entry is encrypted, failed to decompress: " + entry, e); } if (flags.contains(ZipReaderFlags.DONT_USE_FALLBACK)) { throw new RuntimeException("Failed to decompress zip entry: " + entry + ", error: " + e.getMessage(), e); } LOG.warn("Entry '{}' parse failed, switching to fallback parser", entry, e); } @SuppressWarnings("resource") private IZipEntry useFallbackParser(JadxZipEntry entry) { LOG.debug("useFallbackParser used for {}", entry); IZipEntry zipEntry = initFallbackParser().searchEntry(entry.getName()); if (zipEntry == null) { throw new RuntimeException("Fallback parser can't find entry: " + entry); } return zipEntry; } @SuppressWarnings("resource") private ZipContent initFallbackParser() { if (fallbackZipContent == null) { try { fallbackZipContent = new FallbackZipParser(zipFile, options).open(); } catch (Exception e) { throw new RuntimeException("Fallback parser failed to open file: " + zipFile, e); } } return fallbackZipContent; } private boolean isEncrypted(JadxZipEntry entry) { int flags = readFlags(entry); return (flags & 1) != 0; } private int readFlags(JadxZipEntry entry) { ByteBuffer buf = byteBuffer; buf.position(entry.getEntryStart() + 6); return readU2(buf); } static byte[] bufferToBytes(ByteBuffer buf, int start, int size) { byte[] data = new byte[size]; buf.position(start); buf.get(data); return data; } static InputStream bufferToStream(ByteBuffer buf, int start, int size) { buf.position(start); ByteBuffer streamBuf = buf.slice(); streamBuf.limit(size); return new ByteBufferBackedInputStream(streamBuf); } private static int readU2(ByteBuffer buf) { return buf.getShort() & 0xFFFF; } private static String readString(ByteBuffer buf, int fileNameLen) { byte[] bytes = new byte[fileNameLen]; buf.get(bytes); return new String(bytes, StandardCharsets.UTF_8); } @Override public void close() throws IOException { try { if (fileChannel != null) { fileChannel.close(); } if (file != null) { file.close(); } if (fallbackZipContent != null) { fallbackZipContent.close(); } } finally { fileChannel = null; file = null; byteBuffer = null; endOfCDStart = -2; fallbackZipContent = null; } } public File getZipFile() { return zipFile; } @Override public String toString() { return "JadxZipParser{" + zipFile + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/parser/JadxZipEntry.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/parser/JadxZipEntry.java
package jadx.zip.parser; import java.io.File; import java.io.InputStream; import jadx.zip.IZipEntry; public final class JadxZipEntry implements IZipEntry { private final JadxZipParser parser; private final String fileName; private final int compressMethod; private final int entryStart; private final int dataStart; private final long compressedSize; private final long uncompressedSize; JadxZipEntry(JadxZipParser parser, String fileName, int entryStart, int dataStart, int compressMethod, long compressedSize, long uncompressedSize) { this.parser = parser; this.fileName = fileName; this.entryStart = entryStart; this.dataStart = dataStart; this.compressMethod = compressMethod; this.compressedSize = compressedSize; this.uncompressedSize = uncompressedSize; } public boolean isSizesValid() { if (compressedSize <= 0) { return false; } if (uncompressedSize <= 0) { return false; } return compressedSize <= uncompressedSize; } public String getName() { return fileName; } @Override public long getCompressedSize() { return compressedSize; } @Override public long getUncompressedSize() { return uncompressedSize; } @Override public boolean isDirectory() { return fileName.endsWith("/"); } @Override public boolean preferBytes() { return true; } @Override public byte[] getBytes() { return parser.getBytes(this); } @Override public InputStream getInputStream() { return parser.getInputStream(this); } public int getEntryStart() { return entryStart; } public int getDataStart() { return dataStart; } public int getCompressMethod() { return compressMethod; } @Override public File getZipFile() { return parser.getZipFile(); } @Override public String toString() { return parser.getZipFile().getName() + ':' + fileName; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-zip/src/main/java/jadx/zip/parser/ZipDeflate.java
jadx-commons/jadx-zip/src/main/java/jadx/zip/parser/ZipDeflate.java
package jadx.zip.parser; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import static jadx.zip.parser.JadxZipParser.bufferToStream; final class ZipDeflate { private static final int BUFFER_SIZE = 4096; static byte[] decompressEntryToBytes(ByteBuffer buf, JadxZipEntry entry) throws DataFormatException { buf.position(entry.getDataStart()); ByteBuffer entryBuf = buf.slice(); entryBuf.limit((int) entry.getCompressedSize()); byte[] out = new byte[(int) entry.getUncompressedSize()]; Inflater inflater = new Inflater(true); inflater.setInput(entryBuf); int written = inflater.inflate(out); inflater.end(); if (written != out.length) { throw new DataFormatException("Unexpected size of decompressed entry: " + entry + ", got: " + written + ", expected: " + out.length); } return out; } static InputStream decompressEntryToStream(ByteBuffer buf, JadxZipEntry entry) { InputStream stream = bufferToStream(buf, entry.getDataStart(), (int) entry.getCompressedSize()); Inflater inflater = new Inflater(true); return new InflaterInputStream(stream, inflater, BUFFER_SIZE); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-app-commons/src/main/java/jadx/commons/app/JadxCommonFiles.java
jadx-commons/jadx-app-commons/src/main/java/jadx/commons/app/JadxCommonFiles.java
package jadx.commons.app; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.function.Function; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import dev.dirs.ProjectDirectories; import dev.dirs.impl.Windows; import dev.dirs.impl.WindowsPowerShell; import dev.dirs.jni.WindowsJni; public class JadxCommonFiles { private static final Logger LOG = LoggerFactory.getLogger(JadxCommonFiles.class); private static final Path CONFIG_DIR; private static final Path CACHE_DIR; public static Path getConfigDir() { return CONFIG_DIR; } public static Path getCacheDir() { return CACHE_DIR; } static { DirsLoader loader = new DirsLoader(); loader.init(); CONFIG_DIR = loader.getConfigDir(); CACHE_DIR = loader.getCacheDir(); } private static final class DirsLoader { private @Nullable ProjectDirectories dirs; private Path configDir; private Path cacheDir; public void init() { try { configDir = loadEnvDir("JADX_CONFIG_DIR", pd -> pd.configDir); cacheDir = loadEnvDir("JADX_CACHE_DIR", pd -> pd.cacheDir); } catch (Exception e) { throw new RuntimeException("Failed to init common directories", e); } } private Path loadEnvDir(String envVar, Function<ProjectDirectories, String> dirFunc) throws IOException { String envDir = JadxCommonEnv.get(envVar, null); String dirStr; if (envDir != null) { dirStr = envDir; } else { dirStr = dirFunc.apply(loadDirs()); } Path path = Path.of(dirStr).toAbsolutePath(); Files.createDirectories(path); return path; } private synchronized ProjectDirectories loadDirs() { ProjectDirectories currentDirs = dirs; if (currentDirs != null) { return currentDirs; } LOG.debug("Loading system dirs ..."); long start = System.currentTimeMillis(); ProjectDirectories loadedDirs = ProjectDirectories.from("io.github", "skylot", "jadx", DirsLoader::getWinDirs); if (LOG.isDebugEnabled()) { LOG.debug("Loaded system dirs ({}ms): config: {}, cache: {}", System.currentTimeMillis() - start, loadedDirs.configDir, loadedDirs.cacheDir); } dirs = loadedDirs; return loadedDirs; } /** * Return JNI, Foreign or PowerShell implementation */ private static Windows getWinDirs() { Windows defSup = Windows.getDefaultSupplier().get(); if (defSup instanceof WindowsPowerShell) { if (JadxSystemInfo.IS_AMD64) { // JNI library compiled for x86-64 return new WindowsJni(); } } return defSup; } public Path getCacheDir() { return cacheDir; } public Path getConfigDir() { return configDir; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-app-commons/src/main/java/jadx/commons/app/JadxCommonEnv.java
jadx-commons/jadx-app-commons/src/main/java/jadx/commons/app/JadxCommonEnv.java
package jadx.commons.app; public class JadxCommonEnv { public static String get(String varName, String defValue) { String strValue = System.getenv(varName); return isNullOrEmpty(strValue) ? defValue : strValue; } public static boolean getBool(String varName, boolean defValue) { String strValue = System.getenv(varName); if (isNullOrEmpty(strValue)) { return defValue; } return strValue.equalsIgnoreCase("true"); } public static int getInt(String varName, int defValue) { String strValue = System.getenv(varName); if (isNullOrEmpty(strValue)) { return defValue; } return Integer.parseInt(strValue); } private static boolean isNullOrEmpty(String value) { return value == null || value.isEmpty(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-app-commons/src/main/java/jadx/commons/app/JadxTempFiles.java
jadx-commons/jadx-app-commons/src/main/java/jadx/commons/app/JadxTempFiles.java
package jadx.commons.app; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class JadxTempFiles { private static final String JADX_TMP_INSTANCE_PREFIX = "jadx-instance-"; private static final Path TEMP_ROOT_DIR = createTempRootDir(); public static Path getTempRootDir() { return TEMP_ROOT_DIR; } private static Path createTempRootDir() { try { String jadxTmpDir = System.getenv("JADX_TMP_DIR"); Path dir; if (jadxTmpDir != null) { Path customTmpRootDir = Paths.get(jadxTmpDir); Files.createDirectories(customTmpRootDir); dir = Files.createTempDirectory(customTmpRootDir, JADX_TMP_INSTANCE_PREFIX); } else { dir = Files.createTempDirectory(JADX_TMP_INSTANCE_PREFIX); } dir.toFile().deleteOnExit(); return dir; } catch (Exception e) { throw new RuntimeException("Failed to create temp root directory", e); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-commons/jadx-app-commons/src/main/java/jadx/commons/app/JadxSystemInfo.java
jadx-commons/jadx-app-commons/src/main/java/jadx/commons/app/JadxSystemInfo.java
package jadx.commons.app; import java.util.Locale; public class JadxSystemInfo { public static final String JAVA_VM = System.getProperty("java.vm.name", "?"); public static final String JAVA_VER = System.getProperty("java.version", "?"); public static final String OS_NAME = System.getProperty("os.name", "?"); public static final String OS_ARCH = System.getProperty("os.arch", "?"); public static final String OS_VERSION = System.getProperty("os.version", "?"); private static final String OS_NAME_LOWER = OS_NAME.toLowerCase(Locale.ENGLISH); public static final boolean IS_WINDOWS = OS_NAME_LOWER.startsWith("windows"); public static final boolean IS_MAC = OS_NAME_LOWER.startsWith("mac"); public static final boolean IS_LINUX = !IS_WINDOWS && !IS_MAC; public static final boolean IS_UNIX = !IS_WINDOWS; private static final String OS_ARCH_LOWER = OS_NAME.toLowerCase(Locale.ENGLISH); public static final boolean IS_AMD64 = OS_ARCH_LOWER.equals("amd64"); public static final boolean IS_ARM64 = OS_ARCH_LOWER.equals("aarch64"); private JadxSystemInfo() { } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/test/java/jadx/plugins/tools/utils/PluginUtilsTest.java
jadx-cli/src/test/java/jadx/plugins/tools/utils/PluginUtilsTest.java
package jadx.plugins.tools.utils; import org.junit.jupiter.api.Test; import static jadx.plugins.tools.utils.PluginUtils.extractVersion; import static org.assertj.core.api.Assertions.assertThat; class PluginUtilsTest { @Test public void testExtractVersion() { assertThat(extractVersion("plugin-name-v1.2.3.jar")).isEqualTo("1.2.3"); assertThat(extractVersion("plugin-name-v1.2.jar")).isEqualTo("1.2"); assertThat(extractVersion("1.2.3.jar")).isEqualTo("1.2.3"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/test/java/jadx/cli/TestExport.java
jadx-cli/src/test/java/jadx/cli/TestExport.java
package jadx.cli; import org.assertj.core.api.Condition; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class TestExport extends BaseCliIntegrationTest { @Test public void testBasicExport() throws Exception { int result = execJadxCli("samples/small.apk"); assertThat(result).isEqualTo(0); assertThat(collectAllFilesInDir(outputDir)) .map(this::pathToUniformString) .haveExactly(2, new Condition<>(f -> f.startsWith("sources/") && f.endsWith(".java"), "sources")) .haveExactly(10, new Condition<>(f -> f.startsWith("resources/"), "resources")) .haveExactly(1, new Condition<>(f -> f.equals("resources/AndroidManifest.xml"), "manifest")) .hasSize(12); } @Test public void testGradleExportApk() throws Exception { int result = execJadxCli("samples/small.apk", "--export-gradle"); assertThat(result).isEqualTo(0); assertThat(collectAllFilesInDir(outputDir)) .describedAs("check output files") .map(this::pathToUniformString) .haveExactly(2, new Condition<>(f -> f.endsWith(".java"), "java classes")) .haveExactly(0, new Condition<>(f -> f.endsWith("classes.dex"), "dex files")) .hasSize(15); } @Test public void testGradleExportAAR() throws Exception { int result = execJadxCli("samples/test-lib.aar", "--export-gradle"); assertThat(result).isEqualTo(0); assertThat(collectAllFilesInDir(outputDir)) .describedAs("check output files") .map(this::printFileContent) .map(this::pathToUniformString) .haveExactly(1, new Condition<>(f -> f.startsWith("lib/src/main/java/") && f.endsWith(".java"), "java")) .haveExactly(0, new Condition<>(f -> f.endsWith(".jar"), "jar files")) .hasSize(8); } @Test public void testGradleExportSimpleJava() throws Exception { int result = execJadxCli("samples/HelloWorld.class", "--export-gradle"); assertThat(result).isEqualTo(0); assertThat(collectAllFilesInDir(outputDir)) .describedAs("check output files") .map(this::printFileContent) .map(this::pathToUniformString) .haveExactly(1, new Condition<>(f -> f.endsWith(".java") && f.startsWith("app/src/main/java/"), "java")) .haveExactly(0, new Condition<>(f -> f.endsWith(".class"), "class files")) .haveExactly(1, new Condition<>(f -> f.equals("settings.gradle.kts"), "settings")) .haveExactly(1, new Condition<>(f -> f.equals("app/build.gradle.kts"), "build")) .hasSize(3); } @Test public void testGradleExportInvalidType() throws Exception { int result = execJadxCli("samples/HelloWorld.class", "--export-gradle-type", "android-app"); assertThat(result).isEqualTo(0); // expect output in 'android-app' template, but most fields will be set to UNKNOWN. assertThat(collectAllFilesInDir(outputDir)) .describedAs("check output files") .map(this::printFileContent) .map(this::pathToUniformString) .haveExactly(1, new Condition<>(f -> f.endsWith(".java") && f.startsWith("app/src/main/java/"), "java")) .haveExactly(1, new Condition<>(f -> f.equals("settings.gradle"), "settings")) .haveExactly(1, new Condition<>(f -> f.equals("build.gradle"), "build")) .haveExactly(1, new Condition<>(f -> f.equals("app/build.gradle"), "app build")) .hasSize(4); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/test/java/jadx/cli/RenameConverterTest.java
jadx-cli/src/test/java/jadx/cli/RenameConverterTest.java
package jadx.cli; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import jadx.api.JadxArgs.RenameEnum; import jadx.cli.JadxCLIArgs.RenameConverter; import jadx.core.utils.exceptions.JadxArgsValidateException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; public class RenameConverterTest { private RenameConverter converter; @BeforeEach public void init() { converter = new RenameConverter("someParam"); } @Test public void all() { Set<RenameEnum> set = converter.convert("all"); assertThat(set).hasSize(3); assertThat(set).contains(RenameEnum.CASE); assertThat(set).contains(RenameEnum.VALID); assertThat(set).contains(RenameEnum.PRINTABLE); } @Test public void none() { Set<RenameEnum> set = converter.convert("none"); assertThat(set).isEmpty(); } @Test public void wrong() { JadxArgsValidateException thrown = assertThrows(JadxArgsValidateException.class, () -> converter.convert("wrong"), "Expected convert() to throw, but it didn't"); assertThat(thrown.getMessage()).isEqualTo("'wrong' is unknown for parameter someParam, possible values are case, valid, printable"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/test/java/jadx/cli/TestInput.java
jadx-cli/src/test/java/jadx/cli/TestInput.java
package jadx.cli; import java.nio.file.Path; import java.util.List; import org.assertj.core.api.Condition; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class TestInput extends BaseCliIntegrationTest { @Test public void testHelp() { int result = execJadxCli(new String[] { "--help" }); assertThat(result).isEqualTo(0); } @Test public void testApkInput() throws Exception { int result = execJadxCli(buildArgs(List.of(), "samples/small.apk")); assertThat(result).isEqualTo(0); assertThat(collectAllFilesInDir(outputDir)) .describedAs("check output files") .map(p -> p.getFileName().toString()) .haveExactly(2, new Condition<>(f -> f.endsWith(".java"), "java classes")) .haveExactly(9, new Condition<>(f -> f.endsWith(".xml"), "xml resources")) .haveExactly(1, new Condition<>(f -> f.equals("AndroidManifest.xml"), "manifest")) .hasSize(12); } @Test public void testDexInput() throws Exception { decompile("samples/hello.dex"); } @Test public void testSmaliInput() throws Exception { decompile("samples/HelloWorld.smali"); } @Test public void testClassInput() throws Exception { decompile("samples/HelloWorld.class"); } @Test public void testMultipleInput() throws Exception { decompile("samples/hello.dex", "samples/HelloWorld.smali"); } @Test public void testFallbackMode() throws Exception { int result = execJadxCli(buildArgs(List.of("-f"), "samples/hello.dex")); assertThat(result).isEqualTo(0); List<Path> files = collectJavaFilesInDir(outputDir); assertThat(files).hasSize(1); } @Test public void testSimpleMode() throws Exception { int result = execJadxCli(buildArgs(List.of("--decompilation-mode", "simple"), "samples/hello.dex")); assertThat(result).isEqualTo(0); List<Path> files = collectJavaFilesInDir(outputDir); assertThat(files).hasSize(1); } @Test public void testResourceOnly() throws Exception { int result = execJadxCli(buildArgs(List.of(), "samples/resources-only.apk")); assertThat(result).isEqualTo(0); List<Path> files = collectFilesInDir(outputDir, path -> path.getFileName().toString().equalsIgnoreCase("AndroidManifest.xml")); assertThat(files).isNotEmpty(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/test/java/jadx/cli/JadxCLIArgsTest.java
jadx-cli/src/test/java/jadx/cli/JadxCLIArgsTest.java
package jadx.cli; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static jadx.core.utils.Utils.newConstStringMap; import static org.assertj.core.api.Assertions.assertThat; public class JadxCLIArgsTest { private static final Logger LOG = LoggerFactory.getLogger(JadxCLIArgsTest.class); @Test public void testInvertedBooleanOption() { assertThat(parse("--no-replace-consts").isReplaceConsts()).isFalse(); assertThat(parse("").isReplaceConsts()).isTrue(); } @Test public void testEscapeUnicodeOption() { assertThat(parse("--escape-unicode").isEscapeUnicode()).isTrue(); assertThat(parse("").isEscapeUnicode()).isFalse(); } @Test public void testSrcOption() { assertThat(parse("--no-src").isSkipSources()).isTrue(); assertThat(parse("-s").isSkipSources()).isTrue(); assertThat(parse("").isSkipSources()).isFalse(); } @Test public void testOptionsOverride() { assertThat(override(new JadxCLIArgs(), "--no-imports").isUseImports()).isFalse(); assertThat(override(new JadxCLIArgs(), "--no-debug-info").isDebugInfo()).isFalse(); assertThat(override(new JadxCLIArgs(), "").isUseImports()).isTrue(); JadxCLIArgs args = new JadxCLIArgs(); args.useImports = false; assertThat(override(args, "--no-imports").isUseImports()).isFalse(); args.debugInfo = false; assertThat(override(args, "--no-debug-info").isDebugInfo()).isFalse(); args = new JadxCLIArgs(); args.useImports = false; assertThat(override(args, "").isUseImports()).isFalse(); } @Test public void testPluginOptionsOverride() { // add key to empty base map checkPluginOptionsMerge( Collections.emptyMap(), "-Poption=otherValue", newConstStringMap("option", "otherValue")); // override one key checkPluginOptionsMerge( newConstStringMap("option", "value"), "-Poption=otherValue", newConstStringMap("option", "otherValue")); // merge different keys checkPluginOptionsMerge( Collections.singletonMap("option1", "value1"), "-Poption2=otherValue2", newConstStringMap("option1", "value1", "option2", "otherValue2")); // merge and override checkPluginOptionsMerge( newConstStringMap("option1", "value1", "option2", "value2"), "-Poption2=otherValue2", newConstStringMap("option1", "value1", "option2", "otherValue2")); } private void checkPluginOptionsMerge(Map<String, String> baseMap, String providedArgs, Map<String, String> expectedMap) { JadxCLIArgs args = new JadxCLIArgs(); args.pluginOptions = baseMap; Map<String, String> resultMap = override(args, providedArgs).getPluginOptions(); assertThat(resultMap).isEqualTo(expectedMap); } private JadxCLIArgs parse(String... args) { return parse(new JadxCLIArgs(), args); } private JadxCLIArgs parse(JadxCLIArgs jadxArgs, String... args) { return check(jadxArgs, jadxArgs.processArgs(args)); } private JadxCLIArgs override(JadxCLIArgs jadxArgs, String... args) { return check(jadxArgs, overrideProvided(jadxArgs, args)); } private static boolean overrideProvided(JadxCLIArgs jadxArgs, String[] args) { JCommanderWrapper jcw = new JCommanderWrapper(new JadxCLIArgs()); if (!jcw.parse(args)) { return false; } jcw.overrideProvided(jadxArgs); return jadxArgs.process(jcw); } private static JadxCLIArgs check(JadxCLIArgs jadxArgs, boolean res) { assertThat(res).isTrue(); LOG.info("Jadx args: {}", jadxArgs.toJadxArgs()); return jadxArgs; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/test/java/jadx/cli/BaseCliIntegrationTest.java
jadx-cli/src/test/java/jadx/cli/BaseCliIntegrationTest.java
package jadx.cli; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.plugins.loader.JadxBasePluginLoader; import jadx.core.plugins.files.SingleDirFilesGetter; import jadx.core.utils.Utils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class BaseCliIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(BaseCliIntegrationTest.class); static final PathMatcher LOG_ALL_FILES = path -> { LOG.debug("File in result dir: {}", path); return true; }; @TempDir Path testDir; Path outputDir; @BeforeEach public void setUp() { outputDir = testDir.resolve("output"); } int execJadxCli(String sampleName, String... options) { return execJadxCli(buildArgs(List.of(options), sampleName)); } int execJadxCli(String[] args) { return JadxCLI.execute(args, jadxArgs -> { // don't use global config and plugins jadxArgs.setFilesGetter(new SingleDirFilesGetter(testDir)); jadxArgs.setPluginLoader(new JadxBasePluginLoader()); }); } String[] buildArgs(List<String> options, String... inputSamples) { List<String> args = new ArrayList<>(options); args.add("-v"); args.add("-d"); args.add(outputDir.toAbsolutePath().toString()); for (String inputSample : inputSamples) { try { URL resource = getClass().getClassLoader().getResource(inputSample); assertThat(resource).isNotNull(); String sampleFile = resource.toURI().getRawPath(); args.add(sampleFile); } catch (URISyntaxException e) { fail("Failed to load sample: " + inputSample, e); } } return args.toArray(new String[0]); } void decompile(String... inputSamples) throws IOException { int result = execJadxCli(buildArgs(List.of(), inputSamples)); assertThat(result).isEqualTo(0); List<Path> resultJavaFiles = collectJavaFilesInDir(outputDir); assertThat(resultJavaFiles).isNotEmpty(); // do not copy input files as resources for (Path path : collectFilesInDir(outputDir, LOG_ALL_FILES)) { for (String inputSample : inputSamples) { assertThat(path.toAbsolutePath().toString()).doesNotContain(inputSample); } } } static void printFiles(List<Path> files) { LOG.info("Output files (count: {}):", files.size()); for (Path file : files) { LOG.info(" {}", file); } LOG.info(""); } String pathToUniformString(Path path) { return path.toString().replace('\\', '/'); } Path printFileContent(Path file) { try { String content = Files.readString(outputDir.resolve(file)); String spacer = Utils.strRepeat("=", 70); LOG.info("File content: {}\n{}\n{}\n{}", file, spacer, content, spacer); return file; } catch (IOException e) { throw new RuntimeException("Failed to load file: " + file, e); } } static List<Path> collectJavaFilesInDir(Path dir) throws IOException { PathMatcher javaMatcher = dir.getFileSystem().getPathMatcher("glob:**.java"); return collectFilesInDir(dir, javaMatcher); } static List<Path> collectAllFilesInDir(Path dir) throws IOException { try (Stream<Path> pathStream = Files.walk(dir)) { List<Path> files = pathStream .filter(Files::isRegularFile) .map(dir::relativize) .collect(Collectors.toList()); printFiles(files); return files; } } static List<Path> collectFilesInDir(Path dir, PathMatcher matcher) throws IOException { try (Stream<Path> pathStream = Files.walk(dir)) { List<Path> files = pathStream .filter(p -> Files.isRegularFile(p, LinkOption.NOFOLLOW_LINKS)) .filter(matcher::matches) .collect(Collectors.toList()); printFiles(files); return files; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/JadxCLI.java
jadx-cli/src/main/java/jadx/cli/JadxCLI.java
package jadx.cli; import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.api.impl.AnnotatedCodeWriter; import jadx.api.impl.NoOpCodeCache; import jadx.api.impl.SimpleCodeWriter; import jadx.api.usage.impl.EmptyUsageInfoCache; import jadx.cli.LogHelper.LogLevelEnum; import jadx.cli.config.JadxConfigAdapter; import jadx.cli.plugins.JadxFilesGetter; import jadx.core.utils.exceptions.JadxArgsValidateException; import jadx.plugins.tools.JadxExternalPluginsLoader; public class JadxCLI { private static final Logger LOG = LoggerFactory.getLogger(JadxCLI.class); public static void main(String[] args) { int result = 1; try { result = execute(args); } finally { System.exit(result); } } public static int execute(String[] args) { return execute(args, null); } public static int execute(String[] args, @Nullable Consumer<JadxArgs> argsMod) { try { JadxCLIArgs cliArgs = JadxCLIArgs.processArgs(args, new JadxCLIArgs(), new JadxConfigAdapter<>(JadxCLIArgs.class, "cli")); if (cliArgs == null) { return 0; } JadxArgs jadxArgs = buildArgs(cliArgs); if (argsMod != null) { argsMod.accept(jadxArgs); } return runSave(jadxArgs, cliArgs); } catch (JadxArgsValidateException e) { LOG.error("Incorrect arguments: {}", e.getMessage()); return 1; } catch (Throwable e) { LOG.error("Process error:", e); return 1; } } private static JadxArgs buildArgs(JadxCLIArgs cliArgs) { JadxArgs jadxArgs = cliArgs.toJadxArgs(); jadxArgs.setCodeCache(new NoOpCodeCache()); jadxArgs.setUsageInfoCache(new EmptyUsageInfoCache()); jadxArgs.setPluginLoader(new JadxExternalPluginsLoader()); jadxArgs.setFilesGetter(JadxFilesGetter.INSTANCE); initCodeWriterProvider(jadxArgs); JadxAppCommon.applyEnvVars(jadxArgs); return jadxArgs; } private static int runSave(JadxArgs jadxArgs, JadxCLIArgs cliArgs) { try (JadxDecompiler jadx = new JadxDecompiler(jadxArgs)) { jadx.load(); if (checkForErrors(jadx)) { return 1; } if (!SingleClassMode.process(jadx, cliArgs)) { save(jadx); } int errorsCount = jadx.getErrorsCount(); if (errorsCount != 0) { jadx.printErrorsReport(); LOG.error("finished with errors, count: {}", errorsCount); return 1; } LOG.info("done"); return 0; } } private static void initCodeWriterProvider(JadxArgs jadxArgs) { switch (jadxArgs.getOutputFormat()) { case JAVA: jadxArgs.setCodeWriterProvider(SimpleCodeWriter::new); break; case JSON: // needed for code offsets and source lines jadxArgs.setCodeWriterProvider(AnnotatedCodeWriter::new); break; } } private static boolean checkForErrors(JadxDecompiler jadx) { if (jadx.getRoot().getClasses().isEmpty()) { if (jadx.getArgs().isSkipResources()) { LOG.error("Load failed! No classes for decompile!"); return true; } if (!jadx.getArgs().isSkipSources()) { LOG.warn("No classes to decompile; decoding resources only"); jadx.getArgs().setSkipSources(true); } } int errorsCount = jadx.getErrorsCount(); if (errorsCount > 0) { LOG.error("Loading finished with errors! Count: {}", errorsCount); // continue processing } return false; } private static void save(JadxDecompiler jadx) { if (LogHelper.getLogLevel() == LogLevelEnum.QUIET) { jadx.save(); } else { LOG.info("processing ..."); jadx.save(500, (done, total) -> { int progress = (int) (done * 100.0 / total); System.out.printf("INFO - progress: %d of %d (%d%%)\r", done, total, progress); }); // dumb line clear :) System.out.print(" \r"); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/JadxAppCommon.java
jadx-cli/src/main/java/jadx/cli/JadxAppCommon.java
package jadx.cli; import java.util.Set; import jadx.api.JadxArgs; import jadx.api.security.JadxSecurityFlag; import jadx.api.security.impl.JadxSecurity; import jadx.commons.app.JadxCommonEnv; import jadx.zip.security.DisabledZipSecurity; import jadx.zip.security.IJadxZipSecurity; import jadx.zip.security.JadxZipSecurity; public class JadxAppCommon { public static void applyEnvVars(JadxArgs jadxArgs) { Set<JadxSecurityFlag> flags = JadxSecurityFlag.all(); IJadxZipSecurity zipSecurity; boolean disableXmlSecurity = JadxCommonEnv.getBool("JADX_DISABLE_XML_SECURITY", false); if (disableXmlSecurity) { flags.remove(JadxSecurityFlag.SECURE_XML_PARSER); // TODO: not related to 'xml security', but kept for compatibility flags.remove(JadxSecurityFlag.VERIFY_APP_PACKAGE); } boolean disableZipSecurity = JadxCommonEnv.getBool("JADX_DISABLE_ZIP_SECURITY", false); if (disableZipSecurity) { flags.remove(JadxSecurityFlag.SECURE_ZIP_READER); zipSecurity = DisabledZipSecurity.INSTANCE; } else { JadxZipSecurity jadxZipSecurity = new JadxZipSecurity(); int maxZipEntriesCount = JadxCommonEnv.getInt("JADX_ZIP_MAX_ENTRIES_COUNT", -2); if (maxZipEntriesCount != -2) { jadxZipSecurity.setMaxEntriesCount(maxZipEntriesCount); } int zipBombMinUncompressedSize = JadxCommonEnv.getInt("JADX_ZIP_BOMB_MIN_UNCOMPRESSED_SIZE", -2); if (zipBombMinUncompressedSize != -2) { jadxZipSecurity.setZipBombMinUncompressedSize(zipBombMinUncompressedSize); } int setZipBombDetectionFactor = JadxCommonEnv.getInt("JADX_ZIP_BOMB_DETECTION_FACTOR", -2); if (setZipBombDetectionFactor != -2) { jadxZipSecurity.setZipBombDetectionFactor(setZipBombDetectionFactor); } zipSecurity = jadxZipSecurity; } jadxArgs.setSecurity(new JadxSecurity(flags, zipSecurity)); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/JadxCLIArgs.java
jadx-cli/src/main/java/jadx/cli/JadxCLIArgs.java
package jadx.cli; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.DynamicParameter; import com.beust.jcommander.IStringConverter; import com.beust.jcommander.Parameter; import jadx.api.CommentsLevel; import jadx.api.DecompilationMode; import jadx.api.JadxArgs; import jadx.api.JadxArgs.RenameEnum; import jadx.api.JadxArgs.UseKotlinMethodsForVarNames; import jadx.api.JadxDecompiler; import jadx.api.args.GeneratedRenamesMappingFileMode; import jadx.api.args.IntegerFormat; import jadx.api.args.ResourceNameSource; import jadx.api.args.UseSourceNameAsClassNameAlias; import jadx.api.args.UserRenamesMappingsMode; import jadx.cli.config.IJadxConfig; import jadx.cli.config.JadxConfigAdapter; import jadx.cli.config.JadxConfigExclude; import jadx.commons.app.JadxCommonFiles; import jadx.commons.app.JadxTempFiles; import jadx.core.deobf.conditions.DeobfWhitelist; import jadx.core.export.ExportGradleType; import jadx.core.utils.exceptions.JadxArgsValidateException; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; public class JadxCLIArgs implements IJadxConfig { private static final Logger LOG = LoggerFactory.getLogger(JadxCLIArgs.class); @JadxConfigExclude @Parameter(description = "<input files> (.apk, .dex, .jar, .class, .smali, .zip, .aar, .arsc, .aab, .xapk, .apkm, .jadx.kts)") protected List<String> files = Collections.emptyList(); @JadxConfigExclude @Parameter(names = { "-d", "--output-dir" }, description = "output directory") protected String outDir; @JadxConfigExclude @Parameter(names = { "-ds", "--output-dir-src" }, description = "output directory for sources") protected String outDirSrc; @JadxConfigExclude @Parameter(names = { "-dr", "--output-dir-res" }, description = "output directory for resources") protected String outDirRes; @Parameter(names = { "-r", "--no-res" }, description = "do not decode resources") protected boolean skipResources = false; @Parameter(names = { "-s", "--no-src" }, description = "do not decompile source code") protected boolean skipSources = false; @Parameter(names = { "-j", "--threads-count" }, description = "processing threads count") protected int threadsCount = JadxArgs.DEFAULT_THREADS_COUNT; @JadxConfigExclude @Parameter(names = { "--single-class" }, description = "decompile a single class, full name, raw or alias") protected String singleClass = null; @JadxConfigExclude @Parameter(names = { "--single-class-output" }, description = "file or dir for write if decompile a single class") protected String singleClassOutput = null; @Parameter(names = { "--output-format" }, description = "can be 'java' or 'json'") protected String outputFormat = "java"; @Parameter(names = { "-e", "--export-gradle" }, description = "save as gradle project (set '--export-gradle-type' to 'auto')") protected boolean exportAsGradleProject = false; @Parameter( names = { "--export-gradle-type" }, description = "Gradle project template for export:" + "\n 'auto' - detect automatically" + "\n 'android-app' - Android Application (apk)" + "\n 'android-library' - Android Library (aar)" + "\n 'simple-java' - simple Java", converter = ExportGradleTypeConverter.class ) protected @Nullable ExportGradleType exportGradleType = null; @Parameter( names = { "-m", "--decompilation-mode" }, description = "code output mode:" + "\n 'auto' - trying best options (default)" + "\n 'restructure' - restore code structure (normal java code)" + "\n 'simple' - simplified instructions (linear, with goto's)" + "\n 'fallback' - raw instructions without modifications", converter = DecompilationModeConverter.class ) protected DecompilationMode decompilationMode = DecompilationMode.AUTO; @Parameter(names = { "--show-bad-code" }, description = "show inconsistent code (incorrectly decompiled)") protected boolean showInconsistentCode = false; @Parameter(names = { "--no-xml-pretty-print" }, description = "do not prettify XML") protected boolean skipXmlPrettyPrint = false; @Parameter(names = { "--no-imports" }, description = "disable use of imports, always write entire package name") protected boolean useImports = true; @Parameter(names = { "--no-debug-info" }, description = "disable debug info parsing and processing") protected boolean debugInfo = true; @Parameter(names = { "--add-debug-lines" }, description = "add comments with debug line numbers if available") protected boolean addDebugLines = false; @Parameter(names = { "--no-inline-anonymous" }, description = "disable anonymous classes inline") protected boolean inlineAnonymousClasses = true; @Parameter(names = { "--no-inline-methods" }, description = "disable methods inline") protected boolean inlineMethods = true; @Parameter(names = { "--no-move-inner-classes" }, description = "disable move inner classes into parent") protected boolean moveInnerClasses = true; @Parameter(names = { "--no-inline-kotlin-lambda" }, description = "disable inline for Kotlin lambdas") protected boolean allowInlineKotlinLambda = true; @Parameter(names = "--no-finally", description = "don't extract finally block") protected boolean extractFinally = true; @Parameter(names = "--no-restore-switch-over-string", description = "don't restore switch over string") protected boolean restoreSwitchOverString = true; @Parameter(names = "--no-replace-consts", description = "don't replace constant value with matching constant field") protected boolean replaceConsts = true; @Parameter(names = { "--escape-unicode" }, description = "escape non latin characters in strings (with \\u)") protected boolean escapeUnicode = false; @Parameter(names = { "--respect-bytecode-access-modifiers" }, description = "don't change original access modifiers") protected boolean respectBytecodeAccessModifiers = false; @Parameter( names = { "--mappings-path" }, description = "deobfuscation mappings file or directory. Allowed formats: Tiny and Tiny v2 (both '.tiny'), Enigma (.mapping) or Enigma directory" ) protected Path userRenamesMappingsPath; @Parameter( names = { "--mappings-mode" }, description = "set mode for handling the deobfuscation mapping file:" + "\n 'read' - just read, user can always save manually (default)" + "\n 'read-and-autosave-every-change' - read and autosave after every change" + "\n 'read-and-autosave-before-closing' - read and autosave before exiting the app or closing the project" + "\n 'ignore' - don't read or save (can be used to skip loading mapping files referenced in the project file)" ) protected UserRenamesMappingsMode userRenamesMappingsMode = UserRenamesMappingsMode.getDefault(); @Parameter(names = { "--deobf" }, description = "activate deobfuscation") protected boolean deobfuscationOn = false; @Parameter(names = { "--deobf-min" }, description = "min length of name, renamed if shorter") protected int deobfuscationMinLength = 3; @Parameter(names = { "--deobf-max" }, description = "max length of name, renamed if longer") protected int deobfuscationMaxLength = 64; @Parameter( names = { "--deobf-whitelist" }, description = "space separated list of classes (full name) and packages (ends with '.*') to exclude from deobfuscation" ) protected String deobfuscationWhitelistStr = DeobfWhitelist.DEFAULT_STR; @JadxConfigExclude @Parameter( names = { "--deobf-cfg-file" }, description = "deobfuscation mappings file used for JADX auto-generated names (in the JOBF file format)," + " default: same dir and name as input file with '.jobf' extension" ) protected String generatedRenamesMappingFile; @Parameter( names = { "--deobf-cfg-file-mode" }, description = "set mode for handling the JADX auto-generated names' deobfuscation map file:" + "\n 'read' - read if found, don't save (default)" + "\n 'read-or-save' - read if found, save otherwise (don't overwrite)" + "\n 'overwrite' - don't read, always save" + "\n 'ignore' - don't read and don't save", converter = DeobfuscationMapFileModeConverter.class ) protected GeneratedRenamesMappingFileMode generatedRenamesMappingFileMode = GeneratedRenamesMappingFileMode.getDefault(); @SuppressWarnings("DeprecatedIsStillUsed") @Parameter( names = { "--deobf-use-sourcename" }, description = "use source file name as class name alias." + "\nDEPRECATED, use \"--use-source-name-as-class-name-alias\" instead", hidden = true ) @Deprecated protected Boolean deobfuscationUseSourceNameAsAlias = null; @Parameter( names = { "--deobf-res-name-source" }, description = "better name source for resources:" + "\n 'auto' - automatically select best name (default)" + "\n 'resources' - use resources names" + "\n 'code' - use R class fields names", converter = ResourceNameSourceConverter.class ) protected ResourceNameSource resourceNameSource = ResourceNameSource.AUTO; @Parameter( names = { "--use-source-name-as-class-name-alias" }, description = "use source name as class name alias:" + "\n 'always' - always use source name if it's available" + "\n 'if-better' - use source name if it seems better than the current one" + "\n 'never' - never use source name, even if it's available", converter = UseSourceNameAsClassNameConverter.class ) protected UseSourceNameAsClassNameAlias useSourceNameAsClassNameAlias = null; @Parameter( names = { "--source-name-repeat-limit" }, description = "allow using source name if it appears less than a limit number" ) protected int sourceNameRepeatLimit = 10; @Parameter( names = { "--use-kotlin-methods-for-var-names" }, description = "use kotlin intrinsic methods to rename variables, values: disable, apply, apply-and-hide", converter = UseKotlinMethodsForVarNamesConverter.class ) protected UseKotlinMethodsForVarNames useKotlinMethodsForVarNames = UseKotlinMethodsForVarNames.APPLY; @Parameter( names = { "--use-headers-for-detect-resource-extensions" }, description = "Use headers for detect resource extensions if resource obfuscated" ) protected boolean useHeadersForDetectResourceExtensions = false; @Parameter( names = { "--rename-flags" }, description = "fix options (comma-separated list of):" + "\n 'case' - fix case sensitivity issues (according to --fs-case-sensitive option)," + "\n 'valid' - rename java identifiers to make them valid," + "\n 'printable' - remove non-printable chars from identifiers," + "\nor single 'none' - to disable all renames" + "\nor single 'all' - to enable all (default)", listConverter = RenameConverter.class ) protected Set<RenameEnum> renameFlags = EnumSet.allOf(RenameEnum.class); @Parameter( names = { "--integer-format" }, description = "how integers are displayed:" + "\n 'auto' - automatically select (default)" + "\n 'decimal' - use decimal" + "\n 'hexadecimal' - use hexadecimal", converter = IntegerFormatConverter.class ) protected IntegerFormat integerFormat = IntegerFormat.AUTO; @Parameter(names = { "--type-update-limit" }, description = "type update limit count (per one instruction)") protected int typeUpdatesLimitCount = 10; @Parameter(names = { "--fs-case-sensitive" }, description = "treat filesystem as case sensitive, false by default") protected boolean fsCaseSensitive = false; @Parameter(names = { "--cfg" }, description = "save methods control flow graph to dot file") protected boolean cfgOutput = false; @Parameter(names = { "--raw-cfg" }, description = "save methods control flow graph (use raw instructions)") protected boolean rawCfgOutput = false; @Parameter(names = { "-f", "--fallback" }, description = "set '--decompilation-mode' to 'fallback' (deprecated)") protected boolean fallbackMode = false; @Parameter(names = { "--use-dx" }, description = "use dx/d8 to convert java bytecode") protected boolean useDx = false; @Parameter( names = { "--comments-level" }, description = "set code comments level, values: error, warn, info, debug, user-only, none", converter = CommentsLevelConverter.class ) protected CommentsLevel commentsLevel = CommentsLevel.INFO; @Parameter( names = { "--log-level" }, description = "set log level, values: quiet, progress, error, warn, info, debug", converter = LogLevelConverter.class ) protected LogHelper.LogLevelEnum logLevel = LogHelper.LogLevelEnum.PROGRESS; @JadxConfigExclude @Parameter(names = { "-v", "--verbose" }, description = "verbose output (set --log-level to DEBUG)") protected boolean verbose = false; @JadxConfigExclude @Parameter(names = { "-q", "--quiet" }, description = "turn off output (set --log-level to QUIET)") protected boolean quiet = false; @JadxConfigExclude @Parameter(names = { "--disable-plugins" }, description = "comma separated list of plugin ids to disable") protected String disablePlugins = ""; @JadxConfigExclude @Parameter( names = { "--config" }, defaultValueDescription = "<config-ref>", description = "load configuration from file, <config-ref> can be:" + "\n path to '.json' file" + "\n short name - uses file with this name from config directory" + "\n 'none' - to disable config loading" ) protected String config = ""; @JadxConfigExclude @Parameter( names = { "--save-config" }, defaultValueDescription = "<config-ref>", description = "save current options into configuration file and exit, <config-ref> can be:" + "\n empty - for default config" + "\n path to '.json' file" + "\n short name - file will be saved in config directory" ) protected String saveConfig = null; @JadxConfigExclude @Parameter(names = { "--print-files" }, description = "print files and directories used by jadx (config, cache, temp)") protected boolean printFiles = false; @JadxConfigExclude @Parameter(names = { "--version" }, description = "print jadx version") protected boolean printVersion = false; @JadxConfigExclude @Parameter(names = { "-h", "--help" }, description = "print this help", help = true) protected boolean printHelp = false; @DynamicParameter(names = "-P", description = "Plugin options", hidden = true) protected Map<String, String> pluginOptions = new HashMap<>(); /** * Obsolete method without config support, * prefer {@link #processArgs(String[], JadxCLIArgs, JadxConfigAdapter)} */ public boolean processArgs(String[] args) { return processArgs(args, this, null) != null; } public static <T extends JadxCLIArgs> @Nullable T processArgs( String[] args, T argsObj, @Nullable JadxConfigAdapter<T> configAdapter) { JCommanderWrapper jcw = new JCommanderWrapper(argsObj); if (!jcw.parse(args)) { return null; } applyArgs(argsObj); // process commands and early exit flags if (!argsObj.process(jcw)) { return null; } if (configAdapter != null) { if (argsObj.printFiles) { printFilesAndDirs(configAdapter.getDefaultConfigFileName()); return null; } if (!argsObj.config.equalsIgnoreCase("none")) { // load config file and merge with command line args try { configAdapter.useConfigRef(argsObj.config); T configObj = configAdapter.load(); if (configObj != null) { jcw.overrideProvided(configObj); argsObj = configObj; } } catch (Exception e) { LOG.error("Config load failed, continue with default values", e); } } } // verify result object argsObj.verify(); applyArgs(argsObj); // save config if requested if (argsObj.saveConfig != null) { saveConfig(argsObj, configAdapter); return null; } return argsObj; } private static <T extends JadxCLIArgs> void applyArgs(T argsObj) { // apply log levels LogHelper.initLogLevel(argsObj); LogHelper.applyLogLevels(); } public boolean process(JCommanderWrapper jcw) { if (jcw.processCommands()) { return false; } if (printHelp) { jcw.printUsage(); return false; } if (printVersion) { System.out.println(JadxDecompiler.getVersion()); return false; } // unknown options added to 'files', run checks for (String fileName : files) { if (fileName.startsWith("-")) { throw new JadxArgsValidateException("Unknown option: " + fileName); } } return true; } private static void printFilesAndDirs(String defaultConfigFileName) { System.out.println("Files and directories used by jadx:"); System.out.println(" - default config file: " + JadxCommonFiles.getConfigDir().resolve(defaultConfigFileName).toAbsolutePath()); System.out.println(" - config directory: " + JadxCommonFiles.getConfigDir().toAbsolutePath()); System.out.println(" - cache directory: " + JadxCommonFiles.getCacheDir().toAbsolutePath()); System.out.println(" - temp directory: " + JadxTempFiles.getTempRootDir().getParent().toAbsolutePath()); } public void verify() { if (threadsCount <= 0) { throw new JadxArgsValidateException("Threads count must be positive, got: " + threadsCount); } } private static <T extends JadxCLIArgs> void saveConfig(T argsObj, @Nullable JadxConfigAdapter<T> configAdapter) { if (configAdapter == null) { throw new JadxRuntimeException("Config adapter set to null, can't save config"); } configAdapter.useConfigRef(argsObj.saveConfig); configAdapter.save(argsObj); System.out.println("Config saved to " + configAdapter.getConfigPath().toAbsolutePath()); } public JadxArgs toJadxArgs() { JadxArgs args = new JadxArgs(); args.setInputFiles(files.stream().map(FileUtils::toFile).collect(Collectors.toList())); args.setOutDir(FileUtils.toFile(outDir)); args.setOutDirSrc(FileUtils.toFile(outDirSrc)); args.setOutDirRes(FileUtils.toFile(outDirRes)); args.setOutputFormat(JadxArgs.OutputFormatEnum.valueOf(outputFormat.toUpperCase())); args.setThreadsCount(threadsCount); args.setSkipSources(skipSources); args.setSkipResources(skipResources); if (fallbackMode) { args.setDecompilationMode(DecompilationMode.FALLBACK); } else { args.setDecompilationMode(decompilationMode); } args.setShowInconsistentCode(showInconsistentCode); args.setCfgOutput(cfgOutput); args.setRawCFGOutput(rawCfgOutput); args.setReplaceConsts(replaceConsts); if (userRenamesMappingsPath != null) { args.setUserRenamesMappingsPath(userRenamesMappingsPath); } args.setUserRenamesMappingsMode(userRenamesMappingsMode); args.setDeobfuscationOn(deobfuscationOn); args.setGeneratedRenamesMappingFile(FileUtils.toFile(generatedRenamesMappingFile)); args.setGeneratedRenamesMappingFileMode(generatedRenamesMappingFileMode); args.setDeobfuscationMinLength(deobfuscationMinLength); args.setDeobfuscationMaxLength(deobfuscationMaxLength); args.setDeobfuscationWhitelist(Arrays.asList(deobfuscationWhitelistStr.split(" "))); args.setUseSourceNameAsClassNameAlias(getUseSourceNameAsClassNameAlias()); args.setUseHeadersForDetectResourceExtensions(useHeadersForDetectResourceExtensions); args.setSourceNameRepeatLimit(sourceNameRepeatLimit); args.setUseKotlinMethodsForVarNames(useKotlinMethodsForVarNames); args.setResourceNameSource(resourceNameSource); args.setEscapeUnicode(escapeUnicode); args.setRespectBytecodeAccModifiers(respectBytecodeAccessModifiers); args.setExportGradleType(exportGradleType); if (exportAsGradleProject && exportGradleType == null) { args.setExportGradleType(ExportGradleType.AUTO); } args.setSkipXmlPrettyPrint(skipXmlPrettyPrint); args.setUseImports(useImports); args.setDebugInfo(debugInfo); args.setInsertDebugLines(addDebugLines); args.setInlineAnonymousClasses(inlineAnonymousClasses); args.setInlineMethods(inlineMethods); args.setMoveInnerClasses(moveInnerClasses); args.setAllowInlineKotlinLambda(allowInlineKotlinLambda); args.setExtractFinally(extractFinally); args.setRestoreSwitchOverString(restoreSwitchOverString); args.setRenameFlags(buildEnumSetForRenameFlags()); args.setFsCaseSensitive(fsCaseSensitive); args.setCommentsLevel(commentsLevel); args.setIntegerFormat(integerFormat); args.setTypeUpdatesLimitCount(typeUpdatesLimitCount); args.setUseDxInput(useDx); args.setPluginOptions(pluginOptions); args.setDisabledPlugins(Arrays.stream(disablePlugins.split(",")).map(String::trim).collect(Collectors.toSet())); return args; } private EnumSet<RenameEnum> buildEnumSetForRenameFlags() { EnumSet<RenameEnum> set = EnumSet.noneOf(RenameEnum.class); set.addAll(renameFlags); return set; } public List<String> getFiles() { return files; } public void setFiles(List<String> files) { this.files = files; } public String getOutDir() { return outDir; } public String getOutDirSrc() { return outDirSrc; } public String getOutDirRes() { return outDirRes; } public String getSingleClass() { return singleClass; } public String getSingleClassOutput() { return singleClassOutput; } public boolean isSkipResources() { return skipResources; } public void setSkipResources(boolean skipResources) { this.skipResources = skipResources; } public boolean isSkipSources() { return skipSources; } public void setSkipSources(boolean skipSources) { this.skipSources = skipSources; } public int getThreadsCount() { return threadsCount; } public void setThreadsCount(int threadsCount) { this.threadsCount = threadsCount; } public boolean isFallbackMode() { return fallbackMode; } public boolean isUseDx() { return useDx; } public void setUseDx(boolean useDx) { this.useDx = useDx; } public DecompilationMode getDecompilationMode() { return decompilationMode; } public void setDecompilationMode(DecompilationMode decompilationMode) { this.decompilationMode = decompilationMode; } public boolean isShowInconsistentCode() { return showInconsistentCode; } public void setShowInconsistentCode(boolean showInconsistentCode) { this.showInconsistentCode = showInconsistentCode; } public boolean isUseImports() { return useImports; } public void setUseImports(boolean useImports) { this.useImports = useImports; } public boolean isDebugInfo() { return debugInfo; } public void setDebugInfo(boolean debugInfo) { this.debugInfo = debugInfo; } public boolean isAddDebugLines() { return addDebugLines; } public void setAddDebugLines(boolean addDebugLines) { this.addDebugLines = addDebugLines; } public boolean isInlineAnonymousClasses() { return inlineAnonymousClasses; } public void setInlineAnonymousClasses(boolean inlineAnonymousClasses) { this.inlineAnonymousClasses = inlineAnonymousClasses; } public boolean isInlineMethods() { return inlineMethods; } public void setInlineMethods(boolean inlineMethods) { this.inlineMethods = inlineMethods; } public boolean isMoveInnerClasses() { return moveInnerClasses; } public void setMoveInnerClasses(boolean moveInnerClasses) { this.moveInnerClasses = moveInnerClasses; } public boolean isAllowInlineKotlinLambda() { return allowInlineKotlinLambda; } public void setAllowInlineKotlinLambda(boolean allowInlineKotlinLambda) { this.allowInlineKotlinLambda = allowInlineKotlinLambda; } public boolean isExtractFinally() { return extractFinally; } public void setExtractFinally(boolean extractFinally) { this.extractFinally = extractFinally; } public boolean isRestoreSwitchOverString() { return restoreSwitchOverString; } public void setRestoreSwitchOverString(boolean restoreSwitchOverString) { this.restoreSwitchOverString = restoreSwitchOverString; } public Path getUserRenamesMappingsPath() { return userRenamesMappingsPath; } public void setUserRenamesMappingsPath(Path userRenamesMappingsPath) { this.userRenamesMappingsPath = userRenamesMappingsPath; } public UserRenamesMappingsMode getUserRenamesMappingsMode() { return userRenamesMappingsMode; } public void setUserRenamesMappingsMode(UserRenamesMappingsMode userRenamesMappingsMode) { this.userRenamesMappingsMode = userRenamesMappingsMode; } public boolean isDeobfuscationOn() { return deobfuscationOn; } public void setDeobfuscationOn(boolean deobfuscationOn) { this.deobfuscationOn = deobfuscationOn; } public int getDeobfuscationMinLength() { return deobfuscationMinLength; } public void setDeobfuscationMinLength(int deobfuscationMinLength) { this.deobfuscationMinLength = deobfuscationMinLength; } public int getDeobfuscationMaxLength() { return deobfuscationMaxLength; } public void setDeobfuscationMaxLength(int deobfuscationMaxLength) { this.deobfuscationMaxLength = deobfuscationMaxLength; } public String getDeobfuscationWhitelistStr() { return deobfuscationWhitelistStr; } public void setDeobfuscationWhitelistStr(String deobfuscationWhitelistStr) { this.deobfuscationWhitelistStr = deobfuscationWhitelistStr; } public String getGeneratedRenamesMappingFile() { return generatedRenamesMappingFile; } public void setGeneratedRenamesMappingFile(String generatedRenamesMappingFile) { this.generatedRenamesMappingFile = generatedRenamesMappingFile; } public GeneratedRenamesMappingFileMode getGeneratedRenamesMappingFileMode() { return generatedRenamesMappingFileMode; } public void setGeneratedRenamesMappingFileMode(GeneratedRenamesMappingFileMode generatedRenamesMappingFileMode) { this.generatedRenamesMappingFileMode = generatedRenamesMappingFileMode; } public int getSourceNameRepeatLimit() { return sourceNameRepeatLimit; } public void setSourceNameRepeatLimit(int sourceNameRepeatLimit) { this.sourceNameRepeatLimit = sourceNameRepeatLimit; } public UseSourceNameAsClassNameAlias getUseSourceNameAsClassNameAlias() { if (useSourceNameAsClassNameAlias != null) { return useSourceNameAsClassNameAlias; } else if (deobfuscationUseSourceNameAsAlias != null) { // noinspection deprecation return UseSourceNameAsClassNameAlias.create(deobfuscationUseSourceNameAsAlias); } else { return UseSourceNameAsClassNameAlias.getDefault(); } } public void setUseSourceNameAsClassNameAlias(UseSourceNameAsClassNameAlias useSourceNameAsClassNameAlias) { this.useSourceNameAsClassNameAlias = useSourceNameAsClassNameAlias; } /** * @deprecated Use {@link #getUseSourceNameAsClassNameAlias()} instead. */ @Deprecated public boolean isDeobfuscationUseSourceNameAsAlias() { return getUseSourceNameAsClassNameAlias().toBoolean(); } public void setDeobfuscationUseSourceNameAsAlias(Boolean deobfuscationUseSourceNameAsAlias) { this.deobfuscationUseSourceNameAsAlias = deobfuscationUseSourceNameAsAlias; } public ResourceNameSource getResourceNameSource() { return resourceNameSource; } public void setResourceNameSource(ResourceNameSource resourceNameSource) { this.resourceNameSource = resourceNameSource; } public UseKotlinMethodsForVarNames getUseKotlinMethodsForVarNames() { return useKotlinMethodsForVarNames; } public void setUseKotlinMethodsForVarNames(UseKotlinMethodsForVarNames useKotlinMethodsForVarNames) { this.useKotlinMethodsForVarNames = useKotlinMethodsForVarNames; } public IntegerFormat getIntegerFormat() { return integerFormat; } public void setIntegerFormat(IntegerFormat integerFormat) { this.integerFormat = integerFormat; } public int getTypeUpdatesLimitCount() { return typeUpdatesLimitCount; } public void setTypeUpdatesLimitCount(int typeUpdatesLimitCount) { this.typeUpdatesLimitCount = typeUpdatesLimitCount; } public boolean isEscapeUnicode() { return escapeUnicode; } public void setEscapeUnicode(boolean escapeUnicode) { this.escapeUnicode = escapeUnicode; } public boolean isCfgOutput() { return cfgOutput; } public void setCfgOutput(boolean cfgOutput) { this.cfgOutput = cfgOutput; } public boolean isRawCfgOutput() { return rawCfgOutput; } public void setRawCfgOutput(boolean rawCfgOutput) { this.rawCfgOutput = rawCfgOutput; } public boolean isReplaceConsts() { return replaceConsts; } public void setReplaceConsts(boolean replaceConsts) { this.replaceConsts = replaceConsts; } public boolean isRespectBytecodeAccessModifiers() { return respectBytecodeAccessModifiers; } public void setRespectBytecodeAccessModifiers(boolean respectBytecodeAccessModifiers) { this.respectBytecodeAccessModifiers = respectBytecodeAccessModifiers; } public boolean isExportAsGradleProject() { return exportAsGradleProject; } public void setExportAsGradleProject(boolean exportAsGradleProject) { this.exportAsGradleProject = exportAsGradleProject; } public boolean isSkipXmlPrettyPrint() { return skipXmlPrettyPrint; } public void setSkipXmlPrettyPrint(boolean skipXmlPrettyPrint) { this.skipXmlPrettyPrint = skipXmlPrettyPrint; } public boolean isRenameCaseSensitive() { return renameFlags.contains(RenameEnum.CASE); } public boolean isRenameValid() { return renameFlags.contains(RenameEnum.VALID); } public boolean isRenamePrintable() { return renameFlags.contains(RenameEnum.PRINTABLE); } public boolean isFsCaseSensitive() { return fsCaseSensitive; } public void setFsCaseSensitive(boolean fsCaseSensitive) { this.fsCaseSensitive = fsCaseSensitive; } public boolean isUseHeadersForDetectResourceExtensions() { return useHeadersForDetectResourceExtensions; } public void setUseHeadersForDetectResourceExtensions(boolean useHeadersForDetectResourceExtensions) { this.useHeadersForDetectResourceExtensions = useHeadersForDetectResourceExtensions; } public CommentsLevel getCommentsLevel() { return commentsLevel; } public void setCommentsLevel(CommentsLevel commentsLevel) { this.commentsLevel = commentsLevel; } public LogHelper.LogLevelEnum getLogLevel() { return logLevel; } public void setLogLevel(LogHelper.LogLevelEnum logLevel) { this.logLevel = logLevel; } public Map<String, String> getPluginOptions() { return pluginOptions; } public void setPluginOptions(Map<String, String> pluginOptions) { this.pluginOptions = pluginOptions; } public String getDisablePlugins() { return disablePlugins; } public void setDisablePlugins(String disablePlugins) { this.disablePlugins = disablePlugins; } public void setExportGradleType(@Nullable ExportGradleType exportGradleType) { this.exportGradleType = exportGradleType; } public void setOutputFormat(String outputFormat) { this.outputFormat = outputFormat; } public Set<RenameEnum> getRenameFlags() { return renameFlags; } public void setRenameFlags(Set<RenameEnum> renameFlags) { this.renameFlags = renameFlags; } public String getConfig() { return config; } static class RenameConverter implements IStringConverter<Set<RenameEnum>> { private final String paramName; RenameConverter(String paramName) { this.paramName = paramName; } @Override public Set<RenameEnum> convert(String value) { if (value.equalsIgnoreCase("NONE")) { return EnumSet.noneOf(RenameEnum.class); } if (value.equalsIgnoreCase("ALL")) { return EnumSet.allOf(RenameEnum.class); } Set<RenameEnum> set = EnumSet.noneOf(RenameEnum.class); for (String s : value.split(",")) { try { set.add(RenameEnum.valueOf(s.trim().toUpperCase(Locale.ROOT))); } catch (Exception e) { throw new JadxArgsValidateException( '\'' + s + "' is unknown for parameter " + paramName + ", possible values are " + enumValuesString(RenameEnum.values())); } } return set; } } public static class CommentsLevelConverter extends BaseEnumConverter<CommentsLevel> { public CommentsLevelConverter() { super(CommentsLevel::valueOf, CommentsLevel::values); } } public static class UseKotlinMethodsForVarNamesConverter extends BaseEnumConverter<UseKotlinMethodsForVarNames> { public UseKotlinMethodsForVarNamesConverter() { super(UseKotlinMethodsForVarNames::valueOf, UseKotlinMethodsForVarNames::values); } } public static class DeobfuscationMapFileModeConverter extends BaseEnumConverter<GeneratedRenamesMappingFileMode> { public DeobfuscationMapFileModeConverter() { super(GeneratedRenamesMappingFileMode::valueOf, GeneratedRenamesMappingFileMode::values); } } public static class ResourceNameSourceConverter extends BaseEnumConverter<ResourceNameSource> {
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
true
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/SingleClassMode.java
jadx-cli/src/main/java/jadx/cli/SingleClassMode.java
package jadx.cli; import java.io.File; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.JadxDecompiler; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.visitors.SaveCode; import jadx.core.utils.exceptions.JadxArgsValidateException; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; public class SingleClassMode { private static final Logger LOG = LoggerFactory.getLogger(SingleClassMode.class); public static boolean process(JadxDecompiler jadx, JadxCLIArgs cliArgs) { String singleClass = cliArgs.getSingleClass(); String singleClassOutput = cliArgs.getSingleClassOutput(); if (singleClass == null && singleClassOutput == null) { return false; } ClassNode clsForProcess; if (singleClass != null) { clsForProcess = jadx.getRoot().resolveClass(singleClass); if (clsForProcess == null) { clsForProcess = jadx.getRoot().getClasses().stream() .filter(cls -> cls.getClassInfo().getAliasFullName().equals(singleClass)) .findFirst().orElse(null); } if (clsForProcess == null) { throw new JadxArgsValidateException("Input class not found: " + singleClass); } if (clsForProcess.contains(AFlag.DONT_GENERATE)) { throw new JadxArgsValidateException("Input class can't be saved by current jadx settings (marked as DONT_GENERATE)"); } if (clsForProcess.isInner()) { clsForProcess = clsForProcess.getTopParentClass(); LOG.warn("Input class is inner, parent class will be saved: {}", clsForProcess.getFullName()); } } else { // singleClassOutput is set // expect only one class to be loaded List<ClassNode> classes = jadx.getRoot().getClasses().stream() .filter(c -> !c.isInner() && !c.contains(AFlag.DONT_GENERATE)) .collect(Collectors.toList()); int size = classes.size(); if (size == 1) { clsForProcess = classes.get(0); } else { throw new JadxArgsValidateException("Found " + size + " classes, single class output can't be used"); } } ICodeInfo codeInfo; try { codeInfo = clsForProcess.decompile(); } catch (Exception e) { throw new JadxRuntimeException("Class decompilation failed", e); } String fileExt = SaveCode.getFileExtension(jadx.getRoot()); File out; if (singleClassOutput == null) { out = new File(jadx.getArgs().getOutDirSrc(), clsForProcess.getClassInfo().getAliasFullPath() + fileExt); } else { if (singleClassOutput.endsWith(fileExt)) { // treat as file name out = new File(singleClassOutput); } else { // treat as directory out = new File(singleClassOutput, clsForProcess.getShortName() + fileExt); } } File resultOut = FileUtils.prepareFile(out); if (clsForProcess.getClassInfo().hasAlias()) { LOG.info("Saving class '{}' (alias: '{}') to file '{}'", clsForProcess.getClassInfo().getFullName(), clsForProcess.getFullName(), resultOut.getAbsolutePath()); } else { LOG.info("Saving class '{}' to file '{}'", clsForProcess.getFullName(), resultOut.getAbsolutePath()); } SaveCode.save(codeInfo.getCodeStr(), resultOut); return true; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/LogHelper.java
jadx-cli/src/main/java/jadx/cli/LogHelper.java
package jadx.cli; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import jadx.api.JadxDecompiler; public class LogHelper { private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(LogHelper.class); public enum LogLevelEnum { QUIET(Level.OFF), PROGRESS(Level.OFF), ERROR(Level.ERROR), WARN(Level.WARN), INFO(Level.INFO), DEBUG(Level.DEBUG); private final Level level; LogLevelEnum(Level level) { this.level = level; } public Level getLevel() { return level; } } @Nullable("For disable log level control") private static LogLevelEnum logLevelValue; public static void initLogLevel(JadxCLIArgs args) { logLevelValue = getLogLevelFromArgs(args); } private static LogLevelEnum getLogLevelFromArgs(JadxCLIArgs args) { if (isCustomLogConfig()) { return null; } if (args.quiet) { args.logLevel = LogLevelEnum.QUIET; } else if (args.verbose) { args.logLevel = LogLevelEnum.DEBUG; } return args.logLevel; } public static void setLogLevel(LogLevelEnum newLogLevel) { logLevelValue = newLogLevel; applyLogLevel(logLevelValue); } public static void applyLogLevels() { if (logLevelValue == null) { return; } applyLogLevel(logLevelValue); if (logLevelValue == LogLevelEnum.PROGRESS) { fixForShowProgress(); } } /** * Show progress: change to 'INFO' for control classes */ private static void fixForShowProgress() { setLevelForClass(JadxCLI.class, Level.INFO); setLevelForClass(JadxDecompiler.class, Level.INFO); setLevelForClass(SingleClassMode.class, Level.INFO); } private static void applyLogLevel(@NotNull LogLevelEnum logLevel) { Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); rootLogger.setLevel(logLevel.getLevel()); } @Nullable public static LogLevelEnum getLogLevel() { return logLevelValue; } public static void setLevelForClass(Class<?> cls, Level level) { ((Logger) LoggerFactory.getLogger(cls)).setLevel(level); } public static void setLevelForPackage(String pkgName, Level level) { ((Logger) LoggerFactory.getLogger(pkgName)).setLevel(level); } /** * Try to detect if user provide custom logback config via -Dlogback.configurationFile= */ private static boolean isCustomLogConfig() { try { String logbackConfig = System.getProperty("logback.configurationFile"); if (logbackConfig == null) { return false; } LOG.debug("Use custom log config: {}", logbackConfig); return true; } catch (Exception e) { LOG.error("Failed to detect custom log config", e); } return false; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/JadxCLICommands.java
jadx-cli/src/main/java/jadx/cli/JadxCLICommands.java
package jadx.cli; import java.util.LinkedHashMap; import java.util.Map; import com.beust.jcommander.JCommander; import jadx.cli.commands.CommandPlugins; import jadx.cli.commands.ICommand; import jadx.core.utils.exceptions.JadxArgsValidateException; public class JadxCLICommands { private static final Map<String, ICommand> COMMANDS_MAP = new LinkedHashMap<>(); static { JadxCLICommands.register(new CommandPlugins()); } public static void register(ICommand command) { COMMANDS_MAP.put(command.name(), command); } public static void append(JCommander.Builder builder) { COMMANDS_MAP.forEach(builder::addCommand); } public static boolean process(JCommanderWrapper jcw, JCommander jc, String parsedCommand) { ICommand command = COMMANDS_MAP.get(parsedCommand); if (command == null) { throw new JadxArgsValidateException("Unknown command: " + parsedCommand + ". Expected one of: " + COMMANDS_MAP.keySet()); } JCommander subCommander = jc.getCommands().get(parsedCommand); command.process(jcw, subCommander); return true; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/JCommanderWrapper.java
jadx-cli/src/main/java/jadx/cli/JCommanderWrapper.java
package jadx.cli; import java.io.PrintStream; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.function.Supplier; import org.jetbrains.annotations.Nullable; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterDescription; import com.beust.jcommander.ParameterException; import com.beust.jcommander.Parameterized; import jadx.api.JadxDecompiler; import jadx.api.plugins.JadxPluginInfo; import jadx.api.plugins.options.JadxPluginOptions; import jadx.api.plugins.options.OptionDescription; import jadx.core.plugins.JadxPluginManager; import jadx.core.plugins.PluginContext; import jadx.core.utils.Utils; public class JCommanderWrapper { private final JCommander jc; private final JadxCLIArgs argsObj; public JCommanderWrapper(JadxCLIArgs argsObj) { JCommander.Builder builder = JCommander.newBuilder().addObject(argsObj); builder.acceptUnknownOptions(true); // workaround for "default" command JadxCLICommands.append(builder); this.jc = builder.build(); this.argsObj = argsObj; } public boolean parse(String[] args) { try { String[] fixedArgs = fixArgsForEmptySaveConfig(args); jc.parse(fixedArgs); applyFiles(argsObj); return true; } catch (ParameterException e) { System.err.println("Arguments parse error: " + e.getMessage()); return false; } } public void overrideProvided(JadxCLIArgs obj) { applyFiles(obj); for (ParameterDescription parameter : jc.getParameters()) { if (parameter.isAssigned()) { overrideProperty(obj, parameter); } } } public boolean processCommands() { String parsedCommand = jc.getParsedCommand(); if (parsedCommand == null) { return false; } return JadxCLICommands.process(this, jc, parsedCommand); } /** * The main parameter parsing doesn't work if accepting unknown options */ private void applyFiles(JadxCLIArgs argsObj) { argsObj.setFiles(jc.getUnknownOptions()); } /** * Override assigned field value to obj */ private static void overrideProperty(JadxCLIArgs obj, ParameterDescription parameter) { Parameterized parameterized = parameter.getParameterized(); Object providedValue = parameterized.get(parameter.getObject()); Object newValue = mergeValues(parameterized.getType(), providedValue, () -> parameterized.get(obj)); parameterized.set(obj, newValue); } @SuppressWarnings({ "rawtypes", "unchecked" }) private static Object mergeValues(Class<?> type, Object value, Supplier<Object> prevValueProvider) { if (type.isAssignableFrom(Map.class)) { // merge maps instead replacing whole map Map prevMap = (Map) prevValueProvider.get(); return Utils.mergeMaps(prevMap, (Map) value); // value map will override keys in prevMap } // simple override return value; } /** * Workaround to allow empty value (i.e. zero arity) for '--save-config' option * Insert empty string arg if another option start right after this one, or it is a last one. */ private String[] fixArgsForEmptySaveConfig(String[] args) { int len = args.length; for (int i = 0; i < len; i++) { String arg = args[i]; if (arg.equals("--save-config")) { int next = i + 1; if (next == len) { return insertEmptyArg(args, next, true); } if (next < len) { String nextArg = args[next]; if (nextArg.startsWith("-")) { return insertEmptyArg(args, next, false); } } break; } } return args; } private static String[] insertEmptyArg(String[] args, int i, boolean add) { List<String> strings = new ArrayList<>(Arrays.asList(args)); if (add) { strings.add(""); } else { strings.add(i, ""); } return strings.toArray(new String[0]); } public void printUsage() { LogHelper.setLogLevel(LogHelper.LogLevelEnum.ERROR); // mute logger while printing help // print usage in not sorted fields order (by default sorted by description) PrintStream out = System.out; out.println(); out.println("jadx - dex to java decompiler, version: " + JadxDecompiler.getVersion()); out.println(); out.println("usage: jadx [command] [options] " + jc.getMainParameterDescription()); out.println("commands (use '<command> --help' for command options):"); for (String command : jc.getCommands().keySet()) { out.println(" " + command + "\t - " + jc.getUsageFormatter().getCommandDescription(command)); } out.println(); int maxNamesLen = printOptions(jc, out, true); out.println(appendPluginOptions(maxNamesLen)); out.println(); out.println("Environment variables:"); out.println(" JADX_DISABLE_XML_SECURITY - set to 'true' to disable all security checks for XML files"); out.println(" JADX_DISABLE_ZIP_SECURITY - set to 'true' to disable all security checks for zip files"); out.println(" JADX_ZIP_MAX_ENTRIES_COUNT - maximum allowed number of entries in zip files (default: 100 000)"); out.println(" JADX_CONFIG_DIR - custom config directory, using system by default"); out.println(" JADX_CACHE_DIR - custom cache directory, using system by default"); out.println(" JADX_TMP_DIR - custom temp directory, using system by default"); out.println(); out.println("Examples:"); out.println(" jadx -d out classes.dex"); out.println(" jadx --rename-flags \"none\" classes.dex"); out.println(" jadx --rename-flags \"valid, printable\" classes.dex"); out.println(" jadx --log-level ERROR app.apk"); out.println(" jadx -Pdex-input.verify-checksum=no app.apk"); } public void printUsage(JCommander subCommander) { PrintStream out = System.out; out.println("usage: " + subCommander.getProgramName() + " [options]"); printOptions(subCommander, out, false); } private static int printOptions(JCommander jc, PrintStream out, boolean addDefaults) { out.println("options:"); List<ParameterDescription> params = jc.getParameters(); Map<String, ParameterDescription> paramsMap = new HashMap<>(params.size()); int maxNamesLen = 0; for (ParameterDescription p : params) { paramsMap.put(p.getParameterized().getName(), p); int len = p.getNames().length(); String valueDesc = getValueDesc(p); if (valueDesc != null) { len += 1 + valueDesc.length(); } maxNamesLen = Math.max(maxNamesLen, len); } maxNamesLen += 3; Object args = jc.getObjects().get(0); for (Field f : getFields(args.getClass())) { String name = f.getName(); ParameterDescription p = paramsMap.get(name); if (p == null || p.getParameter().hidden()) { continue; } StringBuilder opt = new StringBuilder(); opt.append(" ").append(p.getNames()); String valueDesc = getValueDesc(p); if (valueDesc != null) { opt.append(' ').append(valueDesc); } addSpaces(opt, maxNamesLen - opt.length()); String description = p.getDescription(); if (description.contains("\n")) { String[] lines = description.split("\n"); opt.append("- ").append(lines[0]); for (int i = 1; i < lines.length; i++) { opt.append('\n'); addSpaces(opt, maxNamesLen + 2); opt.append(lines[i]); } } else { opt.append("- ").append(description); } if (addDefaults) { String defaultValue = getDefaultValue(args, f); if (defaultValue != null && !defaultValue.isEmpty() && !description.contains("(default)")) { opt.append(", default: ").append(defaultValue); } } out.println(opt); } return maxNamesLen; } private static @Nullable String getValueDesc(ParameterDescription p) { Parameter parameterAnnotation = p.getParameterAnnotation(); return parameterAnnotation == null ? null : parameterAnnotation.defaultValueDescription(); } /** * Get all declared fields of the specified class and all super classes */ private static List<Field> getFields(Class<?> clazz) { List<Field> fieldList = new ArrayList<>(); while (clazz != null) { fieldList.addAll(Arrays.asList(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } return fieldList; } @Nullable private static String getDefaultValue(Object args, Field f) { try { Class<?> fieldType = f.getType(); if (fieldType == int.class) { return Integer.toString(f.getInt(args)); } if (fieldType == String.class) { return (String) f.get(args); } if (Enum.class.isAssignableFrom(fieldType)) { Enum<?> val = (Enum<?>) f.get(args); if (val != null) { return val.name().toLowerCase(Locale.ROOT); } } } catch (Exception e) { // ignore } return null; } private static void addSpaces(StringBuilder str, int count) { for (int i = 0; i < count; i++) { str.append(' '); } } private String appendPluginOptions(int maxNamesLen) { StringBuilder sb = new StringBuilder(); // load and init all options plugins to print all options try (JadxDecompiler decompiler = new JadxDecompiler(argsObj.toJadxArgs())) { JadxPluginManager pluginManager = decompiler.getPluginManager(); pluginManager.load(decompiler.getArgs().getPluginLoader()); pluginManager.initAll(); try { for (PluginContext context : pluginManager.getAllPluginContexts()) { JadxPluginOptions options = context.getOptions(); if (options != null) { appendPlugin(context.getPluginInfo(), context.getOptions(), sb, maxNamesLen); } } } finally { pluginManager.unloadAll(); } } if (sb.length() == 0) { return ""; } return "\nPlugin options (-P<name>=<value>):" + sb; } private boolean appendPlugin(JadxPluginInfo pluginInfo, JadxPluginOptions options, StringBuilder out, int maxNamesLen) { List<OptionDescription> descs = options.getOptionsDescriptions(); if (descs.isEmpty()) { return false; } out.append("\n "); out.append(pluginInfo.getPluginId()).append(": ").append(pluginInfo.getDescription()); for (OptionDescription desc : descs) { StringBuilder opt = new StringBuilder(); opt.append(" - ").append(desc.name()); addSpaces(opt, maxNamesLen - opt.length()); opt.append("- ").append(desc.description()); if (!desc.values().isEmpty()) { opt.append(", values: ").append(desc.values()); } if (desc.defaultValue() != null) { opt.append(", default: ").append(desc.defaultValue()); } out.append("\n").append(opt); } return true; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/tools/ConvertArscFile.java
jadx-cli/src/main/java/jadx/cli/tools/ConvertArscFile.java
package jadx.cli.tools; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxArgs; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.android.TextResMapFile; import jadx.core.xmlgen.ResTableBinaryParser; import jadx.zip.IZipEntry; import jadx.zip.ZipContent; import jadx.zip.ZipReader; import static jadx.core.utils.files.FileUtils.expandDirs; /** * Utility class for convert '.arsc' to simple text file with mapping id to resource name */ public class ConvertArscFile { private static final Logger LOG = LoggerFactory.getLogger(ConvertArscFile.class); private static int rewritesCount; public static void usage() { LOG.info("<res-map file> <input .arsc/android.jar files or dir>"); LOG.info(""); LOG.info("Note: If res-map already exists - it will be merged and updated"); } public static void main(String[] args) throws IOException { if (args.length < 2) { usage(); System.exit(1); } List<Path> inputPaths = Stream.of(args).map(Paths::get).collect(Collectors.toList()); Path resMapFile = inputPaths.remove(0); List<Path> inputResFiles = filterAndSort(expandDirs(inputPaths)); Map<Integer, String> resMap; if (Files.isReadable(resMapFile)) { resMap = TextResMapFile.read(resMapFile); } else { resMap = new HashMap<>(); } LOG.info("Input entries count: {}", resMap.size()); RootNode root = new RootNode(new JadxArgs()); // not really needed ZipReader zipReader = new ZipReader(); rewritesCount = 0; for (Path resFile : inputResFiles) { ResTableBinaryParser resTableParser = new ResTableBinaryParser(root, true); if (resFile.getFileName().toString().endsWith(".jar")) { // Load resources.arsc from android.jar try (ZipContent zip = zipReader.open(resFile.toFile())) { IZipEntry entry = zip.searchEntry("resources.arsc"); if (entry == null) { LOG.error("Failed to load \"resources.arsc\" from {}", resFile); continue; } try (InputStream inputStream = entry.getInputStream()) { resTableParser.decode(inputStream); } } } else { // Load resources.arsc from extracted file try (InputStream inputStream = Files.newInputStream(resFile)) { resTableParser.decode(inputStream); } } Map<Integer, String> singleResMap = resTableParser.getResStorage().getResourcesNames(); mergeResMaps(resMap, singleResMap); LOG.info("{} entries count: {}, after merge: {}", resFile.getFileName(), singleResMap.size(), resMap.size()); } LOG.info("Output entries count: {}", resMap.size()); LOG.info("Total rewrites count: {}", rewritesCount); TextResMapFile.write(resMapFile, resMap); LOG.info("Result file size: {} B", resMapFile.toFile().length()); LOG.info("done"); } private static List<Path> filterAndSort(List<Path> inputPaths) { return inputPaths.stream() .filter(p -> { String fileName = p.getFileName().toString(); return fileName.endsWith(".arsc") || fileName.endsWith(".jar"); }) .sorted() .collect(Collectors.toList()); } private static void mergeResMaps(Map<Integer, String> mainResMap, Map<Integer, String> newResMap) { for (Map.Entry<Integer, String> entry : newResMap.entrySet()) { Integer id = entry.getKey(); String name = entry.getValue(); String prevName = mainResMap.put(id, name); if (prevName != null && !name.equals(prevName)) { LOG.debug("Rewrite id: {} from: '{}' to: '{}'", Integer.toHexString(id), prevName, name); rewritesCount++; } } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/commands/ICommand.java
jadx-cli/src/main/java/jadx/cli/commands/ICommand.java
package jadx.cli.commands; import com.beust.jcommander.JCommander; import jadx.cli.JCommanderWrapper; public interface ICommand { String name(); void process(JCommanderWrapper jcw, JCommander subCommander); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/commands/CommandPlugins.java
jadx-cli/src/main/java/jadx/cli/commands/CommandPlugins.java
package jadx.cli.commands; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import jadx.api.plugins.JadxPluginInfo; import jadx.cli.JCommanderWrapper; import jadx.cli.LogHelper; import jadx.core.utils.StringUtils; import jadx.plugins.tools.JadxPluginsList; import jadx.plugins.tools.JadxPluginsTools; import jadx.plugins.tools.data.JadxPluginListEntry; import jadx.plugins.tools.data.JadxPluginMetadata; import jadx.plugins.tools.data.JadxPluginUpdate; @Parameters(commandDescription = "manage jadx plugins") public class CommandPlugins implements ICommand { @Parameter(names = { "-i", "--install" }, description = "install plugin with locationId", defaultValueDescription = "<locationId>") protected String install; @Parameter(names = { "-j", "--install-jar" }, description = "install plugin from jar file", defaultValueDescription = "<path-to.jar>") protected String installJar; @Parameter(names = { "-l", "--list" }, description = "list installed plugins") protected boolean list; @Parameter(names = { "-a", "--available" }, description = "list available plugins from jadx-plugins-list (aka marketplace)") protected boolean available; @Parameter(names = { "-u", "--update" }, description = "update installed plugins") protected boolean update; @Parameter(names = { "--uninstall" }, description = "uninstall plugin with pluginId", defaultValueDescription = "<pluginId>") protected String uninstall; @Parameter(names = { "--disable" }, description = "disable plugin with pluginId", defaultValueDescription = "<pluginId>") protected String disable; @Parameter(names = { "--enable" }, description = "enable plugin with pluginId", defaultValueDescription = "<pluginId>") protected String enable; @Parameter(names = { "--list-all" }, description = "list all plugins including bundled and dropins") protected boolean listAll; @Parameter( names = { "--list-versions" }, description = "fetch latest versions of plugin from locationId (will download all artefacts, limited to 10)", defaultValueDescription = "<locationId>" ) protected String listVersions; @Parameter(names = { "-h", "--help" }, description = "print this help", help = true) protected boolean printHelp = false; @Override public String name() { return "plugins"; } @SuppressWarnings("UnnecessaryReturnStatement") @Override public void process(JCommanderWrapper jcw, JCommander subCommander) { if (printHelp) { jcw.printUsage(subCommander); return; } Set<String> unknownOptions = new HashSet<>(subCommander.getUnknownOptions()); boolean verbose = unknownOptions.remove("-v") || unknownOptions.remove("--verbose"); LogHelper.setLogLevel(verbose ? LogHelper.LogLevelEnum.DEBUG : LogHelper.LogLevelEnum.INFO); if (!unknownOptions.isEmpty()) { System.out.println("Error: found unknown options: " + unknownOptions); } if (install != null) { installPlugin(install); return; } if (installJar != null) { installPlugin("file:" + installJar); return; } if (uninstall != null) { boolean uninstalled = JadxPluginsTools.getInstance().uninstall(uninstall); System.out.println(uninstalled ? "Uninstalled" : "Plugin not found"); return; } if (update) { List<JadxPluginUpdate> updates = JadxPluginsTools.getInstance().updateAll(); if (updates.isEmpty()) { System.out.println("No updates"); } else { System.out.println("Installed updates: " + updates.size()); for (JadxPluginUpdate update : updates) { System.out.println(" " + update.getPluginId() + ": " + update.getOldVersion() + " -> " + update.getNewVersion()); } } return; } if (list) { printPlugins(JadxPluginsTools.getInstance().getInstalled()); return; } if (listAll) { printAllPlugins(); return; } if (listVersions != null) { printVersions(listVersions, 10); return; } if (available) { List<JadxPluginListEntry> availableList = JadxPluginsList.getInstance().get(); System.out.println("Available plugins: " + availableList.size()); for (JadxPluginListEntry plugin : availableList) { System.out.println(" - " + plugin.getName() + ": " + plugin.getDescription() + " (" + plugin.getLocationId() + ")"); } return; } if (disable != null) { if (JadxPluginsTools.getInstance().changeDisabledStatus(disable, true)) { System.out.println("Plugin '" + disable + "' disabled."); } else { System.out.println("Plugin '" + disable + "' already disabled."); } return; } if (enable != null) { if (JadxPluginsTools.getInstance().changeDisabledStatus(enable, false)) { System.out.println("Plugin '" + enable + "' enabled."); } else { System.out.println("Plugin '" + enable + "' already enabled."); } return; } } private static void printPlugins(List<JadxPluginMetadata> installed) { System.out.println("Installed plugins: " + installed.size()); for (JadxPluginMetadata plugin : installed) { StringBuilder sb = new StringBuilder(); sb.append(" - ").append(plugin.getPluginId()); String version = plugin.getVersion(); if (version != null) { sb.append(" (").append(version).append(')'); } if (plugin.isDisabled()) { sb.append(" (disabled)"); } sb.append(" - ").append(plugin.getName()); sb.append(": ").append(formatDescription(plugin.getDescription())); System.out.println(sb); } } private void printVersions(String locationId, int limit) { System.out.println("Loading ..."); List<JadxPluginMetadata> versions = JadxPluginsTools.getInstance().getVersionsByLocation(locationId, 1, limit); if (versions.isEmpty()) { System.out.println("No versions found"); return; } JadxPluginMetadata plugin = versions.get(0); System.out.println("Versions for plugin id: " + plugin.getPluginId()); for (JadxPluginMetadata version : versions) { StringBuilder sb = new StringBuilder(); sb.append(" - ").append(version.getVersion()); String reqVer = version.getRequiredJadxVersion(); if (StringUtils.notBlank(reqVer)) { sb.append(", require jadx: ").append(reqVer); } System.out.println(sb); } } private static void printAllPlugins() { List<JadxPluginMetadata> installed = JadxPluginsTools.getInstance().getInstalled(); printPlugins(installed); Set<String> installedSet = installed.stream().map(JadxPluginMetadata::getPluginId).collect(Collectors.toSet()); List<JadxPluginInfo> plugins = JadxPluginsTools.getInstance().getAllPluginsInfo(); System.out.println("Other plugins: " + plugins.size()); for (JadxPluginInfo plugin : plugins) { if (!installedSet.contains(plugin.getPluginId())) { System.out.println(" - " + plugin.getPluginId() + " - " + plugin.getName() + ": " + formatDescription(plugin.getDescription())); } } } private static String formatDescription(String desc) { if (desc.contains("\n")) { // remove new lines desc = desc.replaceAll("\\R+", " "); } int maxLen = 512; if (desc.length() > maxLen) { // truncate very long descriptions desc = desc.substring(0, maxLen) + " ..."; } return desc; } private void installPlugin(String locationId) { JadxPluginMetadata plugin = JadxPluginsTools.getInstance().install(locationId); System.out.println("Plugin installed: " + plugin.getPluginId() + ":" + plugin.getVersion()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/plugins/JadxFilesGetter.java
jadx-cli/src/main/java/jadx/cli/plugins/JadxFilesGetter.java
package jadx.cli.plugins; import java.nio.file.Path; import jadx.commons.app.JadxCommonFiles; import jadx.commons.app.JadxTempFiles; import jadx.core.plugins.files.IJadxFilesGetter; public class JadxFilesGetter implements IJadxFilesGetter { public static final JadxFilesGetter INSTANCE = new JadxFilesGetter(); @Override public Path getConfigDir() { return JadxCommonFiles.getConfigDir(); } @Override public Path getCacheDir() { return JadxCommonFiles.getCacheDir(); } @Override public Path getTempDir() { return JadxTempFiles.getTempRootDir(); } private JadxFilesGetter() { // singleton } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/clst/ConvertToClsSet.java
jadx-cli/src/main/java/jadx/cli/clst/ConvertToClsSet.java
package jadx.cli.clst; import java.nio.file.Path; import java.nio.file.Paths; import java.util.EnumSet; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.api.args.UseSourceNameAsClassNameAlias; import jadx.core.clsp.ClsSet; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.files.FileUtils; /** * Utility class for convert dex or jar to jadx classes set (.jcst) */ public class ConvertToClsSet { private static final Logger LOG = LoggerFactory.getLogger(ConvertToClsSet.class); public static void usage() { LOG.info("<android API level (number)> <output .jcst file> <several input dex or jar files> "); LOG.info("Arguments to update core.jcst: " + "<android API level (number)> " + "<jadx root>/jadx-core/src/main/resources/clst/core.jcst " + "<sdk_root>/platforms/android-<api level>/android.jar" + "<sdk_root>/platforms/android-<api level>/optional/android.car.jar " + "<sdk_root>/platforms/android-<api level>/optional/org.apache.http.legacy.jar"); } public static void main(String[] args) { if (args.length != 5) { usage(); System.exit(1); } int androidApiLevel = Integer.parseInt(args[0]); List<Path> inputPaths = Stream.of(args).skip(1).map(Paths::get).collect(Collectors.toList()); Path output = inputPaths.remove(0); JadxArgs jadxArgs = new JadxArgs(); jadxArgs.setInputFiles(FileUtils.toFiles(inputPaths)); // disable not needed passes executed at prepare stage jadxArgs.setDeobfuscationOn(false); jadxArgs.setRenameFlags(EnumSet.noneOf(JadxArgs.RenameEnum.class)); jadxArgs.setUseSourceNameAsClassNameAlias(UseSourceNameAsClassNameAlias.NEVER); jadxArgs.setMoveInnerClasses(false); jadxArgs.setInlineAnonymousClasses(false); jadxArgs.setInlineMethods(false); // don't require/load class set file jadxArgs.setLoadJadxClsSetFile(false); try (JadxDecompiler decompiler = new JadxDecompiler(jadxArgs)) { decompiler.load(); RootNode root = decompiler.getRoot(); ClsSet set = new ClsSet(root); set.setAndroidApiLevel(androidApiLevel); set.loadFrom(root); set.save(output); LOG.info("Output: {}", output); LOG.info("done"); } catch (Exception e) { LOG.error("Failed with error", e); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/config/IJadxConfig.java
jadx-cli/src/main/java/jadx/cli/config/IJadxConfig.java
package jadx.cli.config; /** * Marker interface for jadx config objects */ public interface IJadxConfig { }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/config/JadxConfigExclude.java
jadx-cli/src/main/java/jadx/cli/config/JadxConfigExclude.java
package jadx.cli.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface JadxConfigExclude { }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-cli/src/main/java/jadx/cli/config/JadxConfigAdapter.java
jadx-cli/src/main/java/jadx/cli/config/JadxConfigAdapter.java
package jadx.cli.config; import java.nio.file.Files; import java.nio.file.Path; import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.stream.JsonReader; import jadx.commons.app.JadxCommonFiles; import jadx.core.utils.GsonUtils; import jadx.core.utils.exceptions.JadxArgsValidateException; import jadx.core.utils.exceptions.JadxRuntimeException; public class JadxConfigAdapter<T extends IJadxConfig> { private static final ExclusionStrategy GSON_EXCLUSION_STRATEGY = new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(JadxConfigExclude.class) != null; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }; private final Class<T> configCls; private final String defaultConfigFileName; private final Gson gson; private Path configPath; public JadxConfigAdapter(Class<T> configCls, String defaultConfigName) { this(configCls, defaultConfigName, gsonBuilder -> { }); } public JadxConfigAdapter(Class<T> configCls, String defaultConfigName, Consumer<GsonBuilder> applyGsonOptions) { this.configCls = configCls; this.defaultConfigFileName = defaultConfigName + ".json"; GsonBuilder gsonBuilder = GsonUtils.defaultGsonBuilder(); gsonBuilder.setExclusionStrategies(GSON_EXCLUSION_STRATEGY); applyGsonOptions.accept(gsonBuilder); this.gson = gsonBuilder.create(); } public void useConfigRef(String configRef) { this.configPath = resolveConfigRef(configRef); } public Path getConfigPath() { return configPath; } public String getDefaultConfigFileName() { return defaultConfigFileName; } public @Nullable T load() { if (!Files.isRegularFile(configPath)) { // file not found return null; } try (JsonReader reader = gson.newJsonReader(Files.newBufferedReader(configPath))) { return gson.fromJson(reader, configCls); } catch (Exception e) { throw new JadxRuntimeException("Failed to load config file: " + configPath, e); } } public void save(T configObject) { try { String jsonStr = gson.toJson(configObject, configCls); // don't use stream writer here because serialization errors will corrupt config Files.writeString(configPath, jsonStr); } catch (Exception e) { throw new JadxRuntimeException("Failed to save config file: " + configPath, e); } } public String objectToJsonString(T configObject) { return gson.toJson(configObject, configCls); } public T jsonStringToObject(String jsonStr) { return gson.fromJson(jsonStr, configCls); } private Path resolveConfigRef(String configRef) { if (configRef == null || configRef.isEmpty()) { // use default config file return JadxCommonFiles.getConfigDir().resolve(defaultConfigFileName); } if (configRef.contains("/") || configRef.contains("\\")) { if (!configRef.toLowerCase().endsWith(".json")) { throw new JadxArgsValidateException("Config file extension should be '.json'"); } return Path.of(configRef); } // treat as a short name return JadxCommonFiles.getConfigDir().resolve(configRef + ".json"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/test/java/jadx/gui/TestI18n.java
jadx-gui/src/test/java/jadx/gui/TestI18n.java
package jadx.gui; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import jadx.gui.utils.LangLocale; import jadx.gui.utils.NLS; import static java.nio.file.Paths.get; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class TestI18n { private static final String DEFAULT_LANG_FILE = "Messages_en_US.properties"; private static Path i18nPath; private static Path refPath; private static Path guiJavaPath; @BeforeAll public static void init() { i18nPath = get("src/main/resources/i18n"); assertThat(i18nPath).exists(); refPath = i18nPath.resolve(DEFAULT_LANG_FILE); assertThat(refPath).exists(); guiJavaPath = get("src/main/java"); assertThat(guiJavaPath).exists(); } @Test public void verifyLocales() { for (LangLocale lang : NLS.getLangLocales()) { Locale locale = lang.get(); System.out.println("Language: " + locale.getLanguage() + " - " + locale.getDisplayLanguage() + ", country: " + locale.getCountry() + " - " + locale.getDisplayCountry() + ", language tag: " + locale.toLanguageTag()); } } @Test public void filesExactlyMatch() throws IOException { List<String> reference = Files.readAllLines(refPath) .stream() .map(TestI18n::getPrefix) .collect(Collectors.toList()); try (Stream<Path> list = Files.list(i18nPath)) { list.filter(p -> !p.equals(refPath)) .forEach(path -> compareToReference(path, reference)); } } /** * Extract prefix: 'key=' */ private static String getPrefix(String line) { if (line.isBlank()) { return ""; } int sep = line.indexOf('='); if (sep == -1) { return line; } if (line.startsWith("#")) { fail(DEFAULT_LANG_FILE + " shouldn't contain commented values: " + line); } return line.substring(0, sep + 1); } private void compareToReference(Path path, List<String> reference) { try { List<String> lines = Files.readAllLines(path); for (int i = 0; i < reference.size(); i++) { String prefix = reference.get(i); if (prefix.isEmpty()) { continue; } if (i >= lines.size()) { fail("File '" + path.getFileName() + "' contains unexpected lines at end"); } String line = lines.get(i); if (!trimComment(line).startsWith(prefix)) { failLine(path, i + 1); } if (line.startsWith("#")) { int sep = line.indexOf('='); if (line.substring(sep + 1).isBlank()) { fail("File '" + path.getFileName() + "' has empty ref text at line " + (i + 1) + ": " + line); } } } if (lines.size() != reference.size()) { failLine(path, reference.size()); } } catch (IOException e) { fail("Process error ", e); } } private static String trimComment(String string) { return string.startsWith("#") ? string.substring(1) : string; } private void failLine(Path path, int line) { fail("I18n file: " + path.getFileName() + " and " + DEFAULT_LANG_FILE + " differ in line " + line); } @Test public void keyIsUsed() throws IOException { Properties properties = new Properties(); try (Reader reader = Files.newBufferedReader(i18nPath.resolve(DEFAULT_LANG_FILE))) { properties.load(reader); } Set<String> keys = new HashSet<>(); for (Object key : properties.keySet()) { keys.add("\"" + key + '"'); } try (Stream<Path> walk = Files.walk(guiJavaPath)) { walk.filter(Files::isRegularFile).forEach(p -> { try { for (String line : Files.readAllLines(p)) { keys.removeIf(line::contains); } } catch (Exception e) { throw new RuntimeException(e); } }); } assertThat(keys).as("keys not used").isEmpty(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/test/java/jadx/gui/device/debugger/smali/DbgSmaliTest.java
jadx-gui/src/test/java/jadx/gui/device/debugger/smali/DbgSmaliTest.java
package jadx.gui.device.debugger.smali; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.dex.nodes.ClassNode; import jadx.tests.api.SmaliTest; import static org.assertj.core.api.Assertions.assertThat; class DbgSmaliTest extends SmaliTest { private static final Logger LOG = LoggerFactory.getLogger(DbgSmaliTest.class); @BeforeEach public void initProject() { setCurrentProject("jadx-gui"); } @Test void testSwitch() { disableCompilation(); ClassNode cls = getClassNodeFromSmali("switch", "SwitchTest"); Smali disasm = Smali.disassemble(cls); LOG.debug("{}", disasm.getCode()); } @Test void testParams() { disableCompilation(); ClassNode cls = getClassNodeFromSmali("params", "ParamsTest"); Smali disasm = Smali.disassemble(cls); String code = disasm.getCode(); LOG.debug("{}", code); assertThat(code) .doesNotContain("Failed to write method") .doesNotContain(".param p1") .contains(".local p1, \"arg0\":Landroid/widget/AdapterView;, \"Landroid/widget/AdapterView<*>;\""); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/test/java/jadx/gui/utils/CertificateManagerTest.java
jadx-gui/src/test/java/jadx/gui/utils/CertificateManagerTest.java
package jadx.gui.utils; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.cert.Certificate; import java.util.Collection; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class CertificateManagerTest { private static final String CERTIFICATE_TEST_DIR = "certificate-test/"; private static final String DSA = "CERT.DSA"; private static final String RSA = "CERT.RSA"; private static final String EMPTY = "EMPTY.txt"; private String emptyPath; private CertificateManager certificateManagerRSA; private CertificateManager certificateManagerDSA; private CertificateManager getCertificateManger(String resName) { String certPath = getResourcePath(resName); try (InputStream in = new FileInputStream(certPath)) { Collection<? extends Certificate> certificates = CertificateManager.readCertificates(in); Certificate cert = certificates.iterator().next(); return new CertificateManager(cert); } catch (Exception e) { throw new RuntimeException("Failed to create CertificateManager"); } } @BeforeEach public void setUp() { emptyPath = getResourcePath(EMPTY); certificateManagerRSA = getCertificateManger(RSA); certificateManagerDSA = getCertificateManger(DSA); } @Test public void decodeNotCertificateFile() throws IOException { try (InputStream in = new FileInputStream(emptyPath)) { String result = CertificateManager.decode(in); assertThat(result).isEmpty(); } } @Test public void decodeRSAKeyHeader() { assertThat(certificateManagerRSA.generateHeader()) .contains("X.509") .contains("0x4bd68052") .contains("CN=test cert, OU=test unit, O=OOO TestOrg, L=St.Peterburg, ST=Russia, C=123456"); } @Test public void decodeDSAKeyHeader() { assertThat(certificateManagerDSA.generateHeader()) .contains("X.509") .contains("0x16420ba2") .contains("O=\"UJMRFVV CN=EDCVBGT C=TG\""); } @Test public void decodeRSAKeySignature() { assertThat(certificateManagerRSA.generateSignature()) .contains("SHA256withRSA") .contains("1.2.840.113549.1.1.11"); } @Test public void decodeDSAKeySignature() { assertThat(certificateManagerDSA.generateSignature()) .contains("SHA1withDSA") .contains("1.2.840.10040.4.3"); } @Test public void decodeRSAFingerprint() { assertThat(certificateManagerRSA.generateFingerprint()) .contains("61 18 0A 71 3F C9 55 16 4E 04 E3 C5 45 08 D9 11") .contains("A0 6E A6 06 DB 2C 6F 3A 16 56 7F 75 97 7B AE 85 C2 13 09 37") .contains("12 53 E8 BB C8 AA 27 A8 49 9B F8 0D 6E 68 CE 32 35 50 DE 55 A7 E7 8C 29 51 00 96 D7 56 F4 54 44"); } @Test public void decodeDSAFingerprint() { assertThat(certificateManagerDSA.generateFingerprint()) .contains("D9 06 A6 2D 1F 79 8C 9D A6 EF 40 C7 2E C2 EA 0B") .contains("18 E9 9C D4 A1 40 8F 63 FA EC 2E 62 A0 F2 AE B7 3F C3 C2 04") .contains("74 F9 48 64 EE AC 92 26 53 2C 7A 0E 55 BE 5E D8 2F A7 D9 A9 99 F5 D5 21 2C 51 21 C4 31 AD 73 40"); } @Test public void decodeRSAPubKey() { assertThat(certificateManagerRSA.generatePublicKey()) .contains("RSA") .contains("65537") .contains("1681953129031804462554643735709908030601939275292568895111488068832920121318010916" + "889038430576806710152191447376363866950356097752126932858298006033288814768019331823126004318941179" + "4465899645633586173494259691101582064441956032924396850221679489313043628562082670183392670094163371" + "8586841184804093747497905514737738452134274762361473284344272721776230189352829291523087538543142199" + "8761760403746876947208990209024335828599173964217021197086277312193991177728010193707324300633538463" + "6193260583579409760790138329893534549366882523130765297472656435892831796545149793228897111760122091" + "442123535919361963075454640516520743"); } @Test public void decodeDSAPubKey() { assertThat(certificateManagerDSA.generatePublicKey()) .contains("DSA") .contains("193233676050581546825633012823454532222793121048898990016982096262547255815113" + "7546996381246109049596383861577383286736433045701055397423798599190480095839416942148507037843474" + "67923797088055637932532829952742936211625049432875384559446523443782422268975073691469424116922209" + "22477368782490423187845815262510366"); } private String getResourcePath(String resName) { URL resource = getClass().getClassLoader().getResource(CERTIFICATE_TEST_DIR + resName); if (resource == null) { throw new RuntimeException("Resource not found: " + resName); } return resource.getPath(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/test/java/jadx/gui/utils/JumpManagerTest.java
jadx-gui/src/test/java/jadx/gui/utils/JumpManagerTest.java
package jadx.gui.utils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import jadx.gui.treemodel.TextNode; import static org.assertj.core.api.Assertions.assertThat; class JumpManagerTest { private JumpManager jm; @BeforeEach public void setup() { jm = new JumpManager(); } @Test public void testEmptyHistory() { assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); } @Test public void testEmptyHistory2() { assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); assertThat(jm.getPrev()).isNull(); } @Test public void testOneElement() { jm.addPosition(makeJumpPos()); assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); } @Test public void testTwoElements() { JumpPosition pos1 = makeJumpPos(); jm.addPosition(pos1); JumpPosition pos2 = makeJumpPos(); jm.addPosition(pos2); assertThat(jm.getPrev()).isSameAs(pos1); assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isSameAs(pos2); assertThat(jm.getNext()).isNull(); } @Test public void testNavigation() { JumpPosition pos1 = makeJumpPos(); jm.addPosition(pos1); // 1@ JumpPosition pos2 = makeJumpPos(); jm.addPosition(pos2); // 1 - 2@ assertThat(jm.getPrev()).isSameAs(pos1); // 1@ - 2 JumpPosition pos3 = makeJumpPos(); jm.addPosition(pos3); // 1 - 3@ assertThat(jm.getNext()).isNull(); assertThat(jm.getPrev()).isSameAs(pos1); // 1@ - 3 assertThat(jm.getNext()).isSameAs(pos3); } @Test public void testNavigation2() { JumpPosition pos1 = makeJumpPos(); jm.addPosition(pos1); // 1@ JumpPosition pos2 = makeJumpPos(); jm.addPosition(pos2); // 1 - 2@ JumpPosition pos3 = makeJumpPos(); jm.addPosition(pos3); // 1 - 2 - 3@ JumpPosition pos4 = makeJumpPos(); jm.addPosition(pos4); // 1 - 2 - 3 - 4@ assertThat(jm.getPrev()).isSameAs(pos3); // 1 - 2 - 3@ - 4 assertThat(jm.getPrev()).isSameAs(pos2); // 1 - 2@ - 3 - 4 JumpPosition pos5 = makeJumpPos(); jm.addPosition(pos5); // 1 - 2 - 5@ assertThat(jm.getNext()).isNull(); assertThat(jm.getNext()).isNull(); assertThat(jm.getPrev()).isSameAs(pos2); // 1 - 2@ - 5 assertThat(jm.getPrev()).isSameAs(pos1); // 1@ - 2 - 5 assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isSameAs(pos2); // 1 - 2@ - 5 assertThat(jm.getNext()).isSameAs(pos5); // 1 - 2 - 5@ assertThat(jm.getNext()).isNull(); } @Test public void addSame() { JumpPosition pos = makeJumpPos(); jm.addPosition(pos); jm.addPosition(pos); assertThat(jm.getPrev()).isNull(); assertThat(jm.getNext()).isNull(); } private JumpPosition makeJumpPos() { return new JumpPosition(new TextNode(""), 0); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/test/java/jadx/gui/utils/cache/code/DiskCodeCacheTest.java
jadx-gui/src/test/java/jadx/gui/utils/cache/code/DiskCodeCacheTest.java
package jadx.gui.utils.cache.code; import java.io.IOException; import java.nio.file.Path; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.impl.NoOpCodeCache; import jadx.core.dex.nodes.ClassNode; import jadx.gui.cache.code.disk.DiskCodeCache; import jadx.tests.api.IntegrationTest; import static org.assertj.core.api.Assertions.assertThat; class DiskCodeCacheTest extends IntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(DiskCodeCacheTest.class); @TempDir public Path tempDir; @Test public void test() throws IOException { disableCompilation(); getArgs().setCodeCache(NoOpCodeCache.INSTANCE); ClassNode clsNode = getClassNode(DiskCodeCacheTest.class); ICodeInfo codeInfo = clsNode.getCode(); DiskCodeCache cache = new DiskCodeCache(clsNode.root(), tempDir); String clsKey = clsNode.getFullName(); cache.add(clsKey, codeInfo); ICodeInfo readCodeInfo = cache.get(clsKey); assertThat(readCodeInfo).isNotNull(); assertThat(readCodeInfo.getCodeStr()).isEqualTo(codeInfo.getCodeStr()); assertThat(readCodeInfo.getCodeMetadata().getLineMapping()).isEqualTo(codeInfo.getCodeMetadata().getLineMapping()); LOG.info("Disk code annotations: {}", readCodeInfo.getCodeMetadata().getAsMap()); assertThat(readCodeInfo.getCodeMetadata().getAsMap()).hasSameSizeAs(codeInfo.getCodeMetadata().getAsMap()); cache.close(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/test/java/jadx/gui/utils/cache/code/disk/adapters/DataAdapterHelperTest.java
jadx-gui/src/test/java/jadx/gui/utils/cache/code/disk/adapters/DataAdapterHelperTest.java
package jadx.gui.utils.cache.code.disk.adapters; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.junit.jupiter.api.Test; import jadx.gui.cache.code.disk.adapters.DataAdapterHelper; import static org.assertj.core.api.Assertions.assertThat; class DataAdapterHelperTest { @Test void uvInt() throws IOException { checkUVIntFor(0); checkUVIntFor(7); checkUVIntFor(0x7f); checkUVIntFor(0x80); checkUVIntFor(0x256); checkUVIntFor(Byte.MAX_VALUE); checkUVIntFor(Short.MAX_VALUE); checkUVIntFor(Integer.MAX_VALUE); } private void checkUVIntFor(int val) throws IOException { assertThat(writeReadUVInt(val)).isEqualTo(val); } private int writeReadUVInt(int val) throws IOException { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(byteOut); DataAdapterHelper.writeUVInt(out, val); DataInput in = new DataInputStream(new ByteArrayInputStream(byteOut.toByteArray())); return DataAdapterHelper.readUVInt(in); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/test/java/jadx/gui/utils/pkgs/TestJRenamePackage.java
jadx-gui/src/test/java/jadx/gui/utils/pkgs/TestJRenamePackage.java
package jadx.gui.utils.pkgs; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class TestJRenamePackage { @Test void isValidName() { valid("foo"); valid("foo.bar"); valid(".bar"); invalid(""); invalid("0foo"); invalid("foo."); invalid("do"); invalid("foo.if"); invalid("foo.if.bar"); } private void valid(String name) { assertThat(JRenamePackage.isValidPackageName(name)) .as("expect valid: %s", name) .isTrue(); } private void invalid(String name) { assertThat(JRenamePackage.isValidPackageName(name)) .as("expect invalid: %s", name) .isFalse(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/JadxWrapper.java
jadx-gui/src/main/java/jadx/gui/JadxWrapper.java
package jadx.gui; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; 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.ICodeInfo; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.api.JavaClass; import jadx.api.JavaNode; import jadx.api.JavaPackage; import jadx.api.ResourceFile; import jadx.api.impl.InMemoryCodeCache; import jadx.api.metadata.ICodeNodeRef; import jadx.api.usage.impl.EmptyUsageInfoCache; import jadx.api.usage.impl.InMemoryUsageInfoCache; import jadx.cli.JadxAppCommon; import jadx.cli.plugins.JadxFilesGetter; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.ProcessState; import jadx.core.dex.nodes.RootNode; import jadx.core.plugins.AppContext; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.cache.code.CodeStringCache; import jadx.gui.cache.code.disk.BufferCodeCache; import jadx.gui.cache.code.disk.DiskCodeCache; import jadx.gui.cache.usage.UsageInfoCache; import jadx.gui.plugins.context.CommonGuiPluginsContext; import jadx.gui.settings.JadxProject; import jadx.gui.settings.JadxSettings; import jadx.gui.ui.MainWindow; import jadx.gui.utils.CacheObject; import jadx.plugins.tools.JadxExternalPluginsLoader; import static jadx.core.dex.nodes.ProcessState.GENERATED_AND_UNLOADED; import static jadx.core.dex.nodes.ProcessState.NOT_LOADED; import static jadx.core.dex.nodes.ProcessState.PROCESS_COMPLETE; @SuppressWarnings("ConstantConditions") public class JadxWrapper { private static final Logger LOG = LoggerFactory.getLogger(JadxWrapper.class); private static final Object DECOMPILER_UPDATE_SYNC = new Object(); private final MainWindow mainWindow; private volatile @Nullable JadxDecompiler decompiler; private CommonGuiPluginsContext guiPluginsContext; public JadxWrapper(MainWindow mainWindow) { this.mainWindow = mainWindow; } public void open() { close(); try { synchronized (DECOMPILER_UPDATE_SYNC) { JadxProject project = getProject(); JadxArgs jadxArgs = getSettings().toJadxArgs(); jadxArgs.setPluginLoader(new JadxExternalPluginsLoader()); jadxArgs.setFilesGetter(JadxFilesGetter.INSTANCE); project.fillJadxArgs(jadxArgs); JadxAppCommon.applyEnvVars(jadxArgs); decompiler = new JadxDecompiler(jadxArgs); guiPluginsContext = initGuiPluginsContext(decompiler, mainWindow); initUsageCache(jadxArgs); decompiler.setEventsImpl(mainWindow.events()); decompiler.load(); initCodeCache(); } } catch (Exception e) { LOG.error("Jadx decompiler wrapper init error", e); close(); } } // TODO: check and move into core package public void unloadClasses() { getCurrentDecompiler().ifPresent(decompiler -> { for (ClassNode cls : decompiler.getRoot().getClasses()) { ProcessState clsState = cls.getState(); cls.unload(); cls.setState(clsState == PROCESS_COMPLETE ? GENERATED_AND_UNLOADED : NOT_LOADED); } }); } public void close() { try { synchronized (DECOMPILER_UPDATE_SYNC) { if (decompiler != null) { decompiler.close(); decompiler = null; } if (guiPluginsContext != null) { resetGuiPluginsContext(); guiPluginsContext = null; } } } catch (Exception e) { LOG.error("Jadx decompiler close error", e); } finally { mainWindow.getCacheObject().reset(); } } private void initCodeCache() { switch (getSettings().getCodeCacheMode()) { case MEMORY: getArgs().setCodeCache(new InMemoryCodeCache()); break; case DISK_WITH_CACHE: getArgs().setCodeCache(new CodeStringCache(buildBufferedDiskCache())); break; case DISK: getArgs().setCodeCache(buildBufferedDiskCache()); break; } } private BufferCodeCache buildBufferedDiskCache() { DiskCodeCache diskCache = new DiskCodeCache(getDecompiler().getRoot(), getProject().getCacheDir()); return new BufferCodeCache(diskCache); } private void initUsageCache(JadxArgs jadxArgs) { switch (getSettings().getUsageCacheMode()) { case NONE: jadxArgs.setUsageInfoCache(new EmptyUsageInfoCache()); break; case MEMORY: jadxArgs.setUsageInfoCache(new InMemoryUsageInfoCache()); break; case DISK: jadxArgs.setUsageInfoCache(new UsageInfoCache(getProject().getCacheDir(), jadxArgs.getInputFiles())); break; } } public static CommonGuiPluginsContext initGuiPluginsContext(JadxDecompiler decompiler, MainWindow mainWindow) { CommonGuiPluginsContext guiPluginsContext = new CommonGuiPluginsContext(mainWindow); decompiler.getPluginManager().registerAddPluginListener(pluginContext -> { AppContext appContext = new AppContext(); appContext.setGuiContext(guiPluginsContext.buildForPlugin(pluginContext)); appContext.setFilesGetter(decompiler.getArgs().getFilesGetter()); pluginContext.setAppContext(appContext); }); return guiPluginsContext; } public CommonGuiPluginsContext getGuiPluginsContext() { return guiPluginsContext; } public void resetGuiPluginsContext() { guiPluginsContext.reset(); } public void reloadPasses() { resetGuiPluginsContext(); decompiler.reloadPasses(); } /** * Get the complete list of classes */ public List<JavaClass> getClasses() { return getDecompiler().getClasses(); } /** * Get all classes that are not excluded by the excluded packages settings */ public List<JavaClass> getIncludedClasses() { List<JavaClass> classList = getDecompiler().getClasses(); List<String> excludedPackages = getExcludedPackages(); if (excludedPackages.isEmpty()) { return classList; } return classList.stream() .filter(cls -> isClassIncluded(excludedPackages, cls)) .collect(Collectors.toList()); } /** * Get all classes that are not excluded by the excluded packages settings including inner classes */ public List<JavaClass> getIncludedClassesWithInners() { List<JavaClass> classes = getDecompiler().getClassesWithInners(); List<String> excludedPackages = getExcludedPackages(); if (excludedPackages.isEmpty()) { return classes; } return classes.stream() .filter(cls -> isClassIncluded(excludedPackages, cls)) .collect(Collectors.toList()); } private static boolean isClassIncluded(List<String> excludedPackages, JavaClass cls) { for (String exclude : excludedPackages) { String clsFullName = cls.getFullName(); if (clsFullName.equals(exclude) || clsFullName.startsWith(exclude + '.')) { return false; } } return true; } public List<List<JavaClass>> buildDecompileBatches(List<JavaClass> classes) { return getDecompiler().getDecompileScheduler().buildBatches(classes); } // TODO: move to CLI and filter classes in JadxDecompiler public List<String> getExcludedPackages() { String excludedPackages = getSettings().getExcludedPackages().trim(); if (excludedPackages.isEmpty()) { return Collections.emptyList(); } return Arrays.asList(excludedPackages.split(" +")); } public void setExcludedPackages(List<String> packagesToExclude) { getSettings().setExcludedPackages(String.join(" ", packagesToExclude).trim()); getSettings().sync(); } public void addExcludedPackage(String packageToExclude) { String newExclusion = getSettings().getExcludedPackages() + ' ' + packageToExclude; getSettings().setExcludedPackages(newExclusion.trim()); getSettings().sync(); } public void removeExcludedPackage(String packageToRemoveFromExclusion) { List<String> list = new ArrayList<>(getExcludedPackages()); list.remove(packageToRemoveFromExclusion); getSettings().setExcludedPackages(String.join(" ", list)); getSettings().sync(); } public Optional<JadxDecompiler> getCurrentDecompiler() { synchronized (DECOMPILER_UPDATE_SYNC) { return Optional.ofNullable(decompiler); } } /** * TODO: make method private * Do not store JadxDecompiler in fields to not leak old instances */ public @NotNull JadxDecompiler getDecompiler() { if (decompiler == null || decompiler.getRoot() == null) { throw new JadxRuntimeException("Decompiler not yet loaded"); } return decompiler; } // TODO: forbid usage of this method public RootNode getRootNode() { return getDecompiler().getRoot(); } public void reloadCodeData() { getDecompiler().reloadCodeData(); } public JavaNode getJavaNodeByRef(ICodeNodeRef nodeRef) { return getDecompiler().getJavaNodeByRef(nodeRef); } public @Nullable JavaNode getEnclosingNode(ICodeInfo codeInfo, int pos) { return getDecompiler().getEnclosingNode(codeInfo, pos); } public List<JavaPackage> getPackages() { return getDecompiler().getPackages(); } public List<ResourceFile> getResources() { return getDecompiler().getResources(); } public JadxArgs getArgs() { return getDecompiler().getArgs(); } public JadxProject getProject() { return mainWindow.getProject(); } public JadxSettings getSettings() { return mainWindow.getSettings(); } public CacheObject getCache() { return mainWindow.getCacheObject(); } /** * @param fullName Full name of an outer class. Inner classes are not supported. */ public @Nullable JavaClass searchJavaClassByFullAlias(String fullName) { return getDecompiler().getClasses().stream() .filter(cls -> cls.getFullName().equals(fullName)) .findFirst() .orElse(null); } public @Nullable JavaClass searchJavaClassByOrigClassName(String fullName) { return getDecompiler().searchJavaClassByOrigFullName(fullName); } /** * @param rawName Full raw name of an outer class. Inner classes are not supported. */ public @Nullable JavaClass searchJavaClassByRawName(String rawName) { return getDecompiler().getClasses().stream() .filter(cls -> cls.getRawName().equals(rawName)) .findFirst() .orElse(null); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/JadxGUI.java
jadx-gui/src/main/java/jadx/gui/JadxGUI.java
package jadx.gui; import java.awt.Desktop; import javax.swing.SwingUtilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.cli.JadxCLIArgs; import jadx.cli.config.JadxConfigAdapter; import jadx.commons.app.JadxSystemInfo; import jadx.core.Jadx; import jadx.core.utils.files.FileUtils; import jadx.gui.logs.LogCollector; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.JadxSettingsData; import jadx.gui.ui.MainWindow; import jadx.gui.utils.LafManager; import jadx.gui.utils.NLS; public class JadxGUI { private static final Logger LOG = LoggerFactory.getLogger(JadxGUI.class); public static void main(String[] args) { try { JadxConfigAdapter<JadxSettingsData> configAdapter = JadxSettings.buildConfigAdapter(); JadxSettingsData settingsData = JadxCLIArgs.processArgs(args, new JadxSettingsData(), configAdapter); if (settingsData == null) { return; } JadxSettings settings = new JadxSettings(configAdapter); settings.loadSettingsData(settingsData); LogCollector.register(); printSystemInfo(); NLS.setLocale(settings.getLangLocale()); SwingUtilities.invokeLater(() -> { LafManager.init(settings); settings.getFontSettings().updateDefaultFont(); MainWindow mw = new MainWindow(settings); registerOpenFileHandler(mw); mw.init(); }); } catch (Exception e) { LOG.error("Error: {}", e.getMessage(), e); System.exit(1); } } private static void registerOpenFileHandler(MainWindow mw) { try { if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.APP_OPEN_FILE)) { desktop.setOpenFileHandler(e -> mw.open(FileUtils.toPaths(e.getFiles()))); } } } catch (Throwable e) { LOG.error("Failed to register open file handler", e); } } private static void printSystemInfo() { if (LOG.isDebugEnabled()) { LOG.debug("Starting jadx-gui. Version: '{}'. JVM: {} {}. OS: {}, version: {}, arch: {}", Jadx.getVersion(), JadxSystemInfo.JAVA_VM, JadxSystemInfo.JAVA_VER, JadxSystemInfo.OS_NAME, JadxSystemInfo.OS_VERSION, JadxSystemInfo.OS_ARCH); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/TaskWithExtraOnFinish.java
jadx-gui/src/main/java/jadx/gui/jobs/TaskWithExtraOnFinish.java
package jadx.gui.jobs; import java.util.Objects; import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import jadx.api.utils.tasks.ITaskExecutor; /** * Add additional `onFinish` action to the existing task */ public class TaskWithExtraOnFinish implements IBackgroundTask { private final IBackgroundTask task; private final Consumer<TaskStatus> extraOnFinish; public TaskWithExtraOnFinish(IBackgroundTask task, Runnable extraOnFinish) { this(task, s -> extraOnFinish.run()); } public TaskWithExtraOnFinish(IBackgroundTask task, Consumer<TaskStatus> extraOnFinish) { this.task = Objects.requireNonNull(task); this.extraOnFinish = Objects.requireNonNull(extraOnFinish); } @Override public void onFinish(ITaskInfo taskInfo) { task.onFinish(taskInfo); extraOnFinish.accept(taskInfo.getStatus()); } @Override public String getTitle() { return task.getTitle(); } @Override public ITaskExecutor scheduleTasks() { return task.scheduleTasks(); } @Override public void onDone(ITaskInfo taskInfo) { task.onDone(taskInfo); } @Override public @Nullable Consumer<ITaskProgress> getProgressListener() { return task.getProgressListener(); } @Override public @Nullable ITaskProgress getTaskProgress() { return task.getTaskProgress(); } @Override public boolean canBeCanceled() { return task.canBeCanceled(); } @Override public boolean isCanceled() { return task.isCanceled(); } @Override public void cancel() { task.cancel(); } @Override public int timeLimit() { return task.timeLimit(); } @Override public boolean checkMemoryUsage() { return task.checkMemoryUsage(); } @Override public int getCancelTimeoutMS() { return task.getCancelTimeoutMS(); } @Override public int getShutdownTimeoutMS() { return task.getShutdownTimeoutMS(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/ITaskInfo.java
jadx-gui/src/main/java/jadx/gui/jobs/ITaskInfo.java
package jadx.gui.jobs; public interface ITaskInfo { TaskStatus getStatus(); long getJobsCount(); long getJobsComplete(); long getJobsSkipped(); long getTime(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/Cancelable.java
jadx-gui/src/main/java/jadx/gui/jobs/Cancelable.java
package jadx.gui.jobs; public interface Cancelable { boolean isCanceled(); void cancel(); default int getCancelTimeoutMS() { return 2000; } default int getShutdownTimeoutMS() { return 5000; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/SimpleTask.java
jadx-gui/src/main/java/jadx/gui/jobs/SimpleTask.java
package jadx.gui.jobs; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import jadx.api.utils.tasks.ITaskExecutor; import jadx.core.utils.tasks.TaskExecutor; /** * Simple not cancelable task with memory check */ public class SimpleTask implements IBackgroundTask { private final String title; private final List<Runnable> jobs; private final @Nullable Consumer<TaskStatus> onFinish; public SimpleTask(String title, Runnable run) { this(title, Collections.singletonList(run), null); } public SimpleTask(String title, Runnable run, Runnable onFinish) { this(title, Collections.singletonList(run), s -> onFinish.run()); } public SimpleTask(String title, List<Runnable> jobs) { this(title, jobs, null); } public SimpleTask(String title, List<Runnable> jobs, @Nullable Consumer<TaskStatus> onFinish) { this.title = title; this.jobs = jobs; this.onFinish = onFinish; } @Override public String getTitle() { return title; } public List<Runnable> getJobs() { return jobs; } public @Nullable Consumer<TaskStatus> getOnFinish() { return onFinish; } @Override public ITaskExecutor scheduleTasks() { TaskExecutor executor = new TaskExecutor(); executor.addParallelTasks(jobs); return executor; } @Override public void onFinish(ITaskInfo taskInfo) { if (onFinish != null) { onFinish.accept(taskInfo.getStatus()); } } @Override public boolean checkMemoryUsage() { return true; } @Override public boolean canBeCanceled() { return false; } @Override public boolean isCanceled() { return false; } @Override public void cancel() { } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/ProgressUpdater.java
jadx-gui/src/main/java/jadx/gui/jobs/ProgressUpdater.java
package jadx.gui.jobs; import java.util.concurrent.BlockingQueue; import java.util.concurrent.DelayQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.Utils; import jadx.gui.ui.panel.ProgressPanel; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; @SuppressWarnings({ "FieldCanBeLocal", "InfiniteLoopStatement" }) public class ProgressUpdater { private static final Logger LOG = LoggerFactory.getLogger(ProgressUpdater.class); private static final int UPDATE_INTERVAL_MS = 1000; private final ProgressPanel progressPane; private final Consumer<InternalTask> cancelCallback; private final ExecutorService bgExecutor = Executors.newSingleThreadExecutor(Utils.simpleThreadFactory("jadx-progress")); private final BlockingQueue<InternalTask> tasks = new DelayQueue<>(); public ProgressUpdater(ProgressPanel progressPane, Consumer<InternalTask> cancelCallback) { this.progressPane = progressPane; this.cancelCallback = cancelCallback; this.bgExecutor.execute(this::updateLoop); } public void addTask(InternalTask task) { if (task.getBgTask().isSilent()) { return; } scheduleNextUpdate(task); } public void taskComplete(InternalTask task) { task.setNextUpdate(0); updateProgress(task); } private void scheduleNextUpdate(InternalTask task) { task.setNextUpdate(System.currentTimeMillis() + UPDATE_INTERVAL_MS); tasks.add(task); } private void updateLoop() { while (true) { try { InternalTask task = tasks.take(); if (task.isRunning()) { updateProgress(task); cancelCheck(task); scheduleNextUpdate(task); } } catch (Exception e) { LOG.warn("Error in ProgressUpdater loop", e); } } } private void updateProgress(InternalTask internalTask) { UiUtils.uiRun(() -> { IBackgroundTask bgTask = internalTask.getBgTask(); if (internalTask.isRunning()) { if (internalTask.checkForFirstUpdate()) { progressPane.setLabel(bgTask.getTitle() + "… "); progressPane.setCancelButtonVisible(bgTask.canBeCanceled()); progressPane.setVisible(true); } ITaskProgress taskProgress = bgTask.getTaskProgress(); if (taskProgress == null) { int progress = internalTask.getTaskExecutor().getProgress(); taskProgress = new TaskProgress(progress, internalTask.getJobsCount()); } progressPane.setProgress(taskProgress); Consumer<ITaskProgress> onProgressListener = bgTask.getProgressListener(); if (onProgressListener != null) { onProgressListener.accept(taskProgress); } } else { progressPane.reset(); progressPane.setVisible(false); } }); } private void cancelCheck(InternalTask task) { TaskStatus taskStatus = task.getCancelCheck().get(); if (taskStatus == null) { return; } task.setStatus(taskStatus); UiUtils.uiRun(() -> { IBackgroundTask bgTask = task.getBgTask(); progressPane.setLabel(bgTask.getTitle() + " (" + NLS.str("progress.canceling") + ")… "); progressPane.setCancelButtonVisible(false); progressPane.setIndeterminate(true); }); cancelCallback.accept(task); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/CancelableBackgroundTask.java
jadx-gui/src/main/java/jadx/gui/jobs/CancelableBackgroundTask.java
package jadx.gui.jobs; import java.util.concurrent.atomic.AtomicBoolean; public abstract class CancelableBackgroundTask implements IBackgroundTask { private final AtomicBoolean cancel = new AtomicBoolean(false); @Override public boolean isCanceled() { return cancel.get(); } @Override public void cancel() { cancel.set(true); } public void resetCancel() { cancel.set(false); } @Override public boolean canBeCanceled() { return true; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/InternalTask.java
jadx-gui/src/main/java/jadx/gui/jobs/InternalTask.java
package jadx.gui.jobs; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; import org.jetbrains.annotations.NotNull; import jadx.api.utils.tasks.ITaskExecutor; public class InternalTask implements Delayed, ITaskInfo { private final long id; private final IBackgroundTask bgTask; private final AtomicBoolean running = new AtomicBoolean(false); private final AtomicLong nextUpdate = new AtomicLong(0); private final AtomicBoolean firstUpdate = new AtomicBoolean(true); private long startTime; private long execTime; private Supplier<TaskStatus> cancelCheck; private TaskStatus status = TaskStatus.WAIT; private ITaskExecutor taskExecutor; private long jobsCount; private long jobsComplete; public InternalTask(long id, IBackgroundTask task) { this.id = id; this.bgTask = task; } public void taskStart(long startTime, Supplier<TaskStatus> cancelCheck) { this.startTime = startTime; this.cancelCheck = cancelCheck; this.status = TaskStatus.STARTED; this.running.set(true); } public void taskComplete() { this.running.set(false); if (status == TaskStatus.STARTED) { // might be already set to error or cancel this.status = TaskStatus.COMPLETE; } updateExecTime(); } public long getId() { return id; } public IBackgroundTask getBgTask() { return bgTask; } public void setNextUpdate(long nextUpdate) { this.nextUpdate.set(nextUpdate); } public boolean isRunning() { return running.get(); } public boolean checkForFirstUpdate() { return firstUpdate.compareAndExchange(true, false); } public Supplier<TaskStatus> getCancelCheck() { return cancelCheck; } public long getStartTime() { return startTime; } @Override public TaskStatus getStatus() { return status; } public void setStatus(TaskStatus taskStatus) { this.status = taskStatus; } public ITaskExecutor getTaskExecutor() { return taskExecutor; } public void setTaskExecutor(ITaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } @Override public long getJobsComplete() { return jobsComplete; } public void setJobsComplete(long jobsComplete) { this.jobsComplete = jobsComplete; } @Override public long getJobsCount() { return jobsCount; } public void setJobsCount(long jobsCount) { this.jobsCount = jobsCount; } @Override public long getJobsSkipped() { return jobsCount - jobsComplete; } @Override public long getTime() { return execTime; } public void updateExecTime() { this.execTime = System.currentTimeMillis() - startTime; } @Override public long getDelay(@NotNull TimeUnit unit) { return unit.convert(nextUpdate.get() - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } @Override public int compareTo(@NotNull Delayed o) { return Long.compare(nextUpdate.get(), ((InternalTask) o).nextUpdate.get()); } @Override public String toString() { return "InternalTask{" + bgTask.getTitle() + ", status=" + status + ", progress=" + jobsComplete + " of " + jobsCount + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/ProcessResult.java
jadx-gui/src/main/java/jadx/gui/jobs/ProcessResult.java
package jadx.gui.jobs; public class ProcessResult { private final int skipped; private final TaskStatus status; private final int timeLimit; public ProcessResult(int skipped, TaskStatus status, int timeLimit) { this.skipped = skipped; this.status = status; this.timeLimit = timeLimit; } public int getSkipped() { return skipped; } public TaskStatus getStatus() { return status; } public int getTimeLimit() { return timeLimit; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/DecompileTask.java
jadx-gui/src/main/java/jadx/gui/jobs/DecompileTask.java
package jadx.gui.jobs; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.JOptionPane; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeCache; import jadx.api.JavaClass; import jadx.api.utils.tasks.ITaskExecutor; import jadx.commons.app.JadxCommonEnv; import jadx.core.utils.tasks.TaskExecutor; import jadx.gui.JadxWrapper; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; public class DecompileTask extends CancelableBackgroundTask { private static final Logger LOG = LoggerFactory.getLogger(DecompileTask.class); private static final int CLS_LIMIT = JadxCommonEnv.getInt("JADX_CLS_PROCESS_LIMIT", 50); public static int calcDecompileTimeLimit(int classCount) { return classCount * CLS_LIMIT + 5000; } private final MainWindow mainWindow; private final JadxWrapper wrapper; private final AtomicInteger complete = new AtomicInteger(0); private int expectedCompleteCount; private ProcessResult result; public DecompileTask(MainWindow mainWindow) { this.mainWindow = mainWindow; this.wrapper = mainWindow.getWrapper(); } @Override public String getTitle() { return NLS.str("progress.decompile"); } @Override public ITaskExecutor scheduleTasks() { TaskExecutor executor = new TaskExecutor(); executor.addParallelTasks(scheduleJobs()); return executor; } public List<Runnable> scheduleJobs() { if (mainWindow.getCacheObject().isFullDecompilationFinished()) { return Collections.emptyList(); } List<JavaClass> classes = wrapper.getIncludedClasses(); expectedCompleteCount = classes.size(); complete.set(0); List<List<JavaClass>> batches; try { batches = wrapper.buildDecompileBatches(classes); } catch (Exception e) { LOG.error("Decompile batches build error", e); return Collections.emptyList(); } return getJobs(batches); } private List<Runnable> getJobs(List<List<JavaClass>> batches) { ICodeCache codeCache = wrapper.getArgs().getCodeCache(); List<Runnable> jobs = new ArrayList<>(batches.size()); for (List<JavaClass> batch : batches) { jobs.add(() -> { for (JavaClass cls : batch) { if (isCanceled()) { return; } try { if (!codeCache.contains(cls.getRawName())) { cls.decompile(); } } catch (Throwable e) { LOG.error("Failed to decompile class: {}", cls, e); } finally { complete.incrementAndGet(); } } }); } return jobs; } @Override public void onDone(ITaskInfo taskInfo) { long taskTime = taskInfo.getTime(); long avgPerCls = taskTime / Math.max(expectedCompleteCount, 1); int timeLimit = timeLimit(); int skippedCls = expectedCompleteCount - complete.get(); if (LOG.isInfoEnabled()) { LOG.info("Decompile and index task complete in " + taskTime + " ms (avg " + avgPerCls + " ms per class)" + ", classes: " + expectedCompleteCount + ", skipped: " + skippedCls + ", time limit:{ total: " + timeLimit + "ms, per cls: " + CLS_LIMIT + "ms }" + ", status: " + taskInfo.getStatus()); } result = new ProcessResult(skippedCls, taskInfo.getStatus(), timeLimit); wrapper.unloadClasses(); processDecompilationResults(); System.gc(); mainWindow.getCacheObject().setFullDecompilationFinished(skippedCls == 0); } private void processDecompilationResults() { int skippedCls = result.getSkipped(); if (skippedCls == 0) { return; } TaskStatus status = result.getStatus(); LOG.warn("Decompile and indexing of some classes skipped: {}, status: {}", skippedCls, status); switch (status) { case CANCEL_BY_USER: { String reason = NLS.str("message.userCancelTask"); String message = NLS.str("message.indexIncomplete", reason, skippedCls); JOptionPane.showMessageDialog(mainWindow, message); break; } case CANCEL_BY_TIMEOUT: { String reason = NLS.str("message.taskTimeout", result.getTimeLimit()); String message = NLS.str("message.indexIncomplete", reason, skippedCls); JOptionPane.showMessageDialog(mainWindow, message); break; } case CANCEL_BY_MEMORY: { mainWindow.showHeapUsageBar(); JOptionPane.showMessageDialog(mainWindow, NLS.str("message.indexingClassesSkipped", skippedCls)); break; } } } @Override public boolean canBeCanceled() { return true; } @Override public int timeLimit() { return calcDecompileTimeLimit(expectedCompleteCount); } @Override public boolean checkMemoryUsage() { return true; } public ProcessResult getResult() { return result; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/ExportTask.java
jadx-gui/src/main/java/jadx/gui/jobs/ExportTask.java
package jadx.gui.jobs; import java.io.File; import javax.swing.JOptionPane; import jadx.api.ICodeCache; import jadx.api.utils.tasks.ITaskExecutor; import jadx.gui.JadxWrapper; import jadx.gui.cache.code.CodeCacheMode; import jadx.gui.cache.code.FixedCodeCache; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; public class ExportTask extends CancelableBackgroundTask { private final MainWindow mainWindow; private final JadxWrapper wrapper; private final File saveDir; private int timeLimit; private ICodeCache uiCodeCache; public ExportTask(MainWindow mainWindow, JadxWrapper wrapper, File saveDir) { this.mainWindow = mainWindow; this.wrapper = wrapper; this.saveDir = saveDir; } @Override public String getTitle() { return NLS.str("msg.saving_sources"); } @Override public ITaskExecutor scheduleTasks() { wrapCodeCache(); wrapper.getArgs().setRootDir(saveDir); ITaskExecutor saveTasks = wrapper.getDecompiler().getSaveTaskExecutor(); this.timeLimit = DecompileTask.calcDecompileTimeLimit(saveTasks.getTasksCount()); return saveTasks; } private void wrapCodeCache() { uiCodeCache = wrapper.getArgs().getCodeCache(); if (mainWindow.getSettings().getCodeCacheMode() != CodeCacheMode.DISK) { // do not save newly decompiled code in cache to not increase memory usage // TODO: maybe make memory limited cache? wrapper.getArgs().setCodeCache(new FixedCodeCache(uiCodeCache)); } } @Override public void onFinish(ITaskInfo taskInfo) { // restore initial code cache wrapper.getArgs().setCodeCache(uiCodeCache); if (taskInfo.getJobsSkipped() == 0) { return; } String reason = getIncompleteReason(taskInfo.getStatus()); if (reason != null) { JOptionPane.showMessageDialog(mainWindow, NLS.str("message.saveIncomplete", reason, taskInfo.getJobsSkipped()), NLS.str("message.errorTitle"), JOptionPane.ERROR_MESSAGE); } } private String getIncompleteReason(TaskStatus status) { switch (status) { case CANCEL_BY_USER: return NLS.str("message.userCancelTask"); case CANCEL_BY_TIMEOUT: return NLS.str("message.taskTimeout", timeLimit()); case CANCEL_BY_MEMORY: mainWindow.showHeapUsageBar(); return NLS.str("message.memoryLow"); case ERROR: return NLS.str("message.taskError"); } return null; } @Override public int timeLimit() { return timeLimit; } @Override public boolean canBeCanceled() { return true; } @Override public boolean checkMemoryUsage() { return true; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/BackgroundExecutor.java
jadx-gui/src/main/java/jadx/gui/jobs/BackgroundExecutor.java
package jadx.gui.jobs; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.utils.tasks.ITaskExecutor; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.settings.JadxSettings; import jadx.gui.ui.MainWindow; import jadx.gui.ui.panel.ProgressPanel; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; /** * Run tasks in the background with progress bar indication. * Use instance created in {@link MainWindow}. */ public class BackgroundExecutor { private static final Logger LOG = LoggerFactory.getLogger(BackgroundExecutor.class); private final JadxSettings settings; private final ProgressUpdater progressUpdater; private ThreadPoolExecutor taskQueueExecutor; private final Map<Long, InternalTask> taskRunning = new ConcurrentHashMap<>(); private final AtomicLong idSupplier = new AtomicLong(0); public BackgroundExecutor(JadxSettings settings, ProgressPanel progressPane) { this.settings = Objects.requireNonNull(settings); this.progressUpdater = new ProgressUpdater(progressPane, this::taskCanceled); reset(); } public synchronized void execute(IBackgroundTask task) { InternalTask internalTask = buildTask(task); taskQueueExecutor.execute(() -> runTask(internalTask)); } public synchronized Future<TaskStatus> executeWithFuture(IBackgroundTask task) { InternalTask internalTask = buildTask(task); return taskQueueExecutor.submit(() -> { runTask(internalTask); return internalTask.getStatus(); }); } public synchronized void cancelAll() { try { taskRunning.values().forEach(this::cancelTask); taskQueueExecutor.shutdownNow(); boolean complete = taskQueueExecutor.awaitTermination(3, TimeUnit.SECONDS); if (complete) { LOG.debug("Background task executor canceled successfully"); } else { String taskNames = taskRunning.values().stream() .map(t -> t.getBgTask().getTitle()) .collect(Collectors.joining(", ")); LOG.debug("Background task executor cancel failed. Running tasks: {}", taskNames); } } catch (Exception e) { LOG.error("Error terminating task executor", e); } finally { reset(); } } public synchronized void waitForComplete() { try { // add empty task and wait its completion taskQueueExecutor.submit(UiUtils.EMPTY_RUNNABLE).get(); } catch (Exception e) { throw new JadxRuntimeException("Failed to wait tasks completion", e); } } public void execute(String title, List<Runnable> backgroundJobs, Consumer<TaskStatus> onFinishUiRunnable) { execute(new SimpleTask(title, backgroundJobs, onFinishUiRunnable)); } public void execute(String title, Runnable backgroundRunnable, Consumer<TaskStatus> onFinishUiRunnable) { execute(new SimpleTask(title, Collections.singletonList(backgroundRunnable), onFinishUiRunnable)); } public void execute(String title, Runnable backgroundRunnable) { execute(new SimpleTask(title, Collections.singletonList(backgroundRunnable))); } public void startLoading(Runnable backgroundRunnable, Runnable onFinishUiRunnable) { execute(new SimpleTask(NLS.str("progress.load"), backgroundRunnable, onFinishUiRunnable)); } public void startLoading(Runnable backgroundRunnable) { execute(new SimpleTask(NLS.str("progress.load"), backgroundRunnable)); } private synchronized void reset() { taskQueueExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1, Utils.simpleThreadFactory("bg")); taskRunning.clear(); idSupplier.set(0); } private InternalTask buildTask(IBackgroundTask task) { long id = idSupplier.incrementAndGet(); InternalTask internalTask = new InternalTask(id, task); taskRunning.put(id, internalTask); return internalTask; } private void runTask(InternalTask internalTask) { try { IBackgroundTask task = internalTask.getBgTask(); ITaskExecutor taskExecutor = task.scheduleTasks(); taskExecutor.setThreadsCount(settings.getThreadsCount()); int tasksCount = taskExecutor.getTasksCount(); internalTask.setTaskExecutor(taskExecutor); internalTask.setJobsCount(tasksCount); if (UiUtils.JADX_GUI_DEBUG) { LOG.debug("Starting background task '{}', jobs count: {}, time limit: {} ms, memory check: {}", task.getTitle(), tasksCount, task.timeLimit(), task.checkMemoryUsage()); } long startTime = System.currentTimeMillis(); Supplier<TaskStatus> cancelCheck = buildCancelCheck(internalTask, startTime); internalTask.taskStart(startTime, cancelCheck); progressUpdater.addTask(internalTask); taskExecutor.execute(); taskExecutor.awaitTermination(); } catch (Exception e) { LOG.error("Task failed", e); internalTask.setStatus(TaskStatus.ERROR); } finally { taskComplete(internalTask); } } private void taskComplete(InternalTask internalTask) { try { IBackgroundTask task = internalTask.getBgTask(); internalTask.setJobsComplete(internalTask.getTaskExecutor().getProgress()); internalTask.setStatus(TaskStatus.COMPLETE); internalTask.updateExecTime(); task.onDone(internalTask); // treat UI task operations as part of the task to not mix with others UiUtils.uiRunAndWait(() -> { try { task.onFinish(internalTask); } catch (Exception e) { LOG.error("Task onFinish failed", e); internalTask.setStatus(TaskStatus.ERROR); } }); } catch (Exception e) { LOG.error("Task complete failed", e); internalTask.setStatus(TaskStatus.ERROR); } finally { internalTask.taskComplete(); progressUpdater.taskComplete(internalTask); removeTask(internalTask); } } private void removeTask(InternalTask internalTask) { taskRunning.remove(internalTask.getId()); } private void cancelTask(InternalTask internalTask) { try { IBackgroundTask task = internalTask.getBgTask(); if (!internalTask.isRunning()) { // task complete or not yet started task.cancel(); removeTask(internalTask); return; } ITaskExecutor taskExecutor = internalTask.getTaskExecutor(); // force termination task.cancel(); taskExecutor.terminate(); ExecutorService executor = taskExecutor.getInternalExecutor(); if (executor == null) { return; } int cancelTimeout = task.getCancelTimeoutMS(); if (cancelTimeout != 0) { if (executor.awaitTermination(cancelTimeout, TimeUnit.MILLISECONDS)) { LOG.debug("Task cancel complete"); return; } } LOG.debug("Forcing tasks cancel"); executor.shutdownNow(); boolean complete = executor.awaitTermination(task.getShutdownTimeoutMS(), TimeUnit.MILLISECONDS); LOG.debug("Forced task cancel status: {}", complete ? "success" : "fail, still active: " + (taskExecutor.getTasksCount() - taskExecutor.getProgress())); } catch (Exception e) { LOG.error("Failed to cancel task: {}", internalTask, e); } } /** * Task cancel notification from progress updater */ private void taskCanceled(InternalTask task) { cancelTask(task); } private Supplier<TaskStatus> buildCancelCheck(InternalTask internalTask, long startTime) { IBackgroundTask task = internalTask.getBgTask(); int timeLimit = task.timeLimit(); long waitUntilTime = timeLimit == 0 ? 0 : startTime + timeLimit; boolean checkMemoryUsage = task.checkMemoryUsage(); return () -> { if (task.isCanceled() || Thread.currentThread().isInterrupted()) { return TaskStatus.CANCEL_BY_USER; } if (waitUntilTime != 0 && waitUntilTime < System.currentTimeMillis()) { LOG.warn("Task '{}' execution timeout, force cancel", task.getTitle()); return TaskStatus.CANCEL_BY_TIMEOUT; } if (checkMemoryUsage && !UiUtils.isFreeMemoryAvailable()) { LOG.warn("High memory usage: {}", UiUtils.memoryInfo()); if (internalTask.getTaskExecutor().getThreadsCount() == 1) { LOG.warn("Task '{}' memory limit reached, force cancel", task.getTitle()); return TaskStatus.CANCEL_BY_MEMORY; } LOG.warn("Low free memory, reduce processing threads count to 1"); // reduce threads count and continue internalTask.getTaskExecutor().setThreadsCount(1); System.gc(); UiUtils.sleep(1000); // wait GC if (!UiUtils.isFreeMemoryAvailable()) { LOG.error("Task '{}' memory limit reached (after GC), force cancel", task.getTitle()); return TaskStatus.CANCEL_BY_MEMORY; } } return null; }; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/LoadTask.java
jadx-gui/src/main/java/jadx/gui/jobs/LoadTask.java
package jadx.gui.jobs; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Supplier; import jadx.api.utils.tasks.ITaskExecutor; import jadx.core.utils.tasks.TaskExecutor; import jadx.gui.utils.NLS; /** * Load task: prepare data in background task and use that data in UI task */ public class LoadTask<T> extends CancelableBackgroundTask { private final String title; private final AtomicReference<T> taskData; private final Runnable bgTask; private final Runnable uiTask; public LoadTask(Supplier<T> loadBgTask, Consumer<T> uiTask) { this(NLS.str("progress.load"), loadBgTask, uiTask); } public LoadTask(String title, Supplier<T> loadBgTask, Consumer<T> uiTask) { this.title = title; this.taskData = new AtomicReference<>(); this.bgTask = () -> taskData.set(loadBgTask.get()); this.uiTask = () -> uiTask.accept(taskData.get()); } @Override public String getTitle() { return title; } @Override public ITaskExecutor scheduleTasks() { TaskExecutor executor = new TaskExecutor(); executor.addSequentialTask(bgTask); return executor; } @Override public void onFinish(ITaskInfo taskInfo) { uiTask.run(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false