repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/others/TestClassGen.java
jadx-core/src/test/java/jadx/tests/integration/others/TestClassGen.java
package jadx.tests.integration.others; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import jadx.tests.api.utils.assertj.JadxAssertions; public class TestClassGen extends IntegrationTest { public static class TestCls { public interface I { int test(); public int test3(); } public abstract static class A { public abstract int test2(); } } @Test public void test() { JadxAssertions.assertThat(getClassNode(TestCls.class)) .code() .contains("public interface I {") .contains(indent(2) + "int test();") .doesNotContain("public int test();") .contains(indent(2) + "int test3();") .contains("public static abstract class A {") .contains(indent(2) + "public abstract int test2();"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/others/TestOverridePackagePrivateMethod.java
jadx-core/src/test/java/jadx/tests/integration/others/TestOverridePackagePrivateMethod.java
package jadx.tests.integration.others; import java.util.List; import org.junit.jupiter.api.Test; import jadx.core.dex.nodes.ClassNode; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestOverridePackagePrivateMethod extends SmaliTest { // @formatter:off /* ----------------------------------------------------------- package test; public class A { void a() { // package-private } } ----------------------------------------------------------- package test; public class B extends A { @Override // test.A public void a() { } } ----------------------------------------------------------- package other; import test.A; public class C extends A { // No @Override here public void a() { } } ----------------------------------------------------------- */ // @formatter:on @Test public void test() { commonChecks(); } @Test public void testDontChangeAccFlags() { getArgs().setRespectBytecodeAccModifiers(true); commonChecks(); } private void commonChecks() { List<ClassNode> classes = loadFromSmaliFiles(); assertThat(searchCls(classes, "test.A")) .code() .doesNotContain("/* access modifiers changed") .containsLine(1, "void a() {"); assertThat(searchCls(classes, "test.B")).code().containsOne("@Override"); assertThat(searchCls(classes, "other.C")).code().doesNotContain("@Override"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/others/TestIncorrectMethodSignature.java
jadx-core/src/test/java/jadx/tests/integration/others/TestIncorrectMethodSignature.java
package jadx.tests.integration.others; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; /** * Issue #858. * Incorrect method signature change argument type and shift register numbers */ public class TestIncorrectMethodSignature extends SmaliTest { @Test public void test() { allowWarnInCode(); assertThat(getClassNodeFromSmali()) .code() .containsOne("public TestIncorrectMethodSignature(String str) {"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/others/TestExplicitOverride.java
jadx-core/src/test/java/jadx/tests/integration/others/TestExplicitOverride.java
package jadx.tests.integration.others; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestExplicitOverride extends SmaliTest { @Test public void test() { assertThat(getClassNodeFromSmali()) .code() .countString(1, "@Override"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumUsesOtherEnum.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumUsesOtherEnum.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import jadx.tests.api.extensions.profiles.TestProfile; import jadx.tests.api.extensions.profiles.TestWithProfiles; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnumUsesOtherEnum extends SmaliTest { public static class TestCls { public enum VType { INT(1), OTHER_INT(INT); private final int type; VType(int type) { this.type = type; } VType(VType refType) { this(refType.type); } } } @TestWithProfiles(TestProfile.D8_J11) public void test() { noDebugInfo(); assertThat(getClassNode(TestCls.class)) .code() .containsOne("OTHER_INT(INT);") .doesNotContain("\n \n"); // no indentation for empty string } @Test public void testSmali() { assertThat(getClassNodeFromSmali()) .code() .containsOne("public enum TestEnumUsesOtherEnum {") .doesNotContain("static {"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumWithConstInlining.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumWithConstInlining.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import jadx.tests.api.utils.assertj.JadxAssertions; public class TestEnumWithConstInlining extends SmaliTest { enum TestCls { E0, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100; /** * Match the length of the $VALUES array. */ public static final int CONST = 101; } @Test public void test() { JadxAssertions.assertThat(getClassNode(TestCls.class)) .code() .containsOne("E42,"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestSwitchOverEnum2.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestSwitchOverEnum2.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; public class TestSwitchOverEnum2 extends IntegrationTest { public enum Count { ONE, TWO, THREE } public enum Animal { CAT, DOG } public int testEnum(Count c, Animal a) { int result = 0; switch (c) { case ONE: result = 1; break; case TWO: result = 2; break; } switch (a) { case CAT: result += 10; break; case DOG: result += 20; break; } return result; } public void check() { assertThat(testEnum(Count.ONE, Animal.DOG)).isEqualTo(21); } @Test public void test() { assertThat(getClassNode(TestSwitchOverEnum2.class)) .code() .countString(1, "synthetic") .countString(2, "switch (c) {") .countString(2, "case ONE:") .countString(2, "case DOG:"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithTernary.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithTernary.java
package jadx.tests.integration.enums; import jadx.tests.api.IntegrationTest; import jadx.tests.api.extensions.profiles.TestProfile; import jadx.tests.api.extensions.profiles.TestWithProfiles; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnumsWithTernary extends IntegrationTest { public enum TestCls { FIRST(useNumber() ? "1" : "A"), SECOND(useNumber() ? "2" : "B"), ANY(useNumber() ? "1" : "2"); private final String str; TestCls(String str) { this.str = str; } public String getStr() { return str; } public static boolean useNumber() { return false; } } @TestWithProfiles({ TestProfile.DX_J8, TestProfile.D8_J8 }) public void test() { noDebugInfo(); assertThat(getClassNode(TestCls.class)) .code() .containsOne("ANY(useNumber() ? \"1\" : \"2\");") .doesNotContain("static {"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestSwitchOverEnum.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestSwitchOverEnum.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestSwitchOverEnum extends SmaliTest { public enum Count { ONE, TWO, THREE } public int testEnum(Count c) { switch (c) { case ONE: return 1; case TWO: return 2; } return 0; } public void check() { assertThat(testEnum(Count.ONE)).isEqualTo(1); assertThat(testEnum(Count.TWO)).isEqualTo(2); assertThat(testEnum(Count.THREE)).isEqualTo(0); } @Test public void test() { // remapping array placed in top class, place test also in top class assertThat(getClassNode(TestSwitchOverEnum.class)) .code() .countString(1, "synthetic") .countString(2, "switch (c) {") .countString(3, "case ONE:"); } /** * Java 21 compiler can omit a remapping array and use switch over ordinal directly */ @Test public void testSmaliDirect() { assertThat(getClassNodeFromSmaliFiles()) .code() .containsOne("switch (v) {") .containsOne("case ONE:"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumObfuscated.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumObfuscated.java
package jadx.tests.integration.enums; import java.util.Collections; import org.junit.jupiter.api.Test; import jadx.api.CommentsLevel; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnumObfuscated extends SmaliTest { // @formatter:off /* public enum TestEnumObfuscated { private static final synthetic TestEnumObfuscated[] $VLS = {ONE, TWO}; public static final TestEnumObfuscated ONE = new TestEnumObfuscated("ONE", 0, 1); public static final TestEnumObfuscated TWO = new TestEnumObfuscated("TWO", 1, 2); private final int num; private TestEnumObfuscated(String str, int i, int i2) { super(str, i); this.num = i2; } public static TestEnumObfuscated vo(String str) { return (TestEnumObfuscated) Enum.valueOf(TestEnumObfuscated.class, str); } public static TestEnumObfuscated[] vs() { return (TestEnumObfuscated[]) $VLS.clone(); } public synthetic int getNum() { return this.num; } // custom values method // should be kept and renamed to avoid collision to enum 'values()' method public static int values() { return new TestEnumObfuscated[0]; } // usage of renamed 'values()' method, should be renamed back to 'values' public static int valuesCount() { return vs().length; } // usage of renamed '$VALUES' field, should be replaced with 'values()' method call public static int valuesFieldUse() { return $VLS.length; } } */ // @formatter:on @Test public void test() { getArgs().setCommentsLevel(CommentsLevel.WARN); getArgs().setRenameFlags(Collections.emptySet()); assertThat(getClassNodeFromSmali()) .code() .doesNotContain("$VLS") .doesNotContain("vo(") .doesNotContain("vs(") .containsOne("int getNum() {"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums4.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums4.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import jadx.tests.api.utils.assertj.JadxAssertions; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnums4 extends IntegrationTest { public static class TestCls { public enum ResType { CODE(".dex", ".class"), MANIFEST("AndroidManifest.xml"), XML(".xml"), ARSC(".arsc"), FONT(".ttf"), IMG(".png", ".gif", ".jpg"), LIB(".so"), UNKNOWN; private final String[] exts; ResType(String... extensions) { this.exts = extensions; } public String[] getExts() { return exts; } } public void check() { assertThat(ResType.CODE.getExts()).containsExactly(new String[] { ".dex", ".class" }); } } @Test public void test() { JadxAssertions.assertThat(getClassNode(TestCls.class)) .code() .containsOne("CODE(\".dex\", \".class\"),") .containsOne("ResType(String... extensions) {"); // assertThat(code, not(containsString("private ResType"))); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithAssert.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithAssert.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.NotYetImplemented; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnumsWithAssert extends IntegrationTest { public static class TestCls { public enum Numbers { ONE(1), TWO(2), THREE(3); private final int num; Numbers(int n) { this.num = n; } public int getNum() { assert num > 0; return num; } } } @Test public void test() { assertThat(getClassNode(TestCls.class)).code() .containsOne("ONE(1)") .doesNotContain("Failed to restore enum class"); } @NotYetImplemented("handle java assert") @Test public void testNYI() { assertThat(getClassNode(TestCls.class)).code() .containsOne("assert num > 0;") .doesNotContain("$assertionsDisabled") .doesNotContain("throw new AssertionError()"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnums extends IntegrationTest { public static class TestCls { public enum EmptyEnum { } @SuppressWarnings("NoWhitespaceBefore") public enum EmptyEnum2 { ; public static void mth() { } } public enum Direction { NORTH, SOUTH, EAST, WEST } public enum Singleton { INSTANCE; public String test() { return ""; } } } @Test public void test() { assertThat(getClassNode(TestCls.class)) .code() .containsLines(1, "public enum EmptyEnum {", "}") .containsLines(1, "public enum EmptyEnum2 {", indent(1) + ';', "", indent(1) + "public static void mth() {", indent(1) + '}', "}") .containsLines(1, "public enum Direction {", indent(1) + "NORTH,", indent(1) + "SOUTH,", indent(1) + "EAST,", indent(1) + "WEST", "}") .containsLines(1, "public enum Singleton {", indent(1) + "INSTANCE;", "", indent(1) + "public String test() {", indent(2) + "return \"\";", indent(1) + '}', "}"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestInnerEnums.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestInnerEnums.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import jadx.tests.api.utils.assertj.JadxAssertions; import static org.assertj.core.api.Assertions.assertThat; public class TestInnerEnums extends IntegrationTest { public static class TestCls { public enum Numbers { ONE((byte) 1, NumString.ONE), TWO((byte) 2, NumString.TWO); private final byte num; private final NumString str; public enum NumString { ONE("one"), TWO("two"); private final String name; NumString(String name) { this.name = name; } public String getName() { return name; } } Numbers(byte n, NumString str) { this.num = n; this.str = str; } public int getNum() { return num; } public NumString getNumStr() { return str; } public String getName() { return str.getName(); } } public void check() { assertThat(Numbers.ONE.getNum()).isEqualTo(1); assertThat(Numbers.ONE.getNumStr()).isEqualTo(Numbers.NumString.ONE); assertThat(Numbers.ONE.getName()).isEqualTo("one"); } } @Test public void test() { JadxAssertions.assertThat(getClassNode(TestCls.class)) .code() .containsOne("ONE((byte) 1, NumString.ONE)") .containsOne("ONE(\"one\")"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumWithFields.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumWithFields.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; public class TestEnumWithFields extends SmaliTest { public static class TestCls { public enum SearchTimeout { DISABLED(0), TWO_SECONDS(2), FIVE_SECONDS(5); public static final SearchTimeout DEFAULT = DISABLED; public static final SearchTimeout MAX = FIVE_SECONDS; public final int sec; SearchTimeout(int val) { this.sec = val; } } public void check() { assertThat(SearchTimeout.DISABLED.sec).isEqualTo(0); assertThat(SearchTimeout.DEFAULT.sec).isEqualTo(0); assertThat(SearchTimeout.TWO_SECONDS.sec).isEqualTo(2); assertThat(SearchTimeout.MAX.sec).isEqualTo(5); } } @Test public void test() { noDebugInfo(); assertThat(getClassNode(TestCls.class)) .code(); } @Test public void test2() { assertThat(getClassNodeFromSmali()) .code(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums2a.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums2a.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static jadx.tests.integration.enums.TestEnums2a.TestCls.DoubleOperations.DIVIDE; import static jadx.tests.integration.enums.TestEnums2a.TestCls.DoubleOperations.TIMES; public class TestEnums2a extends IntegrationTest { public static class TestCls { public interface IOps { double apply(double x, double y); } public enum DoubleOperations implements IOps { TIMES("*") { @Override public double apply(double x, double y) { return x * y; } }, DIVIDE("/") { @Override public double apply(double x, double y) { return x / y; } }; private final String op; DoubleOperations(String op) { this.op = op; } public String getOp() { return op; } } public void check() { assertThat(TIMES.getOp()).isEqualTo("*"); assertThat(DIVIDE.getOp()).isEqualTo("/"); assertThat(TIMES.apply(2, 3)).isEqualTo(6); assertThat(DIVIDE.apply(10, 5)).isEqualTo(2); } } @Test public void test() { assertThat(getClassNode(TestCls.class)) .code() .containsOne("TIMES(\"*\") {") .containsOne("DIVIDE(\"/\")"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums5.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums5.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnums5 extends SmaliTest { @Test public void test() { assertThat(getClassNodeFromSmaliWithClsName("kotlin.collections.State")) .code() .containsLines( "enum State {", indent() + "Ready,", indent() + "NotReady,", indent() + "Done,", indent() + "Failed", "}"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsInterface.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsInterface.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.api.CommentsLevel; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnumsInterface extends IntegrationTest { public static class TestCls { public enum Operation implements IOperation { PLUS { @Override public int apply(int x, int y) { return x + y; } }, MINUS { @Override public int apply(int x, int y) { return x - y; } } } public interface IOperation { int apply(int x, int y); } } @Test public void test() { getArgs().setCommentsLevel(CommentsLevel.WARN); assertThat(getClassNode(TestCls.class)) .code() .containsLines(1, "public enum Operation implements IOperation {", indent(1) + "PLUS {", indent(2) + "@Override", indent(2) + "public int apply(int x, int y) {", indent(3) + "return x + y;", indent(2) + '}', indent(1) + "},", indent(1) + "MINUS {", indent(2) + "@Override", indent(2) + "public int apply(int x, int y) {", indent(3) + "return x - y;", indent(2) + '}', indent(1) + '}', "}"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums3.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums3.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import jadx.tests.api.utils.assertj.JadxAssertions; import static org.assertj.core.api.Assertions.assertThat; public class TestEnums3 extends IntegrationTest { public static class TestCls { private static int three = 3; public enum Numbers { ONE(1), TWO(2), THREE(three), FOUR(three + 1); private final int num; Numbers(int n) { this.num = n; } public int getNum() { return num; } } public void check() { assertThat(Numbers.ONE.getNum()).isEqualTo(1); assertThat(Numbers.THREE.getNum()).isEqualTo(3); assertThat(Numbers.FOUR.getNum()).isEqualTo(4); } } @Test public void test() { JadxAssertions.assertThat(getClassNode(TestCls.class)) .code() .containsOne("ONE(1)") .containsOne("Numbers(int n) {"); // assertThat(code, containsOne("THREE(three)")); // assertThat(code, containsOne("assertTrue(Numbers.ONE.getNum() == 1);")); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums9.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums9.java
package jadx.tests.integration.enums; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnums9 extends IntegrationTest { public static class TestCls { public enum Types { INT, FLOAT, LONG, DOUBLE, OBJECT, ARRAY; private static Set<Types> primitives = EnumSet.of(INT, FLOAT, LONG, DOUBLE); public static List<Types> references = new ArrayList<>(); static { references.add(OBJECT); references.add(ARRAY); } public static Set<Types> getPrimitives() { return primitives; } } public void check() { assertThat(Types.getPrimitives()).contains(Types.INT); assertThat(Types.references).hasSize(2); } } @Test public void test() { assertThat(getClassNode(TestCls.class)) .code() .doesNotContain("EnumSet.of((Enum) INT,"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums10.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums10.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; /** * Some enum field was removed, but still exist in values array */ public class TestEnums10 extends SmaliTest { @Test public void test() { assertThat(getClassNodeFromSmali()) .code() .doesNotContain("Failed to restore enum class") .containsOne("enum TestEnums10 {") .countString(4, "Fake field"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums7.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums7.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnums7 extends IntegrationTest { public static class TestCls { public enum Numbers { ZERO, ONE; private final int n; Numbers() { this.n = this.name().equals("ZERO") ? 0 : 1; } public int getN() { return n; } } public void check() { assertThat(Numbers.ZERO.getN()).isEqualTo(0); assertThat(Numbers.ONE.getN()).isEqualTo(1); } } @Test public void test() { assertThat(getClassNode(TestCls.class)) .code() .containsOne("ZERO,") .containsOne("ONE;") .containsOne("Numbers() {"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithConsts.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithConsts.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnumsWithConsts extends IntegrationTest { public static class TestCls { public static final int C1 = 1; public static final int C2 = 2; public static final int C4 = 4; public static final String S = "NORTH"; public enum Direction { NORTH, SOUTH, EAST, WEST } } @Test public void test() { assertThat(getClassNode(TestCls.class)) .code() .containsLines(1, "public enum Direction {", indent(1) + "NORTH,", indent(1) + "SOUTH,", indent(1) + "EAST,", indent(1) + "WEST", "}"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums8.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums8.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnums8 extends SmaliTest { @Test public void test() { assertThat(getClassNodeFromSmali()) .code() .containsOne("enum TestEnums8"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums2.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums2.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.api.CommentsLevel; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnums2 extends IntegrationTest { public static class TestCls { public enum Operation { PLUS { @Override public int apply(int x, int y) { return x + y; } }, MINUS { @Override public int apply(int x, int y) { return x - y; } }; public abstract int apply(int x, int y); } } @Test public void test() { getArgs().setCommentsLevel(CommentsLevel.WARN); assertThat(getClassNode(TestCls.class)) .code() .containsLines(1, "public enum Operation {", indent(1) + "PLUS {", indent(2) + "@Override", indent(2) + "public int apply(int x, int y) {", indent(3) + "return x + y;", indent(2) + '}', indent(1) + "},", indent(1) + "MINUS {", indent(2) + "@Override", indent(2) + "public int apply(int x, int y) {", indent(3) + "return x - y;", indent(2) + '}', indent(1) + "};", "", indent(1) + "public abstract int apply(int i, int i2);", "}"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithCustomInit.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithCustomInit.java
package jadx.tests.integration.enums; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnumsWithCustomInit extends IntegrationTest { public enum TestCls { ONE("I"), TWO("II"), THREE("III"); public static final Map<String, TestCls> MAP = new HashMap<>(); static { for (TestCls value : values()) { MAP.put(value.toString(), value); } } private final String str; TestCls(String str) { this.str = str; } public String toString() { return str; } } @Test public void test() { assertThat(getClassNode(TestCls.class)) .code() .containsOne("ONE(\"I\"),") .doesNotContain("new TestEnumsWithCustomInit$TestCls("); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums6.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnums6.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; public class TestEnums6 extends IntegrationTest { public static class TestCls { public enum Numbers { ZERO, ONE(1); private final int n; Numbers() { this(0); } Numbers(int n) { this.n = n; } public int getN() { return n; } } public void check() { assertThat(TestCls.Numbers.ZERO.getN()).isEqualTo(0); assertThat(TestCls.Numbers.ONE.getN()).isEqualTo(1); } } @Test public void test() { assertThat(getClassNode(TestCls.class)) .code() .containsOne("ZERO,") .containsOne("Numbers() {") .containsOne("ONE(1);"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithStaticFields.java
jadx-core/src/test/java/jadx/tests/integration/enums/TestEnumsWithStaticFields.java
package jadx.tests.integration.enums; import org.junit.jupiter.api.Test; import jadx.tests.api.SmaliTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestEnumsWithStaticFields extends SmaliTest { @Test public void test() { disableCompilation(); assertThat(getClassNodeFromSmali()) .code() .containsOnlyOnce("INSTANCE;") .containsOnlyOnce("private static c sB") .doesNotContain(" sA") .doesNotContain(" sC") .doesNotContain("private TestEnumsWithStaticFields(String str) {"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/external/BaseExternalTest.java
jadx-core/src/test/java/jadx/tests/external/BaseExternalTest.java
package jadx.tests.external; import java.io.File; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.CommentsLevel; import jadx.api.ICodeInfo; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.api.JadxInternalAccess; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.tests.api.utils.TestUtils; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public abstract class BaseExternalTest extends TestUtils { private static final Logger LOG = LoggerFactory.getLogger(BaseExternalTest.class); protected JadxDecompiler decompiler; protected abstract String getSamplesDir(); protected JadxArgs prepare(String inputFile) { return prepare(new File(getSamplesDir(), inputFile)); } protected JadxArgs prepare(File input) { JadxArgs args = new JadxArgs(); args.getInputFiles().add(input); args.setOutDir(new File("../jadx-external-tests-tmp")); args.setSkipFilesSave(true); args.setSkipResources(true); args.setShowInconsistentCode(true); args.setCommentsLevel(CommentsLevel.DEBUG); return args; } protected JadxDecompiler decompile(JadxArgs jadxArgs) { return decompile(jadxArgs, null, null); } protected JadxDecompiler decompile(JadxArgs jadxArgs, String clsPatternStr) { return decompile(jadxArgs, clsPatternStr, null); } protected JadxDecompiler decompile(JadxArgs jadxArgs, @Nullable String clsPatternStr, @Nullable String mthPatternStr) { decompiler = new JadxDecompiler(jadxArgs); decompiler.load(); if (clsPatternStr == null) { decompiler.save(); } else { processByPatterns(decompiler, clsPatternStr, mthPatternStr); } printErrorReport(decompiler); return decompiler; } private void processByPatterns(JadxDecompiler jadx, String clsPattern, @Nullable String mthPattern) { RootNode root = JadxInternalAccess.getRoot(jadx); int processed = 0; for (ClassNode classNode : root.getClasses(true)) { String clsFullName = classNode.getClassInfo().getFullName(); if (clsFullName.equals(clsPattern)) { if (processCls(mthPattern, classNode)) { processed++; } } } assertThat(processed).as("No classes processed").isGreaterThan(0); } private boolean processCls(@Nullable String mthPattern, ClassNode classNode) { classNode.load(); boolean decompile = false; if (mthPattern == null) { decompile = true; } else { for (MethodNode mth : classNode.getMethods()) { if (isMthMatch(mth, mthPattern)) { decompile = true; break; } } } if (!decompile) { return false; } try { classNode.decompile(); } catch (Exception e) { throw new JadxRuntimeException("Class process failed", e); } LOG.info("----------------------------------------------------------------"); LOG.info("Print class: {} from: {}", classNode.getFullName(), classNode.getInputFileName()); if (mthPattern != null) { printMethods(classNode, mthPattern); } else { LOG.info("Code: \n{}", classNode.getCode()); } checkCode(classNode, false); return true; } private boolean isMthMatch(MethodNode mth, String mthPattern) { String shortId = mth.getMethodInfo().getShortId(); return isMatch(shortId, mthPattern); } private boolean isMatch(String str, String pattern) { if (str.equals(pattern)) { return true; } return str.startsWith(pattern); } private void printMethods(ClassNode classNode, @NotNull String mthPattern) { ICodeInfo codeInfo = classNode.getCode(); String code = codeInfo.getCodeStr(); if (code == null) { return; } String dashLine = "======================================================================================"; for (MethodNode mth : classNode.getMethods()) { if (isMthMatch(mth, mthPattern)) { LOG.info("Print method: {}\n{}\n{}\n{}", mth.getMethodInfo().getRawFullId(), dashLine, mth.getCodeStr(), dashLine); } } } private void printErrorReport(JadxDecompiler jadx) { jadx.printErrorsReport(); assertThat(jadx.getErrorsCount()).isEqualTo(0); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/RaungTest.java
jadx-core/src/test/java/jadx/tests/api/RaungTest.java
package jadx.tests.api; import java.io.File; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import jadx.api.JadxInternalAccess; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.RootNode; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; public abstract class RaungTest extends IntegrationTest { private static final String RAUNG_TESTS_PROJECT = "jadx-core"; private static final String RAUNG_TESTS_DIR = "src/test/raung"; private static final String RAUNG_TESTS_EXT = ".raung"; @BeforeEach public void init() { super.init(); this.useJavaInput(); } /** * Preferred method for one file raung test */ protected ClassNode getClassNodeFromRaung() { String pkg = getTestPkg(); String clsName = getTestName(); return getClassNodeFromRaung(pkg + File.separatorChar + clsName, pkg + '.' + clsName); } protected ClassNode getClassNodeFromRaung(String file, String clsName) { File raungFile = getRaungFile(file); return getClassNodeFromFiles(Collections.singletonList(raungFile), clsName); } protected List<ClassNode> loadFromRaungFiles() { jadxDecompiler = loadFiles(collectRaungFiles(getTestPkg(), getTestName())); RootNode root = JadxInternalAccess.getRoot(jadxDecompiler); List<ClassNode> classes = root.getClasses(false); decompileAndCheck(classes); return classes; } private List<File> collectRaungFiles(String pkg, String testDir) { String raungFilesDir = pkg + File.separatorChar + testDir + File.separatorChar; File raungDir = getRaungDir(raungFilesDir); String[] raungFileNames = raungDir.list((dir, name) -> name.endsWith(".raung")); assertThat(raungFileNames).as("Raung files not found in " + raungDir).isNotNull(); return Stream.of(raungFileNames) .map(file -> new File(raungDir, file)) .collect(Collectors.toList()); } private static File getRaungFile(String baseName) { File raungFile = new File(RAUNG_TESTS_DIR, baseName + RAUNG_TESTS_EXT); if (raungFile.exists()) { return raungFile; } File pathFromRoot = new File(RAUNG_TESTS_PROJECT, raungFile.getPath()); if (pathFromRoot.exists()) { return pathFromRoot; } throw new AssertionError("Raung file not found: " + raungFile.getPath()); } private static File getRaungDir(String baseName) { File raungDir = new File(RAUNG_TESTS_DIR, baseName); if (raungDir.exists()) { return raungDir; } File pathFromRoot = new File(RAUNG_TESTS_PROJECT, raungDir.getPath()); if (pathFromRoot.exists()) { return pathFromRoot; } throw new AssertionError("Raung dir not found: " + raungDir.getPath()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/IntegrationTest.java
jadx-core/src/test/java/jadx/tests/api/IntegrationTest.java
package jadx.tests.api; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.CommentsLevel; import jadx.api.DecompilationMode; import jadx.api.ICodeInfo; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.api.JadxInternalAccess; import jadx.api.JavaClass; import jadx.api.JavaMethod; import jadx.api.JavaVariable; import jadx.api.ResourceFile; import jadx.api.ResourceType; import jadx.api.ResourcesLoader; import jadx.api.args.GeneratedRenamesMappingFileMode; import jadx.api.data.IJavaNodeRef; import jadx.api.data.impl.JadxCodeData; import jadx.api.data.impl.JadxCodeRename; import jadx.api.data.impl.JadxNodeRef; import jadx.api.impl.SimpleCodeInfo; import jadx.api.metadata.ICodeMetadata; import jadx.api.metadata.annotations.InsnCodeOffset; import jadx.api.metadata.annotations.VarNode; import jadx.api.plugins.CustomResourcesLoader; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.core.xmlgen.BinaryXMLStrings; import jadx.core.xmlgen.IResTableParser; import jadx.core.xmlgen.ResContainer; import jadx.core.xmlgen.ResourceStorage; import jadx.core.xmlgen.entry.ResourceEntry; import jadx.tests.api.compiler.CompilerOptions; import jadx.tests.api.compiler.JavaUtils; import jadx.tests.api.compiler.TestCompiler; import jadx.tests.api.utils.TestFilesGetter; import jadx.tests.api.utils.TestUtils; import static org.apache.commons.lang3.StringUtils.leftPad; import static org.apache.commons.lang3.StringUtils.rightPad; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public abstract class IntegrationTest extends TestUtils { private static final Logger LOG = LoggerFactory.getLogger(IntegrationTest.class); private static final String TEST_DIRECTORY = "src/test/java"; private static final String TEST_DIRECTORY2 = "jadx-core/" + TEST_DIRECTORY; private static final String DEFAULT_INPUT_PLUGIN = "dx"; /** * Set 'TEST_INPUT_PLUGIN' env variable to use 'java' or 'dx' input in tests */ static final boolean USE_JAVA_INPUT = Utils.getOrElse(System.getenv("TEST_INPUT_PLUGIN"), DEFAULT_INPUT_PLUGIN).equals("java"); /** * Run auto check method if defined: * * <pre> * public void check() { * } * </pre> */ private static final String CHECK_METHOD_NAME = "check"; protected JadxArgs args; protected boolean compile; private CompilerOptions compilerOptions; private boolean saveTestJar = false; protected Map<Integer, String> resMap = Collections.emptyMap(); private boolean allowWarnInCode; private boolean printLineNumbers; private boolean printOffsets; private boolean printDisassemble; private @Nullable Boolean useJavaInput; private boolean removeParentClassOnInput; private @Nullable TestCompiler sourceCompiler; private @Nullable TestCompiler decompiledCompiler; /** * Run check method on decompiled code even if source check method not found. * Useful for smali test if check method added to smali code */ private boolean forceDecompiledCheck = false; protected JadxDecompiler jadxDecompiler; @TempDir Path testDir; @BeforeEach public void init() { this.compile = true; this.compilerOptions = new CompilerOptions(); this.resMap = Collections.emptyMap(); this.removeParentClassOnInput = true; this.useJavaInput = null; args = new JadxArgs(); args.setOutDir(testDir.toFile()); args.setShowInconsistentCode(true); args.setThreadsCount(1); args.setSkipResources(true); args.setCommentsLevel(CommentsLevel.DEBUG); args.setDeobfuscationOn(false); args.setGeneratedRenamesMappingFileMode(GeneratedRenamesMappingFileMode.IGNORE); args.setRunDebugChecks(true); args.setFilesGetter(new TestFilesGetter(testDir)); // use the same values on all systems args.setFsCaseSensitive(false); args.setCodeNewLineStr("\n"); args.setCodeIndentStr(JadxArgs.DEFAULT_INDENT_STR); } @AfterEach public void after() throws IOException { close(jadxDecompiler); close(sourceCompiler); close(decompiledCompiler); } private void close(Closeable closeable) throws IOException { if (closeable != null) { closeable.close(); } } public void setOutDirSuffix(String suffix) { args.setOutDir(new File(testDir.toFile(), suffix)); } public String getTestName() { return this.getClass().getSimpleName(); } public String getTestPkg() { return this.getClass().getPackage().getName().replace("jadx.tests.integration.", ""); } public ClassNode getClassNode(Class<?> clazz) { try { List<File> files = compileClass(clazz); assertThat(files).as("File list is empty").isNotEmpty(); return getClassNodeFromFiles(files, clazz.getName()); } catch (Exception e) { LOG.error("Failed to get class node", e); fail(e.getMessage()); return null; } } public List<ClassNode> getClassNodes(Class<?>... classes) { try { assertThat(classes).as("Class list is empty").isNotEmpty(); List<File> srcFiles = Stream.of(classes).map(this::getSourceFileForClass).collect(Collectors.toList()); List<File> clsFiles = compileSourceFiles(srcFiles); assertThat(clsFiles).as("Class files list is empty").isNotEmpty(); return decompileFiles(clsFiles); } catch (Exception e) { LOG.error("Failed to get class node", e); fail(e.getMessage()); return null; } } public ClassNode getClassNodeFromFiles(List<File> files, String clsName) { jadxDecompiler = loadFiles(files); RootNode root = JadxInternalAccess.getRoot(jadxDecompiler); ClassNode cls = root.resolveClass(clsName); assertThat(cls).as("Class not found: " + clsName).isNotNull(); if (removeParentClassOnInput) { assertThat(clsName).isEqualTo(cls.getClassInfo().getFullName()); } else { LOG.info("Convert back to top level: {}", cls); cls.getTopParentClass().decompile(); // keep correct process order cls.notInner(); } decompileAndCheck(cls); return cls; } public List<ClassNode> decompileFiles(List<File> files) { jadxDecompiler = loadFiles(files); List<ClassNode> sortedClsNodes = jadxDecompiler.getDecompileScheduler() .buildBatches(jadxDecompiler.getClasses()) .stream() .flatMap(Collection::stream) .map(JavaClass::getClassNode) .collect(Collectors.toList()); decompileAndCheck(sortedClsNodes); return sortedClsNodes; } @NotNull public ClassNode searchTestCls(List<ClassNode> list, String shortClsName) { return searchCls(list, getTestPkg() + '.' + shortClsName); } @NotNull public ClassNode searchCls(List<ClassNode> list, String clsName) { for (ClassNode cls : list) { if (cls.getClassInfo().getFullName().equals(clsName)) { return cls; } } for (ClassNode cls : list) { if (cls.getClassInfo().getShortName().equals(clsName)) { return cls; } } fail("Class not found by name " + clsName + " in list: " + list); return null; } protected JadxDecompiler loadFiles(List<File> inputFiles) { args.setInputFiles(inputFiles); boolean useDx = !isJavaInput(); LOG.info(useDx ? "Using dex input" : "Using java input"); args.setUseDxInput(useDx); JadxDecompiler d = new JadxDecompiler(args); try { insertResources(d); d.load(); return d; } catch (Exception e) { LOG.error("Load failed", e); d.close(); fail(e.getMessage()); return null; } } protected void decompileAndCheck(ClassNode cls) { decompileAndCheck(Collections.singletonList(cls)); } protected void decompileAndCheck(List<ClassNode> clsList) { clsList.forEach(cls -> cls.add(AFlag.DONT_UNLOAD_CLASS)); // keep error and warning attributes clsList.forEach(ClassNode::decompile); for (ClassNode cls : clsList) { System.out.println("-----------------------------------------------------------"); ICodeInfo code = cls.getCode(); if (printLineNumbers) { printCodeWithLineNumbers(code); } else if (printOffsets) { printCodeWithOffsets(code); } else { System.out.println(code); } } System.out.println("-----------------------------------------------------------"); if (printDisassemble) { clsList.forEach(this::printDisasm); } runChecks(clsList); } public void runChecks(ClassNode cls) { runChecks(Collections.singletonList(cls)); } protected void runChecks(List<ClassNode> clsList) { clsList.forEach(cls -> checkCode(cls, allowWarnInCode)); compileClassNode(clsList); clsList.forEach(this::runAutoCheck); } private void printDisasm(ClassNode cls) { System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(cls.getDisassembledCode()); System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); } private void printCodeWithLineNumbers(ICodeInfo code) { String codeStr = code.getCodeStr(); Map<Integer, Integer> lineMapping = code.getCodeMetadata().getLineMapping(); String[] lines = codeStr.split("\\R"); for (int i = 0; i < lines.length; i++) { String line = lines[i]; int curLine = i + 1; String lineNumStr = "/* " + leftPad(String.valueOf(curLine), 3) + " */"; Integer sourceLine = lineMapping.get(curLine); if (sourceLine != null) { lineNumStr += " /* " + sourceLine + " */"; } System.out.println(rightPad(lineNumStr, 20) + line); } } private void printCodeWithOffsets(ICodeInfo code) { String codeStr = code.getCodeStr(); ICodeMetadata metadata = code.getCodeMetadata(); int lineStartPos = 0; String newLineStr = args.getCodeNewLineStr(); int newLineLen = newLineStr.length(); for (String line : codeStr.split(newLineStr)) { Object ann = metadata.getAt(lineStartPos); String offsetStr = ""; if (ann instanceof InsnCodeOffset) { int offset = ((InsnCodeOffset) ann).getOffset(); offsetStr = "/* " + leftPad(String.valueOf(offset), 5) + " */"; } System.out.println(rightPad(offsetStr, 12) + line); lineStartPos += line.length() + newLineLen; } } /** * Insert mock resource table data ('.arsc' file) */ private void insertResources(JadxDecompiler decompiler) throws IOException { if (resMap.isEmpty()) { return; } String resTableName = "test-res-table"; Path resTablePath = testDir.resolve(resTableName); File resTableFile = resTablePath.toFile().getAbsoluteFile(); FileUtils.makeDirsForFile(resTableFile); Files.writeString(resTablePath, resTableName); JadxArgs jadxArgs = decompiler.getArgs(); jadxArgs.getInputFiles().add(resTableFile); // load mock file as 'arsc' decompiler.addCustomResourcesLoader(new CustomResourcesLoader() { @Override public boolean load(ResourcesLoader loader, List<ResourceFile> list, File file) { if (file == resTableFile) { list.add(ResourceFile.createResourceFile(decompiler, resTableFile, ResourceType.ARSC)); return true; } return false; } @Override public void close() { } }); // convert resources map to resource storage object ResourceStorage resStorage = new ResourceStorage(jadxArgs.getSecurity()); for (Map.Entry<Integer, String> entry : resMap.entrySet()) { Integer id = entry.getKey(); String name = entry.getValue(); String[] parts = name.split("\\."); resStorage.add(new ResourceEntry(id, "", parts[0], parts[1], "")); } // mock res table parser to just return resource storage IResTableParser resTableParser = new IResTableParser() { @Override public void decode(InputStream inputStream) { } @Override public ResourceStorage getResStorage() { return resStorage; } @Override public ResContainer decodeFiles() { return ResContainer.textResource(resTableName, new SimpleCodeInfo(resTableName)); } @Override public BinaryXMLStrings getStrings() { return new BinaryXMLStrings(); } }; // directly return generated resource storage instead parsing for mock res file decompiler.getResourcesLoader().addResTableParserProvider(resFile -> { if (resFile.getOriginalName().equals(resTableFile.getAbsolutePath())) { return resTableParser; } return null; }); } private void runAutoCheck(ClassNode cls) { String clsName = cls.getClassInfo().getRawName().replace('/', '.'); try { // run 'check' method from original class boolean sourceCheckFound = runSourceAutoCheck(clsName); // run 'check' method from decompiled class if (compile && (sourceCheckFound || forceDecompiledCheck)) { runDecompiledAutoCheck(cls); } } catch (Exception e) { LOG.error("Auto check failed", e); fail("Auto check exception: " + e.getMessage()); } } private boolean runSourceAutoCheck(String clsName) { if (sourceCompiler == null) { System.out.println("Source check: no code"); return false; } Class<?> origCls; try { origCls = sourceCompiler.getClass(clsName); } catch (ClassNotFoundException e) { rethrow("Missing class: " + clsName, e); return false; } Method checkMth; try { checkMth = sourceCompiler.getMethod(origCls, CHECK_METHOD_NAME, new Class[] {}); } catch (NoSuchMethodException e) { // ignore return false; } if (!checkMth.getReturnType().equals(void.class) || !Modifier.isPublic(checkMth.getModifiers()) || Modifier.isStatic(checkMth.getModifiers())) { fail("Wrong 'check' method"); return false; } try { limitExecTime(() -> checkMth.invoke(origCls.getConstructor().newInstance())); System.out.println("Source check: PASSED"); return true; } catch (Throwable e) { throw new JadxRuntimeException("Source check failed", e); } } public void runDecompiledAutoCheck(ClassNode cls) { try { limitExecTime(() -> invoke(decompiledCompiler, cls.getFullName(), CHECK_METHOD_NAME)); System.out.println("Decompiled check: PASSED"); } catch (Throwable e) { rethrow("Decompiled check failed", e); } } private <T> T limitExecTime(Callable<T> call) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<T> future = executor.submit(call); try { return future.get(5, TimeUnit.SECONDS); } catch (TimeoutException ex) { future.cancel(true); rethrow("Execution timeout", ex); } catch (Throwable ex) { rethrow(ex.getMessage(), ex); } finally { executor.shutdownNow(); } return null; } public static void rethrow(String msg, Throwable e) { if (e instanceof InvocationTargetException) { rethrow(msg, e.getCause()); } else if (e instanceof ExecutionException) { rethrow(msg, e.getCause()); } else if (e instanceof AssertionError) { System.err.println(msg); throw (AssertionError) e; } else { throw new RuntimeException(msg, e); } } protected MethodNode getMethod(ClassNode cls, String methodName) { for (MethodNode mth : cls.getMethods()) { if (mth.getName().equals(methodName)) { return mth; } } fail("Method not found " + methodName + " in class " + cls); return null; } protected FieldNode getField(ClassNode cls, String fieldName) { for (FieldNode fld : cls.getFields()) { if (fld.getName().equals(fieldName)) { return fld; } } fail("Field not found " + fieldName + " in class " + cls); return null; } void compileClassNode(List<ClassNode> clsList) { if (!compile) { return; } try { // TODO: eclipse uses files or compilation units providers added in Java 9 compilerOptions.setUseEclipseCompiler(false); decompiledCompiler = new TestCompiler(compilerOptions); decompiledCompiler.compileNodes(clsList); System.out.println("Compilation: PASSED"); } catch (Exception e) { fail(e); } } public Object invoke(TestCompiler compiler, String clsFullName, String method) throws Exception { assertThat(compiler).as("compiler not ready").isNotNull(); return compiler.invoke(clsFullName, method, new Class<?>[] {}, new Object[] {}); } private List<File> compileClass(Class<?> cls) throws IOException { File sourceFile = getSourceFileForClass(cls); List<File> clsFiles = compileSourceFiles(Collections.singletonList(sourceFile)); if (removeParentClassOnInput) { // remove classes which are parents for test class String clsFullName = cls.getName(); String clsName = clsFullName.substring(clsFullName.lastIndexOf('.') + 1); clsFiles.removeIf(next -> !next.getName().contains(clsName)); } return clsFiles; } private File getSourceFileForClass(Class<?> cls) { String clsFullName = cls.getName(); int innerEnd = clsFullName.indexOf('$'); String rootClsName = innerEnd == -1 ? clsFullName : clsFullName.substring(0, innerEnd); String javaFileName = rootClsName.replace('.', '/') + ".java"; File file = new File(TEST_DIRECTORY, javaFileName); if (file.exists()) { return file; } File file2 = new File(TEST_DIRECTORY2, javaFileName); if (file2.exists()) { return file2; } throw new JadxRuntimeException("Test source not found for class: " + clsFullName); } private List<File> compileSourceFiles(List<File> compileFileList) throws IOException { Path outTmp = Files.createTempDirectory(testDir, "jadx-tmp-classes"); sourceCompiler = new TestCompiler(compilerOptions); List<File> files = sourceCompiler.compileFiles(compileFileList, outTmp); if (saveTestJar) { saveToJar(files, outTmp); } return files; } private void saveToJar(List<File> files, Path baseDir) throws IOException { Path jarFile = Files.createTempFile("tests-" + getTestName() + '-', ".jar"); try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(jarFile))) { for (File file : files) { Path fullPath = file.toPath(); Path relativePath = baseDir.relativize(fullPath); JarEntry entry = new JarEntry(relativePath.toString()); jar.putNextEntry(entry); jar.write(Files.readAllBytes(fullPath)); jar.closeEntry(); } } LOG.info("Test jar saved to: {}", jarFile.toAbsolutePath()); } public JadxArgs getArgs() { return args; } public CompilerOptions getCompilerOptions() { return compilerOptions; } public void setArgs(JadxArgs args) { this.args = args; } public void setResMap(Map<Integer, String> resMap) { this.resMap = resMap; } protected void noDebugInfo() { this.compilerOptions.setIncludeDebugInfo(false); } public void useEclipseCompiler() { Assumptions.assumeTrue(JavaUtils.checkJavaVersion(11), "eclipse compiler library using Java 11"); this.compilerOptions.setUseEclipseCompiler(true); } public void useTargetJavaVersion(int version) { Assumptions.assumeTrue(JavaUtils.checkJavaVersion(version), "skip test for higher java version"); this.compilerOptions.setJavaVersion(version); } protected void setFallback() { disableCompilation(); this.args.setDecompilationMode(DecompilationMode.FALLBACK); } protected void disableCompilation() { this.compile = false; } protected void forceDecompiledCheck() { this.forceDecompiledCheck = true; } protected void enableDeobfuscation() { args.setDeobfuscationOn(true); args.setGeneratedRenamesMappingFileMode(GeneratedRenamesMappingFileMode.IGNORE); args.setDeobfuscationMinLength(2); args.setDeobfuscationMaxLength(64); } protected void allowWarnInCode() { allowWarnInCode = true; } protected void printLineNumbers() { printLineNumbers = true; } protected void printOffsets() { printOffsets = true; } public void useJavaInput() { this.useJavaInput = true; } public void useDexInput() { Assumptions.assumeFalse(USE_JAVA_INPUT, "skip dex input tests"); this.useJavaInput = false; } public void useDexInput(String mode) { useDexInput(); this.getArgs().getPluginOptions().put("java-convert.mode", mode); } protected boolean isJavaInput() { return Utils.getOrElse(useJavaInput, USE_JAVA_INPUT); } public void keepParentClassOnInput() { this.removeParentClassOnInput = false; } // Use only for debug purpose protected void printDisassemble() { this.printDisassemble = true; } // Use only for debug purpose protected void saveTestJar() { this.saveTestJar = true; } protected void addClsRename(String fullClsName, String newName) { JadxNodeRef clsRef = JadxNodeRef.forCls(fullClsName); getCodeData().getRenames().add(new JadxCodeRename(clsRef, newName)); } protected void addMthRename(String fullClsName, String mthSignature, String newName) { JadxNodeRef mthRef = new JadxNodeRef(IJavaNodeRef.RefType.METHOD, fullClsName, mthSignature); getCodeData().getRenames().add(new JadxCodeRename(mthRef, newName)); } protected void addFldRename(String fullClsName, String fldSignature, String newName) { JadxNodeRef fldRef = new JadxNodeRef(IJavaNodeRef.RefType.FIELD, fullClsName, fldSignature); getCodeData().getRenames().add(new JadxCodeRename(fldRef, newName)); } protected JadxCodeData getCodeData() { JadxCodeData codeData = (JadxCodeData) getArgs().getCodeData(); if (codeData == null) { codeData = new JadxCodeData(); codeData.setRenames(new ArrayList<>()); codeData.setComments(new ArrayList<>()); getArgs().setCodeData(codeData); } return codeData; } protected JavaClass toJavaClass(ClassNode cls) { JavaClass javaClass = JadxInternalAccess.convertClassNode(jadxDecompiler, cls); assertThat(javaClass).isNotNull(); return javaClass; } protected JavaMethod toJavaMethod(MethodNode mth) { JavaMethod javaMethod = JadxInternalAccess.convertMethodNode(jadxDecompiler, mth); assertThat(javaMethod).isNotNull(); return javaMethod; } protected JavaVariable toJavaVariable(VarNode varNode) { JavaVariable javaVariable = (JavaVariable) jadxDecompiler.getJavaNodeByCodeAnnotation(null, varNode); assertThat(javaVariable).isNotNull(); return javaVariable; } public File getResourceFile(String filePath) { URL resource = getClass().getClassLoader().getResource(filePath); assertThat(resource).as("Resource not found: %s", filePath).isNotNull(); String resPath = resource.getFile(); return new File(resPath); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/ExportGradleTest.java
jadx-core/src/test/java/jadx/tests/api/ExportGradleTest.java
package jadx.tests.api; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import org.junit.jupiter.api.io.TempDir; import jadx.api.ICodeInfo; import jadx.api.JadxArgs; import jadx.api.ResourceFile; import jadx.api.ResourceFileContainer; import jadx.api.ResourceFileContent; import jadx.api.ResourceType; import jadx.api.impl.SimpleCodeInfo; import jadx.core.dex.nodes.RootNode; import jadx.core.export.ExportGradle; import jadx.core.export.ExportGradleType; import jadx.core.export.OutDirs; import jadx.core.xmlgen.ResContainer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public abstract class ExportGradleTest { private static final String MANIFEST_TESTS_DIR = "manifest"; private final RootNode root = new RootNode(new JadxArgs()); @TempDir private File exportDir; protected ICodeInfo loadResource(String filename) { return new SimpleCodeInfo(loadResourceContent(MANIFEST_TESTS_DIR, filename)); } private static String loadFileContent(File filePath) { try { return Files.readString(filePath.toPath()); } catch (IOException e) { fail("Loading file failed", e); return ""; } } private String loadResourceContent(String dir, String filename) { String resPath = dir + '/' + filename; try (InputStream in = getClass().getClassLoader().getResourceAsStream(resPath)) { if (in == null) { fail("Resource not found: " + resPath); return ""; } return new String(in.readAllBytes(), StandardCharsets.UTF_8); } catch (Exception e) { fail("Loading file failed: " + resPath, e); return ""; } } protected RootNode getRootNode() { return root; } protected void exportGradle(String manifestFilename, String stringsFileName) { ResourceFile androidManifest = new ResourceFileContent("AndroidManifest.xml", ResourceType.MANIFEST, loadResource(manifestFilename)); ResContainer strings = ResContainer.textResource(stringsFileName, loadResource(stringsFileName)); ResContainer arsc = ResContainer.resourceTable("resources.arsc", List.of(strings), new SimpleCodeInfo("empty")); ResourceFile arscFile = new ResourceFileContainer("resources.arsc", ResourceType.ARSC, arsc); List<ResourceFile> resources = List.of(androidManifest, arscFile); root.getArgs().setExportGradleType(ExportGradleType.ANDROID_APP); ExportGradle export = new ExportGradle(root, exportDir, resources); OutDirs outDirs = export.init(); assertThat(outDirs.getSrcOutDir()).exists(); assertThat(outDirs.getResOutDir()).exists(); export.generateGradleFiles(); } protected String getAppGradleBuild() { return loadFileContent(new File(exportDir, "app/build.gradle")); } protected String getSettingsGradle() { return loadFileContent(new File(exportDir, "settings.gradle")); } protected File getGradleProperiesFile() { return new File(exportDir, "gradle.properties"); } protected String getGradleProperties() { return loadFileContent(getGradleProperiesFile()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/SmaliTest.java
jadx-core/src/test/java/jadx/tests/api/SmaliTest.java
package jadx.tests.api; import java.io.File; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import jadx.api.JadxInternalAccess; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.RootNode; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; public abstract class SmaliTest extends IntegrationTest { private static final String SMALI_TESTS_DIR = "src/test/smali"; private static final String SMALI_TESTS_EXT = ".smali"; private String currentProject = "jadx-core"; public void setCurrentProject(String currentProject) { this.currentProject = currentProject; } @BeforeEach public void init() { Assumptions.assumeFalse(USE_JAVA_INPUT, "skip smali test for java input tests"); super.init(); this.useDexInput(); } protected ClassNode getClassNodeFromSmali(String file, String clsName) { File smaliFile = getSmaliFile(file); return getClassNodeFromFiles(Collections.singletonList(smaliFile), clsName); } /** * Preferred method for one file smali test */ protected ClassNode getClassNodeFromSmali() { return getClassNodeFromSmaliWithPkg(getTestPkg(), getTestName()); } protected ClassNode getClassNodeFromSmaliWithClsName(String fullClsName) { return getClassNodeFromSmali(getTestPkg() + File.separatorChar + getTestName(), fullClsName); } protected ClassNode getClassNodeFromSmaliWithPath(String path, String clsName) { return getClassNodeFromSmali(path + File.separatorChar + clsName, clsName); } protected ClassNode getClassNodeFromSmaliWithPkg(String pkg, String clsName) { return getClassNodeFromSmali(pkg + File.separatorChar + clsName, pkg + '.' + clsName); } protected ClassNode getClassNodeFromSmaliFiles(String pkg, String testName, String clsName) { return getClassNodeFromFiles(collectSmaliFiles(pkg, testName), pkg + '.' + clsName); } protected ClassNode getClassNodeFromSmaliFiles(String clsName) { return searchCls(loadFromSmaliFiles(), getTestPkg() + '.' + clsName); } protected ClassNode getClassNodeFromSmaliFiles() { return searchCls(loadFromSmaliFiles(), getTestPkg() + '.' + getTestName()); } protected List<ClassNode> loadFromSmaliFiles() { jadxDecompiler = loadFiles(collectSmaliFiles(getTestPkg(), getTestName())); RootNode root = JadxInternalAccess.getRoot(jadxDecompiler); List<ClassNode> classes = root.getClasses(false); decompileAndCheck(classes); return classes; } private List<File> collectSmaliFiles(String pkg, @Nullable String testDir) { String smaliFilesDir; if (testDir == null) { smaliFilesDir = pkg + File.separatorChar; } else { smaliFilesDir = pkg + File.separatorChar + testDir + File.separatorChar; } File smaliDir = getSmaliDir(smaliFilesDir); String[] smaliFileNames = smaliDir.list((dir, name) -> name.endsWith(".smali")); assertThat(smaliFileNames).as("Smali files not found in " + smaliDir).isNotNull(); return Stream.of(smaliFileNames) .map(file -> new File(smaliDir, file)) .collect(Collectors.toList()); } private File getSmaliFile(String baseName) { File smaliFile = new File(SMALI_TESTS_DIR, baseName + SMALI_TESTS_EXT); if (smaliFile.exists()) { return smaliFile; } File pathFromRoot = new File(currentProject, smaliFile.getPath()); if (pathFromRoot.exists()) { return pathFromRoot; } throw new AssertionError("Smali file not found: " + smaliFile.getPath()); } private File getSmaliDir(String baseName) { File smaliDir = new File(SMALI_TESTS_DIR, baseName); if (smaliDir.exists()) { return smaliDir; } File pathFromRoot = new File(currentProject, smaliDir.getPath()); if (pathFromRoot.exists()) { return pathFromRoot; } throw new AssertionError("Smali dir not found: " + smaliDir.getPath()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/extensions/profiles/JadxTestProfilesExtension.java
jadx-core/src/test/java/jadx/tests/api/extensions/profiles/JadxTestProfilesExtension.java
package jadx.tests.api.extensions.profiles; import java.lang.reflect.Method; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; import org.junit.platform.commons.util.AnnotationUtils; import org.junit.platform.commons.util.Preconditions; import jadx.tests.api.IntegrationTest; import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated; public class JadxTestProfilesExtension implements TestTemplateInvocationContextProvider { @Override public boolean supportsTestTemplate(ExtensionContext context) { return isAnnotated(context.getTestMethod(), TestWithProfiles.class); } @Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext context) { Preconditions.condition(IntegrationTest.class.isAssignableFrom(context.getRequiredTestClass()), "@TestWithProfiles should be used only in IntegrationTest subclasses"); Method testMethod = context.getRequiredTestMethod(); boolean testAnnAdded = AnnotationUtils.findAnnotation(testMethod, Test.class).isPresent(); Preconditions.condition(!testAnnAdded, "@Test annotation should be removed"); TestWithProfiles profilesAnn = AnnotationUtils.findAnnotation(testMethod, TestWithProfiles.class).get(); EnumSet<TestProfile> profilesSet = EnumSet.noneOf(TestProfile.class); Collections.addAll(profilesSet, profilesAnn.value()); if (profilesSet.contains(TestProfile.ALL)) { Collections.addAll(profilesSet, TestProfile.values()); } profilesSet.remove(TestProfile.ALL); return profilesSet.stream() .sorted() .map(RunWithProfile::new); } private static class RunWithProfile implements TestTemplateInvocationContext { private final TestProfile testProfile; public RunWithProfile(TestProfile testProfile) { this.testProfile = testProfile; } @Override public String getDisplayName(int invocationIndex) { return testProfile.getDescription(); } @Override public List<Extension> getAdditionalExtensions() { return Collections.singletonList(beforeTest()); } private BeforeTestExecutionCallback beforeTest() { return execContext -> testProfile.accept((IntegrationTest) execContext.getRequiredTestInstance()); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/extensions/profiles/TestProfile.java
jadx-core/src/test/java/jadx/tests/api/extensions/profiles/TestProfile.java
package jadx.tests.api.extensions.profiles; import java.util.function.Consumer; import jadx.tests.api.IntegrationTest; public enum TestProfile implements Consumer<IntegrationTest> { DX_J8("dx-j8", test -> { test.useTargetJavaVersion(8); test.useDexInput("dx"); }), D8_J8("d8-j8", test -> { test.useTargetJavaVersion(8); test.useDexInput("d8"); }), D8_J11("d8-j11", test -> { test.useTargetJavaVersion(11); test.useDexInput("d8"); }), D8_J11_DESUGAR("d8-j11-desugar", test -> { test.useTargetJavaVersion(11); test.useDexInput("d8"); test.keepParentClassOnInput(); test.getArgs().getPluginOptions().put("java-convert.d8-desugar", "yes"); }), JAVA8("java-8", test -> { test.useTargetJavaVersion(8); test.useJavaInput(); }), JAVA11("java-11", test -> { test.useTargetJavaVersion(11); test.useJavaInput(); }), JAVA17("java-17", test -> { test.useTargetJavaVersion(17); test.useJavaInput(); }), ECJ_DX_J8("ecj-dx-j8", test -> { test.useEclipseCompiler(); test.useTargetJavaVersion(8); test.useDexInput(); }), ECJ_J8("ecj-j8", test -> { test.useEclipseCompiler(); test.useTargetJavaVersion(8); test.useJavaInput(); }), ALL("all", null); private final String description; private final Consumer<IntegrationTest> setup; TestProfile(String description, Consumer<IntegrationTest> setup) { this.description = description; this.setup = setup; } @Override public void accept(IntegrationTest test) { this.setup.accept(test); test.setOutDirSuffix(description); } public String getDescription() { return description; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/extensions/profiles/TestWithProfiles.java
jadx-core/src/test/java/jadx/tests/api/extensions/profiles/TestWithProfiles.java
package jadx.tests.api.extensions.profiles; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; @TestTemplate @ExtendWith(JadxTestProfilesExtension.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface TestWithProfiles { TestProfile[] value(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/utils/TestUtils.java
jadx-core/src/test/java/jadx/tests/api/utils/TestUtils.java
package jadx.tests.api.utils; import java.io.File; import org.junit.jupiter.api.extension.ExtendWith; import jadx.NotYetImplementedExtension; import jadx.api.CommentsLevel; import jadx.api.JadxArgs; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.IAttributeNode; import jadx.core.dex.attributes.nodes.JadxCommentsAttr; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static org.assertj.core.api.Assertions.fail; @ExtendWith(NotYetImplementedExtension.class) public class TestUtils { public static String indent() { return JadxArgs.DEFAULT_INDENT_STR; } public static String indent(int indent) { if (indent == 1) { return JadxArgs.DEFAULT_INDENT_STR; } return Utils.strRepeat(JadxArgs.DEFAULT_INDENT_STR, indent); } public static int count(String string, String substring) { if (substring == null || substring.isEmpty()) { throw new IllegalArgumentException("Substring can't be null or empty"); } int count = 0; int idx = 0; while ((idx = string.indexOf(substring, idx)) != -1) { idx++; count++; } return count; } protected static void checkCode(ClassNode cls, boolean allowWarnInCode) { assertThat(hasErrors(cls, allowWarnInCode)).as("Inconsistent cls: " + cls).isFalse(); for (MethodNode mthNode : cls.getMethods()) { if (hasErrors(mthNode, allowWarnInCode)) { fail("Method with problems: " + mthNode + "\n " + Utils.listToString(mthNode.getAttributesStringsList(), "\n ")); } } if (!cls.contains(AFlag.DONT_GENERATE)) { assertThat(cls) .code() .doesNotContain("inconsistent") .doesNotContain("JADX ERROR"); } } protected static boolean hasErrors(IAttributeNode node, boolean allowWarnInCode) { if (node.contains(AFlag.INCONSISTENT_CODE) || node.contains(AType.JADX_ERROR)) { return true; } if (!allowWarnInCode) { JadxCommentsAttr commentsAttr = node.get(AType.JADX_COMMENTS); if (commentsAttr != null) { return commentsAttr.getComments().get(CommentsLevel.WARN) != null; } } return false; } public static File getFileForSample(String resPath) { try { return new File(ClassLoader.getSystemResource(resPath).toURI().getRawPath()); } catch (Exception e) { throw new JadxRuntimeException("Resource load failed: " + resPath, e); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/utils/TestFilesGetter.java
jadx-core/src/test/java/jadx/tests/api/utils/TestFilesGetter.java
package jadx.tests.api.utils; import java.nio.file.Path; import jadx.core.plugins.files.IJadxFilesGetter; import jadx.core.utils.files.FileUtils; public class TestFilesGetter implements IJadxFilesGetter { private final Path testDir; public TestFilesGetter(Path testDir) { this.testDir = testDir; } @Override public Path getConfigDir() { return makeSubDir("config"); } @Override public Path getCacheDir() { return makeSubDir("cache"); } @Override public Path getTempDir() { return testDir; } private Path makeSubDir(String config) { Path dir = testDir.resolve(config); FileUtils.makeDirs(dir); return dir; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxMethodNodeAssertions.java
jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxMethodNodeAssertions.java
package jadx.tests.api.utils.assertj; import org.assertj.core.api.AbstractObjectAssert; import jadx.core.dex.nodes.MethodNode; import static org.assertj.core.api.Assertions.assertThat; public class JadxMethodNodeAssertions extends AbstractObjectAssert<JadxMethodNodeAssertions, MethodNode> { public JadxMethodNodeAssertions(MethodNode mth) { super(mth, JadxMethodNodeAssertions.class); } public JadxCodeAssertions code() { isNotNull(); String codeStr = actual.getCodeStr(); assertThat(codeStr).isNotBlank(); return new JadxCodeAssertions(codeStr); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxClassNodeAssertions.java
jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxClassNodeAssertions.java
package jadx.tests.api.utils.assertj; import java.util.Map; import org.assertj.core.api.AbstractObjectAssert; import jadx.api.ICodeInfo; import jadx.api.metadata.ICodeAnnotation; import jadx.core.dex.nodes.ClassNode; import jadx.tests.api.IntegrationTest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class JadxClassNodeAssertions extends AbstractObjectAssert<JadxClassNodeAssertions, ClassNode> { public JadxClassNodeAssertions(ClassNode cls) { super(cls, JadxClassNodeAssertions.class); } public JadxCodeInfoAssertions decompile() { isNotNull(); ICodeInfo codeInfo = actual.getCode(); assertThat(codeInfo).isNotNull(); return new JadxCodeInfoAssertions(codeInfo); } public JadxCodeAssertions code() { isNotNull(); ICodeInfo code = actual.getCode(); assertThat(code).isNotNull(); String codeStr = code.getCodeStr(); assertThat(codeStr).isNotBlank(); return new JadxCodeAssertions(codeStr); } public JadxCodeAssertions disasmCode() { isNotNull(); String disasmCode = actual.getDisassembledCode(); assertThat(disasmCode).isNotNull().isNotBlank(); return new JadxCodeAssertions(disasmCode); } public JadxCodeAssertions reloadCode(IntegrationTest testInstance) { isNotNull(); ICodeInfo code = actual.reloadCode(); assertThat(code).isNotNull(); String codeStr = code.getCodeStr(); assertThat(codeStr).isNotBlank(); JadxCodeAssertions codeAssertions = new JadxCodeAssertions(codeStr); codeAssertions.print(); testInstance.runChecks(actual); return codeAssertions; } /** * Force running auto check on decompiled code. * Useful for smali tests. */ public JadxClassNodeAssertions runDecompiledAutoCheck(IntegrationTest testInstance) { isNotNull(); testInstance.runDecompiledAutoCheck(actual); return this; } public JadxClassNodeAssertions checkCodeAnnotationFor(String refStr, ICodeAnnotation node) { checkCodeAnnotationFor(refStr, 0, node); return this; } public JadxClassNodeAssertions checkCodeAnnotationFor(String refStr, int refOffset, ICodeAnnotation node) { ICodeInfo code = actual.getCode(); int codePos = code.getCodeStr().indexOf(refStr); assertThat(codePos).describedAs("String '%s' not found", refStr).isNotEqualTo(-1); int refPos = codePos + refOffset; for (Map.Entry<Integer, ICodeAnnotation> entry : code.getCodeMetadata().getAsMap().entrySet()) { if (entry.getKey() == refPos) { assertThat(entry.getValue()).isEqualTo(node); return this; } } fail("Annotation for reference string: '%s' at position %d not found", refStr, refPos); return this; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxCodeAssertions.java
jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxCodeAssertions.java
package jadx.tests.api.utils.assertj; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.assertj.core.api.AbstractStringAssert; import org.assertj.core.internal.Failures; import jadx.tests.api.utils.TestUtils; import static org.assertj.core.error.ShouldNotContainSubsequence.shouldNotContainSubsequence; public class JadxCodeAssertions extends AbstractStringAssert<JadxCodeAssertions> { private Failures failures = Failures.instance(); public JadxCodeAssertions(String code) { super(code, JadxCodeAssertions.class); } public JadxCodeAssertions containsOne(String substring) { return countString(1, substring); } public JadxCodeAssertions countString(int count, String substring) { isNotNull(); int actualCount = TestUtils.count(actual, substring); if (actualCount != count) { failWithMessage("Expected a substring <%s> count <%d> but was <%d>", substring, count, actualCount); } return this; } public JadxCodeAssertions notContainsLine(int indent, String line) { return countLine(0, indent, line); } public JadxCodeAssertions containsLine(int indent, String line) { return countLine(1, indent, line); } private JadxCodeAssertions countLine(int count, int indent, String line) { String indentStr = TestUtils.indent(indent); return countString(count, indentStr + line); } public JadxCodeAssertions containsLines(String... lines) { return containsLines(0, lines); } public JadxCodeAssertions containsLines(int commonIndent, String... lines) { if (lines.length == 1) { return containsLine(commonIndent, lines[0]); } String indent = TestUtils.indent(commonIndent); StringBuilder sb = new StringBuilder(); for (String line : lines) { sb.append('\n'); if (line.isEmpty()) { // don't add common indent to empty lines continue; } String searchLine = indent + line; sb.append(searchLine); // check every line for easier debugging contains(searchLine); } return containsOnlyOnce(sb.substring(1)); } public JadxCodeAssertions doesNotContainSubsequence(CharSequence... values) { final var regex = Arrays.stream(values) .map(value -> Pattern.quote(value.toString())) .collect(Collectors.joining(".*")); final var pattern = Pattern.compile(regex, Pattern.DOTALL); final var matcher = pattern.matcher(actual); if (matcher.find()) { throw failures.failure(info, shouldNotContainSubsequence(actual, values, matcher.start())); } return this; } public JadxCodeAssertions removeBlockComments() { String code = actual.replaceAll("/\\*.*\\*/", ""); JadxCodeAssertions newCode = new JadxCodeAssertions(code); newCode.print(); return newCode; } public JadxCodeAssertions removeLineComments() { String code = actual.replaceAll("//.*(?!$)", ""); JadxCodeAssertions newCode = new JadxCodeAssertions(code); newCode.print(); return newCode; } public JadxCodeAssertions print() { System.out.println("-----------------------------------------------------------"); System.out.println(actual); System.out.println("-----------------------------------------------------------"); return this; } public JadxCodeAssertions containsOneOf(String... substringArr) { int matches = 0; for (String substring : substringArr) { matches += TestUtils.count(actual, substring); } if (matches != 1) { failWithMessage("Expected only one match from <%s> but was <%d>", Arrays.toString(substringArr), matches); } return this; } @SuppressWarnings("UnusedReturnValue") @SafeVarargs public final JadxCodeAssertions oneOf(Function<JadxCodeAssertions, JadxCodeAssertions>... checks) { int passed = 0; List<Throwable> failed = new ArrayList<>(); for (Function<JadxCodeAssertions, JadxCodeAssertions> check : checks) { try { check.apply(this); passed++; } catch (Throwable e) { failed.add(e); } } if (passed != 1) { failWithMessage("Expected only one match but passed: <%d>, failed: <%d>, details:\n<%s>", passed, failed.size(), failed.stream().map(Throwable::getMessage).collect(Collectors.joining("\nFailed check:\n "))); } return this; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxAssertions.java
jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxAssertions.java
package jadx.tests.api.utils.assertj; import org.assertj.core.api.Assertions; import jadx.api.ICodeInfo; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; public class JadxAssertions extends Assertions { public static JadxClassNodeAssertions assertThat(ClassNode cls) { Assertions.assertThat(cls).isNotNull(); return new JadxClassNodeAssertions(cls); } public static JadxMethodNodeAssertions assertThat(MethodNode mth) { Assertions.assertThat(mth).isNotNull(); return new JadxMethodNodeAssertions(mth); } public static JadxCodeInfoAssertions assertThat(ICodeInfo codeInfo) { Assertions.assertThat(codeInfo).isNotNull(); return new JadxCodeInfoAssertions(codeInfo); } public static JadxCodeAssertions assertThat(String code) { return new JadxCodeAssertions(code); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxCodeInfoAssertions.java
jadx-core/src/test/java/jadx/tests/api/utils/assertj/JadxCodeInfoAssertions.java
package jadx.tests.api.utils.assertj; import java.util.stream.Collectors; import org.assertj.core.api.AbstractObjectAssert; import jadx.api.ICodeInfo; import jadx.api.metadata.annotations.InsnCodeOffset; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class JadxCodeInfoAssertions extends AbstractObjectAssert<JadxCodeInfoAssertions, ICodeInfo> { public JadxCodeInfoAssertions(ICodeInfo cls) { super(cls, JadxCodeInfoAssertions.class); } public JadxCodeAssertions code() { isNotNull(); String codeStr = actual.getCodeStr(); assertThat(codeStr).isNotBlank(); return new JadxCodeAssertions(codeStr); } public JadxCodeInfoAssertions checkCodeOffsets() { long dupOffsetCount = actual.getCodeMetadata().getAsMap().values().stream() .filter(InsnCodeOffset.class::isInstance) .collect(Collectors.groupingBy(o -> ((InsnCodeOffset) o).getOffset(), Collectors.toList())) .values().stream() .filter(list -> list.size() > 1) .count(); assertThat(dupOffsetCount) .describedAs("Found duplicated code offsets") .isEqualTo(0); return this; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/compiler/JavaUtils.java
jadx-core/src/test/java/jadx/tests/api/compiler/JavaUtils.java
package jadx.tests.api.compiler; import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JavaUtils { private static final Logger LOG = LoggerFactory.getLogger(JavaUtils.class); public static final int JAVA_VERSION_INT = getJavaVersionInt(); public static boolean checkJavaVersion(int requiredVersion) { return JAVA_VERSION_INT >= requiredVersion; } private static int getJavaVersionInt() { String javaSpecVerStr = SystemUtils.JAVA_SPECIFICATION_VERSION; if (javaSpecVerStr == null) { LOG.warn("Unknown current java specification version, use 8 as fallback"); return 8; // fallback version } if (javaSpecVerStr.startsWith("1.")) { return Integer.parseInt(javaSpecVerStr.substring(2)); } return Integer.parseInt(javaSpecVerStr); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/compiler/JavaClassObject.java
jadx-core/src/test/java/jadx/tests/api/compiler/JavaClassObject.java
package jadx.tests.api.compiler; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.net.URI; import javax.tools.SimpleJavaFileObject; public class JavaClassObject extends SimpleJavaFileObject { private final String name; private final ByteArrayOutputStream bos = new ByteArrayOutputStream(); public JavaClassObject(String name, Kind kind) { super(URI.create("string:///" + name.replace('.', '/') + kind.extension), kind); this.name = name; } @Override public String getName() { return name; } public byte[] getBytes() { return bos.toByteArray(); } @Override public OutputStream openOutputStream() { return bos; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/compiler/StringJavaFileObject.java
jadx-core/src/test/java/jadx/tests/api/compiler/StringJavaFileObject.java
package jadx.tests.api.compiler; import java.net.URI; import javax.tools.SimpleJavaFileObject; public class StringJavaFileObject extends SimpleJavaFileObject { private final String content; public StringJavaFileObject(String className, String content) { super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); this.content = content; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return content; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/compiler/CompilerOptions.java
jadx-core/src/test/java/jadx/tests/api/compiler/CompilerOptions.java
package jadx.tests.api.compiler; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CompilerOptions { private boolean includeDebugInfo = true; private boolean useEclipseCompiler = false; private int javaVersion = 8; List<String> arguments = Collections.emptyList(); public boolean isIncludeDebugInfo() { return includeDebugInfo; } public void setIncludeDebugInfo(boolean includeDebugInfo) { this.includeDebugInfo = includeDebugInfo; } public boolean isUseEclipseCompiler() { return useEclipseCompiler; } public void setUseEclipseCompiler(boolean useEclipseCompiler) { this.useEclipseCompiler = useEclipseCompiler; } public int getJavaVersion() { return javaVersion; } public void setJavaVersion(int javaVersion) { this.javaVersion = javaVersion; } public List<String> getArguments() { return Collections.unmodifiableList(arguments); } public void addArgument(String argName) { if (arguments.isEmpty()) { arguments = new ArrayList<>(); } arguments.add(argName); } public void addArgument(String argName, String argValue) { if (arguments.isEmpty()) { arguments = new ArrayList<>(); } arguments.add(argName); arguments.add(argValue); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/compiler/DynamicClassLoader.java
jadx-core/src/test/java/jadx/tests/api/compiler/DynamicClassLoader.java
package jadx.tests.api.compiler; import java.security.SecureClassLoader; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.jetbrains.annotations.Nullable; public class DynamicClassLoader extends SecureClassLoader { private final Map<String, JavaClassObject> clsMap = new ConcurrentHashMap<>(); private final Map<String, Class<?>> clsCache = new ConcurrentHashMap<>(); public void add(String className, JavaClassObject clsObject) { this.clsMap.put(className, clsObject); } @Override public Class<?> findClass(String name) throws ClassNotFoundException { Class<?> cls = replaceClass(name); if (cls != null) { return cls; } return super.findClass(name); } public Class<?> loadClass(String name) throws ClassNotFoundException { Class<?> cls = replaceClass(name); if (cls != null) { return cls; } return super.loadClass(name); } @Nullable public Class<?> replaceClass(String name) { Class<?> cacheCls = clsCache.get(name); if (cacheCls != null) { return cacheCls; } JavaClassObject clsObject = clsMap.get(name); if (clsObject == null) { return null; } byte[] clsBytes = clsObject.getBytes(); Class<?> cls = super.defineClass(name, clsBytes, 0, clsBytes.length); clsCache.put(name, cls); return cls; } public Collection<? extends JavaClassObject> getClassObjects() { return clsMap.values(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/compiler/ClassFileManager.java
jadx-core/src/test/java/jadx/tests/api/compiler/ClassFileManager.java
package jadx.tests.api.compiler; import java.io.Closeable; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import static javax.tools.JavaFileObject.Kind; public class ClassFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> implements Closeable { private final DynamicClassLoader classLoader; public ClassFileManager(StandardJavaFileManager standardManager) { super(standardManager); classLoader = new DynamicClassLoader(); } public List<JavaFileObject> getJavaFileObjectsFromFiles(List<File> sourceFiles) { List<JavaFileObject> list = new ArrayList<>(); for (JavaFileObject javaFileObject : fileManager.getJavaFileObjectsFromFiles(sourceFiles)) { list.add(javaFileObject); } return list; } @Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) { JavaClassObject clsObject = new JavaClassObject(className, kind); classLoader.add(className, clsObject); return clsObject; } @Override public ClassLoader getClassLoader(Location location) { return classLoader; } public DynamicClassLoader getClassLoader() { return classLoader; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/compiler/EclipseCompilerUtils.java
jadx-core/src/test/java/jadx/tests/api/compiler/EclipseCompilerUtils.java
package jadx.tests.api.compiler; import javax.tools.JavaCompiler; public class EclipseCompilerUtils { public static JavaCompiler newInstance() { if (!JavaUtils.checkJavaVersion(11)) { throw new IllegalArgumentException("Eclipse compiler build with Java 11"); } try { Class<?> ecjCls = Class.forName("org.eclipse.jdt.internal.compiler.tool.EclipseCompiler"); return (JavaCompiler) ecjCls.getConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException("Failed to init Eclipse compiler", e); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/api/compiler/TestCompiler.java
jadx-core/src/test/java/jadx/tests/api/compiler/TestCompiler.java
package jadx.tests.api.compiler; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.tools.DiagnosticListener; import javax.tools.JavaCompiler; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileObject; import javax.tools.ToolProvider; import org.jetbrains.annotations.NotNull; import jadx.api.impl.SimpleCodeWriter; import jadx.core.dex.nodes.ClassNode; import jadx.core.utils.files.FileUtils; import jadx.tests.api.IntegrationTest; import static org.assertj.core.api.Assertions.assertThat; public class TestCompiler implements Closeable { private final CompilerOptions options; private final JavaCompiler compiler; private final ClassFileManager fileManager; public TestCompiler(CompilerOptions options) { this.options = options; int javaVersion = options.getJavaVersion(); if (!JavaUtils.checkJavaVersion(javaVersion)) { throw new IllegalArgumentException("Current java version not meet requirement: " + "current: " + JavaUtils.JAVA_VERSION_INT + ", required: " + javaVersion); } if (options.isUseEclipseCompiler()) { compiler = EclipseCompilerUtils.newInstance(); } else { compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new IllegalStateException("Can not find compiler, please use JDK instead"); } } fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null)); } public List<File> compileFiles(List<File> sourceFiles, Path outTmp) throws IOException { compile(fileManager.getJavaFileObjectsFromFiles(sourceFiles)); List<File> files = new ArrayList<>(); for (JavaClassObject classObject : fileManager.getClassLoader().getClassObjects()) { Path path = outTmp.resolve(classObject.getName().replace('.', '/') + ".class"); FileUtils.makeDirsForFile(path); Files.write(path, classObject.getBytes()); files.add(path.toFile()); } return files; } public void compileNodes(List<ClassNode> clsNodeList) { List<JavaFileObject> jfObjects = new ArrayList<>(clsNodeList.size()); for (ClassNode clsNode : clsNodeList) { jfObjects.add(new StringJavaFileObject(clsNode.getFullName(), clsNode.getCode().getCodeStr())); } compile(jfObjects); } private void compile(List<JavaFileObject> jfObjects) { List<String> arguments = new ArrayList<>(); arguments.add(options.isIncludeDebugInfo() ? "-g" : "-g:none"); int javaVersion = options.getJavaVersion(); String javaVerStr = javaVersion <= 8 ? "1." + javaVersion : Integer.toString(javaVersion); arguments.add("-source"); arguments.add(javaVerStr); arguments.add("-target"); arguments.add(javaVerStr); arguments.addAll(options.getArguments()); SimpleCodeWriter output = new SimpleCodeWriter(); DiagnosticListener<JavaFileObject> diagnostic = diagObj -> { String msg = "Compiler diagnostic: " + diagObj; output.startLine(msg); System.out.println(msg); }; Writer out = new PrintWriter(System.out); CompilationTask compilerTask = compiler.getTask(out, fileManager, diagnostic, arguments, null, jfObjects); if (Boolean.FALSE.equals(compilerTask.call())) { throw new RuntimeException("Compilation failed: " + output); } } private ClassLoader getClassLoader() { return fileManager.getClassLoader(); } public Class<?> getClass(String clsFullName) throws ClassNotFoundException { return getClassLoader().loadClass(clsFullName); } @NotNull public Method getMethod(Class<?> cls, String methodName, Class<?>[] types) throws NoSuchMethodException { return cls.getMethod(methodName, types); } public Object invoke(String clsFullName, String methodName, Class<?>[] types, Object[] args) { try { for (Class<?> type : types) { checkType(type); } Class<?> cls = getClass(clsFullName); Method mth = getMethod(cls, methodName, types); Object inst = cls.getConstructor().newInstance(); assertThat(mth).as("Failed to get method " + methodName + '(' + Arrays.toString(types) + ')').isNotNull(); return mth.invoke(inst, args); } catch (Throwable e) { IntegrationTest.rethrow("Invoke error for method: " + methodName, e); return null; } } private Class<?> checkType(Class<?> type) throws ClassNotFoundException { if (type.isPrimitive()) { return type; } if (type.isArray()) { return checkType(type.getComponentType()); } Class<?> cls = getClassLoader().loadClass(type.getName()); if (type != cls) { throw new IllegalArgumentException("Internal test class cannot be used in method invoke"); } return cls; } @Override public void close() throws IOException { fileManager.close(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/export/IllegalCharsForGradleWrapper.java
jadx-core/src/test/java/jadx/tests/export/IllegalCharsForGradleWrapper.java
package jadx.tests.export; import org.junit.jupiter.api.Test; import jadx.tests.api.ExportGradleTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; class IllegalCharsForGradleWrapper extends ExportGradleTest { @Test void test() { exportGradle("IllegalCharsForGradleWrapper.xml", "strings.xml"); assertThat(getSettingsGradle()).contains("'JadxTestApp'"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/export/OptionalTargetSdkVersion.java
jadx-core/src/test/java/jadx/tests/export/OptionalTargetSdkVersion.java
package jadx.tests.export; import org.junit.jupiter.api.Test; import jadx.tests.api.ExportGradleTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class OptionalTargetSdkVersion extends ExportGradleTest { @Test void test() { exportGradle("OptionalTargetSdkVersion.xml", "strings.xml"); assertThat(getAppGradleBuild()).contains("targetSdkVersion 14").doesNotContain(" vectorDrawables.useSupportLibrary = true"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/export/VectorDrawablesUseSupportLibrary.java
jadx-core/src/test/java/jadx/tests/export/VectorDrawablesUseSupportLibrary.java
package jadx.tests.export; import org.junit.jupiter.api.Test; import jadx.core.export.GradleInfoStorage; import jadx.tests.api.ExportGradleTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class VectorDrawablesUseSupportLibrary extends ExportGradleTest { @Test void test() { GradleInfoStorage gradleInfo = getRootNode().getGradleInfoStorage(); gradleInfo.setVectorFillType(true); exportGradle("OptionalTargetSdkVersion.xml", "strings.xml"); assertThat(getAppGradleBuild()).contains(" vectorDrawables.useSupportLibrary = true"); gradleInfo.setVectorFillType(false); gradleInfo.setVectorPathData(true); exportGradle("OptionalTargetSdkVersion.xml", "strings.xml"); assertThat(getAppGradleBuild()).contains(" vectorDrawables.useSupportLibrary = true"); exportGradle("MinSdkVersion25.xml", "strings.xml"); assertThat(getAppGradleBuild()).doesNotContain(" vectorDrawables.useSupportLibrary = true"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/export/TestNonFinalResIds.java
jadx-core/src/test/java/jadx/tests/export/TestNonFinalResIds.java
package jadx.tests.export; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import jadx.core.export.GradleInfoStorage; import jadx.tests.api.ExportGradleTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestNonFinalResIds extends ExportGradleTest { @Test void test() { GradleInfoStorage gradleInfo = getRootNode().getGradleInfoStorage(); gradleInfo.setNonFinalResIds(false); exportGradle("OptionalTargetSdkVersion.xml", "strings.xml"); Assertions.assertFalse(getGradleProperiesFile().exists()); gradleInfo.setNonFinalResIds(true); exportGradle("OptionalTargetSdkVersion.xml", "strings.xml"); assertThat(getGradleProperties()).containsOne("android.nonFinalResIds=false"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/export/TestApacheHttpClient.java
jadx-core/src/test/java/jadx/tests/export/TestApacheHttpClient.java
package jadx.tests.export; import org.junit.jupiter.api.Test; import jadx.core.export.GradleInfoStorage; import jadx.tests.api.ExportGradleTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestApacheHttpClient extends ExportGradleTest { @Test void test() { GradleInfoStorage gradleInfo = getRootNode().getGradleInfoStorage(); gradleInfo.setUseApacheHttpLegacy(true); exportGradle("OptionalTargetSdkVersion.xml", "strings.xml"); assertThat(getAppGradleBuild()).contains(" useLibrary 'org.apache.http.legacy'"); gradleInfo.setUseApacheHttpLegacy(false); exportGradle("OptionalTargetSdkVersion.xml", "strings.xml"); assertThat(getAppGradleBuild()).doesNotContain(" useLibrary 'org.apache.http.legacy'"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/functional/SignatureParserTest.java
jadx-core/src/test/java/jadx/tests/functional/SignatureParserTest.java
package jadx.tests.functional; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.ArgType.WildcardBound; import jadx.core.dex.nodes.parser.SignatureParser; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.dex.instructions.args.ArgType.INT; import static jadx.core.dex.instructions.args.ArgType.OBJECT; import static jadx.core.dex.instructions.args.ArgType.array; import static jadx.core.dex.instructions.args.ArgType.generic; import static jadx.core.dex.instructions.args.ArgType.genericType; import static jadx.core.dex.instructions.args.ArgType.object; import static jadx.core.dex.instructions.args.ArgType.outerGeneric; import static jadx.core.dex.instructions.args.ArgType.wildcard; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class SignatureParserTest { @Test public void testSimpleTypes() { checkType("", null); checkType("I", INT); checkType("[I", array(INT)); checkType("Ljava/lang/Object;", OBJECT); checkType("[Ljava/lang/Object;", array(OBJECT)); checkType("[[I", array(array(INT))); } private static void checkType(String str, ArgType type) { assertThat(new SignatureParser(str).consumeType()).isEqualTo(type); } @Test public void testGenerics() { checkType("TD;", genericType("D")); checkType("La<TV;Lb;>;", generic("La;", genericType("V"), object("b"))); checkType("La<Lb<Lc;>;>;", generic("La;", generic("Lb;", object("Lc;")))); checkType("La/b/C<Ld/E<Lf/G;>;>;", generic("La/b/C;", generic("Ld/E;", object("Lf/G;")))); checkType("La<TD;>.c;", outerGeneric(generic("La;", genericType("D")), ArgType.object("c"))); checkType("La<TD;>.c/d;", outerGeneric(generic("La;", genericType("D")), ArgType.object("c.d"))); checkType("La<Lb;>.c<TV;>;", outerGeneric(generic("La;", object("Lb;")), ArgType.generic("c", genericType("V")))); } @Test public void testInnerGeneric() { String signature = "La<TV;>.LinkedHashIterator<Lb$c<Ls;TV;>;>;"; String objectStr = new SignatureParser(signature).consumeType().getObject(); assertThat(objectStr).isEqualTo("a$LinkedHashIterator"); } @Test public void testNestedInnerGeneric() { String signature = "La<TV;>.I.X;"; ArgType result = new SignatureParser(signature).consumeType(); assertThat(result.getObject()).isEqualTo("a$I$X"); // nested 'outerGeneric' objects ArgType obj = generic("La;", genericType("V")); assertThat(result).isEqualTo(outerGeneric(outerGeneric(obj, object("I")), object("X"))); } @Test public void testNestedInnerGeneric2() { // full name in inner class String signature = "Lsome/long/pkg/ba<Lsome/pkg/s;>.some/long/pkg/bb<Lsome/pkg/p;Lsome/pkg/n;>;"; ArgType result = new SignatureParser(signature).consumeType(); System.out.println(result); assertThat(result.getObject()).isEqualTo("some.long.pkg.ba$some.long.pkg.bb"); ArgType baseObj = generic("Lsome/long/pkg/ba;", object("Lsome/pkg/s;")); ArgType innerObj = generic("Lsome/long/pkg/bb;", object("Lsome/pkg/p;"), object("Lsome/pkg/n;")); ArgType obj = outerGeneric(baseObj, innerObj); assertThat(result).isEqualTo(obj); } @Test public void testWildcards() { checkWildcards("*", wildcard()); checkWildcards("+Lb;", wildcard(object("b"), WildcardBound.EXTENDS)); checkWildcards("-Lb;", wildcard(object("b"), WildcardBound.SUPER)); checkWildcards("+TV;", wildcard(genericType("V"), WildcardBound.EXTENDS)); checkWildcards("-TV;", wildcard(genericType("V"), WildcardBound.SUPER)); checkWildcards("**", wildcard(), wildcard()); checkWildcards("*Lb;", wildcard(), object("b")); checkWildcards("*TV;", wildcard(), genericType("V")); checkWildcards("TV;*", genericType("V"), wildcard()); checkWildcards("Lb;*", object("b"), wildcard()); checkWildcards("***", wildcard(), wildcard(), wildcard()); checkWildcards("*Lb;*", wildcard(), object("b"), wildcard()); } private static void checkWildcards(String w, ArgType... types) { ArgType parsedType = new SignatureParser("La<" + w + ">;").consumeType(); ArgType expectedType = generic("La;", types); assertThat(parsedType).isEqualTo(expectedType); } @Test public void testGenericMap() { checkGenerics(""); checkGenerics("<T:Ljava/lang/Object;>", "T", emptyList()); checkGenerics("<K:Ljava/lang/Object;LongType:Ljava/lang/Object;>", "K", emptyList(), "LongType", emptyList()); checkGenerics("<ResultT:Ljava/lang/Exception;:Ljava/lang/Object;>", "ResultT", singletonList(object("java.lang.Exception"))); } @SuppressWarnings("unchecked") private static void checkGenerics(String g, Object... objs) { List<ArgType> genericsList = new SignatureParser(g).consumeGenericTypeParameters(); List<ArgType> expectedList = new ArrayList<>(); for (int i = 0; i < objs.length; i += 2) { String typeVar = (String) objs[i]; List<ArgType> list = (List<ArgType>) objs[i + 1]; expectedList.add(ArgType.genericType(typeVar, list)); } assertThat(genericsList).isEqualTo(expectedList); } @Test public void testMethodArgs() { List<ArgType> argTypes = new SignatureParser("(Ljava/util/List<*>;)V").consumeMethodArgs(1); assertThat(argTypes).hasSize(1); assertThat(argTypes.get(0)).isEqualTo(generic("Ljava/util/List;", wildcard())); } @Test public void testMethodArgs2() { List<ArgType> argTypes = new SignatureParser("(La/b/C<TT;>.d/E;)V").consumeMethodArgs(1); assertThat(argTypes).hasSize(1); ArgType argType = argTypes.get(0); assertThat(argType.getObject().indexOf('/')).isEqualTo(-1); assertThat(argType).isEqualTo(outerGeneric(generic("La/b/C;", genericType("T")), object("d.E"))); } @Test public void testBadGenericMap() { assertThatExceptionOfType(JadxRuntimeException.class) .isThrownBy(() -> new SignatureParser("<A:Ljava/lang/Object;B").consumeGenericTypeParameters()); } @Test public void testBadArgs() { assertThatExceptionOfType(JadxRuntimeException.class) .isThrownBy(() -> new SignatureParser("(TCONTENT)Lpkg/Cls;").consumeMethodArgs(1)); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/functional/JadxClasspathTest.java
jadx-core/src/test/java/jadx/tests/functional/JadxClasspathTest.java
package jadx.tests.functional; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import jadx.api.JadxArgs; import jadx.core.clsp.ClspGraph; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.RootNode; import static jadx.core.dex.instructions.args.ArgType.OBJECT; import static jadx.core.dex.instructions.args.ArgType.STRING; import static jadx.core.dex.instructions.args.ArgType.isCastNeeded; import static jadx.core.dex.instructions.args.ArgType.object; import static org.assertj.core.api.Assertions.assertThat; public class JadxClasspathTest { private static final String JAVA_LANG_EXCEPTION = "java.lang.Exception"; private static final String JAVA_LANG_THROWABLE = "java.lang.Throwable"; private RootNode root; private ClspGraph clsp; @BeforeEach public void initClsp() { this.root = new RootNode(new JadxArgs()); this.root.loadClasses(Collections.emptyList()); this.root.initClassPath(); this.clsp = root.getClsp(); } @Test public void test() { ArgType objExc = object(JAVA_LANG_EXCEPTION); ArgType objThr = object(JAVA_LANG_THROWABLE); assertThat(clsp.isImplements(JAVA_LANG_EXCEPTION, JAVA_LANG_THROWABLE)).isTrue(); assertThat(clsp.isImplements(JAVA_LANG_THROWABLE, JAVA_LANG_EXCEPTION)).isFalse(); assertThat(isCastNeeded(root, objExc, objThr)).isFalse(); assertThat(isCastNeeded(root, objThr, objExc)).isTrue(); assertThat(isCastNeeded(root, OBJECT, STRING)).isTrue(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/functional/AttributeStorageTest.java
jadx-core/src/test/java/jadx/tests/functional/AttributeStorageTest.java
package jadx.tests.functional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.AttributeStorage; import static jadx.core.dex.attributes.AFlag.SYNTHETIC; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class AttributeStorageTest { private AttributeStorage storage; @BeforeEach public void setup() { storage = new AttributeStorage(); } @Test public void testAdd() { storage.add(SYNTHETIC); assertThat(storage.contains(SYNTHETIC)).isTrue(); } @Test public void testRemove() { storage.add(SYNTHETIC); storage.remove(SYNTHETIC); assertThat(storage.contains(SYNTHETIC)).isFalse(); } public static final AType<TestAttr> TEST = new AType<>(); public static class TestAttr implements IJadxAttribute { @Override public AType<TestAttr> getAttrType() { return TEST; } } @Test public void testAddAttribute() { TestAttr attr = new TestAttr(); storage.add(attr); assertThat(storage.contains(TEST)).isTrue(); assertThat(storage.get(TEST)).isEqualTo(attr); } @Test public void testRemoveAttribute() { TestAttr attr = new TestAttr(); storage.add(attr); storage.remove(attr); assertThat(storage.contains(TEST)).isFalse(); assertThat(storage.get(TEST)).isNull(); } @Test public void testRemoveOtherAttribute() { TestAttr attr = new TestAttr(); storage.add(attr); storage.remove(new TestAttr()); assertThat(storage.contains(TEST)).isTrue(); assertThat(storage.get(TEST)).isEqualTo(attr); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/functional/StringUtilsTest.java
jadx-core/src/test/java/jadx/tests/functional/StringUtilsTest.java
package jadx.tests.functional; import org.junit.jupiter.api.Test; import jadx.api.JadxArgs; import jadx.core.utils.StringUtils; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; class StringUtilsTest { private StringUtils stringUtils; @Test @SuppressWarnings("AvoidEscapedUnicodeCharacters") public void testStringUnescape() { JadxArgs args = new JadxArgs(); args.setEscapeUnicode(true); stringUtils = new StringUtils(args); checkStringUnescape("", ""); checkStringUnescape("'", "'"); checkStringUnescape("a", "a"); checkStringUnescape("\n", "\\n"); checkStringUnescape("\t", "\\t"); checkStringUnescape("\r", "\\r"); checkStringUnescape("\b", "\\b"); checkStringUnescape("\f", "\\f"); checkStringUnescape("\\", "\\\\"); checkStringUnescape("\"", "\\\""); checkStringUnescape("\u1234", "\\u1234"); } private void checkStringUnescape(String input, String result) { assertThat(stringUtils.unescapeString(input)).isEqualTo('"' + result + '"'); } @Test public void testCharUnescape() { stringUtils = new StringUtils(new JadxArgs()); checkCharUnescape('a', "a"); checkCharUnescape(' ', " "); checkCharUnescape('\n', "\\n"); checkCharUnescape('\'', "\\'"); assertThat(stringUtils.unescapeChar('\0')).isEqualTo("0"); } private void checkCharUnescape(char input, String result) { assertThat(stringUtils.unescapeChar(input)).isEqualTo('\'' + result + '\''); } @Test public void testResStrValueEscape() { checkResStrValueEscape("line\nnew line", "line\\nnew line"); checkResStrValueEscape("can't", "can\\'t"); checkResStrValueEscape("quote\"end", "quote\\\"end"); } private void checkResStrValueEscape(String input, String result) { assertThat(StringUtils.escapeResStrValue(input)).isEqualTo(result); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/functional/TestIfCondition.java
jadx-core/src/test/java/jadx/tests/functional/TestIfCondition.java
package jadx.tests.functional; import org.junit.jupiter.api.Test; import jadx.core.dex.instructions.IfNode; import jadx.core.dex.instructions.IfOp; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.instructions.args.LiteralArg; import jadx.core.dex.regions.conditions.Compare; import jadx.core.dex.regions.conditions.IfCondition; import static jadx.core.dex.regions.conditions.IfCondition.Mode; import static jadx.core.dex.regions.conditions.IfCondition.Mode.AND; import static jadx.core.dex.regions.conditions.IfCondition.Mode.COMPARE; import static jadx.core.dex.regions.conditions.IfCondition.Mode.NOT; import static jadx.core.dex.regions.conditions.IfCondition.Mode.OR; import static jadx.core.dex.regions.conditions.IfCondition.merge; import static jadx.core.dex.regions.conditions.IfCondition.not; import static jadx.core.dex.regions.conditions.IfCondition.simplify; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestIfCondition { private static IfCondition makeCondition(IfOp op, InsnArg a, InsnArg b) { return IfCondition.fromIfNode(new IfNode(op, -1, a, b)); } private static IfCondition makeSimpleCondition() { return makeCondition(IfOp.EQ, mockArg(), LiteralArg.litTrue()); } private static IfCondition makeNegCondition() { return makeCondition(IfOp.NE, mockArg(), LiteralArg.litTrue()); } private static InsnArg mockArg() { return InsnArg.reg(0, ArgType.INT); } @Test public void testNormalize() { // 'a != false' => 'a == true' InsnArg a = mockArg(); IfCondition c = makeCondition(IfOp.NE, a, LiteralArg.litFalse()); IfCondition simp = simplify(c); assertThat(simp.getMode()).isEqualTo(COMPARE); Compare compare = simp.getCompare(); assertThat(compare.getA()).isEqualTo(a); assertThat(compare.getB()).isEqualTo(LiteralArg.litTrue()); } @Test public void testMerge() { IfCondition a = makeSimpleCondition(); IfCondition b = makeSimpleCondition(); IfCondition c = merge(Mode.OR, a, b); assertThat(c.getMode()).isEqualTo(OR); assertThat(c.first()).isEqualTo(a); assertThat(c.second()).isEqualTo(b); } @Test public void testSimplifyNot() { // !(!a) => a IfCondition a = not(not(makeSimpleCondition())); assertThat(simplify(a)).isEqualTo(a); } @Test public void testSimplifyNot2() { // !(!a) => a IfCondition a = not(makeNegCondition()); assertThat(simplify(a)).isEqualTo(a); } @Test public void testSimplify() { // '!(!a || !b)' => 'a && b' IfCondition a = makeSimpleCondition(); IfCondition b = makeSimpleCondition(); IfCondition c = not(merge(Mode.OR, not(a), not(b))); IfCondition simp = simplify(c); assertThat(simp.getMode()).isEqualTo(AND); assertThat(simp.first()).isEqualTo(a); assertThat(simp.second()).isEqualTo(b); } @Test public void testSimplify2() { // '(!a || !b) && !c' => '!((a && b) || c)' IfCondition a = makeSimpleCondition(); IfCondition b = makeSimpleCondition(); IfCondition c = makeSimpleCondition(); IfCondition cond = merge(Mode.AND, merge(Mode.OR, not(a), not(b)), not(c)); IfCondition simp = simplify(cond); assertThat(simp.getMode()).isEqualTo(NOT); IfCondition f = simp.first(); assertThat(f.getMode()).isEqualTo(OR); assertThat(f.first().getMode()).isEqualTo(AND); assertThat(f.first().first()).isEqualTo(a); assertThat(f.first().second()).isEqualTo(b); assertThat(f.second()).isEqualTo(c); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/functional/NameMapperTest.java
jadx-core/src/test/java/jadx/tests/functional/NameMapperTest.java
package jadx.tests.functional; import org.junit.jupiter.api.Test; import jadx.core.deobf.NameMapper; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class NameMapperTest { @Test public void testValidFullIdentifiers() { String[] validNames = { "C", "Cc", "b.C", "b.Cc", "aAa.b.Cc", "a.b.Cc", "a.b.C_c", "a.b.C$c", "a.b.C9" }; for (String validName : validNames) { assertThat(NameMapper.isValidFullIdentifier(validName)).isTrue(); } } @Test public void testInvalidFullIdentifiers() { String[] invalidNames = { "", "5", "7A", ".C", "b.9C", "b..C", }; for (String invalidName : invalidNames) { assertThat(NameMapper.isValidFullIdentifier(invalidName)).isFalse(); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/functional/TemplateFileTest.java
jadx-core/src/test/java/jadx/tests/functional/TemplateFileTest.java
package jadx.tests.functional; import org.junit.jupiter.api.Test; import jadx.core.export.TemplateFile; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TemplateFileTest { @Test public void testBuildGradle() throws Exception { TemplateFile tmpl = TemplateFile.fromResources("/export/android/app.build.gradle.tmpl"); tmpl.add("applicationId", "SOME_ID"); tmpl.add("minSdkVersion", 1); tmpl.add("targetSdkVersion", 2); tmpl.add("versionCode", 3); tmpl.add("versionName", "1.2.3"); tmpl.add("additionalOptions", "useLibrary 'org.apache.http.legacy'"); tmpl.add("compileSdkVersion", 4); String res = tmpl.build(); System.out.println(res); assertThat(res).contains("applicationId 'SOME_ID'"); assertThat(res).contains("targetSdkVersion 2"); assertThat(res).contains("versionCode 3"); assertThat(res).contains("versionName \"1.2.3\""); assertThat(res).contains("compileSdkVersion 4"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/functional/JadxVisitorsOrderTest.java
jadx-core/src/test/java/jadx/tests/functional/JadxVisitorsOrderTest.java
package jadx.tests.functional; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxArgs; import jadx.core.Jadx; import jadx.core.dex.visitors.IDexTreeVisitor; import jadx.core.dex.visitors.JadxVisitor; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class JadxVisitorsOrderTest { private static final Logger LOG = LoggerFactory.getLogger(JadxVisitorsOrderTest.class); @Test public void testOrder() { checkPassList(Jadx.getPassesList(new JadxArgs())); checkPassList(Jadx.getPreDecompilePassesList()); checkPassList(Jadx.getFallbackPassesList()); } private void checkPassList(List<IDexTreeVisitor> passes) { List<String> errors = check(passes); for (String str : errors) { LOG.error(str); } assertThat(errors).isEmpty(); } private static List<String> check(List<IDexTreeVisitor> passes) { List<Class<?>> classList = new ArrayList<>(passes.size()); for (IDexTreeVisitor pass : passes) { classList.add(pass.getClass()); } List<String> errors = new ArrayList<>(); Set<String> names = new HashSet<>(); Set<Class<?>> passClsSet = new HashSet<>(); for (int i = 0; i < passes.size(); i++) { IDexTreeVisitor pass = passes.get(i); Class<? extends IDexTreeVisitor> passClass = pass.getClass(); JadxVisitor info = passClass.getAnnotation(JadxVisitor.class); if (info == null) { LOG.warn("No JadxVisitor annotation for visitor: {}", passClass.getName()); continue; } boolean firstOccurrence = passClsSet.add(passClass); String passName = passClass.getSimpleName(); if (firstOccurrence && !names.add(passName)) { errors.add("Visitor name conflict: " + passName + ", class: " + passClass.getName()); } for (Class<? extends IDexTreeVisitor> cls : info.runBefore()) { int beforeIndex = classList.indexOf(cls); if (beforeIndex != -1 && beforeIndex < i) { errors.add("Pass " + passName + " must be before " + cls.getSimpleName()); } } for (Class<? extends IDexTreeVisitor> cls : info.runAfter()) { if (classList.indexOf(cls) > i) { errors.add("Pass " + passName + " must be after " + cls.getSimpleName()); } } } return errors; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/api/JadxArgsValidatorOutDirsTest.java
jadx-core/src/test/java/jadx/api/JadxArgsValidatorOutDirsTest.java
package jadx.api; import java.nio.file.Files; 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 static jadx.core.utils.files.FileUtils.toFile; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class JadxArgsValidatorOutDirsTest { private static final Logger LOG = LoggerFactory.getLogger(JadxArgsValidatorOutDirsTest.class); public JadxArgs args; @TempDir Path testDir; @Test public void checkAllSet() { setOutDirs("r", "s", "r"); checkOutDirs("r", "s", "r"); } @Test public void checkRootOnly() { setOutDirs("out", null, null); checkOutDirs("out", "out/" + JadxArgs.DEFAULT_SRC_DIR, "out/" + JadxArgs.DEFAULT_RES_DIR); } @Test public void checkSrcOnly() { setOutDirs(null, "src", null); checkOutDirs("src", "src", "src/" + JadxArgs.DEFAULT_RES_DIR); } @Test public void checkResOnly() { setOutDirs(null, null, "res"); checkOutDirs("res", "res/" + JadxArgs.DEFAULT_SRC_DIR, "res"); } @Test public void checkNone() { setOutDirs(null, null, null); String inputFileBase = args.getInputFiles().get(0).getName().replace(".apk", ""); checkOutDirs(inputFileBase, inputFileBase + '/' + JadxArgs.DEFAULT_SRC_DIR, inputFileBase + '/' + JadxArgs.DEFAULT_RES_DIR); } private void setOutDirs(String outDir, String srcDir, String resDir) { args = makeArgs(); args.setOutDir(toFile(outDir)); args.setOutDirSrc(toFile(srcDir)); args.setOutDirRes(toFile(resDir)); LOG.debug("Set dirs: out={}, src={}, res={}", outDir, srcDir, resDir); } private void checkOutDirs(String outDir, String srcDir, String resDir) { JadxArgsValidator.validate(new JadxDecompiler(args)); LOG.debug("Got dirs: out={}, src={}, res={}", args.getOutDir(), args.getOutDirSrc(), args.getOutDirRes()); assertThat(args.getOutDir()).isEqualTo(toFile(outDir)); assertThat(args.getOutDirSrc()).isEqualTo(toFile(srcDir)); assertThat(args.getOutDirRes()).isEqualTo(toFile(resDir)); } private JadxArgs makeArgs() { try { JadxArgs args = new JadxArgs(); args.getInputFiles().add(Files.createTempFile(testDir, "test-", ".apk").toFile()); return args; } catch (Exception e) { throw new RuntimeException(e); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/api/JadxInternalAccess.java
jadx-core/src/test/java/jadx/api/JadxInternalAccess.java
package jadx.api; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; public class JadxInternalAccess { public static RootNode getRoot(JadxDecompiler d) { return d.getRoot(); } public static JavaClass convertClassNode(JadxDecompiler d, ClassNode clsNode) { return d.convertClassNode(clsNode); } public static JavaMethod convertMethodNode(JadxDecompiler d, MethodNode mthNode) { return d.convertMethodNode(mthNode); } public static JavaField convertFieldNode(JadxDecompiler d, FieldNode fldNode) { return d.convertFieldNode(fldNode); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/api/JadxDecompilerTest.java
jadx-core/src/test/java/jadx/api/JadxDecompilerTest.java
package jadx.api; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import jadx.core.xmlgen.ResContainer; import jadx.plugins.input.dex.DexInputPlugin; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class JadxDecompilerTest { @TempDir File testDir; @Test public void testExampleUsage() { File sampleApk = getFileFromSampleDir("app-with-fake-dex.apk"); // test simple apk loading JadxArgs args = new JadxArgs(); args.getInputFiles().add(sampleApk); args.setOutDir(testDir); try (JadxDecompiler jadx = new JadxDecompiler(args)) { jadx.load(); jadx.save(); jadx.printErrorsReport(); // test class print for (JavaClass cls : jadx.getClasses()) { System.out.println(cls.getCode()); } assertThat(jadx.getClasses()).hasSize(3); assertThat(jadx.getErrorsCount()).isEqualTo(0); } } @Test public void testDirectDexInput() throws IOException { try (JadxDecompiler jadx = new JadxDecompiler(); InputStream in = new FileInputStream(getFileFromSampleDir("hello.dex"))) { jadx.addCustomCodeLoader(new DexInputPlugin().loadDexFromInputStream(in, "input")); jadx.load(); for (JavaClass cls : jadx.getClasses()) { System.out.println(cls.getCode()); } assertThat(jadx.getClasses()).hasSize(1); assertThat(jadx.getErrorsCount()).isEqualTo(0); } } @Test public void testResourcesLoad() { File sampleApk = getFileFromSampleDir("app-with-fake-dex.apk"); JadxArgs args = new JadxArgs(); args.getInputFiles().add(sampleApk); args.setOutDir(testDir); args.setSkipSources(true); try (JadxDecompiler jadx = new JadxDecompiler(args)) { jadx.load(); List<ResourceFile> resources = jadx.getResources(); assertThat(resources).hasSize(8); ResourceFile arsc = resources.stream() .filter(r -> r.getType() == ResourceType.ARSC) .findFirst().orElseThrow(); ResContainer resContainer = arsc.loadContent(); ResContainer xmlRes = resContainer.getSubFiles().stream() .filter(r -> r.getName().equals("res/values/colors.xml")) .findFirst().orElseThrow(); assertThat(xmlRes.getText()) .code() .containsOne("<color name=\"colorPrimary\">#008577</color>"); } } private static final String TEST_SAMPLES_DIR = "test-samples/"; public static File getFileFromSampleDir(String fileName) { URL resource = JadxDecompilerTest.class.getClassLoader().getResource(TEST_SAMPLES_DIR + fileName); assertThat(resource).isNotNull(); String pathStr = resource.getFile(); return new File(pathStr); } // TODO add more tests }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/xmlgen/ResNameUtilsTest.java
jadx-core/src/test/java/jadx/core/xmlgen/ResNameUtilsTest.java
package jadx.core.xmlgen; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.assertj.core.api.Assertions.assertThat; class ResNameUtilsTest { @DisplayName("Check sanitizeAsResourceName(name, postfix, allowNonPrintable)") @ParameterizedTest(name = "({0}, {1}, {2}) -> {3}") @MethodSource("provideArgsForSanitizeAsResourceNameTest") void testSanitizeAsResourceName(String name, String postfix, boolean allowNonPrintable, String expectedResult) { assertThat(ResNameUtils.sanitizeAsResourceName(name, postfix, allowNonPrintable)).isEqualTo(expectedResult); } @DisplayName("Check convertToRFieldName(resourceName)") @ParameterizedTest(name = "{0} -> {1}") @MethodSource("provideArgsForConvertToRFieldNameTest") void testConvertToRFieldName(String resourceName, String expectedResult) { assertThat(ResNameUtils.convertToRFieldName(resourceName)).isEqualTo(expectedResult); } private static Stream<Arguments> provideArgsForSanitizeAsResourceNameTest() { return Stream.of( Arguments.of("name", "_postfix", false, "name"), Arguments.of("/name", "_postfix", true, "_name_postfix"), Arguments.of("na/me", "_postfix", true, "na_me_postfix"), Arguments.of("name/", "_postfix", true, "name__postfix"), Arguments.of("$name", "_postfix", true, "_name_postfix"), Arguments.of("na$me", "_postfix", true, "na_me_postfix"), Arguments.of("name$", "_postfix", true, "name__postfix"), Arguments.of(".name", "_postfix", true, "_.name_postfix"), Arguments.of("na.me", "_postfix", true, "na.me"), Arguments.of("name.", "_postfix", true, "name."), Arguments.of("0name", "_postfix", true, "_0name_postfix"), Arguments.of("na0me", "_postfix", true, "na0me"), Arguments.of("name0", "_postfix", true, "name0"), Arguments.of("-name", "_postfix", true, "_name_postfix"), Arguments.of("na-me", "_postfix", true, "na_me_postfix"), Arguments.of("name-", "_postfix", true, "name__postfix"), Arguments.of("Ĉname", "_postfix", false, "_name_postfix"), Arguments.of("naĈme", "_postfix", false, "na_me_postfix"), Arguments.of("nameĈ", "_postfix", false, "name__postfix"), Arguments.of("Ĉname", "_postfix", true, "Ĉname"), Arguments.of("naĈme", "_postfix", true, "naĈme"), Arguments.of("nameĈ", "_postfix", true, "nameĈ"), // Uncomment this when XID_Start and XID_Continue characters are correctly determined. // Arguments.of("Жname", "_postfix", true, "Жname"), // Arguments.of("naЖme", "_postfix", true, "naЖme"), // Arguments.of("nameЖ", "_postfix", true, "nameЖ"), // // Arguments.of("€name", "_postfix", true, "_name_postfix"), // Arguments.of("na€me", "_postfix", true, "na_me_postfix"), // Arguments.of("name€", "_postfix", true, "name__postfix"), Arguments.of("", "_postfix", true, "_postfix"), Arguments.of("if", "_postfix", true, "if_postfix"), Arguments.of("default", "_postfix", true, "default_postfix"), Arguments.of("true", "_postfix", true, "true_postfix"), Arguments.of("_", "_postfix", true, "__postfix")); } private static Stream<Arguments> provideArgsForConvertToRFieldNameTest() { return Stream.of( Arguments.of("ThemeDesign", "ThemeDesign"), Arguments.of("Theme.Design", "Theme_Design"), Arguments.of("Ĉ_ThemeDesign_Ĉ", "Ĉ_ThemeDesign_Ĉ"), Arguments.of("Ĉ_Theme.Design_Ĉ", "Ĉ_Theme_Design_Ĉ"), // The function must return a plausible result even though the resource name is invalid. Arguments.of("/_ThemeDesign_/", "/_ThemeDesign_/"), Arguments.of("/_Theme.Design_/", "/_Theme_Design_/")); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/xmlgen/ResXmlGenTest.java
jadx-core/src/test/java/jadx/core/xmlgen/ResXmlGenTest.java
package jadx.core.xmlgen; import java.util.ArrayList; import java.util.List; import org.assertj.core.util.Lists; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import jadx.api.JadxArgs; import jadx.api.security.IJadxSecurity; import jadx.api.security.JadxSecurityFlag; import jadx.api.security.impl.JadxSecurity; import jadx.core.xmlgen.entry.RawNamedValue; import jadx.core.xmlgen.entry.RawValue; import jadx.core.xmlgen.entry.ResourceEntry; import jadx.core.xmlgen.entry.ValuesParser; import static org.assertj.core.api.Assertions.assertThat; class ResXmlGenTest { private final JadxArgs args = new JadxArgs(); private final IJadxSecurity security = new JadxSecurity(JadxSecurityFlag.all()); private final ManifestAttributes manifestAttributes = new ManifestAttributes(security); @BeforeEach void init() { args.setCodeNewLineStr("\n"); } @Test void testSimpleAttr() { ResourceStorage resStorage = new ResourceStorage(security); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "attr", "size", ""); re.setNamedValues(Lists.list(new RawNamedValue(16777216, new RawValue(16, 64)))); resStorage.add(re); ValuesParser vp = new ValuesParser(null, resStorage.getResourcesNames()); ResXmlGen resXmlGen = new ResXmlGen(resStorage, vp, manifestAttributes); List<ResContainer> files = resXmlGen.makeResourcesXml(args); assertThat(files).hasSize(1); assertThat(files.get(0).getName()).isEqualTo("res/values/attrs.xml"); String input = files.get(0).getText().toString(); assertThat(input).isEqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n" + " <attr name=\"size\" format=\"dimension\">\n" + " </attr>\n" + "</resources>"); } @Test void testAttrEnum() { ResourceStorage resStorage = new ResourceStorage(security); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "attr", "size", ""); re.setNamedValues( Lists.list( new RawNamedValue(0x01000000, new RawValue(16, 65536)), new RawNamedValue(0x01040000, new RawValue(16, 1)))); resStorage.add(re); ValuesParser vp = new ValuesParser(null, resStorage.getResourcesNames()); ResXmlGen resXmlGen = new ResXmlGen(resStorage, vp, manifestAttributes); List<ResContainer> files = resXmlGen.makeResourcesXml(args); assertThat(files).hasSize(1); assertThat(files.get(0).getName()).isEqualTo("res/values/attrs.xml"); String input = files.get(0).getText().toString(); assertThat(input).isEqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n" + " <attr name=\"size\">\n" + " <enum name=\"android:string.cancel\" value=\"1\" />\n" + " </attr>\n" + "</resources>"); } @Test void testAttrFlag() { ResourceStorage resStorage = new ResourceStorage(security); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "attr", "size", ""); re.setNamedValues( Lists.list( new RawNamedValue(0x01000000, new RawValue(16, 131072)), new RawNamedValue(0x01040000, new RawValue(16, 1)))); resStorage.add(re); ValuesParser vp = new ValuesParser(null, resStorage.getResourcesNames()); ResXmlGen resXmlGen = new ResXmlGen(resStorage, vp, manifestAttributes); List<ResContainer> files = resXmlGen.makeResourcesXml(args); assertThat(files).hasSize(1); assertThat(files.get(0).getName()).isEqualTo("res/values/attrs.xml"); String input = files.get(0).getText().toString(); assertThat(input).isEqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n" + " <attr name=\"size\">\n" + " <flag name=\"android:string.cancel\" value=\"1\" />\n" + " </attr>\n" + "</resources>"); } @Test void testAttrMin() { ResourceStorage resStorage = new ResourceStorage(security); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "attr", "size", ""); re.setNamedValues( Lists.list(new RawNamedValue(16777216, new RawValue(16, 4)), new RawNamedValue(16777217, new RawValue(16, 1)))); resStorage.add(re); ValuesParser vp = new ValuesParser(null, resStorage.getResourcesNames()); ResXmlGen resXmlGen = new ResXmlGen(resStorage, vp, manifestAttributes); List<ResContainer> files = resXmlGen.makeResourcesXml(args); assertThat(files).hasSize(1); assertThat(files.get(0).getName()).isEqualTo("res/values/attrs.xml"); String input = files.get(0).getText().toString(); assertThat(input).isEqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n" + " <attr name=\"size\" format=\"integer\" min=\"1\">\n" + " </attr>\n" + "</resources>"); } @Test void testStyle() { ResourceStorage resStorage = new ResourceStorage(security); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "style", "JadxGui", ""); re.setNamedValues(Lists.list(new RawNamedValue(16842836, new RawValue(1, 17170445)))); resStorage.add(re); re = new ResourceEntry(2130903104, "jadx.gui.app", "style", "JadxGui.Dialog", ""); re.setParentRef(2130903103); re.setNamedValues(new ArrayList<>()); resStorage.add(re); ValuesParser vp = new ValuesParser(null, resStorage.getResourcesNames()); ResXmlGen resXmlGen = new ResXmlGen(resStorage, vp, manifestAttributes); List<ResContainer> files = resXmlGen.makeResourcesXml(args); assertThat(files).hasSize(1); assertThat(files.get(0).getName()).isEqualTo("res/values/styles.xml"); String input = files.get(0).getText().toString(); assertThat(input).isEqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n" + " <style name=\"JadxGui\" parent=\"\">\n" + " <item name=\"android:windowBackground\">@android:color/transparent</item>\n" + " </style>\n" + " <style name=\"JadxGui.Dialog\" parent=\"@style/JadxGui\">\n" + " </style>\n" + "</resources>"); } @Test void testString() { ResourceStorage resStorage = new ResourceStorage(security); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "string", "app_name", ""); re.setSimpleValue(new RawValue(3, 0)); re.setNamedValues(Lists.list()); resStorage.add(re); BinaryXMLStrings strings = new BinaryXMLStrings(); strings.put(0, "Jadx Decompiler App"); ValuesParser vp = new ValuesParser(strings, resStorage.getResourcesNames()); ResXmlGen resXmlGen = new ResXmlGen(resStorage, vp, manifestAttributes); List<ResContainer> files = resXmlGen.makeResourcesXml(args); assertThat(files).hasSize(1); assertThat(files.get(0).getName()).isEqualTo("res/values/strings.xml"); String input = files.get(0).getText().toString(); assertThat(input).isEqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n" + " <string name=\"app_name\">Jadx Decompiler App</string>\n" + "</resources>"); } @Test void testStringFormattedFalse() { ResourceStorage resStorage = new ResourceStorage(security); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "string", "app_name", ""); re.setSimpleValue(new RawValue(3, 0)); re.setNamedValues(Lists.list()); resStorage.add(re); BinaryXMLStrings strings = new BinaryXMLStrings(); strings.put(0, "%s at %s"); ValuesParser vp = new ValuesParser(strings, resStorage.getResourcesNames()); ResXmlGen resXmlGen = new ResXmlGen(resStorage, vp, manifestAttributes); List<ResContainer> files = resXmlGen.makeResourcesXml(args); assertThat(files).hasSize(1); assertThat(files.get(0).getName()).isEqualTo("res/values/strings.xml"); String input = files.get(0).getText().toString(); assertThat(input).isEqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n" + " <string name=\"app_name\" formatted=\"false\">%s at %s</string>\n" + "</resources>"); } @Test void testArrayEscape() { ResourceStorage resStorage = new ResourceStorage(security); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "array", "single_quote_escape_sample", ""); re.setNamedValues( Lists.list(new RawNamedValue(16777216, new RawValue(3, 0)))); resStorage.add(re); BinaryXMLStrings strings = new BinaryXMLStrings(); strings.put(0, "Let's go"); ValuesParser vp = new ValuesParser(strings, resStorage.getResourcesNames()); ResXmlGen resXmlGen = new ResXmlGen(resStorage, vp, manifestAttributes); List<ResContainer> files = resXmlGen.makeResourcesXml(args); assertThat(files).hasSize(1); assertThat(files.get(0).getName()).isEqualTo("res/values/arrays.xml"); String input = files.get(0).getText().toString(); assertThat(input).isEqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n" + " <array name=\"single_quote_escape_sample\">\n" + " <item>Let\\'s go</item>\n" + " </array>\n" + "</resources>"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/xmlgen/entry/ValuesParserTest.java
jadx-core/src/test/java/jadx/core/xmlgen/entry/ValuesParserTest.java
package jadx.core.xmlgen.entry; import java.util.Map; import org.junit.jupiter.api.Test; import jadx.core.utils.android.AndroidResourcesMap; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; class ValuesParserTest { @Test void testResMapLoad() { Map<Integer, String> androidResMap = AndroidResourcesMap.getMap(); assertThat(androidResMap).isNotNull().isNotEmpty(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/utils/TestGetBetterResourceName.java
jadx-core/src/test/java/jadx/core/utils/TestGetBetterResourceName.java
package jadx.core.utils; import org.assertj.core.api.AbstractStringAssert; import org.junit.jupiter.api.Test; import static jadx.core.utils.BetterName.getBetterResourceName; import static org.assertj.core.api.Assertions.assertThat; public class TestGetBetterResourceName { @Test public void testGoodNamesVsSyntheticNames() { assertThatBetterResourceName("color_main", "t0").isEqualTo("color_main"); assertThatBetterResourceName("done", "oOo0oO0o").isEqualTo("done"); } /** * Tests {@link BetterName#getBetterResourceName(String, String)} on equally good names. * In this case, according to the documentation, the method should return the first argument. * * @see BetterName#getBetterResourceName(String, String) */ @Test public void testEquallyGoodNames() { assertThatBetterResourceName("AAAA", "BBBB").isEqualTo("AAAA"); assertThatBetterResourceName("BBBB", "AAAA").isEqualTo("BBBB"); assertThatBetterResourceName("Theme.AppCompat.Light", "Theme_AppCompat_Light") .isEqualTo("Theme.AppCompat.Light"); assertThatBetterResourceName("Theme_AppCompat_Light", "Theme.AppCompat.Light") .isEqualTo("Theme_AppCompat_Light"); } private AbstractStringAssert<?> assertThatBetterResourceName(String firstName, String secondName) { return assertThat(getBetterResourceName(firstName, secondName)); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/utils/PassMergeTest.java
jadx-core/src/test/java/jadx/core/utils/PassMergeTest.java
package jadx.core.utils; import java.util.List; import org.junit.jupiter.api.Test; import jadx.api.impl.passes.DecompilePassWrapper; import jadx.api.plugins.pass.JadxPass; import jadx.api.plugins.pass.JadxPassInfo; import jadx.api.plugins.pass.impl.OrderedJadxPassInfo; import jadx.api.plugins.pass.impl.SimpleJadxPassInfo; import jadx.api.plugins.pass.types.JadxDecompilePass; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.visitors.AbstractVisitor; import jadx.core.dex.visitors.IDexTreeVisitor; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.catchThrowable; class PassMergeTest { @Test public void testSimple() { List<String> base = asList("a", "b", "c"); check(base, mockPass("x"), asList("a", "b", "c", "x")); check(base, mockPass(mockInfo("x").after(JadxPassInfo.START)), asList("x", "a", "b", "c")); check(base, mockPass(mockInfo("x").before(JadxPassInfo.END)), asList("a", "b", "c", "x")); } @Test public void testSingle() { List<String> base = asList("a", "b", "c"); check(base, mockPass(mockInfo("x").after("a")), asList("a", "x", "b", "c")); check(base, mockPass(mockInfo("x").before("c")), asList("a", "b", "x", "c")); check(base, mockPass(mockInfo("x").before("a")), asList("x", "a", "b", "c")); check(base, mockPass(mockInfo("x").after("c")), asList("a", "b", "c", "x")); } @Test public void testMulti() { List<String> base = asList("a", "b", "c"); JadxPass x = mockPass(mockInfo("x").after("a")); JadxPass y = mockPass(mockInfo("y").after("a")); JadxPass z = mockPass(mockInfo("z").before("b")); check(base, asList(x, y, z), asList("a", "y", "x", "z", "b", "c")); } @Test public void testMultiWithDeps() { List<String> base = asList("a", "b", "c"); JadxPass x = mockPass(mockInfo("x").after("a")); JadxPass y = mockPass(mockInfo("y").after("x")); JadxPass z = mockPass(mockInfo("z").before("b").after("y")); check(base, asList(x, y, z), asList("a", "x", "y", "z", "b", "c")); } @Test public void testMultiWithDeps2() { List<String> base = asList("a", "b", "c"); JadxPass x = mockPass(mockInfo("x").before("y")); JadxPass y = mockPass(mockInfo("y").before("b")); JadxPass z = mockPass(mockInfo("z").after("y")); check(base, asList(x, y, z), asList("a", "x", "y", "z", "b", "c")); } @Test public void testMultiWithDeps3() { List<String> base = asList("a", "b", "c"); JadxPass x = mockPass(mockInfo("x")); JadxPass y = mockPass(mockInfo("y").after("x").before("b")); check(base, asList(x, y), asList("a", "x", "y", "b", "c")); } @Test public void testLoop() { List<String> base = asList("a", "b", "c"); JadxPass x = mockPass(mockInfo("x").before("y")); JadxPass y = mockPass(mockInfo("y").before("x")); Throwable thrown = catchThrowable(() -> check(base, asList(x, y), emptyList())); assertThat(thrown).isInstanceOf(JadxRuntimeException.class); } private void check(List<String> visitorNames, JadxPass pass, List<String> result) { check(visitorNames, singletonList(pass), result); } private void check(List<String> visitorNames, List<JadxPass> passes, List<String> result) { List<IDexTreeVisitor> visitors = ListUtils.map(visitorNames, PassMergeTest::mockVisitor); new PassMerge(visitors).merge(passes, p -> new DecompilePassWrapper((JadxDecompilePass) p)); List<String> resultVisitors = ListUtils.map(visitors, IDexTreeVisitor::getName); assertThat(resultVisitors).isEqualTo(result); } private static IDexTreeVisitor mockVisitor(String name) { return new AbstractVisitor() { @Override public String getName() { return name; } }; } private JadxPass mockPass(String name) { return mockPass(new SimpleJadxPassInfo(name)); } private OrderedJadxPassInfo mockInfo(String name) { return new OrderedJadxPassInfo(name, name); } private JadxPass mockPass(JadxPassInfo info) { return new JadxDecompilePass() { @Override public void init(RootNode root) { } @Override public boolean visit(ClassNode cls) { return false; } @Override public void visit(MethodNode mth) { } @Override public JadxPassInfo getInfo() { return info; } @Override public String toString() { return info.getName(); } }; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/utils/TestBetterName.java
jadx-core/src/test/java/jadx/core/utils/TestBetterName.java
package jadx.core.utils; import org.junit.jupiter.api.Test; import static jadx.core.utils.BetterName.calcRating; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestBetterName { @Deprecated @Test public void test() { expectFirst("color_main", "t0"); expectFirst("done", "oOo0oO0o"); } @Deprecated private void expectFirst(String first, String second) { String best = BetterName.compareAndGet(first, second); assertThat(best) .as(() -> String.format("'%s'=%d, '%s'=%d", first, calcRating(first), second, calcRating(second))) .isEqualTo(first); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/utils/TestGetBetterClassName.java
jadx-core/src/test/java/jadx/core/utils/TestGetBetterClassName.java
package jadx.core.utils; import org.assertj.core.api.AbstractStringAssert; import org.junit.jupiter.api.Test; import static jadx.core.utils.BetterName.getBetterClassName; import static org.assertj.core.api.Assertions.assertThat; public class TestGetBetterClassName { @Test public void testGoodNamesVsGeneratedAliases() { assertThatBetterClassName("AppCompatButton", "C2404e2").isEqualTo("AppCompatButton"); assertThatBetterClassName("ContextThemeWrapper", "C2106b1").isEqualTo("ContextThemeWrapper"); assertThatBetterClassName("ListPopupWindow", "C2344a3").isEqualTo("ListPopupWindow"); } @Test public void testShortGoodNamesVsGeneratedAliases() { assertThatBetterClassName("Room", "C2937kh").isEqualTo("Room"); assertThatBetterClassName("Fade", "C1428qi").isEqualTo("Fade"); assertThatBetterClassName("Scene", "C4063yi").isEqualTo("Scene"); } @Test public void testGoodNamesVsGeneratedAliasesWithPrefix() { assertThatBetterClassName("AppCompatActivity", "ActivityC2646h0").isEqualTo("AppCompatActivity"); assertThatBetterClassName("PagerAdapter", "AbstractC3038lk").isEqualTo("PagerAdapter"); assertThatBetterClassName("Lazy", "InterfaceC6434a").isEqualTo("Lazy"); assertThatBetterClassName("MembersInjector", "InterfaceC6435b").isEqualTo("MembersInjector"); assertThatBetterClassName("Subscriber", "InterfaceC6439c").isEqualTo("Subscriber"); } @Test public void testGoodNamesWithDigitsVsGeneratedAliases() { assertThatBetterClassName("ISO8061Formatter", "C1121uq4").isEqualTo("ISO8061Formatter"); assertThatBetterClassName("Jdk9Platform", "C1189rn6").isEqualTo("Jdk9Platform"); assertThatBetterClassName("WrappedDrawableApi14", "C2847i9").isEqualTo("WrappedDrawableApi14"); assertThatBetterClassName("WrappedDrawableApi21", "C2888j9").isEqualTo("WrappedDrawableApi21"); } @Test public void testShortNamesVsLongNames() { assertThatBetterClassName("az", "Observer").isEqualTo("Observer"); assertThatBetterClassName("bb", "RenderEvent").isEqualTo("RenderEvent"); assertThatBetterClassName("aaaa", "FontUtils").isEqualTo("FontUtils"); } /** * Tests {@link BetterName#getBetterClassName(String, String)} on equally good names. * In this case, according to the documentation, the method should return the first argument. * * @see BetterName#getBetterClassName(String, String) */ @Test public void testEquallyGoodNames() { assertThatBetterClassName("AAAA", "BBBB").isEqualTo("AAAA"); assertThatBetterClassName("BBBB", "AAAA").isEqualTo("BBBB"); assertThatBetterClassName("XYXYXY", "YZYZYZ").isEqualTo("XYXYXY"); assertThatBetterClassName("YZYZYZ", "XYXYXY").isEqualTo("YZYZYZ"); } private AbstractStringAssert<?> assertThatBetterClassName(String firstName, String secondName) { return assertThat(getBetterClassName(firstName, secondName)); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/utils/TypeUtilsTest.java
jadx-core/src/test/java/jadx/core/utils/TypeUtilsTest.java
package jadx.core.utils; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxArgs; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.RootNode; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; class TypeUtilsTest { private static final Logger LOG = LoggerFactory.getLogger(TypeUtilsTest.class); private static RootNode root; @BeforeAll public static void init() { root = new RootNode(new JadxArgs()); root.initClassPath(); } @Test public void testReplaceGenericsWithWildcards() { // check classpath graph List<ArgType> classGenerics = root.getTypeUtils().getClassGenerics(ArgType.object("java.util.ArrayList")); assertThat(classGenerics).hasSize(1); ArgType genericInfo = classGenerics.get(0); assertThat(genericInfo.getObject()).isEqualTo("E"); assertThat(genericInfo.getExtendTypes()).hasSize(0); // prepare input ArgType instanceType = ArgType.generic("java.util.ArrayList", ArgType.OBJECT); LOG.debug("instanceType: {}", instanceType); ArgType generic = ArgType.generic("java.util.List", ArgType.wildcard(ArgType.genericType("E"), ArgType.WildcardBound.SUPER)); LOG.debug("generic: {}", generic); // replace ArgType result = root.getTypeUtils().replaceClassGenerics(instanceType, generic); LOG.debug("result: {}", result); ArgType expected = ArgType.generic("java.util.List", ArgType.wildcard(ArgType.OBJECT, ArgType.WildcardBound.SUPER)); assertThat(result).isEqualTo(expected); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/utils/log/LogUtilsTest.java
jadx-core/src/test/java/jadx/core/utils/log/LogUtilsTest.java
package jadx.core.utils.log; import org.junit.jupiter.api.Test; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; class LogUtilsTest { @Test void escape() { assertThat(LogUtils.escape("Guest'%0AUser:'Admin")).isEqualTo("Guest..0AUser..Admin"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/plugins/versions/VerifyRequiredVersionTest.java
jadx-core/src/test/java/jadx/core/plugins/versions/VerifyRequiredVersionTest.java
package jadx.core.plugins.versions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class VerifyRequiredVersionTest { @Test public void test() { isCompatible("1.5.0, r2000", "1.5.1", true); isCompatible("1.5.1, r3000", "1.5.1", true); isCompatible("1.5.1, r3000", "1.6.0", true); isCompatible("1.5.1, r3000", "1.5.0", false); isCompatible("1.5.1, r3000", "r3001.417bb7a", true); isCompatible("1.5.1, r3000", "r4000", true); isCompatible("1.5.1, r3000", "r3000", true); isCompatible("1.5.1, r3000", "r2000", false); } private static void isCompatible(String requiredVersion, String jadxVersion, boolean result) { assertThat(new VerifyRequiredVersion(jadxVersion).isCompatible(requiredVersion)) .as("Expect plugin with required version %s is%s compatible with jadx %s", requiredVersion, result ? "" : " not", jadxVersion) .isEqualTo(result); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/plugins/versions/VersionComparatorTest.java
jadx-core/src/test/java/jadx/core/plugins/versions/VersionComparatorTest.java
package jadx.core.plugins.versions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class VersionComparatorTest { @Test public void testCompare() { checkCompare("", "", 0); checkCompare("1", "1", 0); checkCompare("1", "2", -1); checkCompare("1.1", "1.1", 0); checkCompare("0.5", "0.5", 0); checkCompare("0.5", "0.5.0", 0); checkCompare("0.5", "0.5.00", 0); checkCompare("0.5", "0.5.0.0", 0); checkCompare("0.5", "0.5.0.1", -1); checkCompare("0.5.0", "0.5.0", 0); checkCompare("0.5.0", "0.5.1", -1); checkCompare("0.5", "0.5.1", -1); checkCompare("0.4.8", "0.5", -1); checkCompare("0.4.8", "0.5.0", -1); checkCompare("0.4.8", "0.6", -1); checkCompare("1.3.3.1", "1.3.3", 1); checkCompare("1.3.3-1", "1.3.3", 1); checkCompare("1.3.3.1-1", "1.3.3", 1); } @Test public void testCompareUnstable() { checkCompare("r2190.ce527ed", "jadx-r2299.742d30d", -1); } private static void checkCompare(String a, String b, int result) { assertThat(VersionComparator.checkAndCompare(a, b)) .as("Compare %s and %s expect %d", a, b, result) .isEqualTo(result); assertThat(VersionComparator.checkAndCompare(b, a)) .as("Compare %s and %s expect %d", b, a, -result) .isEqualTo(-result); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/deobf/NameMapperTest.java
jadx-core/src/test/java/jadx/core/deobf/NameMapperTest.java
package jadx.core.deobf; import org.junit.jupiter.api.Test; import static jadx.core.deobf.NameMapper.isValidIdentifier; import static jadx.core.deobf.NameMapper.removeInvalidChars; import static jadx.core.deobf.NameMapper.removeInvalidCharsMiddle; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class NameMapperTest { @Test public void validIdentifiers() { assertThat(isValidIdentifier("ACls")).isTrue(); } @Test public void notValidIdentifiers() { assertThat(isValidIdentifier("1cls")).isFalse(); assertThat(isValidIdentifier("-cls")).isFalse(); assertThat(isValidIdentifier("A-cls")).isFalse(); } @Test public void testRemoveInvalidCharsMiddle() { assertThat(removeInvalidCharsMiddle("1cls")).isEqualTo("1cls"); assertThat(removeInvalidCharsMiddle("-cls")).isEqualTo("cls"); assertThat(removeInvalidCharsMiddle("A-cls")).isEqualTo("Acls"); } @Test public void testRemoveInvalidChars() { assertThat(removeInvalidChars("1cls", "C")).isEqualTo("C1cls"); assertThat(removeInvalidChars("-cls", "C")).isEqualTo("cls"); assertThat(removeInvalidChars("A-cls", "C")).isEqualTo("Acls"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/dex/instructions/args/ArgTypeTest.java
jadx-core/src/test/java/jadx/core/dex/instructions/args/ArgTypeTest.java
package jadx.core.dex.instructions.args; import org.junit.jupiter.api.Test; import static jadx.core.dex.instructions.args.ArgType.WildcardBound.SUPER; import static jadx.core.dex.instructions.args.ArgType.generic; import static jadx.core.dex.instructions.args.ArgType.genericType; import static jadx.core.dex.instructions.args.ArgType.wildcard; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; class ArgTypeTest { @Test public void testEqualsOfGenericTypes() { ArgType first = ArgType.generic("java.lang.List", ArgType.STRING); ArgType second = ArgType.generic("Ljava/lang/List;", ArgType.STRING); assertThat(first).isEqualTo(second); } @Test void testContainsGenericType() { ArgType wildcard = wildcard(genericType("T"), SUPER); assertThat(wildcard.containsTypeVariable()).isTrue(); ArgType type = generic("java.lang.List", wildcard); assertThat(type.containsTypeVariable()).isTrue(); } @Test void testInnerGeneric() { ArgType[] genericTypes = new ArgType[] { ArgType.genericType("K"), ArgType.genericType("V") }; ArgType base = ArgType.generic("java.util.Map", genericTypes); ArgType genericInner = ArgType.outerGeneric(base, ArgType.generic("Entry", genericTypes)); assertThat(genericInner.toString()).isEqualTo("java.util.Map<K, V>$Entry<K, V>"); assertThat(genericInner.containsTypeVariable()).isTrue(); ArgType genericInner2 = ArgType.outerGeneric(base, ArgType.object("Entry")); assertThat(genericInner2.toString()).isEqualTo("java.util.Map<K, V>$Entry"); assertThat(genericInner2.containsTypeVariable()).isTrue(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/dex/nodes/utils/SelectFromDuplicatesTest.java
jadx-core/src/test/java/jadx/core/dex/nodes/utils/SelectFromDuplicatesTest.java
package jadx.core.dex.nodes.utils; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.RootNode; import jadx.tests.api.utils.TestUtils; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; class SelectFromDuplicatesTest { private RootNode root; @BeforeEach public void init() { JadxArgs args = new JadxArgs(); args.addInputFile(TestUtils.getFileForSample("test-samples/hello.dex")); JadxDecompiler decompiler = new JadxDecompiler(args); decompiler.load(); root = decompiler.getRoot(); } @Test void testSelectBySource() { selectBySources(0, false, "classes.dex", "classes2.dex"); selectBySources(2, false, "classes10.dex", "classes20.dex", "classes2.dex"); } @RepeatedTest(10) void testSelectBySourceShuffled() { selectFirstByShuffleSources("classes.dex", "classes2.dex", "classes4.dex"); selectFirstByShuffleSources("classes2.dex", "classes10.dex", "classes20.dex"); selectFirstByShuffleSources("classes10.dex", "classes1.dex", "classes01.dex", "classes000.dex", "classes02.dex"); } private void selectFirstByShuffleSources(String... sources) { selectBySources(0, true, sources); } private void selectBySources(int selectedPos, boolean shuffle, String... sources) { List<ClassNode> clsList = Arrays.stream(sources) .map(this::buildClassNodeBySource) .collect(Collectors.toList()); ClassNode expected = clsList.get(selectedPos); if (shuffle) { Collections.shuffle(clsList, new Random(System.currentTimeMillis() + System.nanoTime())); } ClassNode selectedCls = SelectFromDuplicates.process(clsList); assertThat(selectedCls) .describedAs("Expect %s, but got %s from list: %s", expected, selectedCls, clsList) .isSameAs(expected); } private ClassNode buildClassNodeBySource(String clsSource) { ClassInfo clsInfo = ClassInfo.fromName(root, "ClassFromSource:" + clsSource); ClassNode cls = ClassNode.addSyntheticClass(root, clsInfo, 0); cls.setInputFileName(clsSource); return cls; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/dex/nodes/utils/TypeUtilsTest.java
jadx-core/src/test/java/jadx/core/dex/nodes/utils/TypeUtilsTest.java
package jadx.core.dex.nodes.utils; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import jadx.api.JadxArgs; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.RootNode; import static jadx.core.dex.instructions.args.ArgType.EXCEPTION; import static jadx.core.dex.instructions.args.ArgType.STRING; import static jadx.core.dex.instructions.args.ArgType.array; import static jadx.core.dex.instructions.args.ArgType.generic; import static jadx.core.dex.instructions.args.ArgType.genericType; import static jadx.core.dex.instructions.args.ArgType.object; import static jadx.core.dex.instructions.args.ArgType.outerGeneric; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; class TypeUtilsTest { private TypeUtils typeUtils; @BeforeEach public void init() { typeUtils = new TypeUtils(new RootNode(new JadxArgs())); } @Test void replaceTypeVariablesUsingMap() { ArgType typeVar = genericType("T"); ArgType listCls = object("java.util.List"); Map<ArgType, ArgType> typeMap = Collections.singletonMap(typeVar, STRING); replaceTypeVar(typeVar, typeMap, STRING); replaceTypeVar(generic(listCls, typeVar), typeMap, generic(listCls, STRING)); replaceTypeVar(array(typeVar), typeMap, array(STRING)); } @Test void replaceTypeVariablesUsingMap2() { ArgType kVar = genericType("K"); ArgType vVar = genericType("V"); ArgType mapCls = object("java.util.Map"); ArgType entryCls = object("Entry"); ArgType typedMap = generic(mapCls, kVar, vVar); ArgType typedEntry = generic(entryCls, kVar, vVar); Map<ArgType, ArgType> typeMap = new HashMap<>(); typeMap.put(kVar, STRING); typeMap.put(vVar, EXCEPTION); ArgType replacedMap = typeUtils.replaceTypeVariablesUsingMap(typedMap, typeMap); ArgType replacedEntry = typeUtils.replaceTypeVariablesUsingMap(typedEntry, typeMap); replaceTypeVar(outerGeneric(typedMap, entryCls), typeMap, outerGeneric(replacedMap, entryCls)); replaceTypeVar(outerGeneric(typedMap, typedEntry), typeMap, outerGeneric(replacedMap, replacedEntry)); } private void replaceTypeVar(ArgType typeVar, Map<ArgType, ArgType> typeMap, ArgType expected) { ArgType resultType = typeUtils.replaceTypeVariablesUsingMap(typeVar, typeMap); assertThat(resultType) .as("Replace %s using map %s", typeVar, typeMap) .isEqualTo(expected); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/dex/visitors/typeinference/PrimitiveConversionsTests.java
jadx-core/src/test/java/jadx/core/dex/visitors/typeinference/PrimitiveConversionsTests.java
package jadx.core.dex.visitors.typeinference; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import jadx.api.JadxArgs; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.RootNode; import static jadx.core.dex.instructions.args.ArgType.BOOLEAN; import static jadx.core.dex.instructions.args.ArgType.BYTE; import static jadx.core.dex.instructions.args.ArgType.CHAR; import static jadx.core.dex.instructions.args.ArgType.DOUBLE; import static jadx.core.dex.instructions.args.ArgType.FLOAT; import static jadx.core.dex.instructions.args.ArgType.INT; import static jadx.core.dex.instructions.args.ArgType.LONG; import static jadx.core.dex.instructions.args.ArgType.SHORT; import static jadx.core.dex.instructions.args.ArgType.VOID; import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.CONFLICT; import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.EQUAL; import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.NARROW; import static jadx.core.dex.visitors.typeinference.TypeCompareEnum.WIDER; import static org.assertj.core.api.Assertions.assertThat; public class PrimitiveConversionsTests { private static TypeCompare comparator; @BeforeAll static void before() { JadxArgs args = new JadxArgs(); RootNode root = new RootNode(args); comparator = new TypeCompare(root); } @DisplayName("Check conversion of numeric types") @ParameterizedTest(name = "{0} -> {1} (should be {2})") @MethodSource("provideArgsForNumericConversionsTest") void testNumericConversions(ArgType firstType, ArgType secondType, TypeCompareEnum expectedResult) { assertThat(comparator.compareTypes(firstType, secondType)).isEqualTo(expectedResult); } @DisplayName("Ensure that `boolean` is not convertible to other primitive types") @ParameterizedTest(name = "{0} <-> boolean") @MethodSource("providePrimitiveTypesWithVoid") void testBooleanConversions(ArgType type) { final var expectedResult = type.equals(BOOLEAN) ? EQUAL : CONFLICT; assertThat(comparator.compareTypes(type, BOOLEAN)).isEqualTo(expectedResult); assertThat(comparator.compareTypes(BOOLEAN, type)).isEqualTo(expectedResult); } @DisplayName("Ensure that `void` is not convertible to other primitive types") @ParameterizedTest(name = "{0} <-> void") @MethodSource("providePrimitiveTypesWithVoid") void testVoidConversions(ArgType type) { final var expectedResult = type.equals(VOID) ? EQUAL : CONFLICT; assertThat(comparator.compareTypes(type, VOID)).isEqualTo(expectedResult); assertThat(comparator.compareTypes(VOID, type)).isEqualTo(expectedResult); } private static Stream<Arguments> provideArgsForNumericConversionsTest() { return Stream.of( Arguments.of(BYTE, BYTE, EQUAL), Arguments.of(BYTE, SHORT, NARROW), Arguments.of(BYTE, CHAR, WIDER), Arguments.of(BYTE, INT, NARROW), Arguments.of(BYTE, LONG, NARROW), Arguments.of(BYTE, FLOAT, NARROW), Arguments.of(BYTE, DOUBLE, NARROW), Arguments.of(SHORT, BYTE, WIDER), Arguments.of(SHORT, SHORT, EQUAL), Arguments.of(SHORT, CHAR, WIDER), Arguments.of(SHORT, INT, NARROW), Arguments.of(SHORT, LONG, NARROW), Arguments.of(SHORT, FLOAT, NARROW), Arguments.of(SHORT, DOUBLE, NARROW), Arguments.of(CHAR, BYTE, WIDER), Arguments.of(CHAR, SHORT, WIDER), Arguments.of(CHAR, CHAR, EQUAL), Arguments.of(CHAR, INT, NARROW), Arguments.of(CHAR, LONG, NARROW), Arguments.of(CHAR, FLOAT, NARROW), Arguments.of(CHAR, DOUBLE, NARROW), Arguments.of(INT, BYTE, WIDER), Arguments.of(INT, SHORT, WIDER), Arguments.of(INT, CHAR, WIDER), Arguments.of(INT, INT, EQUAL), Arguments.of(INT, LONG, NARROW), Arguments.of(INT, FLOAT, NARROW), Arguments.of(INT, DOUBLE, NARROW), Arguments.of(LONG, BYTE, WIDER), Arguments.of(LONG, SHORT, WIDER), Arguments.of(LONG, CHAR, WIDER), Arguments.of(LONG, INT, WIDER), Arguments.of(LONG, LONG, EQUAL), Arguments.of(LONG, FLOAT, NARROW), Arguments.of(LONG, DOUBLE, NARROW), Arguments.of(FLOAT, BYTE, WIDER), Arguments.of(FLOAT, SHORT, WIDER), Arguments.of(FLOAT, CHAR, WIDER), Arguments.of(FLOAT, INT, WIDER), Arguments.of(FLOAT, LONG, WIDER), Arguments.of(FLOAT, FLOAT, EQUAL), Arguments.of(FLOAT, DOUBLE, NARROW), Arguments.of(DOUBLE, BYTE, WIDER), Arguments.of(DOUBLE, SHORT, WIDER), Arguments.of(DOUBLE, CHAR, WIDER), Arguments.of(DOUBLE, INT, WIDER), Arguments.of(DOUBLE, LONG, WIDER), Arguments.of(DOUBLE, FLOAT, WIDER), Arguments.of(DOUBLE, DOUBLE, EQUAL)); } private static Stream<ArgType> providePrimitiveTypesWithVoid() { return Stream.of(BYTE, SHORT, CHAR, INT, LONG, FLOAT, DOUBLE, BOOLEAN, VOID); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/dex/visitors/typeinference/TypeCompareTest.java
jadx-core/src/test/java/jadx/core/dex/visitors/typeinference/TypeCompareTest.java
package jadx.core.dex.visitors.typeinference; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.NotYetImplementedExtension; import jadx.api.JadxArgs; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.ArgType.WildcardBound; import jadx.core.dex.nodes.RootNode; import static jadx.core.dex.instructions.args.ArgType.BYTE; import static jadx.core.dex.instructions.args.ArgType.CHAR; import static jadx.core.dex.instructions.args.ArgType.CLASS; import static jadx.core.dex.instructions.args.ArgType.EXCEPTION; import static jadx.core.dex.instructions.args.ArgType.INT; import static jadx.core.dex.instructions.args.ArgType.NARROW; import static jadx.core.dex.instructions.args.ArgType.NARROW_INTEGRAL; import static jadx.core.dex.instructions.args.ArgType.OBJECT; import static jadx.core.dex.instructions.args.ArgType.STRING; import static jadx.core.dex.instructions.args.ArgType.THROWABLE; import static jadx.core.dex.instructions.args.ArgType.UNKNOWN; import static jadx.core.dex.instructions.args.ArgType.UNKNOWN_ARRAY; import static jadx.core.dex.instructions.args.ArgType.UNKNOWN_OBJECT; import static jadx.core.dex.instructions.args.ArgType.array; import static jadx.core.dex.instructions.args.ArgType.generic; import static jadx.core.dex.instructions.args.ArgType.genericType; import static jadx.core.dex.instructions.args.ArgType.object; import static jadx.core.dex.instructions.args.ArgType.wildcard; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; @ExtendWith(NotYetImplementedExtension.class) public class TypeCompareTest { private static final Logger LOG = LoggerFactory.getLogger(TypeCompareTest.class); private TypeCompare compare; @BeforeEach public void init() { JadxArgs args = new JadxArgs(); RootNode root = new RootNode(args); root.loadClasses(Collections.emptyList()); root.initClassPath(); compare = new TypeCompare(root); } @Test public void compareTypes() { check(INT, UNKNOWN_OBJECT, TypeCompareEnum.CONFLICT); check(INT, OBJECT, TypeCompareEnum.CONFLICT); firstIsNarrow(INT, UNKNOWN); firstIsNarrow(CHAR, NARROW_INTEGRAL); firstIsNarrow(array(UNKNOWN), UNKNOWN); firstIsNarrow(array(UNKNOWN), NARROW); firstIsNarrow(array(CHAR), UNKNOWN_OBJECT); } @Test public void compareArrays() { firstIsNarrow(array(CHAR), OBJECT); firstIsNarrow(array(CHAR), array(UNKNOWN)); firstIsNarrow(array(OBJECT), OBJECT); firstIsNarrow(array(OBJECT), array(UNKNOWN_OBJECT)); firstIsNarrow(array(STRING), array(UNKNOWN_OBJECT)); firstIsNarrow(array(STRING), array(OBJECT)); firstIsNarrow(UNKNOWN_ARRAY, OBJECT); firstIsNarrow(array(BYTE), OBJECT); firstIsNarrow(array(array(BYTE)), array(OBJECT)); check(array(OBJECT), array(INT), TypeCompareEnum.CONFLICT); ArgType integerType = object("java.lang.Integer"); check(array(OBJECT), array(integerType), TypeCompareEnum.WIDER); check(array(INT), array(integerType), TypeCompareEnum.CONFLICT); check(array(INT), array(INT), TypeCompareEnum.EQUAL); ArgType wildClass = generic(CLASS, wildcard()); check(array(wildClass), array(CLASS), TypeCompareEnum.NARROW_BY_GENERIC); check(array(CLASS), array(wildClass), TypeCompareEnum.WIDER_BY_GENERIC); } @Test public void compareGenerics() { ArgType mapCls = object("java.util.Map"); ArgType setCls = object("java.util.Set"); ArgType keyType = genericType("K"); ArgType valueType = genericType("V"); ArgType mapGeneric = ArgType.generic(mapCls.getObject(), keyType, valueType); check(mapCls, mapGeneric, TypeCompareEnum.WIDER_BY_GENERIC); check(mapCls, setCls, TypeCompareEnum.CONFLICT); ArgType setGeneric = ArgType.generic(setCls.getObject(), valueType); ArgType setWildcard = ArgType.generic(setCls.getObject(), ArgType.wildcard()); check(setWildcard, setGeneric, TypeCompareEnum.CONFLICT); check(setWildcard, setCls, TypeCompareEnum.NARROW_BY_GENERIC); // TODO implement compare for wildcard with bounds } @Test public void compareWildCards() { ArgType clsWildcard = generic(CLASS.getObject(), wildcard()); check(clsWildcard, CLASS, TypeCompareEnum.NARROW_BY_GENERIC); ArgType clsExtendedWildcard = generic(CLASS.getObject(), wildcard(STRING, WildcardBound.EXTENDS)); check(clsWildcard, clsExtendedWildcard, TypeCompareEnum.WIDER); ArgType listWildcard = generic(CLASS.getObject(), wildcard(object("java.util.List"), WildcardBound.EXTENDS)); ArgType collWildcard = generic(CLASS.getObject(), wildcard(object("java.util.Collection"), WildcardBound.EXTENDS)); check(listWildcard, collWildcard, TypeCompareEnum.NARROW); ArgType collSuperWildcard = generic(CLASS.getObject(), wildcard(object("java.util.Collection"), WildcardBound.SUPER)); check(collSuperWildcard, listWildcard, TypeCompareEnum.CONFLICT); } @Test public void compareGenericWildCards() { // 'java.util.List<T>' and 'java.util.List<? extends T>' ArgType listCls = object("java.util.List"); ArgType genericType = genericType("T"); ArgType genericList = generic(listCls, genericType); ArgType genericExtendedList = generic(listCls, wildcard(genericType, WildcardBound.EXTENDS)); check(genericList, genericExtendedList, TypeCompareEnum.CONFLICT_BY_GENERIC); } @Test public void compareGenericTypes() { ArgType vType = genericType("V"); check(vType, OBJECT, TypeCompareEnum.NARROW); check(vType, STRING, TypeCompareEnum.CONFLICT); ArgType rType = genericType("R"); check(vType, rType, TypeCompareEnum.CONFLICT); check(vType, vType, TypeCompareEnum.EQUAL); ArgType tType = genericType("T"); ArgType tStringType = genericType("T", STRING); check(tStringType, STRING, TypeCompareEnum.NARROW); check(tStringType, OBJECT, TypeCompareEnum.NARROW); check(tStringType, tType, TypeCompareEnum.NARROW); ArgType tObjType = genericType("T", OBJECT); check(tObjType, OBJECT, TypeCompareEnum.NARROW); check(tObjType, tType, TypeCompareEnum.EQUAL); check(tStringType, tObjType, TypeCompareEnum.NARROW); } @Test public void compareGenericTypes2() { ArgType npeType = object("java.lang.NullPointerException"); // check clsp graph check(npeType, THROWABLE, TypeCompareEnum.NARROW); check(npeType, EXCEPTION, TypeCompareEnum.NARROW); check(EXCEPTION, THROWABLE, TypeCompareEnum.NARROW); ArgType typeVar = genericType("T", EXCEPTION); // T extends Exception // target checks check(THROWABLE, typeVar, TypeCompareEnum.WIDER); check(EXCEPTION, typeVar, TypeCompareEnum.WIDER); check(npeType, typeVar, TypeCompareEnum.NARROW); } @Test public void compareOuterGenerics() { ArgType hashMapType = object("java.util.HashMap"); ArgType innerEntrySetType = object("EntrySet"); ArgType firstInstance = ArgType.outerGeneric(generic(hashMapType, STRING, STRING), innerEntrySetType); ArgType secondInstance = ArgType.outerGeneric(generic(hashMapType, OBJECT, OBJECT), innerEntrySetType); check(firstInstance, secondInstance, TypeCompareEnum.NARROW); } private void firstIsNarrow(ArgType first, ArgType second) { check(first, second, TypeCompareEnum.NARROW); } private void check(ArgType first, ArgType second, TypeCompareEnum expectedResult) { LOG.debug("Compare: '{}' and '{}', expect: '{}'", first, second, expectedResult); assertThat(compare.compareTypes(first, second)) .as("Compare '%s' and '%s'", first, second) .isEqualTo(expectedResult); assertThat(compare.compareTypes(second, first)) .as("Compare '%s' and '%s'", second, first) .isEqualTo(expectedResult.invert()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/core/dex/info/AccessInfoTest.java
jadx-core/src/test/java/jadx/core/dex/info/AccessInfoTest.java
package jadx.core.dex.info; import org.junit.jupiter.api.Test; import jadx.api.plugins.input.data.AccessFlags; import jadx.core.dex.info.AccessInfo.AFType; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; public class AccessInfoTest { @Test public void changeVisibility() { AccessInfo accessInfo = new AccessInfo(AccessFlags.PROTECTED | AccessFlags.STATIC, AFType.METHOD); AccessInfo result = accessInfo.changeVisibility(AccessFlags.PUBLIC); assertThat(result.isPublic()).isTrue(); assertThat(result.isPrivate()).isFalse(); assertThat(result.isProtected()).isFalse(); assertThat(result.isStatic()).isTrue(); } @Test public void changeVisibilityNoOp() { AccessInfo accessInfo = new AccessInfo(AccessFlags.PUBLIC, AFType.METHOD); AccessInfo result = accessInfo.changeVisibility(AccessFlags.PUBLIC); assertThat(result).isSameAs(accessInfo); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/ICodeCache.java
jadx-core/src/main/java/jadx/api/ICodeCache.java
package jadx.api; import java.io.Closeable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface ICodeCache extends Closeable { void add(String clsFullName, ICodeInfo codeInfo); void remove(String clsFullName); @NotNull ICodeInfo get(String clsFullName); @Nullable String getCode(String clsFullName); boolean contains(String clsFullName); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/ICodeWriter.java
jadx-core/src/main/java/jadx/api/ICodeWriter.java
package jadx.api; import java.util.Map; import org.jetbrains.annotations.ApiStatus; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeNodeRef; public interface ICodeWriter { boolean isMetadataSupported(); ICodeWriter startLine(); ICodeWriter startLine(char c); ICodeWriter startLine(String str); ICodeWriter startLineWithNum(int sourceLine); ICodeWriter addMultiLine(String str); ICodeWriter add(String str); ICodeWriter add(char c); ICodeWriter add(ICodeWriter code); ICodeWriter newLine(); ICodeWriter addIndent(); void incIndent(); void decIndent(); int getIndent(); void setIndent(int indent); /** * Return current line (only if metadata is supported) */ int getLine(); /** * Return start line position (only if metadata is supported) */ int getLineStartPos(); void attachDefinition(ICodeNodeRef obj); void attachAnnotation(ICodeAnnotation obj); void attachLineAnnotation(ICodeAnnotation obj); void attachSourceLine(int sourceLine); ICodeInfo finish(); String getCodeStr(); int getLength(); StringBuilder getRawBuf(); @ApiStatus.Internal Map<Integer, ICodeAnnotation> getRawAnnotations(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/ResourceFileContent.java
jadx-core/src/main/java/jadx/api/ResourceFileContent.java
package jadx.api; import jadx.core.xmlgen.ResContainer; public class ResourceFileContent extends ResourceFile { private final ICodeInfo content; public ResourceFileContent(String name, ResourceType type, ICodeInfo content) { super(null, name, type); this.content = content; } @Override public ResContainer loadContent() { return ResContainer.textResource(getDeobfName(), content); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/ResourceFileContainer.java
jadx-core/src/main/java/jadx/api/ResourceFileContainer.java
package jadx.api; import jadx.core.xmlgen.ResContainer; public class ResourceFileContainer extends ResourceFile { private final ResContainer container; public ResourceFileContainer(String name, ResourceType type, ResContainer container) { super(null, name, type); this.container = container; } @Override public ResContainer loadContent() { return container; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/DecompilationMode.java
jadx-core/src/main/java/jadx/api/DecompilationMode.java
package jadx.api; public enum DecompilationMode { /** * Trying best options (default) */ AUTO, /** * Restore code structure (normal java code) */ RESTRUCTURE, /** * Simplified instructions (linear with goto's) */ SIMPLE, /** * Raw instructions without modifications */ FALLBACK; public boolean isSpecial() { switch (this) { case AUTO: case RESTRUCTURE: return false; case SIMPLE: case FALLBACK: return true; default: throw new RuntimeException("Unexpected decompilation mode: " + this); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/CommentsLevel.java
jadx-core/src/main/java/jadx/api/CommentsLevel.java
package jadx.api; public enum CommentsLevel { NONE, USER_ONLY, ERROR, WARN, INFO, DEBUG; public boolean filter(CommentsLevel limit) { return this.ordinal() <= limit.ordinal(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/JavaMethod.java
jadx-core/src/main/java/jadx/api/JavaMethod.java
package jadx.api; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.jetbrains.annotations.ApiStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeNodeRef; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.MethodOverrideAttr; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.Utils; public final class JavaMethod implements JavaNode { private static final Logger LOG = LoggerFactory.getLogger(JavaMethod.class); private final MethodNode mth; private final JavaClass parent; JavaMethod(JavaClass cls, MethodNode m) { this.parent = cls; this.mth = m; } @Override public String getName() { return mth.getAlias(); } @Override public String getFullName() { return mth.getMethodInfo().getFullName(); } @Override public JavaClass getDeclaringClass() { return parent; } @Override public JavaClass getTopParentClass() { return parent.getTopParentClass(); } public AccessInfo getAccessFlags() { return mth.getAccessFlags(); } public List<ArgType> getArguments() { List<ArgType> infoArgTypes = mth.getMethodInfo().getArgumentsTypes(); if (infoArgTypes.isEmpty()) { return Collections.emptyList(); } List<ArgType> arguments = mth.getArgTypes(); return Utils.collectionMap(arguments, type -> ArgType.tryToResolveClassAlias(mth.root(), type)); } public ArgType getReturnType() { ArgType retType = mth.getReturnType(); return ArgType.tryToResolveClassAlias(mth.root(), retType); } @Override public List<JavaNode> getUseIn() { return getDeclaringClass().getRootDecompiler().convertNodes(mth.getUseIn()); } public List<JavaMethod> getOverrideRelatedMethods() { MethodOverrideAttr ovrdAttr = mth.get(AType.METHOD_OVERRIDE); if (ovrdAttr == null) { return Collections.emptyList(); } JadxDecompiler decompiler = getDeclaringClass().getRootDecompiler(); return ovrdAttr.getRelatedMthNodes() .stream() .map(decompiler::convertMethodNode) .collect(Collectors.toList()); } public boolean isConstructor() { return mth.getMethodInfo().isConstructor(); } public boolean isClassInit() { return mth.getMethodInfo().isClassInit(); } @Override public int getDefPos() { return mth.getDefPosition(); } public String getCodeStr() { return mth.getCodeStr(); } @Override public void removeAlias() { this.mth.getMethodInfo().removeAlias(); } @Override public boolean isOwnCodeAnnotation(ICodeAnnotation ann) { if (ann.getAnnType() == ICodeAnnotation.AnnType.METHOD) { return ann.equals(mth); } return false; } @Override public ICodeNodeRef getCodeNodeRef() { return mth; } /** * Internal API. Not Stable! */ @ApiStatus.Internal public MethodNode getMethodNode() { return mth; } @Override public int hashCode() { return mth.hashCode(); } @Override public boolean equals(Object o) { return this == o || o instanceof JavaMethod && mth.equals(((JavaMethod) o).mth); } @Override public String toString() { return mth.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/JadxDecompiler.java
jadx-core/src/main/java/jadx/api/JadxDecompiler.java
package jadx.api; import java.io.Closeable; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.function.Predicate; import java.util.stream.Collectors; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeNodeRef; import jadx.api.metadata.annotations.NodeDeclareRef; import jadx.api.metadata.annotations.VarNode; import jadx.api.metadata.annotations.VarRef; import jadx.api.plugins.CustomResourcesLoader; import jadx.api.plugins.JadxPlugin; import jadx.api.plugins.events.IJadxEvents; import jadx.api.plugins.input.ICodeLoader; import jadx.api.plugins.input.JadxCodeInput; import jadx.api.plugins.pass.JadxPass; import jadx.api.plugins.pass.types.JadxAfterLoadPass; import jadx.api.plugins.pass.types.JadxPassType; import jadx.api.utils.tasks.ITaskExecutor; import jadx.core.Jadx; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.PackageNode; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.visitors.SaveCode; import jadx.core.export.ExportGradle; import jadx.core.export.OutDirs; import jadx.core.plugins.JadxPluginManager; import jadx.core.plugins.PluginContext; import jadx.core.plugins.events.JadxEventsImpl; import jadx.core.utils.DecompilerScheduler; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.core.utils.tasks.TaskExecutor; import jadx.core.xmlgen.ResourcesSaver; import jadx.zip.ZipReader; /** * Jadx API usage example: * * <pre> * <code> * * JadxArgs args = new JadxArgs(); * args.getInputFiles().add(new File("test.apk")); * args.setOutDir(new File("jadx-test-output")); * try (JadxDecompiler jadx = new JadxDecompiler(args)) { * jadx.load(); * jadx.save(); * } * </code> * </pre> * <p> * Instead of 'save()' you can iterate over decompiled classes: * * <pre> * <code> * * for(JavaClass cls : jadx.getClasses()) { * System.out.println(cls.getCode()); * } * </code> * </pre> */ public final class JadxDecompiler implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(JadxDecompiler.class); private final JadxArgs args; private final JadxPluginManager pluginManager; private final List<ICodeLoader> loadedInputs = new ArrayList<>(); private final ZipReader zipReader; private RootNode root; private List<JavaClass> classes; private List<ResourceFile> resources; private final IDecompileScheduler decompileScheduler = new DecompilerScheduler(); private final ResourcesLoader resourcesLoader; private final List<ICodeLoader> customCodeLoaders = new ArrayList<>(); private final List<CustomResourcesLoader> customResourcesLoaders = new ArrayList<>(); private final Map<JadxPassType, List<JadxPass>> customPasses = new HashMap<>(); private final List<Closeable> closeableList = new ArrayList<>(); private IJadxEvents events = new JadxEventsImpl(); public JadxDecompiler() { this(new JadxArgs()); } public JadxDecompiler(JadxArgs args) { this.args = Objects.requireNonNull(args); this.pluginManager = new JadxPluginManager(this); this.resourcesLoader = new ResourcesLoader(this); this.zipReader = new ZipReader(args.getSecurity()); } public void load() { reset(); JadxArgsValidator.validate(this); LOG.info("loading ..."); FileUtils.updateTempRootDir(args.getFilesGetter().getTempDir()); loadPlugins(); loadInputFiles(); root = new RootNode(this); root.init(); // load classes and resources root.loadClasses(loadedInputs); root.loadResources(resourcesLoader, getResources()); root.finishClassLoad(); root.initClassPath(); // init passes root.mergePasses(customPasses); root.runPreDecompileStage(); root.initPasses(); loadFinished(); } public void reloadPasses() { LOG.info("reloading (passes only) ..."); customPasses.clear(); root.resetPasses(); events.reset(); loadPlugins(); root.mergePasses(customPasses); root.restartVisitors(); root.initPasses(); loadFinished(); } private void loadInputFiles() { loadedInputs.clear(); List<Path> inputPaths = Utils.collectionMap(args.getInputFiles(), File::toPath); List<Path> inputFiles = FileUtils.expandDirs(inputPaths); long start = System.currentTimeMillis(); for (PluginContext plugin : pluginManager.getResolvedPluginContexts()) { for (JadxCodeInput codeLoader : plugin.getCodeInputs()) { try { ICodeLoader loader = codeLoader.loadFiles(inputFiles); if (loader != null && !loader.isEmpty()) { loadedInputs.add(loader); } } catch (Exception e) { LOG.warn("Failed to load code for plugin: {}", plugin, e); } } } loadedInputs.addAll(customCodeLoaders); if (LOG.isDebugEnabled()) { LOG.debug("Loaded using {} inputs plugin in {} ms", loadedInputs.size(), System.currentTimeMillis() - start); } } private void reset() { unloadPlugins(); root = null; classes = null; resources = null; events.reset(); } @Override public void close() { reset(); closeAll(loadedInputs); closeAll(customCodeLoaders); closeAll(customResourcesLoaders); closeAll(closeableList); FileUtils.deleteDirIfExists(args.getFilesGetter().getTempDir()); args.close(); FileUtils.clearTempRootDir(); } private void closeAll(List<? extends Closeable> list) { try { for (Closeable closeable : list) { try { closeable.close(); } catch (Exception e) { LOG.warn("Fail to close '{}'", closeable, e); } } } finally { list.clear(); } } private void loadPlugins() { pluginManager.providesSuggestion("java-input", args.isUseDxInput() ? "java-convert" : "java-input"); pluginManager.load(args.getPluginLoader()); if (LOG.isDebugEnabled()) { LOG.debug("Resolved plugins: {}", pluginManager.getResolvedPluginContexts()); } pluginManager.initResolved(); if (LOG.isDebugEnabled()) { List<String> passes = customPasses.values().stream().flatMap(Collection::stream) .map(p -> p.getInfo().getName()).collect(Collectors.toList()); LOG.debug("Loaded custom passes: {} {}", passes.size(), passes); } } private void unloadPlugins() { pluginManager.unloadResolved(); } private void loadFinished() { LOG.debug("Load finished"); List<JadxPass> list = customPasses.get(JadxAfterLoadPass.TYPE); if (list != null) { for (JadxPass pass : list) { ((JadxAfterLoadPass) pass).init(this); } } } @SuppressWarnings("unused") public void registerPlugin(JadxPlugin plugin) { pluginManager.register(plugin); } public static String getVersion() { return Jadx.getVersion(); } public void save() { save(!args.isSkipSources(), !args.isSkipResources()); } public interface ProgressListener { void progress(long done, long total); } @SuppressWarnings("BusyWait") public void save(int intervalInMillis, ProgressListener listener) { try { ITaskExecutor tasks = getSaveTaskExecutor(); tasks.execute(); long total = tasks.getTasksCount(); while (tasks.isRunning()) { listener.progress(tasks.getProgress(), total); Thread.sleep(intervalInMillis); } } catch (InterruptedException e) { LOG.error("Save interrupted", e); Thread.currentThread().interrupt(); } } public void saveSources() { save(true, false); } public void saveResources() { save(false, true); } private void save(boolean saveSources, boolean saveResources) { ITaskExecutor executor = getSaveTasks(saveSources, saveResources); executor.execute(); executor.awaitTermination(); } public ITaskExecutor getSaveTaskExecutor() { return getSaveTasks(!args.isSkipSources(), !args.isSkipResources()); } @Deprecated(forRemoval = true) public ExecutorService getSaveExecutor() { ITaskExecutor executor = getSaveTaskExecutor(); executor.execute(); return executor.getInternalExecutor(); } @Deprecated(forRemoval = true) public List<Runnable> getSaveTasks() { return Collections.singletonList(this::save); } private TaskExecutor getSaveTasks(boolean saveSources, boolean saveResources) { if (root == null) { throw new JadxRuntimeException("No loaded files"); } OutDirs outDirs; ExportGradle gradleExport; if (args.getExportGradleType() != null) { gradleExport = new ExportGradle(root, args.getOutDir(), getResources()); outDirs = gradleExport.init(); } else { gradleExport = null; outDirs = new OutDirs(args.getOutDirSrc(), args.getOutDirRes()); outDirs.makeDirs(); } TaskExecutor executor = new TaskExecutor(); executor.setThreadsCount(args.getThreadsCount()); if (saveResources) { // save resources first because decompilation can stop or fail appendResourcesSaveTasks(executor, outDirs.getResOutDir()); } if (saveSources) { appendSourcesSave(executor, outDirs.getSrcOutDir()); } if (gradleExport != null) { executor.addSequentialTask(gradleExport::generateGradleFiles); } return executor; } private void appendResourcesSaveTasks(ITaskExecutor executor, File outDir) { if (args.isSkipFilesSave()) { return; } // process AndroidManifest.xml first to load complete resource ids table for (ResourceFile resourceFile : getResources()) { if (resourceFile.getType() == ResourceType.MANIFEST) { new ResourcesSaver(this, outDir, resourceFile).run(); break; } } Set<String> inputFileNames = args.getInputFiles().stream() .map(File::getAbsolutePath) .collect(Collectors.toSet()); Set<String> codeSources = collectCodeSources(); List<Runnable> tasks = new ArrayList<>(); for (ResourceFile resourceFile : getResources()) { ResourceType resType = resourceFile.getType(); if (resType == ResourceType.MANIFEST) { // already processed continue; } String resOriginalName = resourceFile.getOriginalName(); if (resType != ResourceType.ARSC && inputFileNames.contains(resOriginalName)) { // ignore resource made from an input file continue; } if (codeSources.contains(resOriginalName)) { // don't output code source resources (.dex, .class, etc) // do not trust file extensions, use only sources set as class inputs continue; } tasks.add(new ResourcesSaver(this, outDir, resourceFile)); } executor.addParallelTasks(tasks); } private Set<String> collectCodeSources() { Set<String> set = new HashSet<>(); for (ClassNode cls : root.getClasses(true)) { if (cls.getClsData() == null) { // exclude synthetic classes continue; } String inputFileName = cls.getInputFileName(); if (inputFileName.endsWith(".class")) { // cut .class name to get source .jar file // current template: "<optional input files>:<.jar>:<full class name>" // TODO: add property to set file name or reference to resource name int endIdx = inputFileName.lastIndexOf(':'); if (endIdx != -1) { int startIdx = inputFileName.lastIndexOf(':', endIdx - 1) + 1; inputFileName = inputFileName.substring(startIdx, endIdx); } } set.add(inputFileName); } return set; } private void appendSourcesSave(ITaskExecutor executor, File outDir) { List<JavaClass> classes = getClasses(); List<JavaClass> processQueue = filterClasses(classes); List<List<JavaClass>> batches; try { batches = decompileScheduler.buildBatches(processQueue); } catch (Exception e) { throw new JadxRuntimeException("Decompilation batches build failed", e); } List<Runnable> decompileTasks = new ArrayList<>(batches.size()); for (List<JavaClass> decompileBatch : batches) { decompileTasks.add(() -> { for (JavaClass cls : decompileBatch) { try { ClassNode clsNode = cls.getClassNode(); ICodeInfo code = clsNode.getCode(); SaveCode.save(outDir, clsNode, code); } catch (Exception e) { LOG.error("Error saving class: {}", cls, e); } } }); } executor.addParallelTasks(decompileTasks); } private List<JavaClass> filterClasses(List<JavaClass> classes) { Predicate<String> classFilter = args.getClassFilter(); List<JavaClass> list = new ArrayList<>(classes.size()); for (JavaClass cls : classes) { ClassNode clsNode = cls.getClassNode(); if (clsNode.contains(AFlag.DONT_GENERATE)) { continue; } if (classFilter != null && !classFilter.test(clsNode.getClassInfo().getFullName())) { if (!args.isIncludeDependencies()) { clsNode.add(AFlag.DONT_GENERATE); } continue; } list.add(cls); } return list; } public synchronized List<JavaClass> getClasses() { if (root == null) { return Collections.emptyList(); } if (classes == null) { List<ClassNode> classNodeList = root.getClasses(); List<JavaClass> clsList = new ArrayList<>(classNodeList.size()); for (ClassNode classNode : classNodeList) { if (!classNode.contains(AFlag.DONT_GENERATE) && !classNode.isInner()) { clsList.add(convertClassNode(classNode)); } } classes = Collections.unmodifiableList(clsList); } return classes; } public List<JavaClass> getClassesWithInners() { return Utils.collectionMap(root.getClasses(), this::convertClassNode); } public synchronized List<ResourceFile> getResources() { if (resources == null) { if (root == null) { return Collections.emptyList(); } resources = resourcesLoader.load(root); } return resources; } public List<JavaPackage> getPackages() { return Utils.collectionMap(root.getPackages(), this::convertPackageNode); } public int getErrorsCount() { if (root == null) { return 0; } return root.getErrorsCounter().getErrorCount(); } public int getWarnsCount() { if (root == null) { return 0; } return root.getErrorsCounter().getWarnsCount(); } public void printErrorsReport() { if (root == null) { return; } root.getClsp().printMissingClasses(); root.getErrorsCounter().printReport(); } /** * Internal API. Not Stable! */ @ApiStatus.Internal public RootNode getRoot() { return root; } /** * Get JavaClass by ClassNode without loading and decompilation */ @ApiStatus.Internal synchronized JavaClass convertClassNode(ClassNode cls) { JavaClass javaClass = cls.getJavaNode(); if (javaClass == null) { javaClass = cls.isInner() ? new JavaClass(cls, convertClassNode(cls.getParentClass())) : new JavaClass(cls, this); cls.setJavaNode(javaClass); } return javaClass; } @ApiStatus.Internal synchronized JavaField convertFieldNode(FieldNode fld) { JavaField javaField = fld.getJavaNode(); if (javaField == null) { JavaClass parentCls = convertClassNode(fld.getParentClass()); javaField = new JavaField(parentCls, fld); fld.setJavaNode(javaField); } return javaField; } @ApiStatus.Internal synchronized JavaMethod convertMethodNode(MethodNode mth) { JavaMethod javaMethod = mth.getJavaNode(); if (javaMethod == null) { javaMethod = new JavaMethod(convertClassNode(mth.getParentClass()), mth); mth.setJavaNode(javaMethod); } return javaMethod; } @ApiStatus.Internal synchronized JavaPackage convertPackageNode(PackageNode pkg) { JavaPackage foundPkg = pkg.getJavaNode(); if (foundPkg != null) { return foundPkg; } List<JavaClass> clsList = Utils.collectionMap(pkg.getClasses(), this::convertClassNode); List<JavaClass> clsListNoDup = Utils.collectionMap(pkg.getClassesNoDup(), this::convertClassNode); int subPkgsCount = pkg.getSubPackages().size(); List<JavaPackage> subPkgs = subPkgsCount == 0 ? Collections.emptyList() : new ArrayList<>(subPkgsCount); JavaPackage javaPkg = new JavaPackage(pkg, clsList, clsListNoDup, subPkgs); if (subPkgsCount != 0) { // add subpackages after parent to avoid endless recursion for (PackageNode subPackage : pkg.getSubPackages()) { subPkgs.add(convertPackageNode(subPackage)); } } pkg.setJavaNode(javaPkg); return javaPkg; } @Nullable public JavaClass searchJavaClassByOrigFullName(String fullName) { return getRoot().getClasses().stream() .filter(cls -> cls.getClassInfo().getFullName().equals(fullName)) .findFirst() .map(this::convertClassNode) .orElse(null); } @Nullable public ClassNode searchClassNodeByOrigFullName(String fullName) { return getRoot().getClasses().stream() .filter(cls -> cls.getClassInfo().getFullName().equals(fullName)) .findFirst() .orElse(null); } // returns parent if class contains DONT_GENERATE flag. @Nullable public JavaClass searchJavaClassOrItsParentByOrigFullName(String fullName) { ClassNode node = getRoot().getClasses().stream() .filter(cls -> cls.getClassInfo().getFullName().equals(fullName)) .findFirst() .orElse(null); if (node != null) { if (node.contains(AFlag.DONT_GENERATE)) { return convertClassNode(node.getTopParentClass()); } else { return convertClassNode(node); } } return null; } @Nullable public JavaClass searchJavaClassByAliasFullName(String fullName) { return getRoot().getClasses().stream() .filter(cls -> cls.getClassInfo().getAliasFullName().equals(fullName)) .findFirst() .map(this::convertClassNode) .orElse(null); } @Nullable public JavaNode getJavaNodeByRef(ICodeNodeRef ann) { return getJavaNodeByCodeAnnotation(null, ann); } @Nullable public JavaNode getJavaNodeByCodeAnnotation(@Nullable ICodeInfo codeInfo, @Nullable ICodeAnnotation ann) { if (ann == null) { return null; } switch (ann.getAnnType()) { case CLASS: return convertClassNode((ClassNode) ann); case METHOD: return convertMethodNode((MethodNode) ann); case FIELD: return convertFieldNode((FieldNode) ann); case PKG: return convertPackageNode((PackageNode) ann); case DECLARATION: return getJavaNodeByCodeAnnotation(codeInfo, ((NodeDeclareRef) ann).getNode()); case VAR: return resolveVarNode((VarNode) ann); case VAR_REF: return resolveVarRef(codeInfo, (VarRef) ann); case OFFSET: // offset annotation don't have java node object return null; default: throw new JadxRuntimeException("Unknown annotation type: " + ann.getAnnType() + ", class: " + ann.getClass()); } } private JavaVariable resolveVarNode(VarNode varNode) { JavaMethod javaNode = convertMethodNode(varNode.getMth()); return new JavaVariable(javaNode, varNode); } @Nullable private JavaVariable resolveVarRef(ICodeInfo codeInfo, VarRef varRef) { if (codeInfo == null) { throw new JadxRuntimeException("Missing code info for resolve VarRef: " + varRef); } ICodeAnnotation varNodeAnn = codeInfo.getCodeMetadata().getAt(varRef.getRefPos()); if (varNodeAnn != null && varNodeAnn.getAnnType() == ICodeAnnotation.AnnType.DECLARATION) { ICodeNodeRef nodeRef = ((NodeDeclareRef) varNodeAnn).getNode(); if (nodeRef.getAnnType() == ICodeAnnotation.AnnType.VAR) { return resolveVarNode((VarNode) nodeRef); } } return null; } List<JavaNode> convertNodes(Collection<? extends ICodeNodeRef> nodesList) { return nodesList.stream() .map(this::getJavaNodeByRef) .filter(Objects::nonNull) .collect(Collectors.toList()); } @Nullable public JavaNode getJavaNodeAtPosition(ICodeInfo codeInfo, int pos) { ICodeAnnotation ann = codeInfo.getCodeMetadata().getAt(pos); return getJavaNodeByCodeAnnotation(codeInfo, ann); } @Nullable public JavaNode getClosestJavaNode(ICodeInfo codeInfo, int pos) { ICodeAnnotation ann = codeInfo.getCodeMetadata().getClosestUp(pos); return getJavaNodeByCodeAnnotation(codeInfo, ann); } @Nullable public JavaNode getEnclosingNode(ICodeInfo codeInfo, int pos) { ICodeNodeRef obj = codeInfo.getCodeMetadata().getNodeAt(pos); if (obj == null) { return null; } return getJavaNodeByRef(obj); } public void reloadCodeData() { root.notifyCodeDataListeners(); } public JadxArgs getArgs() { return args; } public JadxPluginManager getPluginManager() { return pluginManager; } public IDecompileScheduler getDecompileScheduler() { return decompileScheduler; } public IJadxEvents events() { return events; } public void setEventsImpl(IJadxEvents eventsImpl) { this.events = eventsImpl; } public void addCustomCodeLoader(ICodeLoader customCodeLoader) { customCodeLoaders.add(customCodeLoader); } public List<ICodeLoader> getCustomCodeLoaders() { return customCodeLoaders; } public void addCustomResourcesLoader(CustomResourcesLoader loader) { if (customResourcesLoaders.contains(loader)) { return; } customResourcesLoaders.add(loader); } public List<CustomResourcesLoader> getCustomResourcesLoaders() { return customResourcesLoaders; } public void addCustomPass(JadxPass pass) { customPasses.computeIfAbsent(pass.getPassType(), l -> new ArrayList<>()).add(pass); } public ResourcesLoader getResourcesLoader() { return resourcesLoader; } public ZipReader getZipReader() { return zipReader; } public void addCloseable(Closeable closeable) { closeableList.add(closeable); } @Override public String toString() { return "jadx decompiler " + getVersion(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/ICodeInfo.java
jadx-core/src/main/java/jadx/api/ICodeInfo.java
package jadx.api; import jadx.api.impl.SimpleCodeInfo; import jadx.api.metadata.ICodeMetadata; public interface ICodeInfo { ICodeInfo EMPTY = new SimpleCodeInfo(""); String getCodeStr(); ICodeMetadata getCodeMetadata(); boolean hasMetadata(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/ResourcesLoader.java
jadx-core/src/main/java/jadx/api/ResourcesLoader.java
package jadx.api; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.impl.SimpleCodeInfo; import jadx.api.plugins.CustomResourcesLoader; import jadx.api.plugins.resources.IResContainerFactory; import jadx.api.plugins.resources.IResTableParserProvider; import jadx.api.plugins.resources.IResourcesLoader; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.Utils; import jadx.core.utils.android.Res9patchStreamDecoder; import jadx.core.utils.exceptions.JadxException; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.core.xmlgen.BinaryXMLParser; import jadx.core.xmlgen.IResTableParser; import jadx.core.xmlgen.ResContainer; import jadx.core.xmlgen.ResTableBinaryParserProvider; import jadx.zip.IZipEntry; import jadx.zip.ZipContent; import static jadx.core.utils.files.FileUtils.READ_BUFFER_SIZE; import static jadx.core.utils.files.FileUtils.copyStream; // TODO: move to core package public final class ResourcesLoader implements IResourcesLoader { private static final Logger LOG = LoggerFactory.getLogger(ResourcesLoader.class); private final JadxDecompiler decompiler; private final List<IResTableParserProvider> resTableParserProviders = new ArrayList<>(); private final List<IResContainerFactory> resContainerFactories = new ArrayList<>(); private BinaryXMLParser binaryXmlParser; ResourcesLoader(JadxDecompiler decompiler) { this.decompiler = decompiler; this.resTableParserProviders.add(new ResTableBinaryParserProvider()); } List<ResourceFile> load(RootNode root) { init(root); List<File> inputFiles = decompiler.getArgs().getInputFiles(); List<ResourceFile> list = new ArrayList<>(inputFiles.size()); for (File file : inputFiles) { loadFile(list, file); } return list; } private void init(RootNode root) { for (IResTableParserProvider resTableParserProvider : resTableParserProviders) { try { resTableParserProvider.init(root); } catch (Exception e) { throw new JadxRuntimeException("Failed to init res table provider: " + resTableParserProvider); } } for (IResContainerFactory resContainerFactory : resContainerFactories) { try { resContainerFactory.init(root); } catch (Exception e) { throw new JadxRuntimeException("Failed to init res container factory: " + resContainerFactory); } } } public interface ResourceDecoder<T> { T decode(long size, InputStream is) throws IOException; } @Override public void addResContainerFactory(IResContainerFactory resContainerFactory) { resContainerFactories.add(resContainerFactory); } @Override public void addResTableParserProvider(IResTableParserProvider resTableParserProvider) { resTableParserProviders.add(resTableParserProvider); } public static <T> T decodeStream(ResourceFile rf, ResourceDecoder<T> decoder) throws JadxException { try { IZipEntry zipEntry = rf.getZipEntry(); if (zipEntry != null) { try (InputStream inputStream = zipEntry.getInputStream()) { return decoder.decode(zipEntry.getUncompressedSize(), inputStream); } } else { File file = new File(rf.getOriginalName()); try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { return decoder.decode(file.length(), inputStream); } } } catch (Exception e) { throw new JadxException("Error decode: " + rf.getOriginalName(), e); } } static ResContainer loadContent(JadxDecompiler jadxRef, ResourceFile rf) { try { ResourcesLoader resLoader = jadxRef.getResourcesLoader(); return decodeStream(rf, (size, is) -> resLoader.loadContent(rf, is)); } catch (JadxException e) { LOG.error("Decode error", e); ICodeWriter cw = jadxRef.getRoot().makeCodeWriter(); cw.add("Error decode ").add(rf.getType().toString().toLowerCase()); Utils.appendStackTrace(cw, e.getCause()); return ResContainer.textResource(rf.getDeobfName(), cw.finish()); } } private ResContainer loadContent(ResourceFile resFile, InputStream inputStream) throws IOException { for (IResContainerFactory customFactory : resContainerFactories) { ResContainer resContainer = customFactory.create(resFile, inputStream); if (resContainer != null) { return resContainer; } } switch (resFile.getType()) { case MANIFEST: case XML: ICodeInfo content = loadBinaryXmlParser().parse(inputStream); return ResContainer.textResource(resFile.getDeobfName(), content); case ARSC: return decodeTable(resFile, inputStream).decodeFiles(); case IMG: return decodeImage(resFile, inputStream); default: return ResContainer.resourceFileLink(resFile); } } public IResTableParser decodeTable(ResourceFile resFile, InputStream is) throws IOException { if (resFile.getType() != ResourceType.ARSC) { throw new IllegalArgumentException("Unexpected resource type for decode: " + resFile.getType() + ", expect '.pb'/'.arsc'"); } IResTableParser parser = null; for (IResTableParserProvider provider : resTableParserProviders) { parser = provider.getParser(resFile); if (parser != null) { break; } } if (parser == null) { throw new JadxRuntimeException("Unknown type of resource file: " + resFile.getOriginalName()); } parser.setBaseFileName(resFile.getDeobfName()); parser.decode(is); return parser; } private static ResContainer decodeImage(ResourceFile rf, InputStream inputStream) { String name = rf.getDeobfName(); if (name.endsWith(".9.png")) { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { Res9patchStreamDecoder decoder = new Res9patchStreamDecoder(); if (decoder.decode(inputStream, os)) { return ResContainer.decodedData(rf.getDeobfName(), os.toByteArray()); } } catch (Exception e) { LOG.error("Failed to decode 9-patch png image, path: {}", name, e); } } return ResContainer.resourceFileLink(rf); } private void loadFile(List<ResourceFile> list, File file) { if (file == null || file.isDirectory()) { return; } // Try to load the resources with a custom loader first for (CustomResourcesLoader loader : decompiler.getCustomResourcesLoaders()) { if (loader.load(this, list, file)) { LOG.debug("Custom loader used for {}", file.getAbsolutePath()); return; } } // If no custom decoder was able to decode the resources, use the default decoder defaultLoadFile(list, file, ""); } public void defaultLoadFile(List<ResourceFile> list, File file, String subDir) { if (FileUtils.isZipFile(file)) { try { ZipContent zipContent = decompiler.getZipReader().open(file); // do not close a zip now, entry content will be read later decompiler.addCloseable(zipContent); for (IZipEntry entry : zipContent.getEntries()) { addEntry(list, file, entry, subDir); } } catch (Exception e) { throw new RuntimeException("Failed to open zip file: " + file.getAbsolutePath(), e); } } else { ResourceType type = ResourceType.getFileType(file.getAbsolutePath()); list.add(ResourceFile.createResourceFile(decompiler, file, type)); } } public void addEntry(List<ResourceFile> list, File zipFile, IZipEntry entry, String subDir) { if (entry.isDirectory()) { return; } String name = entry.getName(); ResourceType type = ResourceType.getFileType(name); ResourceFile rf = ResourceFile.createResourceFile(decompiler, subDir + name, type); if (rf != null) { rf.setZipEntry(entry); list.add(rf); } } public static ICodeInfo loadToCodeWriter(InputStream is) throws IOException { return loadToCodeWriter(is, StandardCharsets.UTF_8); } public static ICodeInfo loadToCodeWriter(InputStream is, Charset charset) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(READ_BUFFER_SIZE); copyStream(is, baos); return new SimpleCodeInfo(baos.toString(charset)); } private synchronized BinaryXMLParser loadBinaryXmlParser() { if (binaryXmlParser == null) { binaryXmlParser = new BinaryXMLParser(decompiler.getRoot()); } return binaryXmlParser; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/JavaPackage.java
jadx-core/src/main/java/jadx/api/JavaPackage.java
package jadx.api; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.jetbrains.annotations.ApiStatus.Internal; import org.jetbrains.annotations.NotNull; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeNodeRef; import jadx.core.dex.info.PackageInfo; import jadx.core.dex.nodes.PackageNode; public final class JavaPackage implements JavaNode, Comparable<JavaPackage> { private final PackageNode pkgNode; private final List<JavaClass> classes; private final List<JavaClass> clsListNoDup; private final List<JavaPackage> subPkgs; JavaPackage(PackageNode pkgNode, List<JavaClass> classes, List<JavaPackage> subPkgs) { this(pkgNode, classes, classes, subPkgs); } JavaPackage(PackageNode pkgNode, List<JavaClass> classes, List<JavaClass> clsListNoDup, List<JavaPackage> subPkgs) { this.pkgNode = pkgNode; this.classes = classes; this.clsListNoDup = clsListNoDup; this.subPkgs = subPkgs; } @Override public String getName() { return pkgNode.getAliasPkgInfo().getName(); } @Override public String getFullName() { return pkgNode.getAliasPkgInfo().getFullName(); } public String getRawName() { return pkgNode.getPkgInfo().getName(); } public String getRawFullName() { return pkgNode.getPkgInfo().getFullName(); } public List<JavaPackage> getSubPackages() { return subPkgs; } public List<JavaClass> getClasses() { return classes; } public List<JavaClass> getClassesNoDup() { return clsListNoDup; } public boolean isRoot() { return pkgNode.isRoot(); } public boolean isLeaf() { return pkgNode.isLeaf(); } public boolean isDefault() { return getFullName().isEmpty(); } public void rename(String alias) { pkgNode.rename(alias); } @Override public void removeAlias() { pkgNode.removeAlias(); } public boolean isParentRenamed() { PackageInfo parent = pkgNode.getPkgInfo().getParentPkg(); PackageInfo aliasParent = pkgNode.getAliasPkgInfo().getParentPkg(); return !Objects.equals(parent, aliasParent); } public boolean isDescendantOf(JavaPackage ancestor) { JavaPackage current = this; while (current != null) { if (ancestor.equals(current)) { return true; } if (current.getPkgNode().getParentPkg() == null) { current = null; } else { current = current.getPkgNode().getParentPkg().getJavaNode(); } } return false; } @Override public ICodeNodeRef getCodeNodeRef() { return pkgNode; } @Internal public PackageNode getPkgNode() { return pkgNode; } @Override public JavaClass getDeclaringClass() { return null; } @Override public JavaClass getTopParentClass() { return null; } @Override public int getDefPos() { return 0; } @Override public List<JavaNode> getUseIn() { List<JavaNode> list = new ArrayList<>(); addUseIn(list); return list; } public void addUseIn(List<JavaNode> list) { list.addAll(classes); for (JavaPackage subPkg : subPkgs) { subPkg.addUseIn(list); } } @Override public boolean isOwnCodeAnnotation(ICodeAnnotation ann) { return false; } @Override public int compareTo(@NotNull JavaPackage o) { return pkgNode.compareTo(o.pkgNode); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JavaPackage that = (JavaPackage) o; return pkgNode.equals(that.pkgNode); } @Override public int hashCode() { return pkgNode.hashCode(); } @Override public String toString() { return pkgNode.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/JavaVariable.java
jadx-core/src/main/java/jadx/api/JavaVariable.java
package jadx.api; import java.util.Collections; import java.util.List; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeNodeRef; import jadx.api.metadata.annotations.VarNode; import jadx.api.metadata.annotations.VarRef; import jadx.core.dex.instructions.args.ArgType; public class JavaVariable implements JavaNode { private final JavaMethod mth; private final VarNode varNode; public JavaVariable(JavaMethod mth, VarNode varNode) { this.mth = mth; this.varNode = varNode; } public JavaMethod getMth() { return mth; } public int getReg() { return varNode.getReg(); } public int getSsa() { return varNode.getSsa(); } @Override public @Nullable String getName() { return varNode.getName(); } @Override public ICodeNodeRef getCodeNodeRef() { return varNode; } @ApiStatus.Internal public VarNode getVarNode() { return varNode; } @Override public String getFullName() { return varNode.getType() + " " + varNode.getName() + " (r" + varNode.getReg() + "v" + varNode.getSsa() + ")"; } public ArgType getType() { return ArgType.tryToResolveClassAlias(mth.getMethodNode().root(), varNode.getType()); } @Override public JavaClass getDeclaringClass() { return mth.getDeclaringClass(); } @Override public JavaClass getTopParentClass() { return mth.getTopParentClass(); } @Override public int getDefPos() { return varNode.getDefPosition(); } @Override public List<JavaNode> getUseIn() { return Collections.singletonList(mth); } @Override public void removeAlias() { varNode.setName(null); } @Override public boolean isOwnCodeAnnotation(ICodeAnnotation ann) { if (ann.getAnnType() == ICodeAnnotation.AnnType.VAR_REF) { VarRef varRef = (VarRef) ann; return varRef.getRefPos() == getDefPos(); } return false; } @Override public int hashCode() { return varNode.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof JavaVariable)) { return false; } return varNode.equals(((JavaVariable) o).varNode); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/JavaField.java
jadx-core/src/main/java/jadx/api/JavaField.java
package jadx.api; import java.util.List; import org.jetbrains.annotations.ApiStatus; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeNodeRef; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.FieldNode; public final class JavaField implements JavaNode { private final FieldNode field; private final JavaClass parent; JavaField(JavaClass cls, FieldNode f) { this.field = f; this.parent = cls; } @Override public String getName() { return field.getAlias(); } @Override public String getFullName() { return parent.getFullName() + '.' + getName(); } public String getRawName() { return field.getName(); } @Override public JavaClass getDeclaringClass() { return parent; } @Override public JavaClass getTopParentClass() { return parent.getTopParentClass(); } public AccessInfo getAccessFlags() { return field.getAccessFlags(); } public ArgType getType() { return ArgType.tryToResolveClassAlias(field.root(), field.getType()); } @Override public int getDefPos() { return field.getDefPosition(); } @Override public List<JavaNode> getUseIn() { return getDeclaringClass().getRootDecompiler().convertNodes(field.getUseIn()); } @Override public void removeAlias() { this.field.getFieldInfo().removeAlias(); } @Override public boolean isOwnCodeAnnotation(ICodeAnnotation ann) { if (ann.getAnnType() == ICodeAnnotation.AnnType.FIELD) { return ann.equals(field); } return false; } @Override public ICodeNodeRef getCodeNodeRef() { return field; } /** * Internal API. Not Stable! */ @ApiStatus.Internal public FieldNode getFieldNode() { return field; } @Override public int hashCode() { return field.hashCode(); } @Override public boolean equals(Object o) { return this == o || o instanceof JavaField && field.equals(((JavaField) o).field); } @Override public String toString() { return field.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/IDecompileScheduler.java
jadx-core/src/main/java/jadx/api/IDecompileScheduler.java
package jadx.api; import java.util.List; public interface IDecompileScheduler { List<List<JavaClass>> buildBatches(List<JavaClass> classes); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/JavaNode.java
jadx-core/src/main/java/jadx/api/JavaNode.java
package jadx.api; import java.util.List; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeNodeRef; public interface JavaNode { ICodeNodeRef getCodeNodeRef(); String getName(); String getFullName(); JavaClass getDeclaringClass(); JavaClass getTopParentClass(); int getDefPos(); List<JavaNode> getUseIn(); void removeAlias(); boolean isOwnCodeAnnotation(ICodeAnnotation ann); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false