repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/api/args/IntegerFormat.java | jadx-core/src/main/java/jadx/api/args/IntegerFormat.java | package jadx.api.args;
public enum IntegerFormat {
AUTO,
DECIMAL,
HEXADECIMAL;
public boolean isHexadecimal() {
return this == HEXADECIMAL;
}
}
| 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/args/UseSourceNameAsClassNameAlias.java | jadx-core/src/main/java/jadx/api/args/UseSourceNameAsClassNameAlias.java | package jadx.api.args;
import jadx.core.utils.exceptions.JadxRuntimeException;
public enum UseSourceNameAsClassNameAlias {
ALWAYS,
IF_BETTER,
NEVER;
public static UseSourceNameAsClassNameAlias getDefault() {
return NEVER;
}
/**
* @deprecated Use {@link UseSourceNameAsClassNameAlias} directly.
*/
@Deprecated
public boolean toBoolean() {
switch (this) {
case IF_BETTER:
return true;
case NEVER:
return false;
case ALWAYS:
throw new JadxRuntimeException("No match between " + this + " and boolean");
default:
throw new JadxRuntimeException("Unhandled strategy: " + this);
}
}
/**
* @deprecated Use {@link UseSourceNameAsClassNameAlias} directly.
*/
@Deprecated
public static UseSourceNameAsClassNameAlias create(boolean useSourceNameAsAlias) {
return useSourceNameAsAlias ? IF_BETTER : NEVER;
}
}
| 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/args/GeneratedRenamesMappingFileMode.java | jadx-core/src/main/java/jadx/api/args/GeneratedRenamesMappingFileMode.java | package jadx.api.args;
public enum GeneratedRenamesMappingFileMode {
/**
* Load if found, don't save (default)
*/
READ,
/**
* Load if found, save only if new (don't overwrite)
*/
READ_OR_SAVE,
/**
* Don't load, always save
*/
OVERWRITE,
/**
* Don't load and don't save
*/
IGNORE;
public static GeneratedRenamesMappingFileMode getDefault() {
return READ;
}
public boolean shouldRead() {
return this == READ || this == READ_OR_SAVE;
}
public boolean shouldWrite() {
return this == READ_OR_SAVE || this == OVERWRITE;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/Jadx.java | jadx-core/src/main/java/jadx/core/Jadx.java | package jadx.core;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.Manifest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.CommentsLevel;
import jadx.api.JadxArgs;
import jadx.core.deobf.DeobfuscatorVisitor;
import jadx.core.deobf.SaveDeobfMapping;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.visitors.AnonymousClassVisitor;
import jadx.core.dex.visitors.ApplyVariableNames;
import jadx.core.dex.visitors.AttachCommentsVisitor;
import jadx.core.dex.visitors.AttachMethodDetails;
import jadx.core.dex.visitors.AttachTryCatchVisitor;
import jadx.core.dex.visitors.CheckCode;
import jadx.core.dex.visitors.ClassModifier;
import jadx.core.dex.visitors.ConstInlineVisitor;
import jadx.core.dex.visitors.ConstructorVisitor;
import jadx.core.dex.visitors.DeboxingVisitor;
import jadx.core.dex.visitors.DotGraphVisitor;
import jadx.core.dex.visitors.EnumVisitor;
import jadx.core.dex.visitors.ExtractFieldInit;
import jadx.core.dex.visitors.FallbackModeVisitor;
import jadx.core.dex.visitors.FixSwitchOverEnum;
import jadx.core.dex.visitors.GenericTypesVisitor;
import jadx.core.dex.visitors.IDexTreeVisitor;
import jadx.core.dex.visitors.InitCodeVariables;
import jadx.core.dex.visitors.InlineMethods;
import jadx.core.dex.visitors.MarkMethodsForInline;
import jadx.core.dex.visitors.MethodInvokeVisitor;
import jadx.core.dex.visitors.MethodThrowsVisitor;
import jadx.core.dex.visitors.MethodVisitor;
import jadx.core.dex.visitors.ModVisitor;
import jadx.core.dex.visitors.MoveInlineVisitor;
import jadx.core.dex.visitors.OverrideMethodVisitor;
import jadx.core.dex.visitors.PrepareForCodeGen;
import jadx.core.dex.visitors.ProcessAnonymous;
import jadx.core.dex.visitors.ProcessInstructionsVisitor;
import jadx.core.dex.visitors.ProcessMethodsForInline;
import jadx.core.dex.visitors.ReplaceNewArray;
import jadx.core.dex.visitors.ShadowFieldVisitor;
import jadx.core.dex.visitors.SignatureProcessor;
import jadx.core.dex.visitors.SimplifyVisitor;
import jadx.core.dex.visitors.blocks.BlockFinisher;
import jadx.core.dex.visitors.blocks.BlockProcessor;
import jadx.core.dex.visitors.blocks.BlockSplitter;
import jadx.core.dex.visitors.debuginfo.DebugInfoApplyVisitor;
import jadx.core.dex.visitors.debuginfo.DebugInfoAttachVisitor;
import jadx.core.dex.visitors.finaly.MarkFinallyVisitor;
import jadx.core.dex.visitors.fixaccessmodifiers.FixAccessModifiers;
import jadx.core.dex.visitors.gradle.NonFinalResIdsVisitor;
import jadx.core.dex.visitors.kotlin.ProcessKotlinInternals;
import jadx.core.dex.visitors.prepare.AddAndroidConstants;
import jadx.core.dex.visitors.prepare.CollectConstValues;
import jadx.core.dex.visitors.regions.CheckRegions;
import jadx.core.dex.visitors.regions.CleanRegions;
import jadx.core.dex.visitors.regions.IfRegionVisitor;
import jadx.core.dex.visitors.regions.LoopRegionVisitor;
import jadx.core.dex.visitors.regions.RegionMakerVisitor;
import jadx.core.dex.visitors.regions.ReturnVisitor;
import jadx.core.dex.visitors.regions.SwitchBreakVisitor;
import jadx.core.dex.visitors.regions.SwitchOverStringVisitor;
import jadx.core.dex.visitors.regions.variables.ProcessVariables;
import jadx.core.dex.visitors.rename.CodeRenameVisitor;
import jadx.core.dex.visitors.rename.RenameVisitor;
import jadx.core.dex.visitors.rename.SourceFileRename;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.dex.visitors.ssa.SSATransform;
import jadx.core.dex.visitors.typeinference.FinishTypeInference;
import jadx.core.dex.visitors.typeinference.FixTypesVisitor;
import jadx.core.dex.visitors.typeinference.TypeInferenceVisitor;
import jadx.core.dex.visitors.usage.UsageInfoVisitor;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class Jadx {
private static final Logger LOG = LoggerFactory.getLogger(Jadx.class);
private Jadx() {
}
public static List<IDexTreeVisitor> getPassesList(JadxArgs args) {
switch (args.getDecompilationMode()) {
case AUTO:
case RESTRUCTURE:
return getRegionsModePasses(args);
case SIMPLE:
return getSimpleModePasses(args);
case FALLBACK:
return getFallbackPassesList();
default:
throw new JadxRuntimeException("Unknown decompilation mode: " + args.getDecompilationMode());
}
}
public static List<IDexTreeVisitor> getPreDecompilePassesList() {
List<IDexTreeVisitor> passes = new ArrayList<>();
passes.add(new SignatureProcessor());
passes.add(new OverrideMethodVisitor());
passes.add(new AddAndroidConstants());
// rename and deobfuscation
passes.add(new DeobfuscatorVisitor());
passes.add(new SourceFileRename());
passes.add(new RenameVisitor());
passes.add(new SaveDeobfMapping());
passes.add(new UsageInfoVisitor());
passes.add(new CollectConstValues());
passes.add(new ProcessAnonymous());
passes.add(new ProcessMethodsForInline());
return passes;
}
public static List<IDexTreeVisitor> getRegionsModePasses(JadxArgs args) {
List<IDexTreeVisitor> passes = new ArrayList<>();
// instructions IR
passes.add(new CheckCode());
if (args.isDebugInfo()) {
passes.add(new DebugInfoAttachVisitor());
}
passes.add(new AttachTryCatchVisitor());
if (args.getCommentsLevel() != CommentsLevel.NONE) {
passes.add(new AttachCommentsVisitor());
}
passes.add(new AttachMethodDetails());
passes.add(new ProcessInstructionsVisitor());
// blocks IR
passes.add(new BlockSplitter());
passes.add(new BlockProcessor());
passes.add(new BlockFinisher());
if (args.isRawCFGOutput()) {
passes.add(DotGraphVisitor.dumpRaw());
}
passes.add(new SSATransform());
passes.add(new MoveInlineVisitor());
passes.add(new ConstructorVisitor());
passes.add(new InitCodeVariables());
if (args.isExtractFinally()) {
passes.add(new MarkFinallyVisitor());
}
passes.add(new ConstInlineVisitor());
passes.add(new TypeInferenceVisitor());
if (args.isDebugInfo()) {
passes.add(new DebugInfoApplyVisitor());
}
passes.add(new FixTypesVisitor());
passes.add(new FinishTypeInference());
if (args.getUseKotlinMethodsForVarNames() != JadxArgs.UseKotlinMethodsForVarNames.DISABLE) {
passes.add(new ProcessKotlinInternals());
}
passes.add(new CodeRenameVisitor());
if (args.isInlineMethods()) {
passes.add(new InlineMethods());
}
passes.add(new GenericTypesVisitor());
passes.add(new ShadowFieldVisitor());
passes.add(new DeboxingVisitor());
passes.add(new AnonymousClassVisitor());
passes.add(new ModVisitor());
passes.add(new CodeShrinkVisitor());
passes.add(new ReplaceNewArray());
if (args.isCfgOutput()) {
passes.add(DotGraphVisitor.dump());
}
// regions IR
passes.add(new RegionMakerVisitor());
passes.add(new IfRegionVisitor());
if (args.isRestoreSwitchOverString()) {
passes.add(new SwitchOverStringVisitor());
}
passes.add(new ReturnVisitor());
passes.add(new CleanRegions());
passes.add(new MethodThrowsVisitor());
passes.add(new CodeShrinkVisitor());
passes.add(new MethodInvokeVisitor());
passes.add(new SimplifyVisitor());
passes.add(new CheckRegions());
passes.add(new EnumVisitor());
passes.add(new FixSwitchOverEnum());
passes.add(new NonFinalResIdsVisitor());
passes.add(new ExtractFieldInit());
passes.add(new FixAccessModifiers());
passes.add(new ClassModifier());
passes.add(new LoopRegionVisitor());
passes.add(new SwitchBreakVisitor());
if (args.isInlineMethods()) {
passes.add(new MarkMethodsForInline());
}
passes.add(new ProcessVariables());
passes.add(new ApplyVariableNames());
passes.add(new PrepareForCodeGen());
if (args.isCfgOutput()) {
passes.add(DotGraphVisitor.dumpRegions());
}
return passes;
}
public static List<IDexTreeVisitor> getSimpleModePasses(JadxArgs args) {
List<IDexTreeVisitor> passes = new ArrayList<>();
if (args.isDebugInfo()) {
passes.add(new DebugInfoAttachVisitor());
}
passes.add(new AttachTryCatchVisitor());
if (args.getCommentsLevel() != CommentsLevel.NONE) {
passes.add(new AttachCommentsVisitor());
}
passes.add(new AttachMethodDetails());
passes.add(new ProcessInstructionsVisitor());
passes.add(new BlockSplitter());
if (args.isRawCFGOutput()) {
passes.add(DotGraphVisitor.dumpRaw());
}
passes.add(new MethodVisitor("DisableBlockLock", mth -> mth.add(AFlag.DISABLE_BLOCKS_LOCK)));
passes.add(new BlockProcessor());
passes.add(new SSATransform());
passes.add(new MoveInlineVisitor());
passes.add(new ConstructorVisitor());
passes.add(new InitCodeVariables());
passes.add(new ConstInlineVisitor());
passes.add(new TypeInferenceVisitor());
if (args.isDebugInfo()) {
passes.add(new DebugInfoApplyVisitor());
}
passes.add(new FixTypesVisitor());
passes.add(new FinishTypeInference());
passes.add(new CodeRenameVisitor());
passes.add(new DeboxingVisitor());
passes.add(new ModVisitor());
passes.add(new CodeShrinkVisitor());
passes.add(new ReplaceNewArray());
passes.add(new SimplifyVisitor());
passes.add(new MethodVisitor("ForceGenerateAll", mth -> mth.remove(AFlag.DONT_GENERATE)));
if (args.isCfgOutput()) {
passes.add(DotGraphVisitor.dump());
}
return passes;
}
public static List<IDexTreeVisitor> getFallbackPassesList() {
List<IDexTreeVisitor> passes = new ArrayList<>();
passes.add(new AttachTryCatchVisitor());
passes.add(new AttachCommentsVisitor());
passes.add(new ProcessInstructionsVisitor());
passes.add(new FallbackModeVisitor());
return passes;
}
public static final String VERSION_DEV = "dev";
private static String version;
public static String getVersion() {
if (version == null) {
version = searchJadxVersion();
}
return version;
}
public static boolean isDevVersion() {
return getVersion().equals(VERSION_DEV);
}
private static String searchJadxVersion() {
try {
ClassLoader classLoader = Jadx.class.getClassLoader();
if (classLoader != null) {
Enumeration<URL> resources = classLoader.getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
try (InputStream is = resources.nextElement().openStream()) {
Manifest manifest = new Manifest(is);
String ver = manifest.getMainAttributes().getValue("jadx-version");
if (ver != null) {
return ver;
}
}
}
}
} catch (Exception e) {
LOG.error("Can't get manifest file", e);
}
return VERSION_DEV;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/Consts.java | jadx-core/src/main/java/jadx/core/Consts.java | package jadx.core;
public class Consts {
public static final boolean DEBUG = false;
public static final boolean DEBUG_WITH_ERRORS = false; // TODO: fix errors
public static final boolean DEBUG_USAGE = false;
public static final boolean DEBUG_TYPE_INFERENCE = false;
public static final boolean DEBUG_OVERLOADED_CASTS = false;
public static final boolean DEBUG_EXC_HANDLERS = false;
public static final boolean DEBUG_FINALLY = false;
public static final boolean DEBUG_ATTRIBUTES = false;
public static final boolean DEBUG_RESTRUCTURE = false;
public static final boolean DEBUG_EVENTS = Jadx.isDevVersion();
public static final String CLASS_OBJECT = "java.lang.Object";
public static final String CLASS_STRING = "java.lang.String";
public static final String CLASS_CLASS = "java.lang.Class";
public static final String CLASS_THROWABLE = "java.lang.Throwable";
public static final String CLASS_ERROR = "java.lang.Error";
public static final String CLASS_EXCEPTION = "java.lang.Exception";
public static final String CLASS_RUNTIME_EXCEPTION = "java.lang.RuntimeException";
public static final String CLASS_ENUM = "java.lang.Enum";
public static final String CLASS_STRING_BUILDER = "java.lang.StringBuilder";
public static final String OVERRIDE_ANNOTATION = "Ljava/lang/Override;";
public static final String DEFAULT_PACKAGE_NAME = "defpackage";
public static final String ANONYMOUS_CLASS_PREFIX = "AnonymousClass";
public static final String MTH_TOSTRING_SIGNATURE = "toString()Ljava/lang/String;";
private Consts() {
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/ProcessClass.java | jadx-core/src/main/java/jadx/core/ProcessClass.java | package jadx.core;
import java.util.List;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeInfo;
import jadx.api.impl.SimpleCodeInfo;
import jadx.core.codegen.CodeGen;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.LoadStage;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.visitors.DepthTraversal;
import jadx.core.dex.visitors.IDexTreeVisitor;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;
import static jadx.core.dex.nodes.ProcessState.GENERATED_AND_UNLOADED;
import static jadx.core.dex.nodes.ProcessState.LOADED;
import static jadx.core.dex.nodes.ProcessState.NOT_LOADED;
import static jadx.core.dex.nodes.ProcessState.PROCESS_COMPLETE;
import static jadx.core.dex.nodes.ProcessState.PROCESS_STARTED;
public class ProcessClass {
private static final Logger LOG = LoggerFactory.getLogger(ProcessClass.class);
private static final ICodeInfo NOT_GENERATED = new SimpleCodeInfo("");
private final List<IDexTreeVisitor> passes;
public ProcessClass(List<IDexTreeVisitor> passesList) {
this.passes = passesList;
}
@Nullable
private ICodeInfo process(ClassNode cls, boolean codegen) {
if (!codegen && cls.getState() == PROCESS_COMPLETE) {
// nothing to do
return null;
}
Utils.checkThreadInterrupt();
synchronized (cls.getClassInfo()) {
try {
if (cls.contains(AFlag.CLASS_DEEP_RELOAD)) {
cls.remove(AFlag.CLASS_DEEP_RELOAD);
cls.deepUnload();
cls.add(AFlag.CLASS_UNLOADED);
}
if (cls.contains(AFlag.CLASS_UNLOADED)) {
cls.root().runPreDecompileStageForClass(cls);
cls.remove(AFlag.CLASS_UNLOADED);
}
if (cls.getState() == GENERATED_AND_UNLOADED) {
// force loading code again
cls.setState(NOT_LOADED);
}
if (codegen) {
cls.setLoadStage(LoadStage.CODEGEN_STAGE);
if (cls.contains(AFlag.RELOAD_AT_CODEGEN_STAGE)) {
cls.remove(AFlag.RELOAD_AT_CODEGEN_STAGE);
cls.unload();
}
} else {
cls.setLoadStage(LoadStage.PROCESS_STAGE);
}
if (cls.getState() == NOT_LOADED) {
cls.load();
}
if (cls.getState() == LOADED) {
cls.setState(PROCESS_STARTED);
for (IDexTreeVisitor visitor : passes) {
DepthTraversal.visit(visitor, cls);
}
cls.setState(PROCESS_COMPLETE);
}
if (codegen) {
Utils.checkThreadInterrupt();
ICodeInfo code = CodeGen.generate(cls);
if (!cls.contains(AFlag.DONT_UNLOAD_CLASS)) {
cls.unload();
cls.setState(GENERATED_AND_UNLOADED);
}
return code;
}
return null;
} catch (StackOverflowError | Exception e) {
if (codegen) {
throw e;
}
cls.addError("Class process error: " + e.getClass().getSimpleName(), e);
return null;
}
}
}
@NotNull
public ICodeInfo generateCode(ClassNode cls) {
ClassNode topParentClass = cls.getTopParentClass();
if (topParentClass != cls) {
return generateCode(topParentClass);
}
try {
if (cls.contains(AFlag.DONT_GENERATE)) {
process(cls, false);
return NOT_GENERATED;
}
for (ClassNode depCls : cls.getDependencies()) {
process(depCls, false);
}
if (!cls.getCodegenDeps().isEmpty()) {
process(cls, false);
for (ClassNode codegenDep : cls.getCodegenDeps()) {
process(codegenDep, false);
}
}
ICodeInfo code = process(cls, true);
if (code == null) {
throw new JadxRuntimeException("Codegen failed");
}
return code;
} catch (StackOverflowError | Exception e) {
throw new JadxRuntimeException("Failed to generate code for class: " + cls.getFullName(), e);
}
}
/**
* Load and process class without its deps
*/
public void forceProcess(ClassNode cls) {
ClassNode topParentClass = cls.getTopParentClass();
if (topParentClass != cls) {
forceProcess(topParentClass);
return;
}
try {
process(cls, false);
} catch (StackOverflowError | Exception e) {
throw new JadxRuntimeException("Failed to process class: " + cls.getFullName(), e);
}
}
/**
* Generate code for class without processing its deps
*/
public @Nullable ICodeInfo forceGenerateCode(ClassNode cls) {
try {
return process(cls, true);
} catch (StackOverflowError | Exception e) {
throw new JadxRuntimeException("Failed to generate code for class: " + cls.getFullName(), e);
}
}
public void initPasses(RootNode root) {
for (IDexTreeVisitor pass : passes) {
try {
pass.init(root);
} catch (Exception e) {
LOG.error("Visitor init failed: {}", pass.getClass().getSimpleName(), e);
}
}
}
// TODO: make passes list private and not visible
public List<IDexTreeVisitor> getPasses() {
return passes;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/NameGen.java | jadx-core/src/main/java/jadx/core/codegen/NameGen.java | package jadx.core.codegen;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import jadx.core.deobf.NameMapper;
import jadx.core.dex.attributes.nodes.LoopLabelAttr;
import jadx.core.dex.instructions.args.CodeVar;
import jadx.core.dex.instructions.args.NamedArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.MethodNode;
public class NameGen {
private final MethodNode mth;
private final boolean fallback;
private final Set<String> varNames = new HashSet<>();
public NameGen(MethodNode mth, ClassGen classGen) {
this.mth = mth;
this.fallback = classGen.isFallbackMode();
NameGen outerNameGen = classGen.getOuterNameGen();
if (outerNameGen != null) {
inheritUsedNames(outerNameGen);
}
addNamesUsedInClass();
}
public void inheritUsedNames(NameGen otherNameGen) {
varNames.addAll(otherNameGen.varNames);
}
private void addNamesUsedInClass() {
ClassNode parentClass = mth.getParentClass();
for (FieldNode field : parentClass.getFields()) {
if (field.isStatic()) {
varNames.add(field.getAlias());
}
}
for (ClassNode innerClass : parentClass.getInnerClasses()) {
varNames.add(innerClass.getClassInfo().getAliasShortName());
}
// add all root package names to avoid collisions with full class names
varNames.addAll(mth.root().getCacheStorage().getRootPkgs());
}
public String assignArg(CodeVar var) {
if (fallback) {
return getFallbackName(var);
}
if (var.isThis()) {
return RegisterArg.THIS_ARG_NAME;
}
String name = getUniqueVarName(makeArgName(var));
var.setName(name);
return name;
}
public String assignNamedArg(NamedArg arg) {
String name = arg.getName();
if (fallback) {
return name;
}
String uniqName = getUniqueVarName(name);
arg.setName(uniqName);
return uniqName;
}
public String useArg(RegisterArg arg) {
String name = arg.getName();
if (name == null || fallback) {
return getFallbackName(arg);
}
return name;
}
// TODO: avoid name collision with variables names
public String getLoopLabel(LoopLabelAttr attr) {
String name = "loop" + attr.getLoop().getId();
varNames.add(name);
return name;
}
private String getUniqueVarName(String name) {
String r = name;
int i = 2;
while (varNames.contains(r)) {
r = name + i;
i++;
}
varNames.add(r);
return r;
}
private String makeArgName(CodeVar var) {
String name = var.getName();
if (NameMapper.isValidAndPrintable(name)) {
return name;
}
return getFallbackName(var);
}
private String getFallbackName(CodeVar var) {
List<SSAVar> ssaVars = var.getSsaVars();
if (ssaVars.isEmpty()) {
return "v";
}
return getFallbackName(ssaVars.get(0).getAssign());
}
private String getFallbackName(RegisterArg arg) {
return "r" + arg.getRegNum();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/InsnGen.java | jadx-core/src/main/java/jadx/core/codegen/InsnGen.java | package jadx.core.codegen;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.CommentsLevel;
import jadx.api.ICodeWriter;
import jadx.api.metadata.annotations.InsnCodeOffset;
import jadx.api.metadata.annotations.VarNode;
import jadx.api.plugins.input.data.MethodHandleType;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.core.codegen.utils.CodeGenUtils;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.FieldInitInsnAttr;
import jadx.core.dex.attributes.nodes.FieldReplaceAttr;
import jadx.core.dex.attributes.nodes.GenericInfoAttr;
import jadx.core.dex.attributes.nodes.LoopLabelAttr;
import jadx.core.dex.attributes.nodes.MethodReplaceAttr;
import jadx.core.dex.attributes.nodes.SkipMethodArgsAttr;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.ArithNode;
import jadx.core.dex.instructions.ArithOp;
import jadx.core.dex.instructions.BaseInvokeNode;
import jadx.core.dex.instructions.ConstClassNode;
import jadx.core.dex.instructions.ConstStringNode;
import jadx.core.dex.instructions.FillArrayInsn;
import jadx.core.dex.instructions.FilledNewArrayNode;
import jadx.core.dex.instructions.GotoNode;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.InvokeCustomNode;
import jadx.core.dex.instructions.InvokeCustomRawNode;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.InvokeType;
import jadx.core.dex.instructions.NewArrayNode;
import jadx.core.dex.instructions.SwitchInsn;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.CodeVar;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.Named;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.instructions.java.JsrNode;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.instructions.mods.TernaryInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.exceptions.CodegenException;
import jadx.core.utils.exceptions.JadxRuntimeException;
import static jadx.core.utils.android.AndroidResourcesUtils.handleAppResField;
public class InsnGen {
private static final Logger LOG = LoggerFactory.getLogger(InsnGen.class);
protected final MethodGen mgen;
protected final MethodNode mth;
protected final RootNode root;
protected final boolean fallback;
protected enum Flags {
BODY_ONLY,
BODY_ONLY_NOWRAP,
INLINE
}
public InsnGen(MethodGen mgen, boolean fallback) {
this.mgen = mgen;
this.mth = mgen.getMethodNode();
this.root = mth.root();
this.fallback = fallback;
}
private boolean isFallback() {
return fallback;
}
public void addArgDot(ICodeWriter code, InsnArg arg) throws CodegenException {
int len = code.getLength();
addArg(code, arg, true);
if (len != code.getLength()) {
code.add('.');
}
}
public void addArg(ICodeWriter code, InsnArg arg) throws CodegenException {
addArg(code, arg, true);
}
public void addArg(ICodeWriter code, InsnArg arg, boolean wrap) throws CodegenException {
addArg(code, arg, wrap ? BODY_ONLY_FLAG : BODY_ONLY_NOWRAP_FLAGS);
}
public void addArg(ICodeWriter code, InsnArg arg, Set<Flags> flags) throws CodegenException {
if (arg.isRegister()) {
RegisterArg reg = (RegisterArg) arg;
if (code.isMetadataSupported()) {
code.attachAnnotation(VarNode.getRef(mth, reg));
}
code.add(mgen.getNameGen().useArg(reg));
} else if (arg.isLiteral()) {
addLiteralArg(code, (LiteralArg) arg, flags);
} else if (arg.isInsnWrap()) {
addWrappedArg(code, (InsnWrapArg) arg, flags);
} else if (arg.isNamed()) {
code.add(((Named) arg).getName());
} else {
throw new CodegenException("Unknown arg type " + arg);
}
}
private void addLiteralArg(ICodeWriter code, LiteralArg litArg, Set<Flags> flags) {
String literalStr = lit(litArg);
if (!flags.contains(Flags.BODY_ONLY_NOWRAP) && literalStr.startsWith("-")) {
code.add('(').add(literalStr).add(')');
} else {
code.add(literalStr);
}
}
private void addWrappedArg(ICodeWriter code, InsnWrapArg arg, Set<Flags> flags) throws CodegenException {
InsnNode wrapInsn = arg.getWrapInsn();
if (wrapInsn.contains(AFlag.FORCE_ASSIGN_INLINE)) {
code.add('(');
makeInsn(wrapInsn, code, Flags.INLINE);
code.add(')');
} else {
makeInsnBody(code, wrapInsn, flags);
}
}
public void assignVar(ICodeWriter code, InsnNode insn) throws CodegenException {
RegisterArg arg = insn.getResult();
if (insn.contains(AFlag.DECLARE_VAR)) {
declareVar(code, arg);
} else {
addArg(code, arg, false);
}
}
public void declareVar(ICodeWriter code, RegisterArg arg) {
declareVar(code, arg.getSVar().getCodeVar());
}
public void declareVar(ICodeWriter code, CodeVar codeVar) {
if (codeVar.isFinal()) {
code.add("final ");
}
useType(code, codeVar.getType());
code.add(' ');
defVar(code, codeVar);
}
/**
* Variable definition without type, only var name
*/
private void defVar(ICodeWriter code, CodeVar codeVar) {
String varName = mgen.getNameGen().assignArg(codeVar);
if (code.isMetadataSupported()) {
code.attachDefinition(VarNode.get(mth, codeVar));
}
code.add(varName);
}
private String lit(LiteralArg arg) {
return TypeGen.literalToString(arg, mth, fallback);
}
private void instanceField(ICodeWriter code, FieldInfo field, InsnArg arg) throws CodegenException {
ClassNode pCls = mth.getParentClass();
FieldNode fieldNode = pCls.root().resolveField(field);
if (fieldNode != null) {
FieldReplaceAttr replace = fieldNode.get(AType.FIELD_REPLACE);
if (replace != null) {
switch (replace.getReplaceType()) {
case CLASS_INSTANCE:
useClass(code, replace.getClsRef());
code.add(".this");
break;
case VAR:
addArg(code, replace.getVarRef());
break;
}
return;
}
}
addArgDot(code, arg);
if (fieldNode != null) {
code.attachAnnotation(fieldNode);
}
if (fieldNode == null) {
code.add(field.getAlias());
} else {
code.add(fieldNode.getAlias());
}
}
protected void staticField(ICodeWriter code, FieldInfo field) throws CodegenException {
FieldNode fieldNode = root.resolveField(field);
if (fieldNode != null
&& fieldNode.contains(AFlag.INLINE_INSTANCE_FIELD)
&& fieldNode.getParentClass().contains(AType.ANONYMOUS_CLASS)) {
FieldInitInsnAttr initInsnAttr = fieldNode.get(AType.FIELD_INIT_INSN);
if (initInsnAttr != null) {
InsnNode insn = initInsnAttr.getInsn();
if (insn instanceof ConstructorInsn) {
fieldNode.add(AFlag.DONT_GENERATE);
inlineAnonymousConstructor(code, fieldNode.getParentClass(), (ConstructorInsn) insn);
return;
}
}
}
makeStaticFieldAccess(code, field, fieldNode, mgen.getClassGen());
}
public static void makeStaticFieldAccess(ICodeWriter code, FieldInfo field, ClassGen clsGen) {
FieldNode fieldNode = clsGen.getClassNode().root().resolveField(field);
makeStaticFieldAccess(code, field, fieldNode, clsGen);
}
private static void makeStaticFieldAccess(ICodeWriter code,
FieldInfo field, @Nullable FieldNode fieldNode, ClassGen clsGen) {
ClassInfo declClass = field.getDeclClass();
// TODO
boolean fieldFromThisClass = clsGen.getClassNode().getClassInfo().equals(declClass);
if (!fieldFromThisClass || !clsGen.isBodyGenStarted()) {
// Android specific resources class handler
if (!handleAppResField(code, clsGen, declClass)) {
clsGen.useClass(code, declClass);
}
code.add('.');
}
if (fieldNode != null) {
code.attachAnnotation(fieldNode);
}
if (fieldNode == null) {
code.add(field.getAlias());
} else {
code.add(fieldNode.getAlias());
}
}
public void useClass(ICodeWriter code, ArgType type) {
mgen.getClassGen().useClass(code, type);
}
public void useClass(ICodeWriter code, ClassInfo cls) {
mgen.getClassGen().useClass(code, cls);
}
protected void useType(ICodeWriter code, ArgType type) {
mgen.getClassGen().useType(code, type);
}
public void makeInsn(InsnNode insn, ICodeWriter code) throws CodegenException {
makeInsn(insn, code, null);
}
private static final Set<Flags> EMPTY_FLAGS = EnumSet.noneOf(Flags.class);
private static final Set<Flags> BODY_ONLY_FLAG = EnumSet.of(Flags.BODY_ONLY);
private static final Set<Flags> BODY_ONLY_NOWRAP_FLAGS = EnumSet.of(Flags.BODY_ONLY_NOWRAP);
protected void makeInsn(InsnNode insn, ICodeWriter code, Flags flag) throws CodegenException {
if (insn.getType() == InsnType.REGION_ARG) {
return;
}
try {
if (flag == Flags.BODY_ONLY || flag == Flags.BODY_ONLY_NOWRAP) {
makeInsnBody(code, insn, flag == Flags.BODY_ONLY ? BODY_ONLY_FLAG : BODY_ONLY_NOWRAP_FLAGS);
} else {
if (flag != Flags.INLINE) {
code.startLineWithNum(insn.getSourceLine());
InsnCodeOffset.attach(code, insn);
if (insn.contains(AFlag.COMMENT_OUT)) {
code.add("// ");
}
}
RegisterArg resArg = insn.getResult();
if (resArg != null) {
SSAVar var = resArg.getSVar();
if (var == null || var.getUseCount() != 0 || insn.getType() != InsnType.CONSTRUCTOR) {
assignVar(code, insn);
code.add(" = ");
}
}
makeInsnBody(code, insn, EMPTY_FLAGS);
if (flag != Flags.INLINE) {
code.add(';');
CodeGenUtils.addCodeComments(code, mth, insn);
}
}
} catch (Exception e) {
throw new CodegenException(mth, "Error generate insn: " + insn, e);
}
}
private void makeInsnBody(ICodeWriter code, InsnNode insn, Set<Flags> state) throws CodegenException {
switch (insn.getType()) {
case CONST_STR:
String str = ((ConstStringNode) insn).getString();
code.add(mth.root().getStringUtils().unescapeString(str));
break;
case CONST_CLASS:
ArgType clsType = ((ConstClassNode) insn).getClsType();
useType(code, clsType);
code.add(".class");
break;
case CONST:
LiteralArg arg = (LiteralArg) insn.getArg(0);
code.add(lit(arg));
break;
case MOVE:
addArg(code, insn.getArg(0), false);
break;
case CHECK_CAST:
case CAST: {
boolean wrap = state.contains(Flags.BODY_ONLY);
if (wrap) {
code.add('(');
}
code.add('(');
useType(code, (ArgType) ((IndexInsnNode) insn).getIndex());
code.add(") ");
addArg(code, insn.getArg(0), true);
if (wrap) {
code.add(')');
}
break;
}
case ARITH:
makeArith((ArithNode) insn, code, state);
break;
case NEG:
oneArgInsn(code, insn, state, '-');
break;
case NOT:
char op = insn.getArg(0).getType() == ArgType.BOOLEAN ? '!' : '~';
oneArgInsn(code, insn, state, op);
break;
case RETURN:
if (insn.getArgsCount() != 0) {
code.add("return ");
addArg(code, insn.getArg(0), false);
} else {
code.add("return");
}
break;
case BREAK:
code.add("break");
LoopLabelAttr labelAttr = insn.get(AType.LOOP_LABEL);
if (labelAttr != null) {
code.add(' ').add(mgen.getNameGen().getLoopLabel(labelAttr));
}
break;
case CONTINUE:
code.add("continue");
break;
case THROW:
code.add("throw ");
addArg(code, insn.getArg(0), true);
break;
case CMP_L:
case CMP_G:
code.add('(');
addArg(code, insn.getArg(0));
code.add(" > ");
addArg(code, insn.getArg(1));
code.add(" ? 1 : (");
addArg(code, insn.getArg(0));
code.add(" == ");
addArg(code, insn.getArg(1));
code.add(" ? 0 : -1))");
break;
case INSTANCE_OF: {
boolean wrap = state.contains(Flags.BODY_ONLY);
if (wrap) {
code.add('(');
}
addArg(code, insn.getArg(0));
code.add(" instanceof ");
useType(code, (ArgType) ((IndexInsnNode) insn).getIndex());
if (wrap) {
code.add(')');
}
break;
}
case CONSTRUCTOR:
makeConstructor((ConstructorInsn) insn, code);
break;
case INVOKE:
makeInvoke((InvokeNode) insn, code);
break;
case NEW_ARRAY: {
ArgType arrayType = ((NewArrayNode) insn).getArrayType();
code.add("new ");
useType(code, arrayType.getArrayRootElement());
int k = 0;
int argsCount = insn.getArgsCount();
for (; k < argsCount; k++) {
code.add('[');
addArg(code, insn.getArg(k), false);
code.add(']');
}
int dim = arrayType.getArrayDimension();
for (; k < dim; k++) {
code.add("[]");
}
break;
}
case ARRAY_LENGTH:
addArg(code, insn.getArg(0));
code.add(".length");
break;
case FILLED_NEW_ARRAY:
filledNewArray((FilledNewArrayNode) insn, code);
break;
case FILL_ARRAY:
FillArrayInsn arrayNode = (FillArrayInsn) insn;
if (fallback) {
String arrStr = arrayNode.dataToString();
addArg(code, insn.getArg(0));
code.add(" = {").add(arrStr.substring(1, arrStr.length() - 1)).add("} // fill-array");
} else {
fillArray(code, arrayNode);
}
break;
case AGET:
addArg(code, insn.getArg(0));
code.add('[');
addArg(code, insn.getArg(1), false);
code.add(']');
break;
case APUT:
addArg(code, insn.getArg(0));
code.add('[');
addArg(code, insn.getArg(1), false);
code.add("] = ");
addArg(code, insn.getArg(2), false);
break;
case IGET: {
FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) insn).getIndex();
instanceField(code, fieldInfo, insn.getArg(0));
break;
}
case IPUT: {
FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) insn).getIndex();
instanceField(code, fieldInfo, insn.getArg(1));
code.add(" = ");
addArg(code, insn.getArg(0), false);
break;
}
case SGET:
staticField(code, (FieldInfo) ((IndexInsnNode) insn).getIndex());
break;
case SPUT:
FieldInfo field = (FieldInfo) ((IndexInsnNode) insn).getIndex();
staticField(code, field);
code.add(" = ");
addArg(code, insn.getArg(0), false);
break;
case STR_CONCAT:
boolean wrap = state.contains(Flags.BODY_ONLY);
if (wrap) {
code.add('(');
}
for (Iterator<InsnArg> it = insn.getArguments().iterator(); it.hasNext();) {
addArg(code, it.next());
if (it.hasNext()) {
code.add(" + ");
}
}
if (wrap) {
code.add(')');
}
break;
case MONITOR_ENTER:
if (isFallback()) {
code.add("monitor-enter(");
addArg(code, insn.getArg(0));
code.add(')');
}
break;
case MONITOR_EXIT:
if (isFallback()) {
code.add("monitor-exit(");
if (insn.getArgsCount() == 1) {
addArg(code, insn.getArg(0));
}
code.add(')');
}
break;
case TERNARY:
makeTernary((TernaryInsn) insn, code, state);
break;
case ONE_ARG:
addArg(code, insn.getArg(0), state);
break;
/* fallback mode instructions */
case IF:
fallbackOnlyInsn(insn);
IfNode ifInsn = (IfNode) insn;
code.add("if (");
addArg(code, insn.getArg(0));
code.add(' ');
code.add(ifInsn.getOp().getSymbol()).add(' ');
addArg(code, insn.getArg(1));
code.add(") goto ").add(MethodGen.getLabelName(ifInsn));
break;
case GOTO:
fallbackOnlyInsn(insn);
code.add("goto ").add(MethodGen.getLabelName(((GotoNode) insn).getTarget()));
break;
case MOVE_EXCEPTION:
fallbackOnlyInsn(insn);
code.add("move-exception");
break;
case SWITCH:
fallbackOnlyInsn(insn);
SwitchInsn sw = (SwitchInsn) insn;
code.add("switch(");
addArg(code, insn.getArg(0));
code.add(") {");
code.incIndent();
int[] keys = sw.getKeys();
int size = keys.length;
BlockNode[] targetBlocks = sw.getTargetBlocks();
if (targetBlocks != null) {
for (int i = 0; i < size; i++) {
code.startLine("case ").add(Integer.toString(keys[i])).add(": goto ");
code.add(MethodGen.getLabelName(targetBlocks[i])).add(';');
}
code.startLine("default: goto ");
code.add(MethodGen.getLabelName(sw.getDefTargetBlock())).add(';');
} else {
int[] targets = sw.getTargets();
for (int i = 0; i < size; i++) {
code.startLine("case ").add(Integer.toString(keys[i])).add(": goto ");
code.add(MethodGen.getLabelName(targets[i])).add(';');
}
code.startLine("default: goto ");
code.add(MethodGen.getLabelName(sw.getDefaultCaseOffset())).add(';');
}
code.decIndent();
code.startLine('}');
break;
case NEW_INSTANCE:
// only fallback - make new instance in constructor invoke
fallbackOnlyInsn(insn);
code.add("new ").add(insn.getResult().getInitType().toString());
break;
case PHI:
fallbackOnlyInsn(insn);
code.add(insn.getType().toString()).add('(');
for (InsnArg insnArg : insn.getArguments()) {
addArg(code, insnArg);
code.add(' ');
}
code.add(')');
break;
case MOVE_RESULT:
fallbackOnlyInsn(insn);
code.add("move-result");
break;
case FILL_ARRAY_DATA:
fallbackOnlyInsn(insn);
code.add("fill-array " + insn);
break;
case SWITCH_DATA:
fallbackOnlyInsn(insn);
code.add(insn.toString());
break;
case MOVE_MULTI:
fallbackOnlyInsn(insn);
int len = insn.getArgsCount();
for (int i = 0; i < len - 1; i += 2) {
addArg(code, insn.getArg(i));
code.add(" = ");
addArg(code, insn.getArg(i + 1));
code.add("; ");
}
break;
case JAVA_JSR:
fallbackOnlyInsn(insn);
code.add("jsr -> ").add(MethodGen.getLabelName(((JsrNode) insn).getTarget()));
break;
case JAVA_RET:
fallbackOnlyInsn(insn);
code.add("ret ");
addArg(code, insn.getArg(0));
break;
default:
throw new CodegenException(mth, "Unknown instruction: " + insn.getType());
}
}
/**
* In most cases must be combined with new array instructions.
* Use one by one array fill (can be replaced with System.arrayCopy)
*/
private void fillArray(ICodeWriter code, FillArrayInsn arrayNode) throws CodegenException {
if (mth.checkCommentsLevel(CommentsLevel.INFO)) {
code.add("// fill-array-data instruction");
}
code.startLine();
InsnArg arrArg = arrayNode.getArg(0);
ArgType arrayType = arrArg.getType();
ArgType elemType;
if (arrayType.isTypeKnown() && arrayType.isArray()) {
elemType = arrayType.getArrayElement();
} else {
ArgType elementType = arrayNode.getElementType(); // unknown type
elemType = elementType.selectFirst();
}
List<LiteralArg> args = arrayNode.getLiteralArgs(elemType);
int len = args.size();
for (int i = 0; i < len; i++) {
if (i != 0) {
code.add(';');
code.startLine();
}
addArg(code, arrArg);
code.add('[').add(Integer.toString(i)).add("] = ").add(lit(args.get(i)));
}
}
private void oneArgInsn(ICodeWriter code, InsnNode insn, Set<Flags> state, char op) throws CodegenException {
boolean wrap = state.contains(Flags.BODY_ONLY);
if (wrap) {
code.add('(');
}
code.add(op);
addArg(code, insn.getArg(0));
if (wrap) {
code.add(')');
}
}
private void fallbackOnlyInsn(InsnNode insn) throws CodegenException {
if (!fallback) {
String msg = insn.getType() + " instruction can be used only in fallback mode";
CodegenException e = new CodegenException(msg);
mth.addError(msg, e);
mth.getParentClass().getTopParentClass().add(AFlag.RESTART_CODEGEN);
throw e;
}
}
private void filledNewArray(FilledNewArrayNode insn, ICodeWriter code) throws CodegenException {
if (!insn.contains(AFlag.DECLARE_VAR)) {
code.add("new ");
useType(code, insn.getArrayType());
}
code.add('{');
int c = insn.getArgsCount();
int wrap = 0;
for (int i = 0; i < c; i++) {
addArg(code, insn.getArg(i), false);
if (i + 1 < c) {
code.add(", ");
}
wrap++;
if (wrap == 1000) {
code.startLine();
wrap = 0;
}
}
code.add('}');
}
private void makeConstructor(ConstructorInsn insn, ICodeWriter code) throws CodegenException {
ClassNode cls = mth.root().resolveClass(insn.getClassType());
if (cls != null && cls.isAnonymous() && !fallback) {
inlineAnonymousConstructor(code, cls, insn);
return;
}
if (insn.isSelf()) {
throw new JadxRuntimeException("Constructor 'self' invoke must be removed!");
}
MethodNode callMth = mth.root().resolveMethod(insn.getCallMth());
MethodNode refMth = callMth;
if (callMth != null) {
MethodReplaceAttr replaceAttr = callMth.get(AType.METHOD_REPLACE);
if (replaceAttr != null) {
refMth = replaceAttr.getReplaceMth();
}
}
if (insn.isSuper()) {
code.attachAnnotation(refMth);
code.add("super");
} else if (insn.isThis()) {
code.attachAnnotation(refMth);
code.add("this");
} else {
boolean forceShortName = addOuterClassInstance(insn, code, callMth);
code.add("new ");
if (refMth == null || refMth.contains(AFlag.DONT_GENERATE)) {
// use class reference if constructor method is missing (default constructor)
code.attachAnnotation(mth.root().resolveClass(insn.getCallMth().getDeclClass()));
} else {
code.attachAnnotation(refMth);
}
if (forceShortName) {
mgen.getClassGen().addClsShortNameForced(code, insn.getClassType());
} else {
mgen.getClassGen().addClsName(code, insn.getClassType());
}
GenericInfoAttr genericInfoAttr = insn.get(AType.GENERIC_INFO);
if (genericInfoAttr != null) {
code.add('<');
if (genericInfoAttr.isExplicit()) {
boolean first = true;
for (ArgType type : genericInfoAttr.getGenericTypes()) {
if (!first) {
code.add(',');
} else {
first = false;
}
mgen.getClassGen().useType(code, type);
}
}
code.add('>');
}
}
generateMethodArguments(code, insn, 0, callMth);
}
private boolean addOuterClassInstance(ConstructorInsn insn, ICodeWriter code, MethodNode callMth) throws CodegenException {
if (callMth == null || !callMth.contains(AFlag.SKIP_FIRST_ARG)) {
return false;
}
ClassNode ctrCls = callMth.getDeclaringClass();
if (!ctrCls.isInner() || insn.getArgsCount() == 0) {
return false;
}
InsnArg instArg = insn.getArg(0);
if (instArg.isThis()) {
return false;
}
// instance arg should be of an outer class type
if (!instArg.getType().equals(ctrCls.getDeclaringClass().getType())) {
return false;
}
addArgDot(code, instArg);
// can't use another dot, force short name of class
return true;
}
private void inlineAnonymousConstructor(ICodeWriter code, ClassNode cls, ConstructorInsn insn) throws CodegenException {
cls.ensureProcessed();
if (this.mth.getParentClass() == cls) {
cls.remove(AType.ANONYMOUS_CLASS);
cls.remove(AFlag.DONT_GENERATE);
mth.getParentClass().getTopParentClass().add(AFlag.RESTART_CODEGEN);
throw new CodegenException("Anonymous inner class unlimited recursion detected."
+ " Convert class to inner: " + cls.getClassInfo().getFullName());
}
ArgType parent = cls.get(AType.ANONYMOUS_CLASS).getBaseType();
// hide empty anonymous constructors
for (MethodNode ctor : cls.getMethods()) {
if (ctor.contains(AFlag.ANONYMOUS_CONSTRUCTOR)
&& RegionUtils.isEmpty(ctor.getRegion())) {
ctor.add(AFlag.DONT_GENERATE);
}
}
code.attachDefinition(cls);
code.add("new ");
useClass(code, parent);
MethodNode callMth = mth.root().resolveMethod(insn.getCallMth());
if (callMth != null) {
// copy var names
List<RegisterArg> mthArgs = callMth.getArgRegs();
int argsCount = Math.min(insn.getArgsCount(), mthArgs.size());
for (int i = 0; i < argsCount; i++) {
InsnArg arg = insn.getArg(i);
if (arg.isRegister()) {
RegisterArg mthArg = mthArgs.get(i);
RegisterArg insnArg = (RegisterArg) arg;
mthArg.getSVar().setCodeVar(insnArg.getSVar().getCodeVar());
}
}
}
generateMethodArguments(code, insn, 0, callMth);
code.add(' ');
ClassGen classGen = new ClassGen(cls, mgen.getClassGen().getParentGen());
classGen.setOuterNameGen(mgen.getNameGen());
classGen.addClassBody(code, true);
mth.getParentClass().addInlinedClass(cls);
}
private void makeInvoke(InvokeNode insn, ICodeWriter code) throws CodegenException {
InvokeType type = insn.getInvokeType();
if (type == InvokeType.CUSTOM) {
makeInvokeLambda(code, (InvokeCustomNode) insn);
return;
}
MethodInfo callMth = insn.getCallMth();
MethodNode callMthNode = mth.root().resolveMethod(callMth);
if (type == InvokeType.CUSTOM_RAW) {
makeInvokeCustomRaw((InvokeCustomRawNode) insn, callMthNode, code);
return;
}
if (insn.isPolymorphicCall()) {
// add missing cast
code.add('(');
useType(code, callMth.getReturnType());
code.add(") ");
}
int k = 0;
switch (type) {
case DIRECT:
case VIRTUAL:
case INTERFACE:
case POLYMORPHIC:
InsnArg arg = insn.getArg(0);
if (needInvokeArg(arg)) {
addArgDot(code, arg);
}
k++;
break;
case SUPER:
callSuper(code, callMth);
k++; // use 'super' instead 'this' in 0 arg
code.add('.');
break;
case STATIC:
ClassInfo insnCls = mth.getParentClass().getClassInfo();
ClassInfo declClass = callMth.getDeclClass();
if (!insnCls.equals(declClass)) {
useClass(code, declClass);
code.add('.');
}
break;
}
if (callMthNode != null) {
code.attachAnnotation(callMthNode);
}
if (insn.contains(AFlag.FORCE_RAW_NAME)) {
code.add(callMth.getName());
} else {
if (callMthNode != null) {
code.add(callMthNode.getAlias());
} else {
code.add(callMth.getAlias());
}
}
generateMethodArguments(code, insn, k, callMthNode);
}
private void makeInvokeCustomRaw(InvokeCustomRawNode insn,
@Nullable MethodNode callMthNode, ICodeWriter code) throws CodegenException {
if (isFallback()) {
code.add("call_site(");
code.incIndent();
for (EncodedValue value : insn.getCallSiteValues()) {
code.startLine(value.toString());
}
code.decIndent();
code.startLine(").invoke");
generateMethodArguments(code, insn, 0, callMthNode);
} else {
ArgType returnType = insn.getCallMth().getReturnType();
if (!returnType.isVoid()) {
code.add('(');
useType(code, returnType);
code.add(") ");
}
makeInvoke(insn.getResolveInvoke(), code);
code.add(".dynamicInvoker().invoke");
generateMethodArguments(code, insn, 0, callMthNode);
code.add(" /* invoke-custom */");
}
}
// FIXME: add 'this' for equals methods in scope
private boolean needInvokeArg(InsnArg arg) {
if (arg.isAnyThis()) {
if (arg.isThis()) {
return false;
}
ClassNode clsNode = mth.root().resolveClass(arg.getType());
if (clsNode != null && clsNode.contains(AFlag.DONT_GENERATE)) {
return false;
}
}
return true;
}
private void makeInvokeLambda(ICodeWriter code, InvokeCustomNode customNode) throws CodegenException {
if (customNode.isUseRef()) {
makeRefLambda(code, customNode);
return;
}
if (fallback || !customNode.isInlineInsn()) {
makeSimpleLambda(code, customNode);
return;
}
MethodNode callMth = (MethodNode) customNode.getCallInsn().get(AType.METHOD_DETAILS);
makeInlinedLambdaMethod(code, customNode, callMth);
}
private void makeRefLambda(ICodeWriter code, InvokeCustomNode customNode) throws CodegenException {
InsnNode callInsn = customNode.getCallInsn();
if (callInsn instanceof ConstructorInsn) {
MethodInfo callMth = ((ConstructorInsn) callInsn).getCallMth();
useClass(code, callMth.getDeclClass());
code.add("::new");
return;
}
if (callInsn instanceof InvokeNode) {
InvokeNode invokeInsn = (InvokeNode) callInsn;
MethodInfo callMth = invokeInsn.getCallMth();
if (customNode.getHandleType() == MethodHandleType.INVOKE_STATIC) {
useClass(code, callMth.getDeclClass());
} else {
addArg(code, customNode.getArg(0));
}
code.add("::").add(callMth.getAlias());
}
}
private void makeSimpleLambda(ICodeWriter code, InvokeCustomNode customNode) {
try {
InsnNode callInsn = customNode.getCallInsn();
MethodInfo implMthInfo = customNode.getImplMthInfo();
int implArgsCount = implMthInfo.getArgsCount();
if (implArgsCount == 0) {
code.add("()");
} else {
code.add('(');
int callArgsCount = callInsn.getArgsCount();
int startArg = callArgsCount - implArgsCount;
if (customNode.getHandleType() != MethodHandleType.INVOKE_STATIC
&& customNode.getArgsCount() > 0
&& customNode.getArg(0).isThis()) {
callInsn.getArg(0).add(AFlag.THIS);
}
if (startArg >= 0) {
for (int i = startArg; i < callArgsCount; i++) {
if (i != startArg) {
code.add(", ");
}
addArg(code, callInsn.getArg(i));
}
} else {
code.add("/* ERROR: " + startArg + " */");
}
code.add(')');
}
code.add(" -> {");
if (fallback) {
code.add(" // ").add(implMthInfo.toString());
}
code.incIndent();
code.startLine();
if (!implMthInfo.getReturnType().isVoid()) {
code.add("return ");
}
makeInsn(callInsn, code, Flags.INLINE);
code.add(";");
code.decIndent();
code.startLine('}');
} catch (Exception e) {
throw new JadxRuntimeException("Failed to generate 'invoke-custom' instruction: " + e.getMessage(), e);
}
}
private void makeInlinedLambdaMethod(ICodeWriter code, InvokeCustomNode customNode, MethodNode callMth) throws CodegenException {
MethodGen callMthGen = new MethodGen(mgen.getClassGen(), callMth);
NameGen nameGen = callMthGen.getNameGen();
nameGen.inheritUsedNames(this.mgen.getNameGen());
List<ArgType> implArgs = customNode.getImplMthInfo().getArgumentsTypes();
List<RegisterArg> callArgs = callMth.getArgRegs();
if (implArgs.isEmpty()) {
code.add("()");
} else {
int callArgsCount = callArgs.size();
int startArg = callArgsCount - implArgs.size();
if (callArgsCount - startArg > 1) {
code.add('(');
}
for (int i = startArg; i < callArgsCount; i++) {
if (i != startArg) {
code.add(", ");
}
CodeVar argCodeVar = callArgs.get(i).getSVar().getCodeVar();
defVar(code, argCodeVar);
}
if (callArgsCount - startArg > 1) {
code.add(')');
}
}
// force set external arg names into call method args
int extArgsCount = customNode.getArgsCount();
int startArg = customNode.getHandleType() == MethodHandleType.INVOKE_STATIC ? 0 : 1; // skip 'this' arg
int callArg = 0;
for (int i = startArg; i < extArgsCount; i++) {
InsnArg arg = customNode.getArg(i);
if (arg.isRegister()) {
RegisterArg extArg = (RegisterArg) arg;
RegisterArg callRegArg = callArgs.get(callArg++);
callRegArg.getSVar().setCodeVar(extArg.getSVar().getCodeVar());
} else {
throw new JadxRuntimeException("Unexpected argument type in lambda call: " + arg.getClass().getSimpleName());
}
}
code.add(" -> {");
code.incIndent();
callMthGen.addInstructions(code);
code.decIndent();
code.startLine('}');
}
private void callSuper(ICodeWriter code, MethodInfo callMth) {
ClassInfo superCallCls = getClassForSuperCall(callMth);
if (superCallCls == null) {
// unknown class, add comment to keep that info
code.add("super/*").add(callMth.getDeclClass().getFullName()).add("*/");
return;
}
ClassInfo curClass = mth.getParentClass().getClassInfo();
if (superCallCls.equals(curClass)) {
code.add("super");
return;
}
// use custom class
useClass(code, superCallCls);
code.add(".super");
}
/**
* Search call class in super types of this
* and all parent classes (needed for inlined synthetic calls)
*/
@Nullable
private ClassInfo getClassForSuperCall(MethodInfo callMth) {
ArgType declClsType = callMth.getDeclClass().getType();
ClassNode parentNode = mth.getParentClass();
while (true) {
ClassInfo parentCls = parentNode.getClassInfo();
if (ArgType.isInstanceOf(root, parentCls.getType(), declClsType)) {
return parentCls;
}
ClassNode nextParent = parentNode.getParentClass();
if (nextParent == parentNode) {
// no parent, class not found
return null;
}
parentNode = nextParent;
}
}
void generateMethodArguments(ICodeWriter code, BaseInvokeNode insn, int startArgNum,
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | true |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/MethodGen.java | jadx-core/src/main/java/jadx/core/codegen/MethodGen.java | package jadx.core.codegen;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.CommentsLevel;
import jadx.api.ICodeWriter;
import jadx.api.JadxArgs;
import jadx.api.args.IntegerFormat;
import jadx.api.metadata.annotations.InsnCodeOffset;
import jadx.api.metadata.annotations.VarNode;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.api.plugins.input.data.attributes.types.AnnotationMethodParamsAttr;
import jadx.core.Consts;
import jadx.core.Jadx;
import jadx.core.codegen.utils.CodeGenUtils;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.JadxError;
import jadx.core.dex.attributes.nodes.JumpInfo;
import jadx.core.dex.attributes.nodes.MethodOverrideAttr;
import jadx.core.dex.attributes.nodes.MethodReplaceAttr;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.instructions.ConstStringNode;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.CodeVar;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.trycatch.CatchAttr;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.dex.visitors.DepthTraversal;
import jadx.core.dex.visitors.IDexTreeVisitor;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.CodegenException;
import jadx.core.utils.exceptions.JadxOverflowException;
import static jadx.core.codegen.MethodGen.FallbackOption.BLOCK_DUMP;
import static jadx.core.codegen.MethodGen.FallbackOption.COMMENTED_DUMP;
import static jadx.core.codegen.MethodGen.FallbackOption.FALLBACK_MODE;
public class MethodGen {
private static final Logger LOG = LoggerFactory.getLogger(MethodGen.class);
private final MethodNode mth;
private final ClassGen classGen;
private final AnnotationGen annotationGen;
private final NameGen nameGen;
public MethodGen(ClassGen classGen, MethodNode mth) {
this.mth = mth;
this.classGen = classGen;
this.annotationGen = classGen.getAnnotationGen();
this.nameGen = new NameGen(mth, classGen);
}
public ClassGen getClassGen() {
return classGen;
}
public NameGen getNameGen() {
return nameGen;
}
public MethodNode getMethodNode() {
return mth;
}
public boolean addDefinition(ICodeWriter code) {
if (mth.getMethodInfo().isClassInit()) {
code.startLine();
code.attachDefinition(mth);
code.add("static");
return true;
}
if (mth.contains(AFlag.ANONYMOUS_CONSTRUCTOR)) {
// don't add method name and arguments
code.startLine();
code.attachDefinition(mth);
return false;
}
if (Consts.DEBUG_USAGE) {
ClassGen.addMthUsageInfo(code, mth);
}
addOverrideAnnotation(code, mth);
annotationGen.addForMethod(code, mth);
AccessInfo clsAccFlags = mth.getParentClass().getAccessFlags();
AccessInfo ai = mth.getAccessFlags();
// don't add 'abstract' and 'public' to methods in interface
if (clsAccFlags.isInterface()) {
ai = ai.remove(AccessFlags.ABSTRACT);
ai = ai.remove(AccessFlags.PUBLIC);
}
// don't add 'public' for annotations
if (clsAccFlags.isAnnotation()) {
ai = ai.remove(AccessFlags.PUBLIC);
}
if (mth.getMethodInfo().isConstructor() && mth.getParentClass().isEnum()) {
ai = ai.remove(AccessInfo.VISIBILITY_FLAGS);
}
if (mth.getMethodInfo().hasAlias() && !ai.isConstructor()) {
CodeGenUtils.addRenamedComment(code, mth, mth.getName());
}
if (mth.contains(AFlag.INCONSISTENT_CODE) && mth.checkCommentsLevel(CommentsLevel.ERROR)) {
code.startLine("/*");
code.incIndent();
code.startLine("Code decompiled incorrectly, please refer to instructions dump.");
if (!mth.root().getArgs().isShowInconsistentCode()) {
if (code.isMetadataSupported()) {
code.startLine("To view partially-correct code enable 'Show inconsistent code' option in preferences");
} else {
code.startLine("To view partially-correct add '--show-bad-code' argument");
}
}
code.decIndent();
code.startLine("*/");
}
code.startLineWithNum(mth.getSourceLine());
code.add(ai.makeString(mth.checkCommentsLevel(CommentsLevel.INFO)));
if (clsAccFlags.isInterface() && !mth.isNoCode() && !mth.getAccessFlags().isStatic()) {
// add 'default' for method with code in interface
code.add("default ");
}
if (classGen.addGenericTypeParameters(code, mth.getTypeParameters(), false)) {
code.add(' ');
}
if (ai.isConstructor()) {
code.attachDefinition(mth);
code.add(classGen.getClassNode().getShortName()); // constructor
} else {
classGen.useType(code, mth.getReturnType());
code.add(' ');
MethodNode defMth = getMethodForDefinition();
code.attachDefinition(defMth);
code.add(defMth.getAlias());
}
code.add('(');
List<RegisterArg> args = mth.getArgRegs();
if (mth.getMethodInfo().isConstructor()
&& mth.getParentClass().contains(AType.ENUM_CLASS)) {
if (args.size() == 2) {
args = Collections.emptyList();
} else if (args.size() > 2) {
args = args.subList(2, args.size());
} else {
mth.addWarnComment("Incorrect number of args for enum constructor: " + args.size() + " (expected >= 2)");
}
} else if (mth.contains(AFlag.SKIP_FIRST_ARG)) {
args = args.subList(1, args.size());
}
addMethodArguments(code, args);
code.add(')');
annotationGen.addThrows(mth, code);
// add default value for annotation class
if (mth.getParentClass().getAccessFlags().isAnnotation()) {
EncodedValue def = annotationGen.getAnnotationDefaultValue(mth);
if (def != null) {
code.add(" default ");
annotationGen.encodeValue(mth.root(), code, def);
}
}
return true;
}
private MethodNode getMethodForDefinition() {
MethodReplaceAttr replaceAttr = mth.get(AType.METHOD_REPLACE);
if (replaceAttr != null) {
return replaceAttr.getReplaceMth();
}
return mth;
}
private void addOverrideAnnotation(ICodeWriter code, MethodNode mth) {
MethodOverrideAttr overrideAttr = mth.get(AType.METHOD_OVERRIDE);
if (overrideAttr == null) {
return;
}
if (!overrideAttr.getBaseMethods().contains(mth)) {
code.startLine("@Override");
if (mth.checkCommentsLevel(CommentsLevel.INFO)) {
code.add(" // ");
code.add(Utils.listToString(overrideAttr.getOverrideList(), ", ",
md -> md.getMethodInfo().getDeclClass().getAliasFullName()));
}
}
if (Consts.DEBUG) {
code.startLine("// related by override: ");
code.add(Utils.listToString(overrideAttr.getRelatedMthNodes(), ", ", m -> m.getParentClass().getFullName()));
}
}
private void addMethodArguments(ICodeWriter code, List<RegisterArg> args) {
AnnotationMethodParamsAttr paramsAnnotation = mth.get(JadxAttrType.ANNOTATION_MTH_PARAMETERS);
int i = 0;
Iterator<RegisterArg> it = args.iterator();
while (it.hasNext()) {
RegisterArg mthArg = it.next();
SSAVar ssaVar = mthArg.getSVar();
CodeVar var;
if (ssaVar == null) {
// abstract or interface methods
var = CodeVar.fromMthArg(mthArg, classGen.isFallbackMode());
} else {
var = ssaVar.getCodeVar();
}
// add argument annotation
if (paramsAnnotation != null) {
annotationGen.addForParameter(code, paramsAnnotation, i);
}
if (var.isFinal()) {
code.add("final ");
}
ArgType argType;
ArgType varType = var.getType();
if (varType == null || varType == ArgType.UNKNOWN) {
// occur on decompilation errors
argType = mthArg.getInitType();
} else {
argType = varType;
}
if (!it.hasNext() && mth.getAccessFlags().isVarArgs()) {
// change last array argument to varargs
if (argType.isArray()) {
ArgType elType = argType.getArrayElement();
classGen.useType(code, elType);
code.add("...");
} else {
mth.addWarnComment("Last argument in varargs method is not array: " + var);
classGen.useType(code, argType);
}
} else {
classGen.useType(code, argType);
}
code.add(' ');
String varName = nameGen.assignArg(var);
if (code.isMetadataSupported() && ssaVar != null /* for fallback mode */) {
code.attachDefinition(VarNode.get(mth, var));
}
code.add(varName);
i++;
if (it.hasNext()) {
code.add(", ");
}
}
}
public void addInstructions(ICodeWriter code) throws CodegenException {
JadxArgs args = mth.root().getArgs();
switch (args.getDecompilationMode()) {
case AUTO:
if (classGen.isFallbackMode() || mth.getRegion() == null) {
// TODO: try simple mode first
dumpInstructions(code);
} else {
addRegionInsns(code);
}
break;
case RESTRUCTURE:
addRegionInsns(code);
break;
case SIMPLE:
addSimpleMethodCode(code);
break;
case FALLBACK:
addFallbackMethodCode(code, FALLBACK_MODE);
break;
}
}
public void addRegionInsns(ICodeWriter code) throws CodegenException {
try {
RegionGen regionGen = new RegionGen(this);
regionGen.makeRegion(code, mth.getRegion());
} catch (StackOverflowError | BootstrapMethodError e) {
mth.addError("Method code generation error", new JadxOverflowException("StackOverflow"));
CodeGenUtils.addErrors(code, mth);
dumpInstructions(code);
} catch (Exception e) {
if (mth.getParentClass().getTopParentClass().contains(AFlag.RESTART_CODEGEN)) {
throw e;
}
mth.addError("Method code generation error", e);
CodeGenUtils.addErrors(code, mth);
dumpInstructions(code);
}
}
private void addSimpleMethodCode(ICodeWriter code) {
if (mth.getBasicBlocks() == null) {
code.startLine("// Blocks not ready for simple mode, using fallback");
addFallbackMethodCode(code, FALLBACK_MODE);
return;
}
JadxArgs args = mth.root().getArgs();
ICodeWriter tmpCode = args.getCodeWriterProvider().apply(args);
try {
tmpCode.setIndent(code.getIndent());
generateSimpleCode(tmpCode);
code.add(tmpCode);
} catch (Exception e) {
mth.addError("Simple mode code generation failed", e);
CodeGenUtils.addError(code, "Simple mode code generation failed", e);
dumpInstructions(code);
}
}
private void generateSimpleCode(ICodeWriter code) throws CodegenException {
SimpleModeHelper helper = new SimpleModeHelper(mth);
List<BlockNode> blocks = helper.prepareBlocks();
InsnGen insnGen = new InsnGen(this, true);
for (BlockNode block : blocks) {
if (block.contains(AFlag.DONT_GENERATE)) {
continue;
}
if (helper.isNeedStartLabel(block)) {
code.decIndent();
code.startLine(getLabelName(block)).add(':');
code.incIndent();
}
for (InsnNode insn : block.getInstructions()) {
if (!insn.contains(AFlag.DONT_GENERATE)) {
if (insn.getResult() != null) {
CodeVar codeVar = insn.getResult().getSVar().getCodeVar();
if (!codeVar.isDeclared()) {
insn.add(AFlag.DECLARE_VAR);
codeVar.setDeclared(true);
}
}
InsnCodeOffset.attach(code, insn);
insnGen.makeInsn(insn, code);
addCatchComment(code, insn, false);
CodeGenUtils.addCodeComments(code, mth, insn);
}
}
if (helper.isNeedEndGoto(block)) {
code.startLine("goto ").add(getLabelName(block.getSuccessors().get(0)));
}
}
}
public void dumpInstructions(ICodeWriter code) {
if (mth.checkCommentsLevel(CommentsLevel.ERROR)) {
code.startLine("/*");
addFallbackMethodCode(code, COMMENTED_DUMP);
code.startLine("*/");
}
code.startLine("throw new UnsupportedOperationException(\"Method not decompiled: ")
.add(mth.getParentClass().getClassInfo().getAliasFullName())
.add('.')
.add(mth.getAlias())
.add('(')
.add(Utils.listToString(mth.getMethodInfo().getArgumentsTypes()))
.add("):")
.add(mth.getMethodInfo().getReturnType().toString())
.add("\");");
}
public void addFallbackMethodCode(ICodeWriter code, FallbackOption fallbackOption) {
if (fallbackOption == COMMENTED_DUMP && mth.getCommentsLevel() != CommentsLevel.DEBUG) {
long insnCountEstimate = mth.getInsnsCount();
if (insnCountEstimate > 200) {
code.incIndent();
code.startLine("Method dump skipped, instruction units count: " + insnCountEstimate);
if (code.isMetadataSupported()) {
code.startLine("To view this dump change 'Code comments level' option to 'DEBUG'");
} else {
code.startLine("To view this dump add '--comments-level debug' option");
}
code.decIndent();
return;
}
}
if (fallbackOption != FALLBACK_MODE) {
List<JadxError> errors = mth.getAll(AType.JADX_ERROR); // preserve error before unload
try {
// load original instructions
mth.unload();
mth.load();
for (IDexTreeVisitor visitor : Jadx.getFallbackPassesList()) {
DepthTraversal.visit(visitor, mth);
}
errors.forEach(err -> mth.addAttr(AType.JADX_ERROR, err));
} catch (Exception e) {
LOG.error("Error reload instructions in fallback mode:", e);
code.startLine("// Can't load method instructions: " + e.getMessage());
return;
} finally {
errors.forEach(err -> mth.addAttr(AType.JADX_ERROR, err));
}
}
InsnNode[] insnArr = mth.getInstructions();
if (insnArr == null) {
code.startLine("// Can't load method instructions.");
return;
}
code.incIndent();
if (mth.getThisArg() != null) {
code.startLine(nameGen.useArg(mth.getThisArg())).add(" = this;");
}
addFallbackInsns(code, mth, insnArr, fallbackOption);
code.decIndent();
}
public enum FallbackOption {
FALLBACK_MODE,
BLOCK_DUMP,
COMMENTED_DUMP
}
public static void addFallbackInsns(ICodeWriter code, MethodNode mth, InsnNode[] insnArr, FallbackOption option) {
int startIndent = code.getIndent();
MethodGen methodGen = getFallbackMethodGen(mth);
InsnGen insnGen = new InsnGen(methodGen, true);
InsnNode prevInsn = null;
for (InsnNode insn : insnArr) {
if (insn == null) {
continue;
}
methodGen.dumpInsn(code, insnGen, option, startIndent, prevInsn, insn);
prevInsn = insn;
}
}
private boolean dumpInsn(ICodeWriter code, InsnGen insnGen, FallbackOption option, int startIndent,
@Nullable InsnNode prevInsn, InsnNode insn) {
if (insn.contains(AType.JADX_ERROR)) {
for (JadxError error : insn.getAll(AType.JADX_ERROR)) {
code.startLine("// ").add(error.getError());
}
return true;
}
if (option != BLOCK_DUMP && needLabel(insn, prevInsn)) {
code.decIndent();
code.startLine(getLabelName(insn.getOffset()) + ':');
code.incIndent();
}
if (insn.getType() == InsnType.NOP) {
return true;
}
try {
boolean escapeComment = isCommentEscapeNeeded(insn, option);
if (escapeComment) {
code.decIndent();
code.startLine("*/");
code.startLine("// ");
} else {
code.startLineWithNum(insn.getSourceLine());
}
InsnCodeOffset.attach(code, insn);
RegisterArg resArg = insn.getResult();
if (resArg != null) {
ArgType varType = resArg.getInitType();
if (varType.isTypeKnown()) {
code.add(varType.toString()).add(' ');
}
}
insnGen.makeInsn(insn, code, InsnGen.Flags.INLINE);
if (escapeComment) {
code.startLine("/*");
code.incIndent();
}
addCatchComment(code, insn, true);
CodeGenUtils.addCodeComments(code, mth, insn);
} catch (Exception e) {
LOG.debug("Error generate fallback instruction: ", e.getCause());
code.setIndent(startIndent);
code.startLine("// error: " + insn);
}
return false;
}
private void addCatchComment(ICodeWriter code, InsnNode insn, boolean raw) {
CatchAttr catchAttr = insn.get(AType.EXC_CATCH);
if (catchAttr == null) {
return;
}
code.add(" // Catch:");
for (ExceptionHandler handler : catchAttr.getHandlers()) {
code.add(' ');
classGen.useClass(code, handler.getArgType());
code.add(" -> ");
if (raw) {
code.add(getLabelName(handler.getHandlerOffset()));
} else {
code.add(getLabelName(handler.getHandlerBlock()));
}
}
}
private static boolean isCommentEscapeNeeded(InsnNode insn, FallbackOption option) {
if (option == COMMENTED_DUMP) {
if (insn.getType() == InsnType.CONST_STR) {
String str = ((ConstStringNode) insn).getString();
return str.contains("*/");
}
}
return false;
}
private static boolean needLabel(InsnNode insn, InsnNode prevInsn) {
if (insn.contains(AType.EXC_HANDLER)) {
return true;
}
if (insn.contains(AType.JUMP)) {
// don't add label for ifs else branch
if (prevInsn != null && prevInsn.getType() == InsnType.IF) {
List<JumpInfo> jumps = insn.getAll(AType.JUMP);
if (jumps.size() == 1) {
JumpInfo jump = jumps.get(0);
if (jump.getSrc() == prevInsn.getOffset() && jump.getDest() == insn.getOffset()) {
int target = ((IfNode) prevInsn).getTarget();
return insn.getOffset() == target;
}
}
}
return true;
}
return false;
}
/**
* Return fallback variant of method codegen
*/
public static MethodGen getFallbackMethodGen(MethodNode mth) {
ClassGen clsGen = new ClassGen(mth.getParentClass(), null, false, true, true, IntegerFormat.AUTO);
return new MethodGen(clsGen, mth);
}
public static String getLabelName(BlockNode block) {
return String.format("L%d", block.getCId());
}
public static String getLabelName(IfNode insn) {
BlockNode thenBlock = insn.getThenBlock();
if (thenBlock != null) {
return getLabelName(thenBlock);
}
return getLabelName(insn.getTarget());
}
public static String getLabelName(int offset) {
if (offset < 0) {
return String.format("LB_%x", -offset);
}
return String.format("L%x", offset);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/SimpleModeHelper.java | jadx-core/src/main/java/jadx/core/codegen/SimpleModeHelper.java | package jadx.core.codegen;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.TargetInsnNode;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.dex.visitors.blocks.BlockProcessor;
import jadx.core.dex.visitors.blocks.BlockSplitter;
import jadx.core.utils.BlockUtils;
public class SimpleModeHelper {
private final MethodNode mth;
private final BitSet startLabel;
private final BitSet endGoto;
public SimpleModeHelper(MethodNode mth) {
this.mth = mth;
this.startLabel = BlockUtils.newBlocksBitSet(mth);
this.endGoto = BlockUtils.newBlocksBitSet(mth);
}
public List<BlockNode> prepareBlocks() {
removeEmptyBlocks();
List<BlockNode> blocksList = getSortedBlocks();
blocksList.removeIf(b -> b.equals(mth.getEnterBlock()) || b.equals(mth.getExitBlock()));
unbindExceptionHandlers();
if (blocksList.isEmpty()) {
return Collections.emptyList();
}
@Nullable
BlockNode prev = null;
int blocksCount = blocksList.size();
for (int i = 0; i < blocksCount; i++) {
BlockNode block = blocksList.get(i);
BlockNode nextBlock = i + 1 == blocksCount ? null : blocksList.get(i + 1);
List<BlockNode> preds = block.getPredecessors();
int predsCount = preds.size();
if (predsCount > 1) {
startLabel.set(block.getId());
} else if (predsCount == 1 && prev != null) {
if (!prev.equals(preds.get(0))) {
if (!block.contains(AFlag.EXC_BOTTOM_SPLITTER)) {
startLabel.set(block.getId());
}
if (prev.getSuccessors().size() == 1 && !mth.isPreExitBlock(prev)) {
endGoto.set(prev.getId());
}
}
}
InsnNode lastInsn = BlockUtils.getLastInsn(block);
if (lastInsn instanceof TargetInsnNode) {
processTargetInsn(block, lastInsn, nextBlock);
}
if (block.contains(AType.EXC_HANDLER)) {
startLabel.set(block.getId());
}
if (nextBlock == null && !mth.isPreExitBlock(block)) {
endGoto.set(block.getId());
}
prev = block;
}
if (mth.isVoidReturn()) {
int last = blocksList.size() - 1;
if (blocksList.get(last).contains(AFlag.RETURN)) {
// remove trailing return
blocksList.remove(last);
}
}
return blocksList;
}
private void removeEmptyBlocks() {
for (BlockNode block : mth.getBasicBlocks()) {
if (block.getInstructions().isEmpty()
&& block.getPredecessors().size() > 0
&& block.getSuccessors().size() == 1) {
BlockNode successor = block.getSuccessors().get(0);
List<BlockNode> predecessors = block.getPredecessors();
BlockSplitter.removeConnection(block, successor);
if (predecessors.size() == 1) {
BlockSplitter.replaceConnection(predecessors.get(0), block, successor);
} else {
for (BlockNode pred : new ArrayList<>(predecessors)) {
BlockSplitter.replaceConnection(pred, block, successor);
}
}
block.add(AFlag.REMOVE);
}
}
BlockProcessor.removeMarkedBlocks(mth);
}
private void unbindExceptionHandlers() {
if (mth.isNoExceptionHandlers()) {
return;
}
for (ExceptionHandler handler : mth.getExceptionHandlers()) {
BlockNode handlerBlock = handler.getHandlerBlock();
if (handlerBlock != null) {
BlockSplitter.removePredecessors(handlerBlock);
}
}
}
private void processTargetInsn(BlockNode block, InsnNode lastInsn, @Nullable BlockNode next) {
if (lastInsn instanceof IfNode) {
IfNode ifInsn = (IfNode) lastInsn;
BlockNode thenBlock = ifInsn.getThenBlock();
if (Objects.equals(next, thenBlock)) {
ifInsn.invertCondition();
startLabel.set(ifInsn.getThenBlock().getId());
} else {
startLabel.set(thenBlock.getId());
}
ifInsn.normalize();
} else {
for (BlockNode successor : block.getSuccessors()) {
startLabel.set(successor.getId());
}
}
}
public boolean isNeedStartLabel(BlockNode block) {
return startLabel.get(block.getId());
}
public boolean isNeedEndGoto(BlockNode block) {
return endGoto.get(block.getId());
}
// DFS sort blocks to reduce goto count
private List<BlockNode> getSortedBlocks() {
List<BlockNode> list = new ArrayList<>(mth.getBasicBlocks().size());
BlockUtils.visitDFS(mth, list::add);
return list;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/ConditionGen.java | jadx-core/src/main/java/jadx/core/codegen/ConditionGen.java | package jadx.core.codegen;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
import jadx.api.ICodeWriter;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.ArithNode;
import jadx.core.dex.instructions.IfOp;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.regions.conditions.Compare;
import jadx.core.dex.regions.conditions.IfCondition;
import jadx.core.dex.regions.conditions.IfCondition.Mode;
import jadx.core.utils.exceptions.CodegenException;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class ConditionGen extends InsnGen {
private static class CondStack {
private final Queue<IfCondition> stack = new ArrayDeque<>();
public Queue<IfCondition> getStack() {
return stack;
}
public void push(IfCondition cond) {
stack.add(cond);
}
public IfCondition pop() {
return stack.poll();
}
}
public ConditionGen(InsnGen insnGen) {
super(insnGen.mgen, insnGen.fallback);
}
public void add(ICodeWriter code, IfCondition condition) throws CodegenException {
add(code, new CondStack(), condition);
}
void wrap(ICodeWriter code, IfCondition condition) throws CodegenException {
wrap(code, new CondStack(), condition);
}
private void add(ICodeWriter code, CondStack stack, IfCondition condition) throws CodegenException {
stack.push(condition);
switch (condition.getMode()) {
case COMPARE:
addCompare(code, stack, condition.getCompare());
break;
case TERNARY:
addTernary(code, stack, condition);
break;
case NOT:
addNot(code, stack, condition);
break;
case AND:
case OR:
addAndOr(code, stack, condition);
break;
default:
throw new JadxRuntimeException("Unknown condition mode: " + condition.getMode());
}
stack.pop();
}
private void wrap(ICodeWriter code, CondStack stack, IfCondition cond) throws CodegenException {
boolean wrap = isWrapNeeded(cond);
if (wrap) {
code.add('(');
}
add(code, stack, cond);
if (wrap) {
code.add(')');
}
}
private void wrap(ICodeWriter code, InsnArg firstArg) throws CodegenException {
boolean wrap = isArgWrapNeeded(firstArg);
if (wrap) {
code.add('(');
}
addArg(code, firstArg, false);
if (wrap) {
code.add(')');
}
}
private void addCompare(ICodeWriter code, CondStack stack, Compare compare) throws CodegenException {
IfOp op = compare.getOp();
InsnArg firstArg = compare.getA();
InsnArg secondArg = compare.getB();
if (firstArg.getType().equals(ArgType.BOOLEAN)
&& secondArg.isLiteral()
&& secondArg.getType().equals(ArgType.BOOLEAN)) {
LiteralArg lit = (LiteralArg) secondArg;
if (lit.getLiteral() == 0) {
op = op.invert();
}
if (op == IfOp.EQ) {
// == true
if (stack.getStack().size() == 1) {
addArg(code, firstArg, false);
} else {
wrap(code, firstArg);
}
return;
} else if (op == IfOp.NE) {
// != true
code.add('!');
wrap(code, firstArg);
return;
}
mth.addWarn("Unsupported boolean condition " + op.getSymbol());
}
addArg(code, firstArg, isArgWrapNeeded(firstArg));
code.add(' ').add(op.getSymbol()).add(' ');
addArg(code, secondArg, isArgWrapNeeded(secondArg));
}
private void addTernary(ICodeWriter code, CondStack stack, IfCondition condition) throws CodegenException {
add(code, stack, condition.first());
code.add(" ? ");
add(code, stack, condition.second());
code.add(" : ");
add(code, stack, condition.third());
}
private void addNot(ICodeWriter code, CondStack stack, IfCondition condition) throws CodegenException {
code.add('!');
wrap(code, stack, condition.getArgs().get(0));
}
private void addAndOr(ICodeWriter code, CondStack stack, IfCondition condition) throws CodegenException {
String mode = condition.getMode() == Mode.AND ? " && " : " || ";
Iterator<IfCondition> it = condition.getArgs().iterator();
while (it.hasNext()) {
wrap(code, stack, it.next());
if (it.hasNext()) {
code.add(mode);
}
}
}
private boolean isWrapNeeded(IfCondition condition) {
if (condition.isCompare() || condition.contains(AFlag.DONT_WRAP)) {
return false;
}
return condition.getMode() != Mode.NOT;
}
private static boolean isArgWrapNeeded(InsnArg arg) {
if (!arg.isInsnWrap()) {
return false;
}
InsnNode insn = ((InsnWrapArg) arg).getWrapInsn();
InsnType insnType = insn.getType();
if (insnType == InsnType.ARITH) {
switch (((ArithNode) insn).getOp()) {
case ADD:
case SUB:
case MUL:
case DIV:
case REM:
return false;
default:
return true;
}
} else {
switch (insnType) {
case INVOKE:
case SGET:
case IGET:
case AGET:
case CONST:
case ARRAY_LENGTH:
return false;
default:
return true;
}
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/ClassGen.java | jadx-core/src/main/java/jadx/core/codegen/ClassGen.java | package jadx.core.codegen;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import jadx.api.CommentsLevel;
import jadx.api.ICodeInfo;
import jadx.api.ICodeWriter;
import jadx.api.JadxArgs;
import jadx.api.args.IntegerFormat;
import jadx.api.metadata.annotations.NodeEnd;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.api.plugins.input.data.annotations.EncodedType;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.core.Consts;
import jadx.core.codegen.utils.CodeGenUtils;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.FieldInitInsnAttr;
import jadx.core.dex.attributes.nodes.EnumClassAttr;
import jadx.core.dex.attributes.nodes.EnumClassAttr.EnumField;
import jadx.core.dex.attributes.nodes.LineAttrNode;
import jadx.core.dex.attributes.nodes.MethodInlineAttr;
import jadx.core.dex.attributes.nodes.SkipMethodArgsAttr;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.EncodedValueUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.android.AndroidResourcesUtils;
import jadx.core.utils.exceptions.CodegenException;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class ClassGen {
private final ClassNode cls;
private final ClassGen parentGen;
private final AnnotationGen annotationGen;
private final boolean fallback;
private final boolean useImports;
private final boolean showInconsistentCode;
private final IntegerFormat integerFormat;
private final Set<ClassInfo> imports = new HashSet<>();
private int clsDeclOffset;
private boolean bodyGenStarted;
@Nullable
private NameGen outerNameGen;
public ClassGen(ClassNode cls, JadxArgs jadxArgs) {
this(cls, null, jadxArgs.isUseImports(), jadxArgs.isFallbackMode(), jadxArgs.isShowInconsistentCode(), jadxArgs.getIntegerFormat());
}
public ClassGen(ClassNode cls, ClassGen parentClsGen) {
this(cls, parentClsGen, parentClsGen.useImports, parentClsGen.fallback, parentClsGen.showInconsistentCode,
parentClsGen.integerFormat);
}
public ClassGen(ClassNode cls, ClassGen parentClsGen, boolean useImports, boolean fallback, boolean showBadCode,
IntegerFormat integerFormat) {
this.cls = cls;
this.parentGen = parentClsGen;
this.fallback = fallback;
this.useImports = useImports;
this.showInconsistentCode = showBadCode;
this.integerFormat = integerFormat;
this.annotationGen = new AnnotationGen(cls, this);
}
public ClassNode getClassNode() {
return cls;
}
public ICodeInfo makeClass() throws CodegenException {
if (cls.contains(AFlag.PACKAGE_INFO)) {
return makePackageInfo();
}
ICodeWriter clsBody = cls.root().makeCodeWriter();
addClassCode(clsBody);
ICodeWriter clsCode = cls.root().makeCodeWriter();
addPackage(clsCode);
clsCode.newLine();
addImports(clsCode);
clsCode.add(clsBody);
return clsCode.finish();
}
private void addPackage(ICodeWriter clsCode) {
if (cls.getPackage().isEmpty()) {
clsCode.add("// default package");
} else {
clsCode.add("package ").add(cls.getPackage()).add(';');
}
}
private void addImports(ICodeWriter clsCode) {
int importsCount = imports.size();
if (importsCount != 0) {
List<ClassInfo> sortedImports = new ArrayList<>(imports);
sortedImports.sort(Comparator.comparing(ClassInfo::getAliasFullName));
sortedImports.forEach(classInfo -> {
clsCode.startLine("import ");
ClassNode classNode = cls.root().resolveClass(classInfo);
if (classNode != null) {
clsCode.attachAnnotation(classNode);
}
clsCode.add(classInfo.getAliasFullName());
clsCode.add(';');
});
clsCode.newLine();
imports.clear();
}
}
private ICodeInfo makePackageInfo() {
ICodeWriter code = cls.root().makeCodeWriter();
annotationGen.addForClass(code);
code.newLine();
code.attachDefinition(cls);
addPackage(code);
code.newLine();
addImports(code);
return code.finish();
}
public void addClassCode(ICodeWriter code) throws CodegenException {
if (cls.contains(AFlag.DONT_GENERATE)) {
return;
}
if (Consts.DEBUG_USAGE) {
addClassUsageInfo(code, cls);
}
CodeGenUtils.addErrorsAndComments(code, cls);
CodeGenUtils.addSourceFileInfo(code, cls);
addClassDeclaration(code);
addClassBody(code);
}
public void addClassDeclaration(ICodeWriter clsCode) {
AccessInfo af = cls.getAccessFlags();
if (af.isInterface()) {
af = af.remove(AccessFlags.ABSTRACT)
.remove(AccessFlags.STATIC);
} else if (af.isEnum()) {
af = af.remove(AccessFlags.FINAL)
.remove(AccessFlags.ABSTRACT)
.remove(AccessFlags.STATIC);
}
// 'static' and 'private' modifier not allowed for top classes (not inner)
if (!cls.getClassInfo().isInner()) {
af = af.remove(AccessFlags.STATIC).remove(AccessFlags.PRIVATE);
}
annotationGen.addForClass(clsCode);
insertRenameInfo(clsCode, cls);
CodeGenUtils.addInputFileInfo(clsCode, cls);
clsCode.startLineWithNum(cls.getSourceLine()).add(af.makeString(cls.checkCommentsLevel(CommentsLevel.INFO)));
if (af.isInterface()) {
if (af.isAnnotation()) {
clsCode.add('@');
}
clsCode.add("interface ");
} else if (af.isEnum()) {
clsCode.add("enum ");
} else {
clsCode.add("class ");
}
clsCode.attachDefinition(cls);
clsCode.add(cls.getClassInfo().getAliasShortName());
addGenericTypeParameters(clsCode, cls.getGenericTypeParameters(), true);
clsCode.add(' ');
ArgType sup = cls.getSuperClass();
if (sup != null
&& !sup.equals(ArgType.OBJECT)
&& !cls.contains(AFlag.REMOVE_SUPER_CLASS)) {
clsCode.add("extends ");
useClass(clsCode, sup);
clsCode.add(' ');
}
if (!cls.getInterfaces().isEmpty() && !af.isAnnotation()) {
if (cls.getAccessFlags().isInterface()) {
clsCode.add("extends ");
} else {
clsCode.add("implements ");
}
for (Iterator<ArgType> it = cls.getInterfaces().iterator(); it.hasNext();) {
ArgType interf = it.next();
useClass(clsCode, interf);
if (it.hasNext()) {
clsCode.add(", ");
}
}
if (!cls.getInterfaces().isEmpty()) {
clsCode.add(' ');
}
}
}
public boolean addGenericTypeParameters(ICodeWriter code, List<ArgType> generics, boolean classDeclaration) {
if (generics == null || generics.isEmpty()) {
return false;
}
code.add('<');
int i = 0;
for (ArgType genericInfo : generics) {
if (i != 0) {
code.add(", ");
}
if (genericInfo.isGenericType()) {
code.add(genericInfo.getObject());
} else {
useClass(code, genericInfo);
}
List<ArgType> list = genericInfo.getExtendTypes();
if (list != null && !list.isEmpty()) {
code.add(" extends ");
for (Iterator<ArgType> it = list.iterator(); it.hasNext();) {
ArgType g = it.next();
if (g.isGenericType()) {
code.add(g.getObject());
} else {
useClass(code, g);
if (classDeclaration
&& !cls.getClassInfo().isInner()
&& cls.root().getArgs().isUseImports()) {
addImport(ClassInfo.fromType(cls.root(), g));
}
}
if (it.hasNext()) {
code.add(" & ");
}
}
}
i++;
}
code.add('>');
return true;
}
public void addClassBody(ICodeWriter clsCode) throws CodegenException {
addClassBody(clsCode, false);
}
/**
* @param printClassName allows to print the original class name as comment (e.g. for inlined
* classes)
*/
public void addClassBody(ICodeWriter clsCode, boolean printClassName) throws CodegenException {
clsCode.add('{');
if (printClassName && cls.checkCommentsLevel(CommentsLevel.INFO)) {
clsCode.add(" // from class: " + cls.getClassInfo().getFullName());
}
setBodyGenStarted(true);
clsDeclOffset = clsCode.getLength();
clsCode.incIndent();
addFields(clsCode);
addInnerClsAndMethods(clsCode);
clsCode.decIndent();
clsCode.startLine('}');
clsCode.attachAnnotation(NodeEnd.VALUE);
}
private void addInnerClsAndMethods(ICodeWriter clsCode) {
Stream.of(cls.getInnerClasses(), cls.getMethods())
.flatMap(Collection::stream)
.filter(node -> !node.contains(AFlag.DONT_GENERATE) || fallback)
.sorted(Comparator.comparingInt(LineAttrNode::getSourceLine))
.forEach(node -> {
if (node instanceof ClassNode) {
addInnerClass(clsCode, (ClassNode) node);
} else {
addMethod(clsCode, (MethodNode) node);
}
});
}
private void addInnerClass(ICodeWriter code, ClassNode innerCls) {
try {
ClassGen inClGen = new ClassGen(innerCls, getParentGen());
code.newLine();
inClGen.addClassCode(code);
imports.addAll(inClGen.getImports());
} catch (Exception e) {
innerCls.addError("Inner class code generation error", e);
}
}
private boolean isInnerClassesPresents() {
for (ClassNode innerCls : cls.getInnerClasses()) {
if (!innerCls.contains(AType.ANONYMOUS_CLASS)) {
return true;
}
}
return false;
}
private void addMethod(ICodeWriter code, MethodNode mth) {
if (skipMethod(mth)) {
return;
}
if (code.getLength() != clsDeclOffset) {
code.newLine();
}
int savedIndent = code.getIndent();
try {
addMethodCode(code, mth);
} catch (Exception e) {
if (mth.getParentClass().getTopParentClass().contains(AFlag.RESTART_CODEGEN)) {
throw new JadxRuntimeException("Method generation error", e);
}
mth.addError("Method generation error", e);
CodeGenUtils.addErrors(code, mth);
code.setIndent(savedIndent);
}
}
/**
* Additional checks for inlined methods
*/
private boolean skipMethod(MethodNode mth) {
if (cls.root().getArgs().getDecompilationMode().isSpecial()) {
// show all methods for special decompilation modes
return false;
}
MethodInlineAttr inlineAttr = mth.get(AType.METHOD_INLINE);
if (inlineAttr == null || inlineAttr.notNeeded()) {
return false;
}
try {
if (mth.getUseIn().isEmpty()) {
mth.add(AFlag.DONT_GENERATE);
return true;
}
List<MethodNode> useInCompleted = mth.getUseIn().stream()
.filter(m -> m.getTopParentClass().getState().isProcessComplete())
.collect(Collectors.toList());
if (useInCompleted.isEmpty()) {
mth.add(AFlag.DONT_GENERATE);
return true;
}
mth.addDebugComment("Method not inlined, still used in: " + useInCompleted);
return false;
} catch (Exception e) {
// check failed => keep method
mth.addWarnComment("Failed to check method usage", e);
return false;
}
}
private boolean isMethodsPresents() {
for (MethodNode mth : cls.getMethods()) {
if (!mth.contains(AFlag.DONT_GENERATE)) {
return true;
}
}
return false;
}
public void addMethodCode(ICodeWriter code, MethodNode mth) throws CodegenException {
CodeGenUtils.addErrorsAndComments(code, mth);
if (mth.isNoCode()) {
MethodGen mthGen = new MethodGen(this, mth);
mthGen.addDefinition(code);
code.add(';');
} else {
boolean badCode = mth.contains(AFlag.INCONSISTENT_CODE);
if (badCode && showInconsistentCode) {
badCode = false;
}
MethodGen mthGen;
if (badCode || fallback || mth.contains(AType.JADX_ERROR)) {
mthGen = MethodGen.getFallbackMethodGen(mth);
} else {
mthGen = new MethodGen(this, mth);
}
if (mthGen.addDefinition(code)) {
code.add(' ');
}
code.add('{');
code.incIndent();
mthGen.addInstructions(code);
code.decIndent();
code.startLine('}');
code.attachAnnotation(NodeEnd.VALUE);
}
}
private void addFields(ICodeWriter code) throws CodegenException {
addEnumFields(code);
for (FieldNode f : cls.getFields()) {
addField(code, f);
}
}
public void addField(ICodeWriter code, FieldNode f) {
if (f.contains(AFlag.DONT_GENERATE)) {
return;
}
if (f.contains(JadxAttrType.ANNOTATION_LIST)
|| f.contains(AType.JADX_COMMENTS)
|| f.contains(AType.CODE_COMMENTS)
|| f.getFieldInfo().hasAlias()) {
code.newLine();
}
if (Consts.DEBUG_USAGE) {
addFieldUsageInfo(code, f);
}
if (f.getFieldInfo().hasAlias()) {
CodeGenUtils.addRenamedComment(code, f, f.getName());
}
CodeGenUtils.addComments(code, f);
annotationGen.addForField(code, f);
code.startLine(f.getAccessFlags().makeString(f.checkCommentsLevel(CommentsLevel.INFO)));
useType(code, f.getType());
code.add(' ');
code.attachDefinition(f);
code.add(f.getAlias());
FieldInitInsnAttr initInsnAttr = f.get(AType.FIELD_INIT_INSN);
if (initInsnAttr != null) {
InsnGen insnGen = makeInsnGen(initInsnAttr.getInsnMth());
code.add(" = ");
addInsnBody(insnGen, code, initInsnAttr.getInsn());
} else {
EncodedValue constVal = f.get(JadxAttrType.CONSTANT_VALUE);
if (constVal != null) {
code.add(" = ");
if (constVal.getType() == EncodedType.ENCODED_NULL) {
code.add(TypeGen.literalToString(0, f.getType(), cls, fallback));
} else {
Object val = EncodedValueUtils.convertToConstValue(constVal);
if (val instanceof LiteralArg) {
long lit = ((LiteralArg) val).getLiteral();
code.add(getIntegerString(lit, f.getType()));
} else {
annotationGen.encodeValue(cls.root(), code, constVal);
}
}
}
}
code.add(';');
}
private String getIntegerString(long lit, ArgType type) {
if (integerFormat != IntegerFormat.DECIMAL && AndroidResourcesUtils.isResourceFieldValue(cls, type)) {
return String.format("0x%08x", lit);
}
// force literal type to be same as field (java bytecode can use different type)
return TypeGen.literalToString(lit, type, cls, fallback);
}
private boolean isFieldsPresents() {
for (FieldNode field : cls.getFields()) {
if (!field.contains(AFlag.DONT_GENERATE)) {
return true;
}
}
return false;
}
private void addEnumFields(ICodeWriter code) throws CodegenException {
EnumClassAttr enumFields = cls.get(AType.ENUM_CLASS);
if (enumFields == null) {
return;
}
InsnGen igen = null;
for (Iterator<EnumField> it = enumFields.getFields().iterator(); it.hasNext();) {
EnumField f = it.next();
CodeGenUtils.addComments(code, f.getField());
code.startLine(f.getField().getAlias());
ConstructorInsn constrInsn = f.getConstrInsn();
MethodNode callMth = cls.root().resolveMethod(constrInsn.getCallMth());
int skipCount = getEnumCtrSkipArgsCount(callMth);
if (constrInsn.getArgsCount() > skipCount) {
if (igen == null) {
igen = makeInsnGen(enumFields.getStaticMethod());
}
igen.generateMethodArguments(code, constrInsn, 0, callMth);
}
if (f.getCls() != null) {
code.add(' ');
new ClassGen(f.getCls(), this).addClassBody(code, true);
}
if (it.hasNext()) {
code.add(',');
}
}
if (isMethodsPresents() || isFieldsPresents() || isInnerClassesPresents()) {
if (enumFields.getFields().isEmpty()) {
code.startLine();
}
code.add(';');
if (isFieldsPresents()) {
code.newLine();
}
}
}
private int getEnumCtrSkipArgsCount(@Nullable MethodNode callMth) {
if (callMth != null) {
SkipMethodArgsAttr skipArgsAttr = callMth.get(AType.SKIP_MTH_ARGS);
if (skipArgsAttr != null) {
return skipArgsAttr.getSkipCount();
}
}
return 0;
}
private InsnGen makeInsnGen(MethodNode mth) {
MethodGen mthGen = new MethodGen(this, mth);
return new InsnGen(mthGen, false);
}
private void addInsnBody(InsnGen insnGen, ICodeWriter code, InsnNode insn) {
try {
insnGen.makeInsn(insn, code, InsnGen.Flags.BODY_ONLY_NOWRAP);
} catch (Exception e) {
cls.addError("Failed to generate init code", e);
}
}
public void useType(ICodeWriter code, ArgType type) {
PrimitiveType stype = type.getPrimitiveType();
if (stype == null) {
code.add(type.toString());
} else if (stype == PrimitiveType.OBJECT) {
if (type.isGenericType()) {
code.add(type.getObject());
} else {
useClass(code, type);
}
} else if (stype == PrimitiveType.ARRAY) {
useType(code, type.getArrayElement());
code.add("[]");
} else {
code.add(stype.getLongName());
}
}
public void useClass(ICodeWriter code, String rawCls) {
useClass(code, ArgType.object(rawCls));
}
public void useClass(ICodeWriter code, ArgType type) {
ArgType outerType = type.getOuterType();
if (outerType != null) {
useClass(code, outerType);
code.add('.');
addInnerType(code, type);
return;
}
useClass(code, ClassInfo.fromType(cls.root(), type));
addGenerics(code, type);
}
private void addInnerType(ICodeWriter code, ArgType baseType) {
ArgType innerType = baseType.getInnerType();
ArgType outerType = innerType.getOuterType();
if (outerType != null) {
useClassWithShortName(code, baseType, outerType);
code.add('.');
addInnerType(code, innerType);
return;
}
useClassWithShortName(code, baseType, innerType);
}
private void useClassWithShortName(ICodeWriter code, ArgType baseType, ArgType type) {
String fullNameObj;
if (type.getObject().contains(".")) {
fullNameObj = type.getObject();
} else {
fullNameObj = baseType.getObject();
}
ClassInfo classInfo = ClassInfo.fromName(cls.root(), fullNameObj);
ClassNode classNode = cls.root().resolveClass(classInfo);
if (classNode != null) {
code.attachAnnotation(classNode);
}
code.add(classInfo.getAliasShortName());
addGenerics(code, type);
}
private void addGenerics(ICodeWriter code, ArgType type) {
List<ArgType> generics = type.getGenericTypes();
if (generics != null) {
code.add('<');
int len = generics.size();
for (int i = 0; i < len; i++) {
if (i != 0) {
code.add(", ");
}
ArgType gt = generics.get(i);
ArgType wt = gt.getWildcardType();
if (wt != null) {
ArgType.WildcardBound bound = gt.getWildcardBound();
code.add(bound.getStr());
if (bound != ArgType.WildcardBound.UNBOUND) {
useType(code, wt);
}
} else {
useType(code, gt);
}
}
code.add('>');
}
}
public void useClass(ICodeWriter code, ClassInfo classInfo) {
ClassNode classNode = cls.root().resolveClass(classInfo);
if (classNode != null) {
useClass(code, classNode);
} else {
addClsName(code, classInfo);
}
}
public void useClass(ICodeWriter code, ClassNode classNode) {
code.attachAnnotation(classNode);
addClsName(code, classNode.getClassInfo());
}
public void addClsName(ICodeWriter code, ClassInfo classInfo) {
String clsName = useClassInternal(cls.getClassInfo(), classInfo);
code.add(clsName);
}
public void addClsShortNameForced(ICodeWriter code, ClassInfo classInfo) {
code.add(classInfo.getAliasShortName());
if (!isBothClassesInOneTopClass(cls.getClassInfo(), classInfo)) {
addImport(classInfo);
}
}
private String useClassInternal(ClassInfo useCls, ClassInfo extClsInfo) {
String fullName = extClsInfo.getAliasFullName();
if (fallback || !useImports) {
return fullName;
}
String shortName = extClsInfo.getAliasShortName();
if (useCls.equals(extClsInfo)) {
return shortName;
}
if (extClsInfo.getAliasPkg().isEmpty()) {
// omit import for default package
return shortName;
}
if (isClassInnerFor(useCls, extClsInfo)) {
return shortName;
}
if (extClsInfo.isInner()) {
return expandInnerClassName(useCls, extClsInfo);
}
if (checkInnerCollision(cls.root(), useCls, extClsInfo)
|| checkInPackageCollision(cls.root(), useCls, extClsInfo)) {
return fullName;
}
if (isBothClassesInOneTopClass(useCls, extClsInfo)) {
return shortName;
}
// don't add import for top classes from 'java.lang' package (subpackages excluded)
if (extClsInfo.getPackage().equals("java.lang") && extClsInfo.getParentClass() == null) {
return shortName;
}
// don't add import if this class from same package
if (extClsInfo.getPackage().equals(useCls.getPackage()) && !extClsInfo.isInner()) {
return shortName;
}
if (extClsInfo.getAliasPkg().equals(useCls.getAliasPkg())) {
fullName = extClsInfo.getAliasNameWithoutPackage();
}
for (ClassInfo importCls : getImports()) {
if (!importCls.equals(extClsInfo)
&& importCls.getAliasShortName().equals(shortName)) {
if (extClsInfo.isInner()) {
String parent = useClassInternal(useCls, extClsInfo.getParentClass());
return parent + '.' + shortName;
} else {
return fullName;
}
}
}
addImport(extClsInfo);
return shortName;
}
private String expandInnerClassName(ClassInfo useCls, ClassInfo extClsInfo) {
List<ClassInfo> clsList = new ArrayList<>();
clsList.add(extClsInfo);
ClassInfo parentCls = extClsInfo.getParentClass();
boolean addImport = true;
while (parentCls != null) {
if (parentCls == useCls || isClassInnerFor(useCls, parentCls)) {
addImport = false;
break;
}
clsList.add(parentCls);
parentCls = parentCls.getParentClass();
}
Collections.reverse(clsList);
if (addImport) {
addImport(clsList.get(0));
}
return Utils.listToString(clsList, ".", ClassInfo::getAliasShortName);
}
private void addImport(ClassInfo classInfo) {
if (parentGen != null) {
parentGen.addImport(classInfo);
} else {
imports.add(classInfo);
}
}
public Set<ClassInfo> getImports() {
if (parentGen != null) {
return parentGen.getImports();
} else {
return imports;
}
}
private static boolean isBothClassesInOneTopClass(ClassInfo useCls, ClassInfo extClsInfo) {
ClassInfo a = useCls.getTopParentClass();
ClassInfo b = extClsInfo.getTopParentClass();
if (a != null) {
return a.equals(b);
}
// useCls - is a top class
return useCls.equals(b);
}
private static boolean isClassInnerFor(ClassInfo inner, ClassInfo parent) {
if (inner.isInner()) {
ClassInfo p = inner.getParentClass();
return Objects.equals(p, parent) || isClassInnerFor(p, parent);
}
return false;
}
private static boolean checkInnerCollision(RootNode root, @Nullable ClassInfo useCls, ClassInfo searchCls) {
if (useCls == null) {
return false;
}
String shortName = searchCls.getAliasShortName();
if (useCls.getAliasShortName().equals(shortName)) {
return true;
}
ClassNode classNode = root.resolveClass(useCls);
if (classNode != null) {
for (ClassNode inner : classNode.getInnerClasses()) {
if (inner.getShortName().equals(shortName)
&& !inner.getFullName().equals(searchCls.getAliasFullName())) {
return true;
}
}
}
return checkInnerCollision(root, useCls.getParentClass(), searchCls);
}
/**
* Check if class with same name exists in current package
*/
private static boolean checkInPackageCollision(RootNode root, ClassInfo useCls, ClassInfo searchCls) {
String currentPkg = useCls.getAliasPkg();
if (currentPkg.equals(searchCls.getAliasPkg())) {
// search class already from current package
return false;
}
String shortName = searchCls.getAliasShortName();
return root.getClsp().isClsKnown(currentPkg + '.' + shortName);
}
private void insertRenameInfo(ICodeWriter code, ClassNode cls) {
ClassInfo classInfo = cls.getClassInfo();
if (classInfo.hasAlias() && cls.checkCommentsLevel(CommentsLevel.INFO)) {
CodeGenUtils.addRenamedComment(code, cls, classInfo.getType().getObject());
}
}
private static void addClassUsageInfo(ICodeWriter code, ClassNode cls) {
List<ClassNode> deps = cls.getDependencies();
code.startLine("// deps - ").add(Integer.toString(deps.size()));
for (ClassNode depCls : deps) {
code.startLine("// ").add(depCls.getClassInfo().getFullName());
}
List<ClassNode> useIn = cls.getUseIn();
code.startLine("// use in - ").add(Integer.toString(useIn.size()));
for (ClassNode useCls : useIn) {
code.startLine("// ").add(useCls.getClassInfo().getFullName());
}
List<MethodNode> useInMths = cls.getUseInMth();
code.startLine("// use in methods - ").add(Integer.toString(useInMths.size()));
for (MethodNode useMth : useInMths) {
code.startLine("// ").add(useMth.toString());
}
}
static void addMthUsageInfo(ICodeWriter code, MethodNode mth) {
List<MethodNode> useInMths = mth.getUseIn();
code.startLine("// use in methods - ").add(Integer.toString(useInMths.size()));
for (MethodNode useMth : useInMths) {
code.startLine("// ").add(useMth.toString());
}
}
private static void addFieldUsageInfo(ICodeWriter code, FieldNode fieldNode) {
List<MethodNode> useInMths = fieldNode.getUseIn();
code.startLine("// use in methods - ").add(Integer.toString(useInMths.size()));
for (MethodNode useMth : useInMths) {
code.startLine("// ").add(useMth.toString());
}
}
public ClassGen getParentGen() {
return parentGen == null ? this : parentGen;
}
public AnnotationGen getAnnotationGen() {
return annotationGen;
}
public boolean isFallbackMode() {
return fallback;
}
public boolean isBodyGenStarted() {
return bodyGenStarted;
}
public void setBodyGenStarted(boolean bodyGenStarted) {
this.bodyGenStarted = bodyGenStarted;
}
@Nullable
public NameGen getOuterNameGen() {
return outerNameGen;
}
public void setOuterNameGen(@NotNull NameGen outerNameGen) {
this.outerNameGen = outerNameGen;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/RegionGen.java | jadx-core/src/main/java/jadx/core/codegen/RegionGen.java | package jadx.core.codegen;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.CommentsLevel;
import jadx.api.ICodeWriter;
import jadx.api.metadata.annotations.InsnCodeOffset;
import jadx.api.metadata.annotations.VarNode;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.core.clsp.ClspClass;
import jadx.core.codegen.utils.CodeGenUtils;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.DeclareVariablesAttr;
import jadx.core.dex.attributes.nodes.ForceReturnAttr;
import jadx.core.dex.attributes.nodes.LoopLabelAttr;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.SwitchInsn;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.CodeVar;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.NamedArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.regions.SwitchRegion;
import jadx.core.dex.regions.SwitchRegion.CaseInfo;
import jadx.core.dex.regions.SynchronizedRegion;
import jadx.core.dex.regions.TryCatchRegion;
import jadx.core.dex.regions.conditions.IfCondition;
import jadx.core.dex.regions.conditions.IfRegion;
import jadx.core.dex.regions.loops.ForEachLoop;
import jadx.core.dex.regions.loops.ForLoop;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.regions.loops.LoopType;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.utils.BlockUtils;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.CodegenException;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class RegionGen extends InsnGen {
private static final Logger LOG = LoggerFactory.getLogger(RegionGen.class);
public RegionGen(MethodGen mgen) {
super(mgen, false);
}
public void makeRegion(ICodeWriter code, IContainer cont) throws CodegenException {
declareVars(code, cont);
cont.generate(this, code);
}
private void declareVars(ICodeWriter code, IContainer cont) {
DeclareVariablesAttr declVars = cont.get(AType.DECLARE_VARIABLES);
if (declVars != null) {
for (CodeVar v : declVars.getVars()) {
code.startLine();
declareVar(code, v);
code.add(';');
CodeGenUtils.addCodeComments(code, mth, v.getAnySsaVar().getAssign());
}
}
}
private void makeRegionIndent(ICodeWriter code, IContainer region) throws CodegenException {
code.incIndent();
makeRegion(code, region);
code.decIndent();
}
public void makeSimpleBlock(IBlock block, ICodeWriter code) throws CodegenException {
if (block.contains(AFlag.DONT_GENERATE)) {
return;
}
for (InsnNode insn : block.getInstructions()) {
if (!insn.contains(AFlag.DONT_GENERATE)) {
makeInsn(insn, code);
}
}
ForceReturnAttr retAttr = block.get(AType.FORCE_RETURN);
if (retAttr != null) {
makeInsn(retAttr.getReturnInsn(), code);
}
}
public void makeIf(IfRegion region, ICodeWriter code, boolean newLine) throws CodegenException {
if (newLine) {
code.startLineWithNum(region.getSourceLine());
} else {
code.attachSourceLine(region.getSourceLine());
}
boolean comment = region.contains(AFlag.COMMENT_OUT);
if (comment) {
code.add("// ");
}
code.add("if (");
new ConditionGen(this).add(code, region.getCondition());
code.add(") {");
if (code.isMetadataSupported()) {
List<BlockNode> conditionBlocks = region.getConditionBlocks();
if (!conditionBlocks.isEmpty()) {
BlockNode blockNode = conditionBlocks.get(0);
InsnNode lastInsn = BlockUtils.getLastInsn(blockNode);
InsnCodeOffset.attach(code, lastInsn);
CodeGenUtils.addCodeComments(code, mth, lastInsn);
}
}
makeRegionIndent(code, region.getThenRegion());
if (comment) {
code.startLine("// }");
} else {
code.startLine('}');
}
IContainer els = region.getElseRegion();
if (RegionUtils.notEmpty(els)) {
code.add(" else ");
if (connectElseIf(code, els)) {
return;
}
code.add('{');
makeRegionIndent(code, els);
if (comment) {
code.startLine("// }");
} else {
code.startLine('}');
}
}
}
/**
* Connect if-else-if block
*/
private boolean connectElseIf(ICodeWriter code, IContainer els) throws CodegenException {
if (els.contains(AFlag.ELSE_IF_CHAIN)) {
IContainer elseBlock = RegionUtils.getSingleSubBlock(els);
if (elseBlock instanceof IfRegion) {
declareVars(code, elseBlock);
makeIf((IfRegion) elseBlock, code, false);
return true;
}
}
return false;
}
public void makeLoop(LoopRegion region, ICodeWriter code) throws CodegenException {
code.startLineWithNum(region.getSourceLine());
LoopLabelAttr labelAttr = region.getInfo().getStart().get(AType.LOOP_LABEL);
if (labelAttr != null) {
code.add(mgen.getNameGen().getLoopLabel(labelAttr)).add(": ");
}
IfCondition condition = region.getCondition();
if (condition == null) {
// infinite loop
code.add("while (true) {");
makeRegionIndent(code, region.getBody());
code.startLine('}');
return;
}
InsnNode condInsn = condition.getFirstInsn();
InsnCodeOffset.attach(code, condInsn);
ConditionGen conditionGen = new ConditionGen(this);
LoopType type = region.getType();
if (type != null) {
if (type instanceof ForLoop) {
ForLoop forLoop = (ForLoop) type;
code.add("for (");
makeInsn(forLoop.getInitInsn(), code, Flags.INLINE);
code.add("; ");
conditionGen.add(code, condition);
code.add("; ");
makeInsn(forLoop.getIncrInsn(), code, Flags.INLINE);
code.add(") {");
CodeGenUtils.addCodeComments(code, mth, condInsn);
makeRegionIndent(code, region.getBody());
code.startLine('}');
return;
}
if (type instanceof ForEachLoop) {
ForEachLoop forEachLoop = (ForEachLoop) type;
code.add("for (");
declareVar(code, forEachLoop.getVarArg());
code.add(" : ");
addArg(code, forEachLoop.getIterableArg(), false);
code.add(") {");
CodeGenUtils.addCodeComments(code, mth, condInsn);
makeRegionIndent(code, region.getBody());
code.startLine('}');
return;
}
throw new JadxRuntimeException("Unknown loop type: " + type.getClass());
}
if (region.isConditionAtEnd()) {
code.add("do {");
CodeGenUtils.addCodeComments(code, mth, condInsn);
makeRegionIndent(code, region.getBody());
code.startLineWithNum(region.getSourceLine());
code.add("} while (");
conditionGen.add(code, condition);
code.add(");");
} else {
code.add("while (");
conditionGen.add(code, condition);
code.add(") {");
CodeGenUtils.addCodeComments(code, mth, condInsn);
makeRegionIndent(code, region.getBody());
code.startLine('}');
}
}
public void makeSynchronizedRegion(SynchronizedRegion cont, ICodeWriter code) throws CodegenException {
code.startLine("synchronized (");
InsnNode monitorEnterInsn = cont.getEnterInsn();
addArg(code, monitorEnterInsn.getArg(0));
code.add(") {");
InsnCodeOffset.attach(code, monitorEnterInsn);
CodeGenUtils.addCodeComments(code, mth, monitorEnterInsn);
makeRegionIndent(code, cont.getRegion());
code.startLine('}');
}
public void makeSwitch(SwitchRegion sw, ICodeWriter code) throws CodegenException {
SwitchInsn insn = (SwitchInsn) BlockUtils.getLastInsn(sw.getHeader());
Objects.requireNonNull(insn, "Switch insn not found in header");
InsnArg arg = insn.getArg(0);
code.startLine("switch (");
addArg(code, arg, false);
code.add(") {");
InsnCodeOffset.attach(code, insn);
CodeGenUtils.addCodeComments(code, mth, insn);
code.incIndent();
for (CaseInfo caseInfo : sw.getCases()) {
List<Object> keys = caseInfo.getKeys();
IContainer c = caseInfo.getContainer();
for (Object k : keys) {
if (k == SwitchRegion.DEFAULT_CASE_KEY) {
code.startLine("default:");
} else {
code.startLine("case ");
addCaseKey(code, arg, k);
code.add(':');
}
}
makeRegionIndent(code, c);
}
code.decIndent();
code.startLine('}');
}
private void addCaseKey(ICodeWriter code, InsnArg arg, Object k) throws CodegenException {
if (k instanceof FieldNode) {
FieldNode fld = (FieldNode) k;
useField(code, fld.getFieldInfo(), fld);
} else if (k instanceof FieldInfo) {
useField(code, (FieldInfo) k, null);
} else if (k instanceof Integer) {
code.add(TypeGen.literalToString((Integer) k, arg.getType(), mth, fallback));
} else if (k instanceof String) {
code.add('\"').add((String) k).add('\"');
} else {
throw new JadxRuntimeException("Unexpected key in switch: " + (k != null ? k.getClass() : null));
}
}
private void useField(ICodeWriter code, FieldInfo fldInfo, @Nullable FieldNode fld) throws CodegenException {
boolean isEnum;
if (fld != null) {
isEnum = fld.getParentClass().isEnum();
} else {
ClspClass clsDetails = root.getClsp().getClsDetails(fldInfo.getDeclClass().getType());
isEnum = clsDetails != null && clsDetails.hasAccFlag(AccessFlags.ENUM);
}
if (isEnum) {
if (fld != null) {
code.attachAnnotation(fld);
}
code.add(fldInfo.getAlias());
return;
}
staticField(code, fldInfo);
if (fld != null && mth.checkCommentsLevel(CommentsLevel.INFO)) {
// print original value, sometimes replaced with incorrect field
EncodedValue constVal = fld.get(JadxAttrType.CONSTANT_VALUE);
if (constVal != null && constVal.getValue() != null) {
code.add(" /* ").add(constVal.getValue().toString()).add(" */");
}
}
}
public void makeTryCatch(TryCatchRegion region, ICodeWriter code) throws CodegenException {
code.startLine("try {");
InsnNode insn = BlockUtils.getFirstInsn(Utils.first(region.getTryCatchBlock().getBlocks()));
InsnCodeOffset.attach(code, insn);
CodeGenUtils.addCodeComments(code, mth, insn);
makeRegionIndent(code, region.getTryRegion());
// TODO: move search of 'allHandler' to 'TryCatchRegion'
ExceptionHandler allHandler = null;
for (Map.Entry<ExceptionHandler, IContainer> entry : region.getCatchRegions().entrySet()) {
ExceptionHandler handler = entry.getKey();
if (handler.isCatchAll()) {
if (allHandler != null) {
LOG.warn("Several 'all' handlers in try/catch block in {}", mth);
}
allHandler = handler;
} else {
makeCatchBlock(code, handler);
}
}
if (allHandler != null) {
makeCatchBlock(code, allHandler);
}
IContainer finallyRegion = region.getFinallyRegion();
if (finallyRegion != null) {
code.startLine("} finally {");
makeRegionIndent(code, finallyRegion);
}
code.startLine('}');
}
private void makeCatchBlock(ICodeWriter code, ExceptionHandler handler) throws CodegenException {
IContainer region = handler.getHandlerRegion();
if (region == null) {
return;
}
code.startLine("} catch (");
if (handler.isCatchAll()) {
useClass(code, ArgType.THROWABLE);
} else {
Iterator<ClassInfo> it = handler.getCatchTypes().iterator();
if (it.hasNext()) {
useClass(code, it.next());
}
while (it.hasNext()) {
code.add(" | ");
useClass(code, it.next());
}
}
code.add(' ');
InsnArg arg = handler.getArg();
if (arg == null) {
code.add("unknown"); // throwing exception is too late at this point
} else if (arg instanceof RegisterArg) {
SSAVar ssaVar = ((RegisterArg) arg).getSVar();
if (code.isMetadataSupported()) {
code.attachDefinition(VarNode.get(mth, ssaVar));
}
code.add(mgen.getNameGen().assignArg(ssaVar.getCodeVar()));
} else if (arg instanceof NamedArg) {
code.add(mgen.getNameGen().assignNamedArg((NamedArg) arg));
} else {
throw new JadxRuntimeException("Unexpected arg type in catch block: " + arg + ", class: " + arg.getClass().getSimpleName());
}
code.add(") {");
InsnCodeOffset.attach(code, handler.getHandlerOffset());
CodeGenUtils.addCodeComments(code, mth, handler.getHandlerBlock());
makeRegionIndent(code, region);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/CodeGen.java | jadx-core/src/main/java/jadx/core/codegen/CodeGen.java | package jadx.core.codegen;
import java.util.concurrent.Callable;
import jadx.api.ICodeInfo;
import jadx.api.JadxArgs;
import jadx.api.impl.SimpleCodeInfo;
import jadx.core.codegen.json.JsonCodeGen;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class CodeGen {
public static ICodeInfo generate(ClassNode cls) {
if (cls.contains(AFlag.DONT_GENERATE)) {
return ICodeInfo.EMPTY;
}
JadxArgs args = cls.root().getArgs();
switch (args.getOutputFormat()) {
case JAVA:
return generateJavaCode(cls, args);
case JSON:
return generateJson(cls);
default:
throw new JadxRuntimeException("Unknown output format");
}
}
private static ICodeInfo generateJavaCode(ClassNode cls, JadxArgs args) {
ClassGen clsGen = new ClassGen(cls, args);
return wrapCodeGen(cls, clsGen::makeClass);
}
private static ICodeInfo generateJson(ClassNode cls) {
JsonCodeGen codeGen = new JsonCodeGen(cls);
String clsJson = wrapCodeGen(cls, codeGen::process);
return new SimpleCodeInfo(clsJson);
}
private static <R> R wrapCodeGen(ClassNode cls, Callable<R> codeGenFunc) {
try {
return codeGenFunc.call();
} catch (Exception e) {
if (cls.contains(AFlag.RESTART_CODEGEN)) {
cls.remove(AFlag.RESTART_CODEGEN);
try {
return codeGenFunc.call();
} catch (Exception ex) {
throw new JadxRuntimeException("Code generation error after restart", ex);
}
} else {
throw new JadxRuntimeException("Code generation error", e);
}
}
}
private CodeGen() {
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/AnnotationGen.java | jadx-core/src/main/java/jadx/core/codegen/AnnotationGen.java | package jadx.core.codegen;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.jetbrains.annotations.Nullable;
import jadx.api.ICodeWriter;
import jadx.api.plugins.input.data.IFieldRef;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.api.plugins.input.data.annotations.IAnnotation;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.api.plugins.input.data.attributes.types.AnnotationDefaultAttr;
import jadx.api.plugins.input.data.attributes.types.AnnotationMethodParamsAttr;
import jadx.api.plugins.input.data.attributes.types.AnnotationsAttr;
import jadx.core.Consts;
import jadx.core.dex.attributes.IAttributeNode;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.StringUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class AnnotationGen {
private final ClassNode cls;
private final ClassGen classGen;
public AnnotationGen(ClassNode cls, ClassGen classGen) {
this.cls = cls;
this.classGen = classGen;
}
public void addForClass(ICodeWriter code) {
add(cls, code);
}
public void addForMethod(ICodeWriter code, MethodNode mth) {
add(mth, code);
}
public void addForField(ICodeWriter code, FieldNode field) {
add(field, code);
}
public void addForParameter(ICodeWriter code, AnnotationMethodParamsAttr paramsAnnotations, int n) {
List<AnnotationsAttr> paramList = paramsAnnotations.getParamList();
if (n >= paramList.size()) {
return;
}
AnnotationsAttr aList = paramList.get(n);
if (aList == null || aList.isEmpty()) {
return;
}
for (IAnnotation a : aList.getAll()) {
formatAnnotation(code, a);
code.add(' ');
}
}
private void add(IAttributeNode node, ICodeWriter code) {
AnnotationsAttr aList = node.get(JadxAttrType.ANNOTATION_LIST);
if (aList == null || aList.isEmpty()) {
return;
}
for (IAnnotation a : aList.getAll()) {
String aCls = a.getAnnotationClass();
if (!aCls.equals(Consts.OVERRIDE_ANNOTATION)) {
code.startLine();
formatAnnotation(code, a);
}
}
}
private void formatAnnotation(ICodeWriter code, IAnnotation a) {
code.add('@');
ClassNode annCls = cls.root().resolveClass(a.getAnnotationClass());
if (annCls != null) {
classGen.useClass(code, annCls);
} else {
classGen.useClass(code, a.getAnnotationClass());
}
Map<String, EncodedValue> vl = a.getValues();
if (!vl.isEmpty()) {
code.add('(');
for (Iterator<Entry<String, EncodedValue>> it = vl.entrySet().iterator(); it.hasNext();) {
Entry<String, EncodedValue> e = it.next();
String paramName = getParamName(annCls, e.getKey());
if (paramName.equals("value") && vl.size() == 1) {
// don't add "value = " if no other parameters
} else {
code.add(paramName);
code.add(" = ");
}
encodeValue(cls.root(), code, e.getValue());
if (it.hasNext()) {
code.add(", ");
}
}
code.add(')');
}
}
private String getParamName(@Nullable ClassNode annCls, String paramName) {
if (annCls != null) {
// TODO: save value type and search using signature
MethodNode mth = annCls.searchMethodByShortName(paramName);
if (mth != null) {
return mth.getAlias();
}
}
return paramName;
}
public void addThrows(MethodNode mth, ICodeWriter code) {
List<ArgType> throwList = mth.getThrows();
if (!throwList.isEmpty()) {
code.add(" throws ");
for (Iterator<ArgType> it = throwList.iterator(); it.hasNext();) {
ArgType ex = it.next();
classGen.useType(code, ex);
if (it.hasNext()) {
code.add(", ");
}
}
}
}
public EncodedValue getAnnotationDefaultValue(MethodNode mth) {
AnnotationDefaultAttr defaultAttr = mth.get(JadxAttrType.ANNOTATION_DEFAULT);
if (defaultAttr == null) {
return null;
}
return defaultAttr.getValue();
}
// TODO: refactor this boilerplate code
public void encodeValue(RootNode root, ICodeWriter code, EncodedValue encodedValue) {
if (encodedValue == null) {
code.add("null");
return;
}
StringUtils stringUtils = getStringUtils();
Object value = encodedValue.getValue();
switch (encodedValue.getType()) {
case ENCODED_NULL:
code.add("null");
break;
case ENCODED_BOOLEAN:
code.add(Boolean.TRUE.equals(value) ? "true" : "false");
break;
case ENCODED_BYTE:
code.add(stringUtils.formatByte((Byte) value, false));
break;
case ENCODED_SHORT:
code.add(stringUtils.formatShort((Short) value, false));
break;
case ENCODED_CHAR:
code.add(stringUtils.unescapeChar((Character) value));
break;
case ENCODED_INT:
code.add(stringUtils.formatInteger((Integer) value, false));
break;
case ENCODED_LONG:
code.add(stringUtils.formatLong((Long) value, false));
break;
case ENCODED_FLOAT:
code.add(StringUtils.formatFloat((Float) value));
break;
case ENCODED_DOUBLE:
code.add(StringUtils.formatDouble((Double) value));
break;
case ENCODED_STRING:
code.add(stringUtils.unescapeString((String) value));
break;
case ENCODED_TYPE:
classGen.useType(code, ArgType.parse((String) value));
code.add(".class");
break;
case ENCODED_ENUM:
case ENCODED_FIELD:
// must be a static field
if (value instanceof IFieldRef) {
FieldInfo fieldInfo = FieldInfo.fromRef(root, (IFieldRef) value);
InsnGen.makeStaticFieldAccess(code, fieldInfo, classGen);
} else if (value instanceof FieldInfo) {
InsnGen.makeStaticFieldAccess(code, (FieldInfo) value, classGen);
} else {
throw new JadxRuntimeException("Unexpected field type class: " + value.getClass());
}
break;
case ENCODED_METHOD:
// TODO
break;
case ENCODED_ARRAY:
code.add('{');
Iterator<?> it = ((Iterable<?>) value).iterator();
while (it.hasNext()) {
EncodedValue v = (EncodedValue) it.next();
encodeValue(cls.root(), code, v);
if (it.hasNext()) {
code.add(", ");
}
}
code.add('}');
break;
case ENCODED_ANNOTATION:
formatAnnotation(code, (IAnnotation) value);
break;
default:
throw new JadxRuntimeException("Can't decode value: " + encodedValue.getType() + " (" + encodedValue + ')');
}
}
private StringUtils getStringUtils() {
return cls.root().getStringUtils();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/TypeGen.java | jadx-core/src/main/java/jadx/core/codegen/TypeGen.java | package jadx.core.codegen;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.nodes.IDexNode;
import jadx.core.utils.StringUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class TypeGen {
private static final Logger LOG = LoggerFactory.getLogger(TypeGen.class);
private TypeGen() {
}
public static String signature(ArgType type) {
PrimitiveType stype = type.getPrimitiveType();
if (stype == PrimitiveType.OBJECT) {
return Utils.makeQualifiedObjectName(type.getObject());
}
if (stype == PrimitiveType.ARRAY) {
return '[' + signature(type.getArrayElement());
}
return stype.getShortName();
}
/**
* Convert literal arg to string (preferred method)
*/
public static String literalToString(LiteralArg arg, IDexNode dexNode, boolean fallback) {
return literalToString(arg.getLiteral(), arg.getType(),
dexNode.root().getStringUtils(),
fallback,
arg.contains(AFlag.EXPLICIT_PRIMITIVE_TYPE));
}
/**
* Convert literal value to string according to value type
*
* @throws JadxRuntimeException for incorrect type or literal value
*/
public static String literalToString(long lit, ArgType type, IDexNode dexNode, boolean fallback) {
return literalToString(lit, type, dexNode.root().getStringUtils(), fallback, false);
}
public static String literalToString(long lit, ArgType type, StringUtils stringUtils, boolean fallback, boolean cast) {
if (type == null || !type.isTypeKnown()) {
String n = Long.toString(lit);
if (fallback && Math.abs(lit) > 100) {
StringBuilder sb = new StringBuilder();
sb.append(n).append("(0x").append(Long.toHexString(lit));
if (type == null || type.contains(PrimitiveType.FLOAT)) {
sb.append(", float:").append(Float.intBitsToFloat((int) lit));
}
if (type == null || type.contains(PrimitiveType.DOUBLE)) {
sb.append(", double:").append(Double.longBitsToDouble(lit));
}
sb.append(')');
return sb.toString();
}
return n;
}
switch (type.getPrimitiveType()) {
case BOOLEAN:
return lit == 0 ? "false" : "true";
case CHAR:
return stringUtils.unescapeChar((char) lit, cast);
case BYTE:
return stringUtils.formatByte(lit, cast);
case SHORT:
return stringUtils.formatShort(lit, cast);
case INT:
return stringUtils.formatInteger(lit, cast);
case LONG:
return stringUtils.formatLong(lit, cast);
case FLOAT:
return StringUtils.formatFloat(Float.intBitsToFloat((int) lit));
case DOUBLE:
return StringUtils.formatDouble(Double.longBitsToDouble(lit));
case OBJECT:
case ARRAY:
if (lit != 0) {
LOG.warn("Wrong object literal: {} for type: {}", lit, type);
return Long.toString(lit);
}
return "null";
default:
throw new JadxRuntimeException("Unknown type in literalToString: " + type);
}
}
@Nullable
public static String literalToRawString(LiteralArg arg) {
ArgType type = arg.getType();
if (type == null) {
return null;
}
long lit = arg.getLiteral();
switch (type.getPrimitiveType()) {
case BOOLEAN:
return lit == 0 ? "false" : "true";
case CHAR:
return String.valueOf((char) lit);
case BYTE:
case SHORT:
case INT:
case LONG:
return Long.toString(lit);
case FLOAT:
return Float.toString(Float.intBitsToFloat((int) lit));
case DOUBLE:
return Double.toString(Double.longBitsToDouble(lit));
case OBJECT:
case ARRAY:
if (lit != 0) {
LOG.warn("Wrong object literal: {} for type: {}", lit, type);
return Long.toString(lit);
}
return "null";
default:
return null;
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/JsonCodeGen.java | jadx-core/src/main/java/jadx/core/codegen/json/JsonCodeGen.java | package jadx.core.codegen.json;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.Nullable;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import jadx.api.ICodeInfo;
import jadx.api.ICodeWriter;
import jadx.api.JadxArgs;
import jadx.api.impl.AnnotatedCodeWriter;
import jadx.api.impl.SimpleCodeWriter;
import jadx.api.metadata.ICodeMetadata;
import jadx.api.metadata.annotations.InsnCodeOffset;
import jadx.core.codegen.ClassGen;
import jadx.core.codegen.MethodGen;
import jadx.core.codegen.json.cls.JsonClass;
import jadx.core.codegen.json.cls.JsonCodeLine;
import jadx.core.codegen.json.cls.JsonField;
import jadx.core.codegen.json.cls.JsonMethod;
import jadx.core.codegen.utils.CodeGenUtils;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.GsonUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class JsonCodeGen {
private static final Gson GSON = GsonUtils.defaultGsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
.disableHtmlEscaping()
.create();
private final ClassNode cls;
private final JadxArgs args;
private final RootNode root;
public JsonCodeGen(ClassNode cls) {
this.cls = cls;
this.root = cls.root();
this.args = root.getArgs();
}
public String process() {
JsonClass jsonCls = processCls(cls, null);
return GSON.toJson(jsonCls);
}
private JsonClass processCls(ClassNode cls, @Nullable ClassGen parentCodeGen) {
ClassGen classGen;
if (parentCodeGen == null) {
classGen = new ClassGen(cls, args);
} else {
classGen = new ClassGen(cls, parentCodeGen);
}
ClassInfo classInfo = cls.getClassInfo();
JsonClass jsonCls = new JsonClass();
jsonCls.setPkg(classInfo.getAliasPkg());
jsonCls.setDex(cls.getInputFileName());
jsonCls.setName(classInfo.getFullName());
if (classInfo.hasAlias()) {
jsonCls.setAlias(classInfo.getAliasFullName());
}
jsonCls.setType(getClassTypeStr(cls));
jsonCls.setAccessFlags(cls.getAccessFlags().rawValue());
ArgType superClass = cls.getSuperClass();
if (superClass != null
&& !superClass.equals(ArgType.OBJECT)
&& !cls.contains(AFlag.REMOVE_SUPER_CLASS)) {
jsonCls.setSuperClass(getTypeAlias(classGen, superClass));
}
if (!cls.getInterfaces().isEmpty()) {
jsonCls.setInterfaces(Utils.collectionMap(cls.getInterfaces(), clsType -> getTypeAlias(classGen, clsType)));
}
ICodeWriter cw = new SimpleCodeWriter(args);
CodeGenUtils.addErrorsAndComments(cw, cls);
classGen.addClassDeclaration(cw);
jsonCls.setDeclaration(cw.getCodeStr());
addFields(cls, jsonCls, classGen);
addMethods(cls, jsonCls, classGen);
addInnerClasses(cls, jsonCls, classGen);
if (!cls.getClassInfo().isInner()) {
List<String> imports = Utils.collectionMap(classGen.getImports(), ClassInfo::getAliasFullName);
Collections.sort(imports);
jsonCls.setImports(imports);
}
return jsonCls;
}
private void addInnerClasses(ClassNode cls, JsonClass jsonCls, ClassGen classGen) {
List<ClassNode> innerClasses = cls.getInnerClasses();
if (innerClasses.isEmpty()) {
return;
}
jsonCls.setInnerClasses(new ArrayList<>(innerClasses.size()));
for (ClassNode innerCls : innerClasses) {
if (innerCls.contains(AFlag.DONT_GENERATE)) {
continue;
}
JsonClass innerJsonCls = processCls(innerCls, classGen);
jsonCls.getInnerClasses().add(innerJsonCls);
}
}
private void addFields(ClassNode cls, JsonClass jsonCls, ClassGen classGen) {
jsonCls.setFields(new ArrayList<>());
for (FieldNode field : cls.getFields()) {
if (field.contains(AFlag.DONT_GENERATE)) {
continue;
}
JsonField jsonField = new JsonField();
jsonField.setName(field.getName());
if (field.getFieldInfo().hasAlias()) {
jsonField.setAlias(field.getAlias());
}
ICodeWriter cw = new SimpleCodeWriter(args);
classGen.addField(cw, field);
jsonField.setDeclaration(cw.getCodeStr());
jsonField.setAccessFlags(field.getAccessFlags().rawValue());
jsonCls.getFields().add(jsonField);
}
}
private void addMethods(ClassNode cls, JsonClass jsonCls, ClassGen classGen) {
jsonCls.setMethods(new ArrayList<>());
for (MethodNode mth : cls.getMethods()) {
if (mth.contains(AFlag.DONT_GENERATE)) {
continue;
}
JsonMethod jsonMth = new JsonMethod();
jsonMth.setName(mth.getName());
if (mth.getMethodInfo().hasAlias()) {
jsonMth.setAlias(mth.getAlias());
}
jsonMth.setSignature(mth.getMethodInfo().getShortId());
jsonMth.setReturnType(getTypeAlias(classGen, mth.getReturnType()));
jsonMth.setArguments(Utils.collectionMap(mth.getMethodInfo().getArgumentsTypes(), clsType -> getTypeAlias(classGen, clsType)));
MethodGen mthGen = new MethodGen(classGen, mth);
ICodeWriter cw = new AnnotatedCodeWriter(args);
mthGen.addDefinition(cw);
jsonMth.setDeclaration(cw.getCodeStr());
jsonMth.setAccessFlags(mth.getAccessFlags().rawValue());
jsonMth.setLines(fillMthCode(mth, mthGen));
jsonMth.setOffset("0x" + Long.toHexString(mth.getMethodCodeOffset()));
jsonCls.getMethods().add(jsonMth);
}
}
private List<JsonCodeLine> fillMthCode(MethodNode mth, MethodGen mthGen) {
if (mth.isNoCode()) {
return Collections.emptyList();
}
ICodeWriter cw = mth.root().makeCodeWriter();
try {
mthGen.addInstructions(cw);
} catch (Exception e) {
throw new JadxRuntimeException("Method generation error", e);
}
ICodeInfo code = cw.finish();
String codeStr = code.getCodeStr();
if (codeStr.isEmpty()) {
return Collections.emptyList();
}
String[] lines = codeStr.split(args.getCodeNewLineStr());
Map<Integer, Integer> lineMapping = code.getCodeMetadata().getLineMapping();
ICodeMetadata metadata = code.getCodeMetadata();
long mthCodeOffset = mth.getMethodCodeOffset() + 16;
int linesCount = lines.length;
List<JsonCodeLine> codeLines = new ArrayList<>(linesCount);
int lineStartPos = 0;
int newLineLen = args.getCodeNewLineStr().length();
for (int i = 0; i < linesCount; i++) {
String codeLine = lines[i];
int line = i + 2;
JsonCodeLine jsonCodeLine = new JsonCodeLine();
jsonCodeLine.setCode(codeLine);
jsonCodeLine.setSourceLine(lineMapping.get(line));
Object obj = metadata.getAt(lineStartPos);
if (obj instanceof InsnCodeOffset) {
long offset = ((InsnCodeOffset) obj).getOffset();
jsonCodeLine.setOffset("0x" + Long.toHexString(mthCodeOffset + offset * 2));
}
codeLines.add(jsonCodeLine);
lineStartPos += codeLine.length() + newLineLen;
}
return codeLines;
}
private String getTypeAlias(ClassGen classGen, ArgType clsType) {
ICodeWriter code = new SimpleCodeWriter(args);
classGen.useType(code, clsType);
return code.getCodeStr();
}
private String getClassTypeStr(ClassNode cls) {
if (cls.isEnum()) {
return "enum";
}
if (cls.getAccessFlags().isInterface()) {
return "interface";
}
return "class";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/JsonMappingGen.java | jadx-core/src/main/java/jadx/core/codegen/json/JsonMappingGen.java | package jadx.core.codegen.json;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import jadx.api.JadxArgs;
import jadx.core.codegen.json.mapping.JsonClsMapping;
import jadx.core.codegen.json.mapping.JsonFieldMapping;
import jadx.core.codegen.json.mapping.JsonMapping;
import jadx.core.codegen.json.mapping.JsonMthMapping;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.MethodInfo;
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.GsonUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.utils.files.FileUtils;
public class JsonMappingGen {
private static final Logger LOG = LoggerFactory.getLogger(JsonMappingGen.class);
private static final Gson GSON = GsonUtils.defaultGsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
.disableHtmlEscaping()
.create();
public static void dump(RootNode root) {
JsonMapping mapping = new JsonMapping();
fillMapping(mapping, root);
JadxArgs args = root.getArgs();
File outDirSrc = args.getOutDirSrc().getAbsoluteFile();
File mappingFile = new File(outDirSrc, "mapping.json");
FileUtils.makeDirsForFile(mappingFile);
try (Writer writer = new FileWriter(mappingFile)) {
GSON.toJson(mapping, writer);
LOG.info("Save mappings to {}", mappingFile.getAbsolutePath());
} catch (Exception e) {
throw new JadxRuntimeException("Failed to save mapping json", e);
}
}
private static void fillMapping(JsonMapping mapping, RootNode root) {
List<ClassNode> classes = root.getClasses(true);
mapping.setClasses(new ArrayList<>(classes.size()));
for (ClassNode cls : classes) {
ClassInfo classInfo = cls.getClassInfo();
JsonClsMapping jsonCls = new JsonClsMapping();
jsonCls.setName(classInfo.getRawName());
jsonCls.setAlias(classInfo.getAliasFullName());
jsonCls.setInner(classInfo.isInner());
jsonCls.setJson(cls.getTopParentClass().getClassInfo().getAliasFullPath() + ".json");
if (classInfo.isInner()) {
jsonCls.setTopClass(cls.getTopParentClass().getClassInfo().getFullName());
}
addFields(cls, jsonCls);
addMethods(cls, jsonCls);
mapping.getClasses().add(jsonCls);
}
}
private static void addMethods(ClassNode cls, JsonClsMapping jsonCls) {
List<MethodNode> methods = cls.getMethods();
if (methods.isEmpty()) {
return;
}
jsonCls.setMethods(new ArrayList<>(methods.size()));
for (MethodNode method : methods) {
JsonMthMapping jsonMethod = new JsonMthMapping();
MethodInfo methodInfo = method.getMethodInfo();
jsonMethod.setSignature(methodInfo.getShortId());
jsonMethod.setName(methodInfo.getName());
jsonMethod.setAlias(methodInfo.getAlias());
jsonMethod.setOffset("0x" + Long.toHexString(method.getMethodCodeOffset()));
jsonCls.getMethods().add(jsonMethod);
}
}
private static void addFields(ClassNode cls, JsonClsMapping jsonCls) {
List<FieldNode> fields = cls.getFields();
if (fields.isEmpty()) {
return;
}
jsonCls.setFields(new ArrayList<>(fields.size()));
for (FieldNode field : fields) {
JsonFieldMapping jsonField = new JsonFieldMapping();
jsonField.setName(field.getName());
jsonField.setAlias(field.getAlias());
jsonCls.getFields().add(jsonField);
}
}
private JsonMappingGen() {
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/mapping/JsonMthMapping.java | jadx-core/src/main/java/jadx/core/codegen/json/mapping/JsonMthMapping.java | package jadx.core.codegen.json.mapping;
public class JsonMthMapping {
private String signature;
private String name;
private String alias;
private String offset;
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getOffset() {
return offset;
}
public void setOffset(String offset) {
this.offset = offset;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/mapping/JsonFieldMapping.java | jadx-core/src/main/java/jadx/core/codegen/json/mapping/JsonFieldMapping.java | package jadx.core.codegen.json.mapping;
public class JsonFieldMapping {
private String name;
private String alias;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/mapping/JsonClsMapping.java | jadx-core/src/main/java/jadx/core/codegen/json/mapping/JsonClsMapping.java | package jadx.core.codegen.json.mapping;
import java.util.List;
public class JsonClsMapping {
private String name;
private String alias;
private String json;
private boolean inner;
private String topClass;
private List<JsonFieldMapping> fields;
private List<JsonMthMapping> methods;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
public boolean isInner() {
return inner;
}
public void setInner(boolean inner) {
this.inner = inner;
}
public String getTopClass() {
return topClass;
}
public void setTopClass(String topClass) {
this.topClass = topClass;
}
public List<JsonFieldMapping> getFields() {
return fields;
}
public void setFields(List<JsonFieldMapping> fields) {
this.fields = fields;
}
public List<JsonMthMapping> getMethods() {
return methods;
}
public void setMethods(List<JsonMthMapping> methods) {
this.methods = methods;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/mapping/JsonMapping.java | jadx-core/src/main/java/jadx/core/codegen/json/mapping/JsonMapping.java | package jadx.core.codegen.json.mapping;
import java.util.List;
public class JsonMapping {
private List<JsonClsMapping> classes;
public List<JsonClsMapping> getClasses() {
return classes;
}
public void setClasses(List<JsonClsMapping> classes) {
this.classes = 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/core/codegen/json/cls/JsonField.java | jadx-core/src/main/java/jadx/core/codegen/json/cls/JsonField.java | package jadx.core.codegen.json.cls;
public class JsonField extends JsonNode {
String type;
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/cls/JsonClass.java | jadx-core/src/main/java/jadx/core/codegen/json/cls/JsonClass.java | package jadx.core.codegen.json.cls;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class JsonClass extends JsonNode {
@SerializedName("package")
private String pkg;
private String type; // class, interface, enum
@SerializedName("extends")
private String superClass;
@SerializedName("implements")
private List<String> interfaces;
private String dex;
private List<JsonField> fields;
private List<JsonMethod> methods;
private List<JsonClass> innerClasses;
private List<String> imports;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSuperClass() {
return superClass;
}
public void setSuperClass(String superClass) {
this.superClass = superClass;
}
public List<String> getInterfaces() {
return interfaces;
}
public void setInterfaces(List<String> interfaces) {
this.interfaces = interfaces;
}
public List<JsonField> getFields() {
return fields;
}
public void setFields(List<JsonField> fields) {
this.fields = fields;
}
public List<JsonMethod> getMethods() {
return methods;
}
public void setMethods(List<JsonMethod> methods) {
this.methods = methods;
}
public List<JsonClass> getInnerClasses() {
return innerClasses;
}
public void setInnerClasses(List<JsonClass> innerClasses) {
this.innerClasses = innerClasses;
}
public String getPkg() {
return pkg;
}
public void setPkg(String pkg) {
this.pkg = pkg;
}
public String getDex() {
return dex;
}
public void setDex(String dex) {
this.dex = dex;
}
public List<String> getImports() {
return imports;
}
public void setImports(List<String> imports) {
this.imports = imports;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/cls/JsonCodeLine.java | jadx-core/src/main/java/jadx/core/codegen/json/cls/JsonCodeLine.java | package jadx.core.codegen.json.cls;
import org.jetbrains.annotations.Nullable;
public class JsonCodeLine {
private String code;
private String offset;
private Integer sourceLine;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getOffset() {
return offset;
}
public void setOffset(String offset) {
this.offset = offset;
}
public Integer getSourceLine() {
return sourceLine;
}
public void setSourceLine(@Nullable Integer sourceLine) {
this.sourceLine = sourceLine;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/cls/JsonNode.java | jadx-core/src/main/java/jadx/core/codegen/json/cls/JsonNode.java | package jadx.core.codegen.json.cls;
public class JsonNode {
private String name;
private String alias;
private String declaration;
private int accessFlags;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getDeclaration() {
return declaration;
}
public void setDeclaration(String declaration) {
this.declaration = declaration;
}
public int getAccessFlags() {
return accessFlags;
}
public void setAccessFlags(int accessFlags) {
this.accessFlags = accessFlags;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/json/cls/JsonMethod.java | jadx-core/src/main/java/jadx/core/codegen/json/cls/JsonMethod.java | package jadx.core.codegen.json.cls;
import java.util.List;
public class JsonMethod extends JsonNode {
private String signature;
private String returnType;
private List<String> arguments;
private List<JsonCodeLine> lines;
private String offset;
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getReturnType() {
return returnType;
}
public void setReturnType(String returnType) {
this.returnType = returnType;
}
public List<String> getArguments() {
return arguments;
}
public void setArguments(List<String> arguments) {
this.arguments = arguments;
}
public List<JsonCodeLine> getLines() {
return lines;
}
public void setLines(List<JsonCodeLine> lines) {
this.lines = lines;
}
public String getOffset() {
return offset;
}
public void setOffset(String offset) {
this.offset = offset;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/utils/CodeGenUtils.java | jadx-core/src/main/java/jadx/core/codegen/utils/CodeGenUtils.java | package jadx.core.codegen.utils;
import java.util.List;
import java.util.regex.Pattern;
import org.jetbrains.annotations.Nullable;
import jadx.api.CommentsLevel;
import jadx.api.ICodeWriter;
import jadx.api.data.CommentStyle;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.api.plugins.input.data.attributes.types.SourceFileAttr;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.IAttributeNode;
import jadx.core.dex.attributes.nodes.JadxCommentsAttr;
import jadx.core.dex.attributes.nodes.JadxError;
import jadx.core.dex.attributes.nodes.NotificationAttrNode;
import jadx.core.dex.attributes.nodes.RenameReasonAttr;
import jadx.core.dex.instructions.args.CodeVar;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.ICodeNode;
import jadx.core.utils.Utils;
public class CodeGenUtils {
public static void addErrorsAndComments(ICodeWriter code, NotificationAttrNode node) {
addErrors(code, node);
addComments(code, node);
}
public static void addErrors(ICodeWriter code, NotificationAttrNode node) {
if (!node.checkCommentsLevel(CommentsLevel.ERROR)) {
return;
}
List<JadxError> errors = node.getAll(AType.JADX_ERROR);
if (!errors.isEmpty()) {
errors.stream().distinct().sorted().forEach(err -> {
addError(code, err.getError(), err.getCause());
});
}
}
public static void addError(ICodeWriter code, String errMsg, Throwable cause) {
code.startLine("/* JADX ERROR: ").add(errMsg);
if (cause != null) {
code.incIndent();
Utils.appendStackTrace(code, cause);
code.decIndent();
}
code.add("*/");
}
public static void addComments(ICodeWriter code, NotificationAttrNode node) {
JadxCommentsAttr commentsAttr = node.get(AType.JADX_COMMENTS);
if (commentsAttr != null) {
commentsAttr.formatAndFilter(node.getCommentsLevel())
.forEach(comment -> code.startLine("/* ").addMultiLine(comment).add(" */"));
}
addCodeComments(code, node, node);
}
public static void addCodeComments(ICodeWriter code, NotificationAttrNode parent, @Nullable IAttributeNode node) {
if (node == null) {
return;
}
if (parent.checkCommentsLevel(CommentsLevel.USER_ONLY)) {
addCodeComments(code, node);
}
}
private static void addCodeComments(ICodeWriter code, @Nullable IAttributeNode node) {
if (node == null) {
return;
}
boolean startNewLine = node instanceof ICodeNode; // add on same line for instructions
for (CodeComment comment : node.getAll(AType.CODE_COMMENTS)) {
addCodeComment(code, comment, startNewLine);
}
}
private static void addCodeComment(ICodeWriter code, CodeComment comment, boolean startNewLine) {
if (startNewLine) {
code.startLine();
} else {
code.add(' ');
}
CommentStyle style = comment.getStyle();
appendMultiLineString(code, "", style.getStart());
appendMultiLineString(code, style.getOnNewLine(), comment.getComment());
appendMultiLineString(code, "", style.getEnd());
}
private static final Pattern NEW_LINE_PATTERN = Pattern.compile("\\R");
private static void appendMultiLineString(ICodeWriter code, String onNewLine, String str) {
String[] lines = NEW_LINE_PATTERN.split(str);
int linesCount = lines.length;
if (linesCount == 0) {
return;
}
code.add(lines[0]);
for (int i = 1; i < linesCount; i++) {
code.startLine(onNewLine);
code.add(lines[i]);
}
}
public static void addRenamedComment(ICodeWriter code, NotificationAttrNode node, String origName) {
if (!node.checkCommentsLevel(CommentsLevel.INFO)) {
return;
}
code.startLine("/* renamed from: ").add(origName);
RenameReasonAttr renameReasonAttr = node.get(AType.RENAME_REASON);
if (renameReasonAttr != null) {
code.add(", reason: ").add(renameReasonAttr.getDescription());
}
code.add(" */");
}
public static void addSourceFileInfo(ICodeWriter code, ClassNode node) {
if (!node.checkCommentsLevel(CommentsLevel.INFO)) {
return;
}
SourceFileAttr sourceFileAttr = node.get(JadxAttrType.SOURCE_FILE);
if (sourceFileAttr != null) {
String fileName = sourceFileAttr.getFileName();
String topClsName = node.getTopParentClass().getClassInfo().getShortName();
if (topClsName.contains(fileName)) {
// ignore similar name
return;
}
code.startLine("/* compiled from: ").add(fileName).add(" */");
}
}
public static void addInputFileInfo(ICodeWriter code, ClassNode cls) {
if (cls.checkCommentsLevel(CommentsLevel.INFO) && cls.getClsData() != null) {
String inputFileName = cls.getClsData().getInputFileName();
if (inputFileName != null) {
ClassNode declCls = cls.getDeclaringClass();
if (declCls != null
&& declCls.getClsData() != null
&& inputFileName.equals(declCls.getClsData().getInputFileName())) {
// don't add same comment for inner classes
return;
}
code.startLine("/* loaded from: ").add(inputFileName).add(" */");
}
}
}
public static CodeVar getCodeVar(RegisterArg arg) {
SSAVar svar = arg.getSVar();
if (svar != null) {
return svar.getCodeVar();
}
return null;
}
private CodeGenUtils() {
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/codegen/utils/CodeComment.java | jadx-core/src/main/java/jadx/core/codegen/utils/CodeComment.java | package jadx.core.codegen.utils;
import jadx.api.data.CommentStyle;
import jadx.api.data.ICodeComment;
public class CodeComment {
private final String comment;
private final CommentStyle style;
public CodeComment(String comment, CommentStyle style) {
this.comment = comment;
this.style = style;
}
public CodeComment(ICodeComment comment) {
this(comment.getComment(), comment.getStyle());
}
public String getComment() {
return comment;
}
public CommentStyle getStyle() {
return style;
}
@Override
public String toString() {
return "CodeComment{" + style + ": '" + comment + "'}";
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/ParserConstants.java | jadx-core/src/main/java/jadx/core/xmlgen/ParserConstants.java | package jadx.core.xmlgen;
import java.util.HashMap;
import java.util.Map;
public class ParserConstants {
protected ParserConstants() {
}
protected static final String ANDROID_NS_URL = "http://schemas.android.com/apk/res/android";
protected static final String ANDROID_NS_VALUE = "android";
/**
* Chunk types as defined in frameworks/base/libs/androidfw/include/androidfw/ResourceTypes.h (AOSP)
*/
protected static final int RES_NULL_TYPE = 0x0000;
protected static final int RES_STRING_POOL_TYPE = 0x0001;
protected static final int RES_TABLE_TYPE = 0x0002;
protected static final int RES_XML_TYPE = 0x0003;
protected static final int RES_XML_FIRST_CHUNK_TYPE = 0x0100;
protected static final int RES_XML_START_NAMESPACE_TYPE = 0x0100;
protected static final int RES_XML_END_NAMESPACE_TYPE = 0x0101;
protected static final int RES_XML_START_ELEMENT_TYPE = 0x0102;
protected static final int RES_XML_END_ELEMENT_TYPE = 0x0103;
protected static final int RES_XML_CDATA_TYPE = 0x0104;
protected static final int RES_XML_LAST_CHUNK_TYPE = 0x017f;
protected static final int RES_XML_RESOURCE_MAP_TYPE = 0x0180;
protected static final int RES_TABLE_PACKAGE_TYPE = 0x0200; // 512
protected static final int RES_TABLE_TYPE_TYPE = 0x0201; // 513
protected static final int RES_TABLE_TYPE_SPEC_TYPE = 0x0202; // 514
protected static final int RES_TABLE_TYPE_LIBRARY = 0x0203; // 515
protected static final int RES_TABLE_TYPE_OVERLAY = 0x0204; // 516
protected static final int RES_TABLE_TYPE_OVERLAY_POLICY = 0x0205; // 517
protected static final int RES_TABLE_TYPE_STAGED_ALIAS = 0x0206; // 518
/**
* Type constants
*/
// Contains no data.
protected static final int TYPE_NULL = 0x00;
// The 'data' holds a ResTable_ref, a reference to another resource table entry.
protected static final int TYPE_REFERENCE = 0x01;
// The 'data' holds an attribute resource identifier.
protected static final int TYPE_ATTRIBUTE = 0x02;
// The 'data' holds an index into the containing resource table's global value string pool.
protected static final int TYPE_STRING = 0x03;
// The 'data' holds a single-precision floating point number.
protected static final int TYPE_FLOAT = 0x04;
// The 'data' holds a complex number encoding a dimension value, such as "100in".
protected static final int TYPE_DIMENSION = 0x05;
// The 'data' holds a complex number encoding a fraction of a container.
protected static final int TYPE_FRACTION = 0x06;
/**
* The 'data' holds a dynamic reference, a reference to another resource table entry.
* See https://github.com/skylot/jadx/issues/919
*/
protected static final int TYPE_DYNAMIC_REFERENCE = 0x07;
/**
* According to the sources of apktool this type seem to be related to themes
* See https://github.com/skylot/jadx/issues/919
*/
protected static final int TYPE_DYNAMIC_ATTRIBUTE = 0x08;
// Beginning of integer flavors...
protected static final int TYPE_FIRST_INT = 0x10;
// The 'data' is a raw integer value of the form n..n.
protected static final int TYPE_INT_DEC = 0x10;
// The 'data' is a raw integer value of the form 0xn..n.
protected static final int TYPE_INT_HEX = 0x11;
// The 'data' is either 0 or 1, for input "false" or "true" respectively.
protected static final int TYPE_INT_BOOLEAN = 0x12;
// Beginning of color integer flavors...
protected static final int TYPE_FIRST_COLOR_INT = 0x1c;
// The 'data' is a raw integer value of the form #aarrggbb.
protected static final int TYPE_INT_COLOR_ARGB8 = 0x1c;
// The 'data' is a raw integer value of the form #rrggbb.
protected static final int TYPE_INT_COLOR_RGB8 = 0x1d;
// The 'data' is a raw integer value of the form #argb.
protected static final int TYPE_INT_COLOR_ARGB4 = 0x1e;
// The 'data' is a raw integer value of the form #rgb.
protected static final int TYPE_INT_COLOR_RGB4 = 0x1f;
// ...end of integer flavors.
protected static final int TYPE_LAST_COLOR_INT = 0x1f;
// ...end of integer flavors.
protected static final int TYPE_LAST_INT = 0x1f;
// Where the unit type information is. This gives us 16 possible
// types, as defined below.
protected static final int COMPLEX_UNIT_SHIFT = 0;
protected static final int COMPLEX_UNIT_MASK = 0xf;
// TYPE_DIMENSION: Value is raw pixels.
protected static final int COMPLEX_UNIT_PX = 0;
// TYPE_DIMENSION: Value is Device Independent Pixels.
protected static final int COMPLEX_UNIT_DIP = 1;
// TYPE_DIMENSION: Value is a Scaled device independent Pixels.
protected static final int COMPLEX_UNIT_SP = 2;
// TYPE_DIMENSION: Value is in points.
protected static final int COMPLEX_UNIT_PT = 3;
// TYPE_DIMENSION: Value is in inches.
protected static final int COMPLEX_UNIT_IN = 4;
// TYPE_DIMENSION: Value is in millimeters.
protected static final int COMPLEX_UNIT_MM = 5;
// TYPE_FRACTION: A basic fraction of the overall size.
protected static final int COMPLEX_UNIT_FRACTION = 0;
// TYPE_FRACTION: A fraction of the parent size.
protected static final int COMPLEX_UNIT_FRACTION_PARENT = 1;
// Where the radix information is, telling where the decimal place
// appears in the mantissa. This give us 4 possible fixed point
// representations as defined below.
protected static final int COMPLEX_RADIX_SHIFT = 4;
protected static final int COMPLEX_RADIX_MASK = 0x3;
// The mantissa is an integral number -- i.e., 0xnnnnnn.0
protected static final int COMPLEX_RADIX_23P0 = 0;
// The mantissa magnitude is 16 bits -- i.e, 0xnnnn.nn
protected static final int COMPLEX_RADIX_16P7 = 1;
// The mantissa magnitude is 8 bits -- i.e, 0xnn.nnnn
protected static final int COMPLEX_RADIX_8P15 = 2;
// The mantissa magnitude is 0 bits -- i.e, 0x0.nnnnnn
protected static final int COMPLEX_RADIX_0P23 = 3;
// Where the actual value is. This gives us 23 bits of
// precision. The top bit is the sign.
protected static final int COMPLEX_MANTISSA_SHIFT = 8;
protected static final int COMPLEX_MANTISSA_MASK = 0xffffff;
protected static final double MANTISSA_MULT = 1.0f / (1 << COMPLEX_MANTISSA_SHIFT);
protected static final double[] RADIX_MULTS = new double[] {
1.0f * MANTISSA_MULT,
1.0f / (1 << 7) * MANTISSA_MULT,
1.0f / (1 << 15) * MANTISSA_MULT,
1.0f / (1 << 23) * MANTISSA_MULT
};
/**
* String pool flags
*/
protected static final int SORTED_FLAG = 1;
protected static final int UTF8_FLAG = 1 << 8;
/**
* ResTable_type
*/
protected static final int NO_ENTRY = 0xFFFFFFFF;
// If set, the entry is sparse, and encodes both the entry ID and offset into each entry,
// and a binary search is used to find the key. Only available on platforms >= O.
// Mark any types that use this with a v26 qualifier to prevent runtime issues on older
// platforms.
protected static final int FLAG_SPARSE = 0x01;
// If set, the offsets to the entries are encoded in 16-bit, real_offset = offset * 4u
// An 16-bit offset of 0xffffu means a NO_ENTRY
protected static final int FLAG_OFFSET16 = 0x02;
/**
* ResTable_entry
*/
// If set, this is a complex entry, holding a set of name/value mappings.
// It is followed by an array of ResTable_map structures.
protected static final int FLAG_COMPLEX = 0x0001;
// If set, this resource has been declared public, so libraries are allowed to reference it.
protected static final int FLAG_PUBLIC = 0x0002;
// If set, this is a weak resource and may be overridden by strong resources of the same name/type.
// This is only useful during linking with other resource tables.
protected static final int FLAG_WEAK = 0x0004;
// If set, this is a compact entry with data type and value directly
// encoded in the entry, see ResTable_entry::compact
protected static final int FLAG_COMPACT = 0x0008;
/**
* ResTable_map
*/
protected static final int ATTR_TYPE = makeResInternal(0);
// For integral attributes, this is the minimum value it can hold.
protected static final int ATTR_MIN = makeResInternal(1);
// For integral attributes, this is the maximum value it can hold.
protected static final int ATTR_MAX = makeResInternal(2);
// Localization of this resource is can be encouraged or required with an aapt flag if this is set
protected static final int ATTR_L10N = makeResInternal(3);
// for plural support, see android.content.res.PluralRules#attrForQuantity(int)
protected static final int ATTR_OTHER = makeResInternal(4);
protected static final int ATTR_ZERO = makeResInternal(5);
protected static final int ATTR_ONE = makeResInternal(6);
protected static final int ATTR_TWO = makeResInternal(7);
protected static final int ATTR_FEW = makeResInternal(8);
protected static final int ATTR_MANY = makeResInternal(9);
protected static final Map<Integer, String> PLURALS_MAP;
static {
PLURALS_MAP = new HashMap<>();
PLURALS_MAP.put(ATTR_OTHER, "other");
PLURALS_MAP.put(ATTR_ZERO, "zero");
PLURALS_MAP.put(ATTR_ONE, "one");
PLURALS_MAP.put(ATTR_TWO, "two");
PLURALS_MAP.put(ATTR_FEW, "few");
PLURALS_MAP.put(ATTR_MANY, "many");
}
private static int makeResInternal(int entry) {
return 0x01000000 | entry & 0xFFFF;
}
protected static boolean isResInternalId(int resid) {
return (resid & 0xFFFF0000) != 0 && (resid & 0xFF0000) == 0;
}
// Bit mask of allowed types, for use with ATTR_TYPE.
protected static final int ATTR_TYPE_ANY = 0x0000FFFF;
// Attribute holds a references to another resource.
protected static final int ATTR_TYPE_REFERENCE = 1;
// Attribute holds a generic string.
protected static final int ATTR_TYPE_STRING = 1 << 1;
// Attribute holds an integer value. ATTR_MIN and ATTR_MIN can
// optionally specify a constrained range of possible integer values.
protected static final int ATTR_TYPE_INTEGER = 1 << 2;
// Attribute holds a boolean integer.
protected static final int ATTR_TYPE_BOOLEAN = 1 << 3;
// Attribute holds a color value.
protected static final int ATTR_TYPE_COLOR = 1 << 4;
// Attribute holds a floating point value.
protected static final int ATTR_TYPE_FLOAT = 1 << 5;
// Attribute holds a dimension value, such as "20px".
protected static final int ATTR_TYPE_DIMENSION = 1 << 6;
// Attribute holds a fraction value, such as "20%".
protected static final int ATTR_TYPE_FRACTION = 1 << 7;
// Attribute holds an enumeration. The enumeration values are
// supplied as additional entries in the map.
protected static final int ATTR_TYPE_ENUM = 1 << 16;
// Attribute holds a bitmaks of flags. The flag bit values are
// supplied as additional entries in the map.
protected static final int ATTR_TYPE_FLAGS = 1 << 17;
// Enum of localization modes, for use with ATTR_L10N
protected static final int ATTR_L10N_NOT_REQUIRED = 0;
protected static final int ATTR_L10N_SUGGESTED = 1;
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/BinaryXMLParser.java | jadx-core/src/main/java/jadx/core/xmlgen/BinaryXMLParser.java | package jadx.core.xmlgen;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeInfo;
import jadx.api.ICodeWriter;
import jadx.api.ResourcesLoader;
import jadx.core.dex.info.ConstStorage;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.StringUtils;
import jadx.core.utils.android.AndroidResourcesMap;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.xmlgen.entry.ValuesParser;
public class BinaryXMLParser extends CommonBinaryParser {
private static final Logger LOG = LoggerFactory.getLogger(BinaryXMLParser.class);
private final RootNode rootNode;
private final ManifestAttributes manifestAttributes;
private final boolean attrNewLine;
private final Map<Integer, String> resNames;
private Map<String, String> nsMap;
private Set<String> nsMapGenerated;
private Set<String> definedNamespaces;
private final Map<String, String> tagAttrDeobfNames = new HashMap<>();
private ICodeWriter writer;
private BinaryXMLStrings strings;
private String currentTag = "ERROR";
private boolean firstElement;
private ValuesParser valuesParser;
private boolean isLastEnd = true;
private boolean isOneLine = true;
private int namespaceDepth = 0;
private @Nullable int[] resourceIds;
private String appPackageName;
private Map<String, ClassNode> classNameCache;
public BinaryXMLParser(RootNode rootNode) {
this.rootNode = rootNode;
this.manifestAttributes = rootNode.initManifestAttributes();
this.attrNewLine = !rootNode.getArgs().isSkipXmlPrettyPrint();
try {
ConstStorage constStorage = rootNode.getConstValues();
resNames = constStorage.getResourcesNames();
} catch (Exception e) {
throw new JadxRuntimeException("BinaryXMLParser init error", e);
}
}
public synchronized ICodeInfo parse(InputStream inputStream) throws IOException {
resourceIds = null;
is = new ParserStream(inputStream);
if (!isBinaryXml()) {
return ResourcesLoader.loadToCodeWriter(is);
}
nsMapGenerated = new HashSet<>();
nsMap = new HashMap<>();
definedNamespaces = new HashSet<>();
writer = rootNode.makeCodeWriter();
writer.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
firstElement = true;
decode();
nsMap = null;
definedNamespaces = null;
ICodeInfo codeInfo = writer.finish();
this.classNameCache = null; // reset class name cache
return codeInfo;
}
private boolean isBinaryXml() throws IOException {
is.mark(4);
int v = is.readInt16(); // version
int h = is.readInt16(); // header size
// Some APK Manifest.xml the version is 0
if (h == 0x0008) {
return true;
}
is.reset();
return false;
}
void decode() throws IOException {
int size = is.readInt32();
while (is.getPos() < size) {
int type = is.readInt16();
switch (type) {
case RES_NULL_TYPE:
// NullType is just doing nothing
break;
case RES_STRING_POOL_TYPE:
strings = parseStringPoolNoType();
valuesParser = new ValuesParser(strings, resNames);
break;
case RES_XML_RESOURCE_MAP_TYPE:
parseResourceMap();
break;
case RES_XML_START_NAMESPACE_TYPE:
parseNameSpace();
break;
case RES_XML_CDATA_TYPE:
parseCData();
break;
case RES_XML_END_NAMESPACE_TYPE:
parseNameSpaceEnd();
break;
case RES_XML_START_ELEMENT_TYPE:
parseElement();
break;
case RES_XML_END_ELEMENT_TYPE:
parseElementEnd();
break;
default:
if (namespaceDepth == 0) {
// skip padding on file end
return;
}
die("Type: 0x" + Integer.toHexString(type) + " not yet implemented");
break;
}
}
}
private void parseResourceMap() throws IOException {
if (is.readInt16() != 0x8) {
die("Header size of resmap is not 8!");
}
int size = is.readInt32();
int len = (size - 8) / 4;
resourceIds = new int[len];
for (int i = 0; i < len; i++) {
resourceIds[i] = is.readInt32();
}
}
private void parseNameSpace() throws IOException {
int headerSize = is.readInt16();
if (headerSize > 0x10) {
LOG.warn("Invalid namespace header");
} else if (headerSize < 0x10) {
die("NAMESPACE header is not 0x10 big");
}
int size = is.readInt32();
if (size > 0x18) {
LOG.warn("Invalid namespace size");
} else if (size < 0x18) {
die("NAMESPACE header chunk is not 0x18 big");
}
int beginLineNumber = is.readInt32();
int comment = is.readInt32();
int beginPrefix = is.readInt32();
int beginURI = is.readInt32();
is.skip(headerSize - 0x10);
String nsKey = getString(beginURI);
String nsValue = getString(beginPrefix);
if (StringUtils.notBlank(nsKey) && !nsMap.containsValue(nsValue)) {
nsMap.putIfAbsent(nsKey, nsValue);
}
namespaceDepth++;
}
private void parseNameSpaceEnd() throws IOException {
int headerSize = is.readInt16();
if (headerSize > 0x10) {
LOG.warn("Invalid namespace end");
} else if (headerSize < 0x10) {
die("NAMESPACE end is not 0x10 big");
}
int dataSize = is.readInt32();
if (dataSize != 0x18) {
LOG.warn("Invalid namespace end size");
}
int endLineNumber = is.readInt32();
int comment = is.readInt32();
int endPrefix = is.readInt32();
int endURI = is.readInt32();
is.skip(headerSize - 0x10);
namespaceDepth--;
String nsKey = getString(endURI);
String nsValue = getString(endPrefix);
if (StringUtils.notBlank(nsKey) && !nsMap.containsValue(nsValue)) {
nsMap.putIfAbsent(nsKey, nsValue);
}
}
private void parseCData() throws IOException {
if (is.readInt16() != 0x10) {
die("CDATA header is not 0x10");
}
if (is.readInt32() != 0x1C) {
die("CDATA header chunk is not 0x1C");
}
int lineNumber = is.readInt32();
is.skip(4);
int strIndex = is.readInt32();
String str = getString(strIndex);
if (!isLastEnd) {
isLastEnd = true;
writer.add('>');
}
writer.attachSourceLine(lineNumber);
String escapedStr = StringUtils.escapeXML(str);
writer.add(escapedStr);
long size = is.readInt16();
is.skip(size - 2);
}
private void parseElement() throws IOException {
if (firstElement) {
firstElement = false;
} else {
writer.incIndent();
}
if (is.readInt16() != 0x10) {
die("ELEMENT HEADER SIZE is not 0x10");
}
// TODO: Check element chunk size
long startPos = is.getPos();
int elementSize = is.readInt32();
int elementBegLineNumber = is.readInt32();
int comment = is.readInt32();
int startNS = is.readInt32();
int startNSName = is.readInt32(); // actually is elementName...
if (!isLastEnd && !"ERROR".equals(currentTag)) {
writer.add('>');
}
isOneLine = true;
isLastEnd = false;
currentTag = deobfClassName(getString(startNSName));
currentTag = getValidTagAttributeName(currentTag);
writer.startLine('<').add(currentTag);
writer.attachSourceLine(elementBegLineNumber);
int attributeStart = is.readInt16();
if (attributeStart != 0x14) {
die("startNS's attributeStart is not 0x14");
}
int attributeSize = is.readInt16();
if (attributeSize < 0x14) {
die("startNS's attributeSize is less than 0x14");
}
int attributeCount = is.readInt16();
int idIndex = is.readInt16();
int classIndex = is.readInt16();
int styleIndex = is.readInt16();
if ("manifest".equals(currentTag) || definedNamespaces.size() != nsMap.size()) {
for (Map.Entry<String, String> entry : nsMap.entrySet()) {
if (!definedNamespaces.contains(entry.getKey())) {
definedNamespaces.add(entry.getKey());
String nsValue = getValidTagAttributeName(entry.getValue());
writer.add(" xmlns");
if (nsValue != null && !nsValue.trim().isEmpty()) {
writer.add(':');
writer.add(nsValue);
}
writer.add("=\"").add(StringUtils.escapeXML(entry.getKey())).add('"');
}
}
}
Set<String> attrCache = new HashSet<>();
boolean attrNewLine = attributeCount != 1 && this.attrNewLine;
for (int i = 0; i < attributeCount; i++) {
parseAttribute(i, attrNewLine, attrCache, attributeSize);
}
long endPos = is.getPos();
if (endPos - startPos + 0x4 < elementSize) {
is.skip(elementSize - (endPos - startPos + 0x4));
}
}
private void parseAttribute(int i, boolean newLine, Set<String> attrCache, int attributeSize) throws IOException {
int attributeNS = is.readInt32();
int attributeName = is.readInt32();
int attributeRawValue = is.readInt32();
is.skip(3);
int attrValDataType = is.readInt8();
int attrValData = is.readInt32();
is.skip(attributeSize - 0x14);
String shortNsName = null;
if (attributeNS != -1) {
shortNsName = getAttributeNS(attributeNS, newLine);
}
String attrName = getValidTagAttributeName(getAttributeName(attributeName));
String attrFullName = shortNsName != null ? shortNsName + ":" + attrName : attrName;
// do not dump duplicated values
if (XmlDeobf.isDuplicatedAttr(attrFullName, attrCache)) {
return;
}
if (newLine) {
writer.startLine().addIndent();
} else {
writer.add(' ');
}
writer.add(attrFullName).add("=\"");
String decodedAttr = manifestAttributes.decode(attrFullName, attrValData);
if (decodedAttr != null) {
memorizePackageName(attrName, decodedAttr);
if (isDeobfCandidateAttr(attrFullName)) {
decodedAttr = deobfClassName(decodedAttr);
}
attachClassNode(writer, attrName, decodedAttr);
writer.add(StringUtils.escapeXML(decodedAttr));
} else {
decodeAttribute(attributeNS, attrValDataType, attrValData,
attrFullName);
}
if (shortNsName != null && shortNsName.equals("android")) {
if (attrName.equals("pathData")) {
rootNode.getGradleInfoStorage().setVectorPathData(true);
} else if (attrName.equals("fillType")) {
rootNode.getGradleInfoStorage().setVectorFillType(true);
}
}
writer.add('"');
}
private String getAttributeNS(int attributeNS, boolean newLine) {
String attrUrl = getString(attributeNS);
if (attrUrl == null || attrUrl.isEmpty()) {
if (isResInternalId(attributeNS)) {
return null;
} else {
attrUrl = ANDROID_NS_URL;
}
}
String attrName = nsMap.get(attrUrl);
if (attrName == null) {
attrName = generateNameForNS(attrUrl, newLine);
}
return attrName;
}
private String generateNameForNS(String attrUrl, boolean newLine) {
String attrName;
if (ANDROID_NS_URL.equals(attrUrl)) {
attrName = ANDROID_NS_VALUE;
nsMap.put(ANDROID_NS_URL, attrName);
} else {
for (int i = 1;; i++) {
attrName = "ns" + i;
if (!nsMapGenerated.contains(attrName) && !nsMap.containsValue(attrName)) {
nsMapGenerated.add(attrName);
// do not add generated value to nsMap
// because attrUrl might be used in a neighbor element, but never defined
break;
}
}
}
if (newLine) {
writer.startLine().addIndent();
} else {
writer.add(' ');
}
writer.add("xmlns:").add(attrName).add("=\"").add(attrUrl).add("\" ");
return attrName;
}
private String getAttributeName(int id) {
// As the outcome of https://github.com/skylot/jadx/issues/1208
// Android seems to favor entries from AndroidResMap and only if
// there is no entry uses the values form the XML string pool
if (resourceIds != null && 0 <= id && id < resourceIds.length) {
int resId = resourceIds[id];
String str = AndroidResourcesMap.getResName(resId);
if (str != null) {
// cut type before /
int typeEnd = str.indexOf('/');
if (typeEnd != -1) {
return str.substring(typeEnd + 1);
}
return str;
}
}
String str = getString(id);
if (str == null || str.isEmpty()) {
return "NOT_FOUND_0x" + Integer.toHexString(id);
}
return str;
}
private String getString(int strId) {
if (0 <= strId && strId < strings.size()) {
return strings.get(strId);
}
return "NOT_FOUND_STR_0x" + Integer.toHexString(strId);
}
private void decodeAttribute(int attributeNS, int attrValDataType, int attrValData, String attrFullName) {
if (attrValDataType == TYPE_REFERENCE) {
// reference custom processing
String resName = resNames.get(attrValData);
if (resName != null) {
writer.add('@');
if (resName.startsWith("id/")) {
writer.add('+');
}
writer.add(resName);
} else {
String androidResName = AndroidResourcesMap.getResName(attrValData);
if (androidResName != null) {
writer.add("@android:").add(androidResName);
} else if (attrValData == 0) {
writer.add("@null");
} else {
writer.add("0x").add(Integer.toHexString(attrValData));
}
}
} else {
String str;
try {
str = valuesParser.decodeValue(attrValDataType, attrValData);
} catch (JadxRuntimeException e) {
LOG.error("Failed to decode attribute value of \"{}\"", attrFullName, e);
str = null;
}
memorizePackageName(attrFullName, str);
if (isDeobfCandidateAttr(attrFullName)) {
str = deobfClassName(str);
}
attachClassNode(writer, attrFullName, str);
writer.add(str != null ? StringUtils.escapeXML(str) : "null");
}
}
private void parseElementEnd() throws IOException {
if (is.readInt16() != 0x10) {
die("ELEMENT END header is not 0x10");
}
if (is.readInt32() != 0x18) {
die("ELEMENT END header chunk is not 0x18 big");
}
int endLineNumber = is.readInt32();
int comment = is.readInt32();
int elementNS = is.readInt32();
int elementNameId = is.readInt32();
String elemName = deobfClassName(getString(elementNameId));
elemName = getValidTagAttributeName(elemName);
if (currentTag.equals(elemName) && isOneLine && !isLastEnd) {
writer.add("/>");
} else {
writer.startLine("</");
writer.attachSourceLine(endLineNumber);
// if (elementNS != -1) {
// writer.add(getString(elementNS)).add(':');
// }
writer.add(elemName).add('>');
}
isLastEnd = true;
if (writer.getIndent() != 0) {
writer.decIndent();
}
}
private String getValidTagAttributeName(String originalName) {
if (XMLChar.isValidName(originalName)) {
return originalName;
}
if (tagAttrDeobfNames.containsKey(originalName)) {
return tagAttrDeobfNames.get(originalName);
}
String generated;
do {
generated = generateTagAttrName();
} while (tagAttrDeobfNames.containsValue(generated));
tagAttrDeobfNames.put(originalName, generated);
return generated;
}
private static String generateTagAttrName() {
final int length = 6;
Random r = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= length; i++) {
sb.append((char) (r.nextInt(26) + 'a'));
}
return sb.toString();
}
private void attachClassNode(ICodeWriter writer, String attrFullName, String clsName) {
if (!writer.isMetadataSupported()) {
return;
}
if (clsName == null || !attrFullName.equals("android:name")) {
return;
}
String clsFullName;
if (clsName.startsWith(".")) {
clsFullName = appPackageName + clsName;
} else {
clsFullName = clsName;
}
if (classNameCache == null) {
classNameCache = rootNode.buildFullAliasClassCache();
}
ClassNode classNode = classNameCache.get(clsFullName);
if (classNode != null) {
writer.attachAnnotation(classNode);
}
}
private String deobfClassName(String className) {
String newName = XmlDeobf.deobfClassName(rootNode, className, appPackageName);
if (newName != null) {
return newName;
}
return className;
}
private boolean isDeobfCandidateAttr(String attrFullName) {
return "android:name".equals(attrFullName);
}
private void memorizePackageName(String attrFullName, String attrValue) {
if ("manifest".equals(currentTag) && "package".equals(attrFullName)) {
appPackageName = attrValue;
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/XmlGenUtils.java | jadx-core/src/main/java/jadx/core/xmlgen/XmlGenUtils.java | package jadx.core.xmlgen;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import jadx.api.ICodeInfo;
import jadx.api.ICodeWriter;
import jadx.core.xmlgen.entry.ResourceEntry;
import jadx.core.xmlgen.entry.ValuesParser;
public class XmlGenUtils {
private XmlGenUtils() {
}
public static byte[] readData(InputStream i) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] data = new byte[16384];
int read;
while ((read = i.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, read);
}
return buffer.toByteArray();
}
public static ICodeInfo makeXmlDump(ICodeWriter writer, ResourceStorage resStorage) {
writer.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
writer.startLine("<resources>");
writer.incIndent();
Set<String> addedValues = new HashSet<>();
for (ResourceEntry ri : resStorage.getResources()) {
if (addedValues.add(ri.getTypeName() + '.' + ri.getKeyName())) {
String format = String.format("<public type=\"%s\" name=\"%s\" id=\"0x%08x\" />",
ri.getTypeName(), ri.getKeyName(), ri.getId());
writer.startLine(format);
}
}
writer.decIndent();
writer.startLine("</resources>");
return writer.finish();
}
public static String decodeComplex(int data, boolean isFraction) {
double value = (data & ParserConstants.COMPLEX_MANTISSA_MASK << ParserConstants.COMPLEX_MANTISSA_SHIFT)
* ParserConstants.RADIX_MULTS[data >> ParserConstants.COMPLEX_RADIX_SHIFT & ParserConstants.COMPLEX_RADIX_MASK];
int unitType = data & ParserConstants.COMPLEX_UNIT_MASK;
String unit;
if (isFraction) {
value *= 100;
switch (unitType) {
case ParserConstants.COMPLEX_UNIT_FRACTION:
unit = "%";
break;
case ParserConstants.COMPLEX_UNIT_FRACTION_PARENT:
unit = "%p";
break;
default:
unit = "?f" + Integer.toHexString(unitType);
}
} else {
switch (unitType) {
case ParserConstants.COMPLEX_UNIT_PX:
unit = "px";
break;
case ParserConstants.COMPLEX_UNIT_DIP:
unit = "dp";
break;
case ParserConstants.COMPLEX_UNIT_SP:
unit = "sp";
break;
case ParserConstants.COMPLEX_UNIT_PT:
unit = "pt";
break;
case ParserConstants.COMPLEX_UNIT_IN:
unit = "in";
break;
case ParserConstants.COMPLEX_UNIT_MM:
unit = "mm";
break;
default:
unit = "?d" + Integer.toHexString(unitType);
}
}
return doubleToString(value) + unit;
}
public static String doubleToString(double value) {
if (Double.compare(value, Math.floor(value)) == 0
&& !Double.isInfinite(value)) {
return Integer.toString((int) value);
}
// remove trailing zeroes
NumberFormat f = NumberFormat.getInstance(Locale.ROOT);
f.setMaximumFractionDigits(4);
f.setMinimumIntegerDigits(1);
return f.format(value);
}
public static String floatToString(float value) {
return doubleToString(value);
}
public static String getAttrTypeAsString(int type) {
String s = "";
if ((type & ValuesParser.ATTR_TYPE_REFERENCE) != 0) {
s += "|reference";
}
if ((type & ValuesParser.ATTR_TYPE_STRING) != 0) {
s += "|string";
}
if ((type & ValuesParser.ATTR_TYPE_INTEGER) != 0) {
s += "|integer";
}
if ((type & ValuesParser.ATTR_TYPE_BOOLEAN) != 0) {
s += "|boolean";
}
if ((type & ValuesParser.ATTR_TYPE_COLOR) != 0) {
s += "|color";
}
if ((type & ValuesParser.ATTR_TYPE_FLOAT) != 0) {
s += "|float";
}
if ((type & ValuesParser.ATTR_TYPE_DIMENSION) != 0) {
s += "|dimension";
}
if ((type & ValuesParser.ATTR_TYPE_FRACTION) != 0) {
s += "|fraction";
}
if (s.isEmpty()) {
return null;
}
return s.substring(1);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/StringFormattedCheck.java | jadx-core/src/main/java/jadx/core/xmlgen/StringFormattedCheck.java | package jadx.core.xmlgen;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/*
* This class contains source code form https://github.com/iBotPeaches/Apktool/
* see:
* https://github.com/iBotPeaches/Apktool/blob/master/brut.apktool/apktool-lib/src/main/java/brut/
* androlib/res/xml/ResXmlEncoders.java
*/
public class StringFormattedCheck {
public static boolean hasMultipleNonPositionalSubstitutions(String str) {
Duo<List<Integer>, List<Integer>> tuple = findSubstitutions(str, 4);
return !tuple.m1.isEmpty() && tuple.m1.size() + tuple.m2.size() > 1;
}
@SuppressWarnings("checkstyle:ClassTypeParameterName")
private static class Duo<T1, T2> {
public final T1 m1;
public final T2 m2;
public Duo(T1 t1, T2 t2) {
this.m1 = t1;
this.m2 = t2;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("unchecked")
final Duo<T1, T2> other = (Duo<T1, T2>) obj;
if (!Objects.equals(this.m1, other.m1)) {
return false;
}
return Objects.equals(this.m2, other.m2);
}
@Override
public int hashCode() {
int hash = 3;
hash = 71 * hash + (this.m1 != null ? this.m1.hashCode() : 0);
hash = 71 * hash + (this.m2 != null ? this.m2.hashCode() : 0);
return hash;
}
}
/**
* It returns a tuple of:
* - a list of offsets of non positional substitutions. non-pos is defined as any "%" which isn't
* "%%" nor "%\d+\$"
* - a list of offsets of positional substitutions
*/
@SuppressWarnings({ "checkstyle:NeedBraces", "checkstyle:EmptyStatement" })
private static Duo<List<Integer>, List<Integer>> findSubstitutions(String str, int nonPosMax) {
if (nonPosMax == -1) {
nonPosMax = Integer.MAX_VALUE;
}
int pos;
int pos2 = 0;
List<Integer> nonPositional = new ArrayList<>();
List<Integer> positional = new ArrayList<>();
if (str == null) {
return new Duo<>(nonPositional, positional);
}
int length = str.length();
while ((pos = str.indexOf('%', pos2)) != -1) {
pos2 = pos + 1;
if (pos2 == length) {
nonPositional.add(pos);
break;
}
char c = str.charAt(pos2++);
if (c == '%') {
continue;
}
if (c >= '0' && c <= '9' && pos2 < length) {
while ((c = str.charAt(pos2++)) >= '0' && c <= '9' && pos2 < length)
;
if (c == '$') {
positional.add(pos);
continue;
}
}
nonPositional.add(pos);
if (nonPositional.size() >= nonPosMax) {
break;
}
}
return new Duo<>(nonPositional, positional);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/ResTableBinaryParserProvider.java | jadx-core/src/main/java/jadx/core/xmlgen/ResTableBinaryParserProvider.java | package jadx.core.xmlgen;
import org.jetbrains.annotations.Nullable;
import jadx.api.ResourceFile;
import jadx.api.plugins.resources.IResTableParserProvider;
import jadx.core.dex.nodes.RootNode;
public class ResTableBinaryParserProvider implements IResTableParserProvider {
private RootNode root;
@Override
public void init(RootNode root) {
this.root = root;
}
@Override
public @Nullable IResTableParser getParser(ResourceFile resFile) {
String fileName = resFile.getOriginalName();
if (!fileName.endsWith(".arsc")) {
return null;
}
return new ResTableBinaryParser(root);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/IResTableParser.java | jadx-core/src/main/java/jadx/core/xmlgen/IResTableParser.java | package jadx.core.xmlgen;
import java.io.IOException;
import java.io.InputStream;
public interface IResTableParser {
void decode(InputStream inputStream) throws IOException;
ResContainer decodeFiles();
ResourceStorage getResStorage();
BinaryXMLStrings getStrings();
default void setBaseFileName(String fileName) {
// optional
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/ResContainer.java | jadx-core/src/main/java/jadx/core/xmlgen/ResContainer.java | package jadx.core.xmlgen;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.jetbrains.annotations.NotNull;
import jadx.api.ICodeInfo;
import jadx.api.ResourceFile;
public class ResContainer implements Comparable<ResContainer> {
public enum DataType {
TEXT, DECODED_DATA, RES_LINK, RES_TABLE
}
private final DataType dataType;
private final String name;
private final Object data;
private final List<ResContainer> subFiles;
public static ResContainer textResource(String name, ICodeInfo content) {
return new ResContainer(name, Collections.emptyList(), content, DataType.TEXT);
}
public static ResContainer decodedData(String name, byte[] data) {
return new ResContainer(name, Collections.emptyList(), data, DataType.DECODED_DATA);
}
public static ResContainer resourceFileLink(ResourceFile resFile) {
return new ResContainer(resFile.getDeobfName(), Collections.emptyList(), resFile, DataType.RES_LINK);
}
public static ResContainer resourceTable(String name, List<ResContainer> subFiles, ICodeInfo rootContent) {
return new ResContainer(name, subFiles, rootContent, DataType.RES_TABLE);
}
private ResContainer(String name, List<ResContainer> subFiles, Object data, DataType dataType) {
this.name = Objects.requireNonNull(name);
this.subFiles = Objects.requireNonNull(subFiles);
this.data = Objects.requireNonNull(data);
this.dataType = Objects.requireNonNull(dataType);
}
public String getName() {
return name;
}
public String getFileName() {
return name.replace('/', File.separatorChar);
}
public List<ResContainer> getSubFiles() {
return subFiles;
}
public DataType getDataType() {
return dataType;
}
public ICodeInfo getText() {
return (ICodeInfo) data;
}
public byte[] getDecodedData() {
return (byte[]) data;
}
public ResourceFile getResLink() {
return (ResourceFile) data;
}
@Override
public int compareTo(@NotNull ResContainer o) {
return name.compareTo(o.name);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ResContainer)) {
return false;
}
ResContainer that = (ResContainer) o;
return name.equals(that.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return "Res{" + name + ", type=" + dataType + ", subFiles=" + subFiles + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/ManifestAttributes.java | jadx-core/src/main/java/jadx/core/xmlgen/ManifestAttributes.java | package jadx.core.xmlgen;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import jadx.api.security.IJadxSecurity;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.xmlgen.entry.RawNamedValue;
import jadx.core.xmlgen.entry.ResourceEntry;
import jadx.core.xmlgen.entry.ValuesParser;
// TODO: move to Android specific module!
/**
* Load and store Android Manifest attributes specification
*/
public class ManifestAttributes {
private static final Logger LOG = LoggerFactory.getLogger(ManifestAttributes.class);
private static final String ATTR_XML = "/android/attrs.xml";
private static final String MANIFEST_ATTR_XML = "/android/attrs_manifest.xml";
private enum MAttrType {
ENUM, FLAG
}
private static class MAttr {
private final MAttrType type;
private final Map<Long, String> values = new LinkedHashMap<>();
public MAttr(MAttrType type) {
this.type = type;
}
public MAttrType getType() {
return type;
}
public Map<Long, String> getValues() {
return values;
}
public void addValue(long key, String value) {
values.put(key, value);
}
@Override
public String toString() {
return "[" + type + ", " + values + ']';
}
}
private final IJadxSecurity security;
/**
* Map containing default Android resource attribute definitions.
* Keys are Android attribute names (e.g., "android:layout_width"),
* and values are their corresponding {@link MAttr} objects.
*/
private final Map<String, MAttr> attrMap = new HashMap<>();
private final Map<String, MAttr> appAttrMap = new HashMap<>();
public ManifestAttributes(IJadxSecurity security) {
this.security = security;
parseAll();
}
private void parseAll() {
parse(loadXML(ATTR_XML));
parse(loadXML(MANIFEST_ATTR_XML));
LOG.debug("Loaded android attributes count: {}", attrMap.size());
}
private Document loadXML(String xml) {
Document doc;
try (InputStream xmlStream = ManifestAttributes.class.getResourceAsStream(xml)) {
if (xmlStream == null) {
throw new JadxRuntimeException(xml + " not found in classpath");
}
doc = security.parseXml(xmlStream);
} catch (Exception e) {
throw new JadxRuntimeException("Xml load error, file: " + xml, e);
}
return doc;
}
private void parse(Document doc) {
NodeList nodeList = doc.getChildNodes();
for (int count = 0; count < nodeList.getLength(); count++) {
Node node = nodeList.item(count);
if (node.getNodeType() == Node.ELEMENT_NODE
&& node.hasChildNodes()) {
parseAttrList(node.getChildNodes());
}
}
}
private void parseAttrList(NodeList nodeList) {
for (int count = 0; count < nodeList.getLength(); count++) {
Node tempNode = nodeList.item(count);
if (tempNode.getNodeType() == Node.ELEMENT_NODE
&& tempNode.hasAttributes()
&& tempNode.hasChildNodes()) {
String name = null;
NamedNodeMap nodeMap = tempNode.getAttributes();
for (int i = 0; i < nodeMap.getLength(); i++) {
Node node = nodeMap.item(i);
if (node.getNodeName().equals("name")) {
name = node.getNodeValue();
break;
}
}
if (name != null && tempNode.getNodeName().equals("attr")) {
parseValues(name, tempNode.getChildNodes());
} else {
parseAttrList(tempNode.getChildNodes());
}
}
}
}
private void parseValues(String name, NodeList nodeList) {
MAttr attr = null;
for (int count = 0; count < nodeList.getLength(); count++) {
Node tempNode = nodeList.item(count);
if (tempNode.getNodeType() == Node.ELEMENT_NODE
&& tempNode.hasAttributes()) {
if (attr == null) {
if (tempNode.getNodeName().equals("enum")) {
attr = new MAttr(MAttrType.ENUM);
} else if (tempNode.getNodeName().equals("flag")) {
attr = new MAttr(MAttrType.FLAG);
}
if (attr == null) {
return;
}
attrMap.put("android:" + name, attr);
}
NamedNodeMap attributes = tempNode.getAttributes();
Node nameNode = attributes.getNamedItem("name");
if (nameNode != null) {
Node valueNode = attributes.getNamedItem("value");
if (valueNode != null) {
try {
long key;
String nodeValue = valueNode.getNodeValue();
if (nodeValue.startsWith("0x")) {
nodeValue = nodeValue.substring(2);
key = Long.parseLong(nodeValue, 16);
} else {
key = Long.parseLong(nodeValue);
}
attr.addValue(key, nameNode.getNodeValue());
} catch (NumberFormatException e) {
LOG.debug("Failed parse manifest number", e);
}
}
}
}
}
}
public String decode(String attrName, long value) {
MAttr attr = attrMap.get(attrName);
if (attr == null) {
if (attrName.contains(":")) {
attrName = attrName.split(":", 2)[1];
}
attr = appAttrMap.get(attrName);
if (attr == null) {
return null;
}
}
Map<Long, String> attrValuesMap = attr.getValues();
if (attr.getType() == MAttrType.ENUM) {
return attrValuesMap.get(value);
} else if (attr.getType() == MAttrType.FLAG) {
List<String> flagList = new ArrayList<>();
List<Long> attrKeys = new ArrayList<>(attrValuesMap.keySet());
attrKeys.sort((a, b) -> Long.compare(b, a)); // sort descending
for (Long key : attrKeys) {
String attrValue = attrValuesMap.get(key);
if (value == key) {
flagList.add(attrValue);
break;
} else if ((key != 0) && ((value & key) == key)) {
flagList.add(attrValue);
value ^= key;
}
}
return String.join("|", flagList);
}
return null;
}
public void updateAttributes(IResTableParser parser) {
appAttrMap.clear();
ResourceStorage resStorage = parser.getResStorage();
ValuesParser vp = new ValuesParser(parser.getStrings(), resStorage.getResourcesNames());
for (ResourceEntry ri : resStorage.getResources()) {
if (ri.getProtoValue() != null) {
// Aapt proto decoder resolves attributes by itself.
continue;
}
if (ri.getTypeName().equals("attr") && ri.getNamedValues().size() > 1) {
RawNamedValue first = ri.getNamedValues().get(0);
MAttrType attrTyp;
int attrTypeVal = first.getRawValue().getData() & 0xff0000;
if (attrTypeVal == ValuesParser.ATTR_TYPE_FLAGS) {
attrTyp = MAttrType.FLAG;
} else if (attrTypeVal == ValuesParser.ATTR_TYPE_ENUM) {
attrTyp = MAttrType.ENUM;
} else {
continue;
}
MAttr attr = new MAttr(attrTyp);
for (int i = 1; i < ri.getNamedValues().size(); i++) {
RawNamedValue rv = ri.getNamedValues().get(i);
String value = vp.decodeNameRef(rv.getNameRef());
attr.addValue(rv.getRawValue().getData(), value.startsWith("id.") ? value.substring(3) : value);
}
appAttrMap.put(ri.getKeyName(), 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/main/java/jadx/core/xmlgen/ResTableBinaryParser.java | jadx-core/src/main/java/jadx/core/xmlgen/ResTableBinaryParser.java | package jadx.core.xmlgen;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeInfo;
import jadx.api.args.ResourceNameSource;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.IFieldInfoRef;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.BetterName;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.xmlgen.entry.EntryConfig;
import jadx.core.xmlgen.entry.RawNamedValue;
import jadx.core.xmlgen.entry.RawValue;
import jadx.core.xmlgen.entry.ResourceEntry;
import jadx.core.xmlgen.entry.ValuesParser;
public class ResTableBinaryParser extends CommonBinaryParser implements IResTableParser {
private static final Logger LOG = LoggerFactory.getLogger(ResTableBinaryParser.class);
private static final class PackageChunk {
private final int id;
private final String name;
private final BinaryXMLStrings typeStrings;
private final BinaryXMLStrings keyStrings;
private PackageChunk(int id, String name, BinaryXMLStrings typeStrings, BinaryXMLStrings keyStrings) {
this.id = id;
this.name = name;
this.typeStrings = typeStrings;
this.keyStrings = keyStrings;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public BinaryXMLStrings getTypeStrings() {
return typeStrings;
}
public BinaryXMLStrings getKeyStrings() {
return keyStrings;
}
}
/**
* No renaming, pattern checking or name generation. Required for res-map.txt building
*/
private final boolean useRawResName;
private final RootNode root;
private ResourceStorage resStorage;
private BinaryXMLStrings strings;
private String baseFileName = "";
public ResTableBinaryParser(RootNode root) {
this(root, false);
}
public ResTableBinaryParser(RootNode root, boolean useRawResNames) {
this.root = root;
this.useRawResName = useRawResNames;
}
@Override
public void setBaseFileName(String fileName) {
this.baseFileName = fileName;
}
@Override
public void decode(InputStream inputStream) throws IOException {
long start = System.currentTimeMillis();
is = new ParserStream(new BufferedInputStream(inputStream, 32768));
resStorage = new ResourceStorage(root.getArgs().getSecurity());
decodeTableChunk();
resStorage.finish();
if (LOG.isDebugEnabled()) {
LOG.debug("Resource table parsed: size: {}, time: {}ms",
resStorage.size(), System.currentTimeMillis() - start);
}
}
@Override
public ResContainer decodeFiles() {
ValuesParser vp = new ValuesParser(strings, resStorage.getResourcesNames());
ResXmlGen resGen = new ResXmlGen(resStorage, vp, root.initManifestAttributes());
ICodeInfo content = XmlGenUtils.makeXmlDump(root.makeCodeWriter(), resStorage);
List<ResContainer> xmlFiles = resGen.makeResourcesXml(root.getArgs());
return ResContainer.resourceTable(baseFileName, xmlFiles, content);
}
void decodeTableChunk() throws IOException {
is.checkInt16(RES_TABLE_TYPE, "Not a table chunk");
is.checkInt16(0x000c, "Unexpected table header size");
int size = is.readInt32();
int pkgCount = is.readInt32();
int pkgNum = 0;
while (is.getPos() < size) {
long chuckStart = is.getPos();
int type = is.readInt16();
int headerSize = is.readInt16();
long chunkSize = is.readUInt32();
long chunkEnd = chuckStart + chunkSize;
switch (type) {
case RES_NULL_TYPE:
// skip
break;
case RES_STRING_POOL_TYPE:
strings = parseStringPoolNoSize(chuckStart, chunkEnd);
break;
case RES_TABLE_PACKAGE_TYPE:
parsePackage(chuckStart, headerSize, chunkEnd);
pkgNum++;
break;
}
is.skipToPos(chunkEnd, "Skip to table chunk end");
}
if (pkgNum != pkgCount) {
LOG.warn("Unexpected package chunks, read: {}, expected: {}", pkgNum, pkgCount);
}
}
private void parsePackage(long pkgChunkStart, int headerSize, long pkgChunkEnd) throws IOException {
if (headerSize < 0x011c) {
die("Package header size too small");
return;
}
int id = is.readInt32();
String name = is.readString16Fixed(128);
long typeStringsOffset = pkgChunkStart + is.readInt32();
int lastPublicType = is.readInt32();
long keyStringsOffset = pkgChunkStart + is.readInt32();
int lastPublicKey = is.readInt32();
if (headerSize >= 0x0120) {
int typeIdOffset = is.readInt32();
}
is.skipToPos(pkgChunkStart + headerSize, "package header end");
BinaryXMLStrings typeStrings = null;
if (typeStringsOffset != 0) {
is.skipToPos(typeStringsOffset, "Expected typeStrings string pool");
typeStrings = parseStringPool();
}
BinaryXMLStrings keyStrings = null;
if (keyStringsOffset != 0) {
is.skipToPos(keyStringsOffset, "Expected keyStrings string pool");
keyStrings = parseStringPool();
}
PackageChunk pkg = new PackageChunk(id, name, typeStrings, keyStrings);
resStorage.setAppPackage(name);
while (is.getPos() < pkgChunkEnd) {
long chunkStart = is.getPos();
int type = is.readInt16();
LOG.trace("res package chunk start at {} type {}", chunkStart, type);
switch (type) {
case RES_NULL_TYPE:
LOG.info("Null chunk type encountered at offset {}", chunkStart);
break;
case RES_TABLE_TYPE_TYPE: // 0x0201
parseTypeChunk(chunkStart, pkg);
break;
case RES_TABLE_TYPE_SPEC_TYPE: // 0x0202
parseTypeSpecChunk(chunkStart);
break;
case RES_TABLE_TYPE_LIBRARY: // 0x0203
parseLibraryTypeChunk(chunkStart);
break;
case RES_TABLE_TYPE_OVERLAY: // 0x0204
parseOverlayTypeChunk(chunkStart);
break;
case RES_TABLE_TYPE_OVERLAY_POLICY: // 0x0205
throw new IOException(
String.format("Encountered unsupported chunk type RES_TABLE_TYPE_OVERLAY_POLICY at offset 0x%x ", chunkStart));
case RES_TABLE_TYPE_STAGED_ALIAS: // 0x0206
parseStagedAliasChunk(chunkStart);
break;
default:
LOG.warn("Unknown chunk type {} encountered at offset {}", type, chunkStart);
}
}
}
@SuppressWarnings("unused")
private void parseTypeSpecChunk(long chunkStart) throws IOException {
is.checkInt16(0x0010, "Unexpected type spec header size");
int chunkSize = is.readInt32();
long expectedEndPos = chunkStart + chunkSize;
int id = is.readInt8();
is.skip(3);
int entryCount = is.readInt32();
for (int i = 0; i < entryCount; i++) {
int entryFlag = is.readInt32();
}
if (is.getPos() != expectedEndPos) {
throw new IOException(String.format("Error reading type spec chunk at offset 0x%x", chunkStart));
}
}
private void parseLibraryTypeChunk(long chunkStart) throws IOException {
LOG.trace("parsing library type chunk starting at offset {}", chunkStart);
is.checkInt16(12, "Unexpected header size");
int chunkSize = is.readInt32();
long expectedEndPos = chunkStart + chunkSize;
int count = is.readInt32();
for (int i = 0; i < count; i++) {
int packageId = is.readInt32();
String packageName = is.readString16Fixed(128);
LOG.info("Found resource shared library {}, pkgId: {}", packageName, packageId);
if (is.getPos() > expectedEndPos) {
throw new IOException("reading after chunk end");
}
}
if (is.getPos() != expectedEndPos) {
throw new IOException(String.format("Error reading library chunk at offset 0x%x", chunkStart));
}
}
/**
* Parse an <code>ResTable_type</code> (except for the 2 bytes <code>uint16_t</code>
* from <code>ResChunk_header</code>).
*
* @see <a href=
* "https://github.com/aosp-mirror/platform_frameworks_base/blob/master/libs/androidfw/include/androidfw/ResourceTypes.h"></a>ResourceTypes.h</a>
*/
private void parseTypeChunk(long start, PackageChunk pkg) throws IOException {
/* int headerSize = */
is.readInt16();
/* int size = */
long chunkSize = is.readUInt32();
long chunkEnd = start + chunkSize;
is.mark((int) chunkSize);
// The type identifier this chunk is holding. Type IDs start at 1 (corresponding
// to the value of the type bits in a resource identifier). 0 is invalid.
int id = is.readInt8();
String typeName = pkg.getTypeStrings().get(id - 1);
int flags = is.readInt8();
boolean isSparse = (flags & FLAG_SPARSE) != 0;
boolean isOffset16 = (flags & FLAG_OFFSET16) != 0;
is.readInt16(); // ignore reserved value - should be zero but in some apps it is not zero; see #2402
int entryCount = is.readInt32();
long entriesStart = start + is.readInt32();
EntryConfig config = parseConfig();
if (config.isInvalid) {
LOG.warn("Invalid config flags detected: {}{}", typeName, config.getQualifiers());
}
List<EntryOffset> offsets = new ArrayList<>(entryCount);
if (isSparse) {
for (int i = 0; i < entryCount; i++) {
int idx = is.readInt16();
int offset = is.readInt16() * 4; // The offset in ResTable_sparseTypeEntry::offset is stored divided by 4.
offsets.add(new EntryOffset(idx, offset));
}
} else if (isOffset16) {
for (int i = 0; i < entryCount; i++) {
int offset = is.readInt16();
if (offset != 0xFFFF) {
offsets.add(new EntryOffset(i, offset * 4));
}
}
} else {
for (int i = 0; i < entryCount; i++) {
offsets.add(new EntryOffset(i, is.readInt32()));
}
}
is.skipToPos(entriesStart, "Failed to skip to entries start");
int ignoredEoc = 0; // ignored entries because they are located after end of chunk
for (EntryOffset entryOffset : offsets) {
int offset = entryOffset.getOffset();
if (offset == NO_ENTRY) {
continue;
}
long entryStartOffset = entriesStart + offset;
if (entryStartOffset >= chunkEnd) {
// Certain resource obfuscated apps like com.facebook.orca have more entries defined
// than actually fit into the chunk size -> ignore this entry
ignoredEoc++;
// LOG.debug("Pos is after chunk end: {} end {}", entryStartOffset, chunkEnd);
continue;
}
if (entryStartOffset < is.getPos()) {
// workaround for issue #2343: if the entryStartOffset is located before our current position
is.reset();
}
int index = entryOffset.getIdx();
is.skipToPos(entryStartOffset, "Expected start of entry " + index);
parseEntry(pkg, id, index, config.getQualifiers());
}
if (ignoredEoc > 0) {
// invalid = data offset is after the chunk end
LOG.warn("{} entries of type {} has been ignored (invalid offset)", ignoredEoc, typeName);
}
is.skipToPos(chunkEnd, "End of chunk");
}
private static class EntryOffset {
private final int idx;
private final int offset;
private EntryOffset(int idx, int offset) {
this.idx = idx;
this.offset = offset;
}
public int getIdx() {
return idx;
}
public int getOffset() {
return offset;
}
}
private void parseOverlayTypeChunk(long chunkStart) throws IOException {
LOG.trace("parsing overlay type chunk starting at offset {}", chunkStart);
// read ResTable_overlayable_header
/* headerSize = */
is.readInt16(); // usually 1032 bytes
int chunkSize = is.readInt32(); // e.g. 1056 bytes
long expectedEndPos = chunkStart + chunkSize;
String name = is.readString16Fixed(256); // 512 bytes
String actor = is.readString16Fixed(256); // 512 bytes
LOG.trace("Overlay header data: name={} actor={}", name, actor);
// skip: ResTable_overlayable_policy_header + ResTable_ref * x
is.skipToPos(expectedEndPos, "overlay chunk end");
}
private void parseStagedAliasChunk(long chunkStart) throws IOException {
// read ResTable_staged_alias_header
LOG.trace("parsing staged alias chunk starting at offset {}", chunkStart);
/* headerSize = */
is.readInt16();
int chunkSize = is.readInt32();
long expectedEndPos = chunkStart + chunkSize;
int count = is.readInt32();
for (int i = 0; i < count; i++) {
// read ResTable_staged_alias_entry
int stagedResId = is.readInt32();
int finalizedResId = is.readInt32();
LOG.debug("Staged alias: stagedResId {} finalizedResId {}", stagedResId, finalizedResId);
}
is.skipToPos(expectedEndPos, "staged alias chunk end");
}
private void parseEntry(PackageChunk pkg, int typeId, int entryId, String config) throws IOException {
int size = is.readInt16();
int flags = is.readInt16();
boolean isComplex = (flags & FLAG_COMPLEX) != 0;
boolean isCompact = (flags & FLAG_COMPACT) != 0;
int key = isCompact ? size : is.readInt32();
if (key == -1) {
return;
}
int resRef = pkg.getId() << 24 | typeId << 16 | entryId;
String typeName = pkg.getTypeStrings().get(typeId - 1);
String origKeyName = pkg.getKeyStrings().get(key);
ResourceEntry newResEntry = buildResourceEntry(pkg, config, resRef, typeName, origKeyName);
if (isCompact) {
int dataType = flags >> 8;
int data = is.readInt32();
newResEntry.setSimpleValue(new RawValue(dataType, data));
} else if (isComplex || size == 16) {
int parentRef = is.readInt32();
int count = is.readInt32();
newResEntry.setParentRef(parentRef);
List<RawNamedValue> values = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
values.add(parseValueMap());
}
newResEntry.setNamedValues(values);
} else {
newResEntry.setSimpleValue(parseValue());
}
}
private static final ResourceEntry STUB_ENTRY = new ResourceEntry(-1, "stub", "stub", "stub", "");
private ResourceEntry buildResourceEntry(PackageChunk pkg, String config, int resRef, String typeName, String origKeyName) {
if (!root.getArgs().getSecurity().isValidEntryName(origKeyName)) {
// malicious entry, ignore it
// can't return null here, return stub without adding it to storage
return STUB_ENTRY;
}
ResourceEntry newResEntry;
if (useRawResName) {
newResEntry = new ResourceEntry(resRef, pkg.getName(), typeName, origKeyName, config);
} else {
String resName = getResName(resRef, origKeyName);
newResEntry = new ResourceEntry(resRef, pkg.getName(), typeName, resName, config);
ResourceEntry prevResEntry = resStorage.searchEntryWithSameName(newResEntry);
if (prevResEntry != null) {
newResEntry = newResEntry.copyWithId();
// rename also previous entry for consistency
ResourceEntry replaceForPrevEntry = prevResEntry.copyWithId();
resStorage.replace(prevResEntry, replaceForPrevEntry);
resStorage.addRename(replaceForPrevEntry);
}
if (!Objects.equals(origKeyName, newResEntry.getKeyName())) {
resStorage.addRename(newResEntry);
}
}
resStorage.add(newResEntry);
return newResEntry;
}
private String getResName(int resRef, String origKeyName) {
if (this.useRawResName) {
return origKeyName;
}
String renamedKey = resStorage.getRename(resRef);
if (renamedKey != null) {
return renamedKey;
}
IFieldInfoRef fldRef = root.getConstValues().getGlobalConstFields().get(resRef);
FieldNode constField = fldRef instanceof FieldNode ? (FieldNode) fldRef : null;
String newResName = getNewResName(resRef, origKeyName, constField);
if (!origKeyName.equals(newResName)) {
resStorage.addRename(resRef, newResName);
}
if (constField != null) {
final String newFieldName = ResNameUtils.convertToRFieldName(newResName);
constField.rename(newFieldName);
constField.add(AFlag.DONT_RENAME);
}
return newResName;
}
private String getNewResName(int resRef, String origKeyName, @Nullable FieldNode constField) {
String newResName;
if (constField == null || constField.getTopParentClass().isSynthetic()) {
newResName = origKeyName;
} else {
newResName = getBetterName(root.getArgs().getResourceNameSource(), origKeyName, constField.getName());
}
if (root.getArgs().isRenameValid()) {
final boolean allowNonPrintable = !root.getArgs().isRenamePrintable();
newResName = ResNameUtils.sanitizeAsResourceName(newResName, String.format("_res_0x%08x", resRef), allowNonPrintable);
}
return newResName;
}
public static String getBetterName(ResourceNameSource nameSource, String resName, String codeName) {
switch (nameSource) {
case AUTO:
return BetterName.getBetterResourceName(resName, codeName);
case RESOURCES:
return resName;
case CODE:
return codeName;
default:
throw new JadxRuntimeException("Unexpected ResourceNameSource value: " + nameSource);
}
}
private RawNamedValue parseValueMap() throws IOException {
int nameRef = is.readInt32();
return new RawNamedValue(nameRef, parseValue());
}
private RawValue parseValue() throws IOException {
is.checkInt16(8, "value size");
is.checkInt8(0, "value res0 not 0");
int dataType = is.readInt8();
int data = is.readInt32();
return new RawValue(dataType, data);
}
private EntryConfig parseConfig() throws IOException {
long start = is.getPos();
int size = is.readInt32();
if (size < 4) {
throw new IOException("Config size < 4");
}
// Android zero fill this structure and only read the data present
var configData = new byte[Math.max(52, size - 4)];
is.readFully(configData, 0, size - 4);
var configIs = new ParserStream(new ByteArrayInputStream(configData));
short mcc = (short) configIs.readInt16();
short mnc = (short) configIs.readInt16();
char[] language = unpackLocaleOrRegion((byte) configIs.readInt8(), (byte) configIs.readInt8(), 'a');
char[] country = unpackLocaleOrRegion((byte) configIs.readInt8(), (byte) configIs.readInt8(), '0');
byte orientation = (byte) configIs.readInt8();
byte touchscreen = (byte) configIs.readInt8();
int density = configIs.readInt16();
byte keyboard = (byte) configIs.readInt8();
byte navigation = (byte) configIs.readInt8();
byte inputFlags = (byte) configIs.readInt8();
byte grammaticalInflection = (byte) configIs.readInt8();
short screenWidth = (short) configIs.readInt16();
short screenHeight = (short) configIs.readInt16();
short sdkVersion = (short) configIs.readInt16();
configIs.readInt16(); // minorVersion must always be 0
byte screenLayout = (byte) configIs.readInt8();
byte uiMode = (byte) configIs.readInt8();
short smallestScreenWidthDp = (short) configIs.readInt16();
short screenWidthDp = (short) configIs.readInt16();
short screenHeightDp = (short) configIs.readInt16();
char[] localeScript = readScriptOrVariantChar(4, configIs).toCharArray();
char[] localeVariant = readScriptOrVariantChar(8, configIs).toCharArray();
byte screenLayout2 = (byte) configIs.readInt8();
byte colorMode = (byte) configIs.readInt8();
configIs.readInt16(); // reserved padding
is.checkPos(start + size, "Config skip trailing bytes");
return new EntryConfig(mcc, mnc, language, country,
orientation, touchscreen, density, keyboard, navigation,
inputFlags, grammaticalInflection, screenWidth, screenHeight, sdkVersion,
screenLayout, uiMode, smallestScreenWidthDp, screenWidthDp,
screenHeightDp,
localeScript.length == 0 ? null : localeScript,
localeVariant.length == 0 ? null : localeVariant,
screenLayout2,
colorMode, false, size);
}
private char[] unpackLocaleOrRegion(byte in0, byte in1, char base) {
// check high bit, if so we have a packed 3 letter code
if (((in0 >> 7) & 1) == 1) {
int first = in1 & 0x1F;
int second = ((in1 & 0xE0) >> 5) + ((in0 & 0x03) << 3);
int third = (in0 & 0x7C) >> 2;
// since this function handles languages & regions, we add the value(s) to the base char
// which is usually 'a' or '0' depending on language or region.
return new char[] { (char) (first + base), (char) (second + base), (char) (third + base) };
}
return new char[] { (char) in0, (char) in1 };
}
private String readScriptOrVariantChar(int length) throws IOException {
return readScriptOrVariantChar(length, is);
}
private static String readScriptOrVariantChar(int length, ParserStream ps) throws IOException {
long start = ps.getPos();
StringBuilder sb = new StringBuilder(16);
for (int i = 0; i < length; i++) {
short ch = (short) ps.readInt8();
if (ch == 0) {
break;
}
sb.append((char) ch);
}
ps.skipToPos(start + length, "readScriptOrVariantChar");
return sb.toString();
}
@Override
public ResourceStorage getResStorage() {
return resStorage;
}
@Override
public BinaryXMLStrings getStrings() {
return strings;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/ParserStream.java | jadx-core/src/main/java/jadx/core/xmlgen/ParserStream.java | package jadx.core.xmlgen;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.jetbrains.annotations.NotNull;
public class ParserStream extends InputStream {
protected static final Charset STRING_CHARSET_UTF16 = StandardCharsets.UTF_16LE;
protected static final Charset STRING_CHARSET_UTF8 = StandardCharsets.UTF_8;
private static final int[] EMPTY_INT_ARRAY = new int[0];
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private final InputStream input;
private long readPos = 0;
private long markPos = 0;
public ParserStream(@NotNull InputStream inputStream) {
this.input = inputStream.markSupported() ? inputStream : new BufferedInputStream(inputStream);
}
public long getPos() {
return readPos;
}
public int readInt8() throws IOException {
readPos++;
return input.read();
}
public int readInt16() throws IOException {
readPos += 2;
int b1 = input.read();
int b2 = input.read();
return (b2 & 0xFF) << 8 | b1 & 0xFF;
}
public int readInt32() throws IOException {
readPos += 4;
InputStream in = input;
int b1 = in.read();
int b2 = in.read();
int b3 = in.read();
int b4 = in.read();
return b4 << 24 | (b3 & 0xFF) << 16 | (b2 & 0xFF) << 8 | b1 & 0xFF;
}
public long readUInt32() throws IOException {
return readInt32() & 0xFFFFFFFFL;
}
public String readString16Fixed(int len) throws IOException {
String str = new String(readInt8Array(len * 2), STRING_CHARSET_UTF16);
return str.trim();
}
public int[] readInt32Array(int count) throws IOException {
if (count == 0) {
return EMPTY_INT_ARRAY;
}
int[] arr = new int[count];
for (int i = 0; i < count; i++) {
arr[i] = readInt32();
}
return arr;
}
public byte[] readInt8Array(int count) throws IOException {
if (count == 0) {
return EMPTY_BYTE_ARRAY;
}
readPos += count;
byte[] arr = new byte[count];
int pos = input.read(arr, 0, count);
while (pos < count) {
int read = input.read(arr, pos, count - pos);
if (read == -1) {
throw new IOException("No data, can't read " + count + " bytes");
}
pos += read;
}
return arr;
}
@Override
public long skip(long count) throws IOException {
readPos += count;
long pos = input.skip(count);
while (pos < count) {
long skipped = input.skip(count - pos);
if (skipped == 0) {
throw new IOException("No data, can't skip " + count + " bytes");
}
pos += skipped;
}
return pos;
}
public void checkInt8(int expected, String error) throws IOException {
int v = readInt8();
if (v != expected) {
throwException(error, expected, v);
}
}
public void checkInt16(int expected, String error) throws IOException {
int v = readInt16();
if (v != expected) {
throwException(error, expected, v);
}
}
private void throwException(String error, int expected, int actual) throws IOException {
throw new IOException(error
+ ", expected: 0x" + Integer.toHexString(expected)
+ ", actual: 0x" + Integer.toHexString(actual)
+ ", offset: 0x" + Long.toHexString(getPos()));
}
public void checkPos(long expectedOffset, String error) throws IOException {
if (getPos() != expectedOffset) {
throw new IOException(error + ", expected offset: 0x" + Long.toHexString(expectedOffset)
+ ", actual: 0x" + Long.toHexString(getPos()));
}
}
public void skipToPos(long expectedOffset, String error) throws IOException {
long pos = getPos();
if (pos > expectedOffset) {
throw new IOException(error + ", expected offset not reachable: 0x" + Long.toHexString(expectedOffset)
+ ", actual: 0x" + Long.toHexString(getPos()));
}
if (pos < expectedOffset) {
skip(expectedOffset - pos);
}
checkPos(expectedOffset, error);
}
@Override
public void mark(int len) {
if (!input.markSupported()) {
throw new RuntimeException("Mark not supported for input stream " + input.getClass());
}
input.mark(len);
markPos = readPos;
}
@Override
public void reset() throws IOException {
input.reset();
readPos = markPos;
}
public void readFully(byte[] b) throws IOException {
readFully(b, 0, b.length);
}
public void readFully(byte[] b, int off, int len) throws IOException {
readPos += len;
if (len < 0) {
throw new IndexOutOfBoundsException();
}
int n = 0;
while (n < len) {
int count = input.read(b, off + n, len - n);
if (count < 0) {
throw new EOFException();
}
n += count;
}
}
@Override
public int read() throws IOException {
return input.read();
}
@Override
public int read(@NotNull byte[] b, int off, int len) throws IOException {
return input.read(b, off, len);
}
@Override
public String toString() {
return "pos: 0x" + Long.toHexString(readPos);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/XmlDeobf.java | jadx-core/src/main/java/jadx/core/xmlgen/XmlDeobf.java | package jadx.core.xmlgen;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.RootNode;
/*
* Modifies android:name attributes and xml tags which were changed during deobfuscation
*/
public class XmlDeobf {
private XmlDeobf() {
}
@Nullable
public static String deobfClassName(RootNode root, String potentialClassName, String packageName) {
if (potentialClassName.indexOf('.') == -1) {
return null;
}
if (packageName != null && potentialClassName.startsWith(".")) {
potentialClassName = packageName + potentialClassName;
}
ArgType clsType = ArgType.object(potentialClassName);
ClassInfo classInfo = root.getInfoStorage().getCls(clsType);
if (classInfo == null) {
// unknown class reference
return null;
}
return classInfo.getAliasFullName();
}
public static boolean isDuplicatedAttr(String attrFullName, Set<String> attrCache) {
return !attrCache.add(attrFullName);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/ResXmlGen.java | jadx-core/src/main/java/jadx/core/xmlgen/ResXmlGen.java | package jadx.core.xmlgen;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jadx.api.ICodeInfo;
import jadx.api.ICodeWriter;
import jadx.api.JadxArgs;
import jadx.api.impl.SimpleCodeWriter;
import jadx.core.utils.StringUtils;
import jadx.core.xmlgen.entry.ProtoValue;
import jadx.core.xmlgen.entry.RawNamedValue;
import jadx.core.xmlgen.entry.ResourceEntry;
import jadx.core.xmlgen.entry.ValuesParser;
import static jadx.core.xmlgen.ParserConstants.PLURALS_MAP;
import static jadx.core.xmlgen.ParserConstants.TYPE_REFERENCE;
public class ResXmlGen {
/**
* Skip only file based resource type
*/
private static final Set<String> SKIP_RES_TYPES = new HashSet<>(Arrays.asList(
"anim",
"animator",
"font",
"id", // skip id type, it is usually auto generated when used this syntax "@+id/my_id"
"interpolator",
"layout",
"menu",
"mipmap",
"navigation",
"raw",
"transition",
"xml"));
private final ResourceStorage resStorage;
private final ValuesParser vp;
private final ManifestAttributes manifestAttributes;
public ResXmlGen(ResourceStorage resStorage, ValuesParser vp, ManifestAttributes manifestAttributes) {
this.resStorage = resStorage;
this.vp = vp;
this.manifestAttributes = manifestAttributes;
}
public List<ResContainer> makeResourcesXml(JadxArgs args) {
Map<String, ICodeWriter> contMap = new HashMap<>();
for (ResourceEntry ri : resStorage.getResources()) {
if (SKIP_RES_TYPES.contains(ri.getTypeName())) {
continue;
}
String fn = getFileName(ri);
ICodeWriter cw = contMap.get(fn);
if (cw == null) {
cw = new SimpleCodeWriter(args);
cw.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
cw.startLine("<resources>");
cw.incIndent();
contMap.put(fn, cw);
}
addValue(cw, ri);
}
List<ResContainer> files = new ArrayList<>(contMap.size());
for (Map.Entry<String, ICodeWriter> entry : contMap.entrySet()) {
String fileName = entry.getKey();
ICodeWriter content = entry.getValue();
content.decIndent();
content.startLine("</resources>");
ICodeInfo codeInfo = content.finish();
files.add(ResContainer.textResource(fileName, codeInfo));
}
Collections.sort(files);
return files;
}
private void addValue(ICodeWriter cw, ResourceEntry ri) {
if (ri.getProtoValue() != null) {
ProtoValue protoValue = ri.getProtoValue();
if (protoValue.getValue() != null && protoValue.getNamedValues() == null) {
addSimpleValue(cw, ri.getTypeName(), ri.getTypeName(), "name", ri.getKeyName(), protoValue.getValue());
} else {
cw.startLine();
cw.add('<').add(ri.getTypeName()).add(' ');
String itemTag = "item";
cw.add("name=\"").add(ri.getKeyName()).add('\"');
if (ri.getTypeName().equals("attr") && protoValue.getValue() != null) {
cw.add(" format=\"").add(protoValue.getValue()).add('\"');
}
if (protoValue.getParent() != null) {
cw.add(" parent=\"").add(protoValue.getParent()).add('\"');
}
cw.add(">");
cw.incIndent();
for (ProtoValue value : protoValue.getNamedValues()) {
addProtoItem(cw, itemTag, ri.getTypeName(), value);
}
cw.decIndent();
cw.startLine().add("</").add(ri.getTypeName()).add('>');
}
} else if (ri.getSimpleValue() != null) {
String valueStr = vp.decodeValue(ri.getSimpleValue());
addSimpleValue(cw, ri.getTypeName(), ri.getTypeName(), "name", ri.getKeyName(), valueStr);
} else {
boolean skipNamedValues = false;
cw.startLine();
cw.add('<').add(ri.getTypeName()).add(" name=\"");
String itemTag = "item";
if (ri.getTypeName().equals("attr") && !ri.getNamedValues().isEmpty()) {
cw.add(ri.getKeyName());
int type = ri.getNamedValues().get(0).getRawValue().getData();
if ((type & ValuesParser.ATTR_TYPE_ENUM) != 0) {
itemTag = "enum";
} else if ((type & ValuesParser.ATTR_TYPE_FLAGS) != 0) {
itemTag = "flag";
}
String formatValue = XmlGenUtils.getAttrTypeAsString(type);
if (formatValue != null) {
cw.add("\" format=\"").add(formatValue);
}
if (ri.getNamedValues().size() > 1) {
for (RawNamedValue rv : ri.getNamedValues()) {
if (rv.getNameRef() == ParserConstants.ATTR_MIN) {
cw.add("\" min=\"").add(String.valueOf(rv.getRawValue().getData()));
skipNamedValues = true;
}
}
}
} else {
cw.add(ri.getKeyName());
}
if (ri.getTypeName().equals("style") || ri.getParentRef() != 0) {
cw.add("\" parent=\"");
if (ri.getParentRef() != 0) {
String parent = vp.decodeValue(TYPE_REFERENCE, ri.getParentRef());
cw.add(parent);
}
}
cw.add("\">");
if (!skipNamedValues) {
cw.incIndent();
for (RawNamedValue value : ri.getNamedValues()) {
addItem(cw, itemTag, ri.getTypeName(), value);
}
cw.decIndent();
}
cw.startLine().add("</").add(ri.getTypeName()).add('>');
}
}
private void addProtoItem(ICodeWriter cw, String itemTag, String typeName, ProtoValue protoValue) {
String name = protoValue.getName();
String value = protoValue.getValue();
switch (typeName) {
case "attr":
if (name != null) {
addSimpleValue(cw, typeName, itemTag, name, value, "");
}
break;
case "style":
if (name != null) {
addSimpleValue(cw, typeName, itemTag, name, "", value);
}
break;
case "plurals":
addSimpleValue(cw, typeName, itemTag, "quantity", name, value);
break;
default:
addSimpleValue(cw, typeName, itemTag, null, null, value);
break;
}
}
private void addItem(ICodeWriter cw, String itemTag, String typeName, RawNamedValue value) {
String nameStr = vp.decodeNameRef(value.getNameRef());
String valueStr = vp.decodeValue(value.getRawValue());
int dataType = value.getRawValue().getDataType();
if (!typeName.equals("attr")) {
if (dataType == ParserConstants.TYPE_REFERENCE && (valueStr == null || valueStr.equals("0"))) {
valueStr = "@null";
}
if (dataType == ParserConstants.TYPE_INT_DEC && nameStr != null) {
try {
int intVal = Integer.parseInt(valueStr);
String newVal = manifestAttributes.decode(nameStr.replace("android:", "").replace("attr.", ""), intVal);
if (newVal != null) {
valueStr = newVal;
}
} catch (NumberFormatException e) {
// ignore
}
}
if (dataType == ParserConstants.TYPE_INT_HEX && nameStr != null) {
try {
int intVal = Integer.decode(valueStr);
String newVal = manifestAttributes.decode(nameStr.replace("android:", "").replace("attr.", ""), intVal);
if (newVal != null) {
valueStr = newVal;
}
} catch (NumberFormatException e) {
// ignore
}
}
}
switch (typeName) {
case "attr":
if (nameStr != null) {
addSimpleValue(cw, typeName, itemTag, nameStr, valueStr, "");
}
break;
case "style":
if (nameStr != null) {
addSimpleValue(cw, typeName, itemTag, nameStr, "", valueStr);
}
break;
case "plurals":
final String quantity = PLURALS_MAP.get(value.getNameRef());
addSimpleValue(cw, typeName, itemTag, "quantity", quantity, valueStr);
break;
default:
addSimpleValue(cw, typeName, itemTag, null, null, valueStr);
break;
}
}
private void addSimpleValue(ICodeWriter cw, String typeName, String itemTag, String attrName, String attrValue, String valueStr) {
if (valueStr == null) {
return;
}
if (valueStr.startsWith("res/")) {
// remove duplicated resources.
return;
}
cw.startLine();
cw.add('<').add(itemTag);
if (attrName != null && attrValue != null) {
if (typeName.equals("attr")) {
cw.add(' ').add("name=\"").add(attrName.replace("id.", "")).add("\" value=\"").add(attrValue).add('"');
} else if (typeName.equals("style")) {
cw.add(' ').add("name=\"").add(attrName.replace("attr.", "")).add('"');
} else {
cw.add(' ').add(attrName).add("=\"").add(attrValue).add('"');
}
}
if (itemTag.equals("string") && valueStr.contains("%") && StringFormattedCheck.hasMultipleNonPositionalSubstitutions(valueStr)) {
cw.add(" formatted=\"false\"");
}
if (valueStr.isEmpty()) {
cw.add(" />");
} else {
cw.add('>');
if (itemTag.equals("string") || (typeName.equals("array") && valueStr.charAt(0) != '@')) {
cw.add(StringUtils.escapeResStrValue(valueStr));
} else {
cw.add(StringUtils.escapeResValue(valueStr));
}
cw.add("</").add(itemTag).add('>');
}
}
private String getFileName(ResourceEntry ri) {
StringBuilder sb = new StringBuilder();
String qualifiers = ri.getConfig();
sb.append("res/values");
if (!qualifiers.isEmpty()) {
sb.append(qualifiers);
}
sb.append('/');
sb.append(ri.getTypeName());
if (!ri.getTypeName().endsWith("s")) {
sb.append('s');
}
sb.append(".xml");
return sb.toString();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/CommonBinaryParser.java | jadx-core/src/main/java/jadx/core/xmlgen/CommonBinaryParser.java | package jadx.core.xmlgen;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CommonBinaryParser extends ParserConstants {
private static final Logger LOG = LoggerFactory.getLogger(CommonBinaryParser.class);
protected ParserStream is;
protected BinaryXMLStrings parseStringPool() throws IOException {
is.checkInt16(RES_STRING_POOL_TYPE, "String pool expected");
return parseStringPoolNoType();
}
protected BinaryXMLStrings parseStringPoolNoType() throws IOException {
long start = is.getPos() - 2;
int headerSize = is.readInt16();
if (headerSize != 0x1c) {
LOG.warn("Unexpected string pool header size: 0x{}, expected: 0x1C", Integer.toHexString(headerSize));
}
long size = is.readUInt32();
long chunkEnd = start + size;
return parseStringPoolNoSize(start, chunkEnd);
}
protected BinaryXMLStrings parseStringPoolNoSize(long start, long chunkEnd) throws IOException {
int stringCount = is.readInt32();
int styleCount = is.readInt32();
int flags = is.readInt32();
long stringsStart = is.readInt32();
long stylesStart = is.readInt32();
// Correct the offset of actual strings, as the header is already read.
stringsStart = stringsStart - (is.getPos() - start);
byte[] buffer = is.readInt8Array((int) (chunkEnd - is.getPos()));
is.checkPos(chunkEnd, "Expected strings pool end");
return new BinaryXMLStrings(
stringCount,
stringsStart,
buffer,
(flags & UTF8_FLAG) != 0);
}
protected void die(String message) throws IOException {
throw new IOException("Decode error: " + message
+ ", position: 0x" + Long.toHexString(is.getPos()));
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/ResourceStorage.java | jadx-core/src/main/java/jadx/core/xmlgen/ResourceStorage.java | package jadx.core.xmlgen;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import jadx.api.security.IJadxSecurity;
import jadx.core.xmlgen.entry.ResourceEntry;
public class ResourceStorage {
private static final Comparator<ResourceEntry> RES_ENTRY_NAME_COMPARATOR = Comparator
.comparing(ResourceEntry::getConfig)
.thenComparing(ResourceEntry::getTypeName)
.thenComparing(ResourceEntry::getKeyName);
private final List<ResourceEntry> list = new ArrayList<>();
private final IJadxSecurity security;
private String appPackage;
/**
* Names in one config and type must be unique
*/
private final Map<ResourceEntry, ResourceEntry> uniqNameEntries = new TreeMap<>(RES_ENTRY_NAME_COMPARATOR);
/**
* Preserve same name for same id across different configs
*/
private final Map<Integer, String> renames = new HashMap<>();
public ResourceStorage(IJadxSecurity security) {
this.security = security;
}
public void add(ResourceEntry resEntry) {
list.add(resEntry);
uniqNameEntries.put(resEntry, resEntry);
}
public void replace(ResourceEntry prevResEntry, ResourceEntry newResEntry) {
int idx = list.indexOf(prevResEntry);
if (idx != -1) {
list.set(idx, newResEntry);
}
// don't remove from unique names so old name stays occupied
}
public void addRename(ResourceEntry entry) {
addRename(entry.getId(), entry.getKeyName());
}
public void addRename(int id, String keyName) {
renames.put(id, keyName);
}
public String getRename(int id) {
return renames.get(id);
}
public ResourceEntry searchEntryWithSameName(ResourceEntry resourceEntry) {
return uniqNameEntries.get(resourceEntry);
}
public void finish() {
list.sort(Comparator.comparingInt(ResourceEntry::getId));
uniqNameEntries.clear();
renames.clear();
}
public int size() {
return list.size();
}
public Iterable<ResourceEntry> getResources() {
return list;
}
public String getAppPackage() {
return appPackage;
}
public void setAppPackage(String appPackage) {
this.appPackage = security.verifyAppPackage(appPackage);
}
public Map<Integer, String> getResourcesNames() {
Map<Integer, String> map = new HashMap<>();
for (ResourceEntry entry : list) {
map.put(entry.getId(), entry.getTypeName() + '/' + entry.getKeyName());
}
return map;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/BinaryXMLStrings.java | jadx-core/src/main/java/jadx/core/xmlgen/BinaryXMLStrings.java | package jadx.core.xmlgen;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class BinaryXMLStrings {
public static final String INVALID_STRING_PLACEHOLDER = "⟨STRING_DECODE_ERROR⟩";
private final int stringCount;
private final long stringsStart;
private final ByteBuffer buffer;
private final boolean isUtf8;
// This cache include strings that have been overridden by the deobfuscator.
private final Map<Integer, String> cache = new HashMap<>();
public BinaryXMLStrings() {
stringCount = 0;
stringsStart = 0;
buffer = ByteBuffer.allocate(0);
buffer.order(ByteOrder.LITTLE_ENDIAN);
isUtf8 = false;
}
public BinaryXMLStrings(int stringCount, long stringsStart, byte[] buffer, boolean isUtf8) {
this.stringCount = stringCount;
this.stringsStart = stringsStart;
this.buffer = ByteBuffer.wrap(buffer);
this.buffer.order(ByteOrder.LITTLE_ENDIAN);
this.isUtf8 = isUtf8;
}
public String get(int id) {
String cached = cache.get(id);
if (cached != null) {
return cached;
}
if (id * 4 >= buffer.limit() - 3) {
return INVALID_STRING_PLACEHOLDER;
}
long offset = stringsStart + buffer.getInt(id * 4);
String extracted;
if (isUtf8) {
extracted = extractString8(this.buffer.array(), (int) offset);
} else {
// don't trust specified string length, read until \0
// stringsOffset can be same for different indexes
extracted = extractString16(this.buffer.array(), (int) offset);
}
cache.put(id, extracted);
return extracted;
}
public void put(int id, String content) {
cache.put(id, content);
}
public int size() {
return this.stringCount;
}
private static String extractString8(byte[] strArray, int offset) {
if (offset >= strArray.length) {
return INVALID_STRING_PLACEHOLDER;
}
int start = offset + skipStrLen8(strArray, offset);
int len = strArray[start++];
if (len == 0) {
return "";
}
if ((len & 0x80) != 0) {
len = (len & 0x7F) << 8 | strArray[start++] & 0xFF;
}
byte[] arr = Arrays.copyOfRange(strArray, start, start + len);
return new String(arr, ParserStream.STRING_CHARSET_UTF8);
}
private static String extractString16(byte[] strArray, int offset) {
if (offset + 2 >= strArray.length) {
return INVALID_STRING_PLACEHOLDER;
}
int len = strArray.length;
int start = offset + skipStrLen16(strArray, offset);
int end = start;
while (true) {
if (end + 1 >= len) {
break;
}
if (strArray[end] == 0 && strArray[end + 1] == 0) {
break;
}
end += 2;
}
byte[] arr = Arrays.copyOfRange(strArray, start, end);
return new String(arr, ParserStream.STRING_CHARSET_UTF16);
}
private static int skipStrLen8(byte[] strArray, int offset) {
return (strArray[offset] & 0x80) == 0 ? 1 : 2;
}
private static int skipStrLen16(byte[] strArray, int offset) {
return (strArray[offset + 1] & 0x80) == 0 ? 2 : 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/main/java/jadx/core/xmlgen/ResourcesSaver.java | jadx-core/src/main/java/jadx/core/xmlgen/ResourcesSaver.java | package jadx.core.xmlgen;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.JadxDecompiler;
import jadx.api.ResourceFile;
import jadx.api.ResourcesLoader;
import jadx.api.security.IJadxSecurity;
import jadx.core.dex.visitors.SaveCode;
import jadx.core.utils.exceptions.JadxException;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.utils.files.FileUtils;
public class ResourcesSaver implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(ResourcesSaver.class);
private final ResourceFile resourceFile;
private final File outDir;
private final IJadxSecurity security;
public ResourcesSaver(JadxDecompiler decompiler, File outDir, ResourceFile resourceFile) {
this.resourceFile = resourceFile;
this.outDir = outDir;
this.security = decompiler.getArgs().getSecurity();
}
@Override
public void run() {
try {
saveResources(resourceFile.loadContent());
} catch (StackOverflowError | Exception e) {
LOG.warn("Failed to save resource: {}", resourceFile.getOriginalName(), e);
}
}
private void saveResources(ResContainer rc) {
if (rc == null) {
return;
}
if (rc.getDataType() == ResContainer.DataType.RES_TABLE) {
saveToFile(rc, new File(outDir, "res/values/public.xml"));
for (ResContainer subFile : rc.getSubFiles()) {
saveResources(subFile);
}
} else {
save(rc, outDir);
}
}
private void save(ResContainer rc, File outDir) {
File outFile = new File(outDir, rc.getFileName());
if (!security.isInSubDirectory(outDir, outFile)) {
LOG.error("Invalid resource name or path traversal attack detected: {}", outFile.getPath());
return;
}
saveToFile(rc, outFile);
}
private void saveToFile(ResContainer rc, File outFile) {
switch (rc.getDataType()) {
case TEXT:
case RES_TABLE:
SaveCode.save(rc.getText(), outFile);
return;
case DECODED_DATA:
byte[] data = rc.getDecodedData();
FileUtils.makeDirsForFile(outFile);
try {
Files.write(outFile.toPath(), data);
} catch (Exception e) {
LOG.warn("Resource '{}' not saved, got exception", rc.getName(), e);
}
return;
case RES_LINK:
ResourceFile resFile = rc.getResLink();
FileUtils.makeDirsForFile(outFile);
try {
saveResourceFile(resFile, outFile);
} catch (Exception e) {
LOG.warn("Resource '{}' not saved, got exception", rc.getName(), e);
}
return;
default:
LOG.warn("Resource '{}' not saved, unknown type", rc.getName());
break;
}
}
private void saveResourceFile(ResourceFile resFile, File outFile) throws JadxException {
ResourcesLoader.decodeStream(resFile, (size, is) -> {
Path target = outFile.toPath();
try {
Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
Files.deleteIfExists(target); // delete partially written file
throw new JadxRuntimeException("Resource file save error", e);
}
return null;
});
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/XMLChar.java | jadx-core/src/main/java/jadx/core/xmlgen/XMLChar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jadx.core.xmlgen;
import java.util.Arrays;
/**
* This class defines the basic XML character properties. The data
* in this class can be used to verify that a character is a valid
* XML character or if the character is a space, name start, or name
* character.
* <p>
* A series of convenience methods are supplied to ease the burden
* of the developer. Because inlining the checks can improve per
* character performance, the tables of character properties are
* public. Using the character as an index into the <code>CHARS</code>
* array and applying the appropriate mask flag (e.g.
* <code>MASK_VALID</code>), yields the same results as calling the
* convenience methods. There is one exception: check the comments
* for the <code>isValid</code> method for details.
*
* @author Glenn Marcy, IBM
* @author Andy Clark, IBM
* @author Eric Ye, IBM
* @author Arnaud Le Hors, IBM
* @author Michael Glavassevich, IBM
* @author Rahul Srivastava, Sun Microsystems Inc.
* @version $Id: XMLChar.java 674378 2008-07-07 00:52:45Z mrglavas $
*/
public class XMLChar {
//
// Constants
//
/**
* Character flags.
*/
private static final byte[] CHARS = new byte[1 << 16];
/**
* Valid character mask.
*/
public static final int MASK_VALID = 0x01;
/**
* Space character mask.
*/
public static final int MASK_SPACE = 0x02;
/**
* Name start character mask.
*/
public static final int MASK_NAME_START = 0x04;
/**
* Name character mask.
*/
public static final int MASK_NAME = 0x08;
/**
* Pubid character mask.
*/
public static final int MASK_PUBID = 0x10;
/**
* Content character mask. Special characters are those that can
* be considered the start of markup, such as '<' and '&'.
* The various newline characters are considered special as well.
* All other valid XML characters can be considered content.
* <p>
* This is an optimization for the inner loop of character scanning.
*/
public static final int MASK_CONTENT = 0x20;
/**
* NCName start character mask.
*/
public static final int MASK_NCNAME_START = 0x40;
/**
* NCName character mask.
*/
public static final int MASK_NCNAME = 0x80;
//
// Static initialization
//
static {
// Initializing the Character Flag Array
// Code generated by: XMLCharGenerator.
CHARS[9] = 35;
CHARS[10] = 19;
CHARS[13] = 19;
CHARS[32] = 51;
CHARS[33] = 49;
CHARS[34] = 33;
Arrays.fill(CHARS, 35, 38, (byte) 49); // Fill 3 of value (byte) 49
CHARS[38] = 1;
Arrays.fill(CHARS, 39, 45, (byte) 49); // Fill 6 of value (byte) 49
Arrays.fill(CHARS, 45, 47, (byte) -71); // Fill 2 of value (byte) -71
CHARS[47] = 49;
Arrays.fill(CHARS, 48, 58, (byte) -71); // Fill 10 of value (byte) -71
CHARS[58] = 61;
CHARS[59] = 49;
CHARS[60] = 1;
CHARS[61] = 49;
CHARS[62] = 33;
Arrays.fill(CHARS, 63, 65, (byte) 49); // Fill 2 of value (byte) 49
Arrays.fill(CHARS, 65, 91, (byte) -3); // Fill 26 of value (byte) -3
Arrays.fill(CHARS, 91, 93, (byte) 33); // Fill 2 of value (byte) 33
CHARS[93] = 1;
CHARS[94] = 33;
CHARS[95] = -3;
CHARS[96] = 33;
Arrays.fill(CHARS, 97, 123, (byte) -3); // Fill 26 of value (byte) -3
Arrays.fill(CHARS, 123, 183, (byte) 33); // Fill 60 of value (byte) 33
CHARS[183] = -87;
Arrays.fill(CHARS, 184, 192, (byte) 33); // Fill 8 of value (byte) 33
Arrays.fill(CHARS, 192, 215, (byte) -19); // Fill 23 of value (byte) -19
CHARS[215] = 33;
Arrays.fill(CHARS, 216, 247, (byte) -19); // Fill 31 of value (byte) -19
CHARS[247] = 33;
Arrays.fill(CHARS, 248, 306, (byte) -19); // Fill 58 of value (byte) -19
Arrays.fill(CHARS, 306, 308, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 308, 319, (byte) -19); // Fill 11 of value (byte) -19
Arrays.fill(CHARS, 319, 321, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 321, 329, (byte) -19); // Fill 8 of value (byte) -19
CHARS[329] = 33;
Arrays.fill(CHARS, 330, 383, (byte) -19); // Fill 53 of value (byte) -19
CHARS[383] = 33;
Arrays.fill(CHARS, 384, 452, (byte) -19); // Fill 68 of value (byte) -19
Arrays.fill(CHARS, 452, 461, (byte) 33); // Fill 9 of value (byte) 33
Arrays.fill(CHARS, 461, 497, (byte) -19); // Fill 36 of value (byte) -19
Arrays.fill(CHARS, 497, 500, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 500, 502, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 502, 506, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 506, 536, (byte) -19); // Fill 30 of value (byte) -19
Arrays.fill(CHARS, 536, 592, (byte) 33); // Fill 56 of value (byte) 33
Arrays.fill(CHARS, 592, 681, (byte) -19); // Fill 89 of value (byte) -19
Arrays.fill(CHARS, 681, 699, (byte) 33); // Fill 18 of value (byte) 33
Arrays.fill(CHARS, 699, 706, (byte) -19); // Fill 7 of value (byte) -19
Arrays.fill(CHARS, 706, 720, (byte) 33); // Fill 14 of value (byte) 33
Arrays.fill(CHARS, 720, 722, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 722, 768, (byte) 33); // Fill 46 of value (byte) 33
Arrays.fill(CHARS, 768, 838, (byte) -87); // Fill 70 of value (byte) -87
Arrays.fill(CHARS, 838, 864, (byte) 33); // Fill 26 of value (byte) 33
Arrays.fill(CHARS, 864, 866, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 866, 902, (byte) 33); // Fill 36 of value (byte) 33
CHARS[902] = -19;
CHARS[903] = -87;
Arrays.fill(CHARS, 904, 907, (byte) -19); // Fill 3 of value (byte) -19
CHARS[907] = 33;
CHARS[908] = -19;
CHARS[909] = 33;
Arrays.fill(CHARS, 910, 930, (byte) -19); // Fill 20 of value (byte) -19
CHARS[930] = 33;
Arrays.fill(CHARS, 931, 975, (byte) -19); // Fill 44 of value (byte) -19
CHARS[975] = 33;
Arrays.fill(CHARS, 976, 983, (byte) -19); // Fill 7 of value (byte) -19
Arrays.fill(CHARS, 983, 986, (byte) 33); // Fill 3 of value (byte) 33
CHARS[986] = -19;
CHARS[987] = 33;
CHARS[988] = -19;
CHARS[989] = 33;
CHARS[990] = -19;
CHARS[991] = 33;
CHARS[992] = -19;
CHARS[993] = 33;
Arrays.fill(CHARS, 994, 1012, (byte) -19); // Fill 18 of value (byte) -19
Arrays.fill(CHARS, 1012, 1025, (byte) 33); // Fill 13 of value (byte) 33
Arrays.fill(CHARS, 1025, 1037, (byte) -19); // Fill 12 of value (byte) -19
CHARS[1037] = 33;
Arrays.fill(CHARS, 1038, 1104, (byte) -19); // Fill 66 of value (byte) -19
CHARS[1104] = 33;
Arrays.fill(CHARS, 1105, 1117, (byte) -19); // Fill 12 of value (byte) -19
CHARS[1117] = 33;
Arrays.fill(CHARS, 1118, 1154, (byte) -19); // Fill 36 of value (byte) -19
CHARS[1154] = 33;
Arrays.fill(CHARS, 1155, 1159, (byte) -87); // Fill 4 of value (byte) -87
Arrays.fill(CHARS, 1159, 1168, (byte) 33); // Fill 9 of value (byte) 33
Arrays.fill(CHARS, 1168, 1221, (byte) -19); // Fill 53 of value (byte) -19
Arrays.fill(CHARS, 1221, 1223, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 1223, 1225, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 1225, 1227, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 1227, 1229, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 1229, 1232, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 1232, 1260, (byte) -19); // Fill 28 of value (byte) -19
Arrays.fill(CHARS, 1260, 1262, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 1262, 1270, (byte) -19); // Fill 8 of value (byte) -19
Arrays.fill(CHARS, 1270, 1272, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 1272, 1274, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 1274, 1329, (byte) 33); // Fill 55 of value (byte) 33
Arrays.fill(CHARS, 1329, 1367, (byte) -19); // Fill 38 of value (byte) -19
Arrays.fill(CHARS, 1367, 1369, (byte) 33); // Fill 2 of value (byte) 33
CHARS[1369] = -19;
Arrays.fill(CHARS, 1370, 1377, (byte) 33); // Fill 7 of value (byte) 33
Arrays.fill(CHARS, 1377, 1415, (byte) -19); // Fill 38 of value (byte) -19
Arrays.fill(CHARS, 1415, 1425, (byte) 33); // Fill 10 of value (byte) 33
Arrays.fill(CHARS, 1425, 1442, (byte) -87); // Fill 17 of value (byte) -87
CHARS[1442] = 33;
Arrays.fill(CHARS, 1443, 1466, (byte) -87); // Fill 23 of value (byte) -87
CHARS[1466] = 33;
Arrays.fill(CHARS, 1467, 1470, (byte) -87); // Fill 3 of value (byte) -87
CHARS[1470] = 33;
CHARS[1471] = -87;
CHARS[1472] = 33;
Arrays.fill(CHARS, 1473, 1475, (byte) -87); // Fill 2 of value (byte) -87
CHARS[1475] = 33;
CHARS[1476] = -87;
Arrays.fill(CHARS, 1477, 1488, (byte) 33); // Fill 11 of value (byte) 33
Arrays.fill(CHARS, 1488, 1515, (byte) -19); // Fill 27 of value (byte) -19
Arrays.fill(CHARS, 1515, 1520, (byte) 33); // Fill 5 of value (byte) 33
Arrays.fill(CHARS, 1520, 1523, (byte) -19); // Fill 3 of value (byte) -19
Arrays.fill(CHARS, 1523, 1569, (byte) 33); // Fill 46 of value (byte) 33
Arrays.fill(CHARS, 1569, 1595, (byte) -19); // Fill 26 of value (byte) -19
Arrays.fill(CHARS, 1595, 1600, (byte) 33); // Fill 5 of value (byte) 33
CHARS[1600] = -87;
Arrays.fill(CHARS, 1601, 1611, (byte) -19); // Fill 10 of value (byte) -19
Arrays.fill(CHARS, 1611, 1619, (byte) -87); // Fill 8 of value (byte) -87
Arrays.fill(CHARS, 1619, 1632, (byte) 33); // Fill 13 of value (byte) 33
Arrays.fill(CHARS, 1632, 1642, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 1642, 1648, (byte) 33); // Fill 6 of value (byte) 33
CHARS[1648] = -87;
Arrays.fill(CHARS, 1649, 1720, (byte) -19); // Fill 71 of value (byte) -19
Arrays.fill(CHARS, 1720, 1722, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 1722, 1727, (byte) -19); // Fill 5 of value (byte) -19
CHARS[1727] = 33;
Arrays.fill(CHARS, 1728, 1743, (byte) -19); // Fill 15 of value (byte) -19
CHARS[1743] = 33;
Arrays.fill(CHARS, 1744, 1748, (byte) -19); // Fill 4 of value (byte) -19
CHARS[1748] = 33;
CHARS[1749] = -19;
Arrays.fill(CHARS, 1750, 1765, (byte) -87); // Fill 15 of value (byte) -87
Arrays.fill(CHARS, 1765, 1767, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 1767, 1769, (byte) -87); // Fill 2 of value (byte) -87
CHARS[1769] = 33;
Arrays.fill(CHARS, 1770, 1774, (byte) -87); // Fill 4 of value (byte) -87
Arrays.fill(CHARS, 1774, 1776, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 1776, 1786, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 1786, 2305, (byte) 33); // Fill 519 of value (byte) 33
Arrays.fill(CHARS, 2305, 2308, (byte) -87); // Fill 3 of value (byte) -87
CHARS[2308] = 33;
Arrays.fill(CHARS, 2309, 2362, (byte) -19); // Fill 53 of value (byte) -19
Arrays.fill(CHARS, 2362, 2364, (byte) 33); // Fill 2 of value (byte) 33
CHARS[2364] = -87;
CHARS[2365] = -19;
Arrays.fill(CHARS, 2366, 2382, (byte) -87); // Fill 16 of value (byte) -87
Arrays.fill(CHARS, 2382, 2385, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 2385, 2389, (byte) -87); // Fill 4 of value (byte) -87
Arrays.fill(CHARS, 2389, 2392, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 2392, 2402, (byte) -19); // Fill 10 of value (byte) -19
Arrays.fill(CHARS, 2402, 2404, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 2404, 2406, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2406, 2416, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 2416, 2433, (byte) 33); // Fill 17 of value (byte) 33
Arrays.fill(CHARS, 2433, 2436, (byte) -87); // Fill 3 of value (byte) -87
CHARS[2436] = 33;
Arrays.fill(CHARS, 2437, 2445, (byte) -19); // Fill 8 of value (byte) -19
Arrays.fill(CHARS, 2445, 2447, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2447, 2449, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 2449, 2451, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2451, 2473, (byte) -19); // Fill 22 of value (byte) -19
CHARS[2473] = 33;
Arrays.fill(CHARS, 2474, 2481, (byte) -19); // Fill 7 of value (byte) -19
CHARS[2481] = 33;
CHARS[2482] = -19;
Arrays.fill(CHARS, 2483, 2486, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 2486, 2490, (byte) -19); // Fill 4 of value (byte) -19
Arrays.fill(CHARS, 2490, 2492, (byte) 33); // Fill 2 of value (byte) 33
CHARS[2492] = -87;
CHARS[2493] = 33;
Arrays.fill(CHARS, 2494, 2501, (byte) -87); // Fill 7 of value (byte) -87
Arrays.fill(CHARS, 2501, 2503, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2503, 2505, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 2505, 2507, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2507, 2510, (byte) -87); // Fill 3 of value (byte) -87
Arrays.fill(CHARS, 2510, 2519, (byte) 33); // Fill 9 of value (byte) 33
CHARS[2519] = -87;
Arrays.fill(CHARS, 2520, 2524, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 2524, 2526, (byte) -19); // Fill 2 of value (byte) -19
CHARS[2526] = 33;
Arrays.fill(CHARS, 2527, 2530, (byte) -19); // Fill 3 of value (byte) -19
Arrays.fill(CHARS, 2530, 2532, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 2532, 2534, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2534, 2544, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 2544, 2546, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 2546, 2562, (byte) 33); // Fill 16 of value (byte) 33
CHARS[2562] = -87;
Arrays.fill(CHARS, 2563, 2565, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2565, 2571, (byte) -19); // Fill 6 of value (byte) -19
Arrays.fill(CHARS, 2571, 2575, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 2575, 2577, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 2577, 2579, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2579, 2601, (byte) -19); // Fill 22 of value (byte) -19
CHARS[2601] = 33;
Arrays.fill(CHARS, 2602, 2609, (byte) -19); // Fill 7 of value (byte) -19
CHARS[2609] = 33;
Arrays.fill(CHARS, 2610, 2612, (byte) -19); // Fill 2 of value (byte) -19
CHARS[2612] = 33;
Arrays.fill(CHARS, 2613, 2615, (byte) -19); // Fill 2 of value (byte) -19
CHARS[2615] = 33;
Arrays.fill(CHARS, 2616, 2618, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 2618, 2620, (byte) 33); // Fill 2 of value (byte) 33
CHARS[2620] = -87;
CHARS[2621] = 33;
Arrays.fill(CHARS, 2622, 2627, (byte) -87); // Fill 5 of value (byte) -87
Arrays.fill(CHARS, 2627, 2631, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 2631, 2633, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 2633, 2635, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2635, 2638, (byte) -87); // Fill 3 of value (byte) -87
Arrays.fill(CHARS, 2638, 2649, (byte) 33); // Fill 11 of value (byte) 33
Arrays.fill(CHARS, 2649, 2653, (byte) -19); // Fill 4 of value (byte) -19
CHARS[2653] = 33;
CHARS[2654] = -19;
Arrays.fill(CHARS, 2655, 2662, (byte) 33); // Fill 7 of value (byte) 33
Arrays.fill(CHARS, 2662, 2674, (byte) -87); // Fill 12 of value (byte) -87
Arrays.fill(CHARS, 2674, 2677, (byte) -19); // Fill 3 of value (byte) -19
Arrays.fill(CHARS, 2677, 2689, (byte) 33); // Fill 12 of value (byte) 33
Arrays.fill(CHARS, 2689, 2692, (byte) -87); // Fill 3 of value (byte) -87
CHARS[2692] = 33;
Arrays.fill(CHARS, 2693, 2700, (byte) -19); // Fill 7 of value (byte) -19
CHARS[2700] = 33;
CHARS[2701] = -19;
CHARS[2702] = 33;
Arrays.fill(CHARS, 2703, 2706, (byte) -19); // Fill 3 of value (byte) -19
CHARS[2706] = 33;
Arrays.fill(CHARS, 2707, 2729, (byte) -19); // Fill 22 of value (byte) -19
CHARS[2729] = 33;
Arrays.fill(CHARS, 2730, 2737, (byte) -19); // Fill 7 of value (byte) -19
CHARS[2737] = 33;
Arrays.fill(CHARS, 2738, 2740, (byte) -19); // Fill 2 of value (byte) -19
CHARS[2740] = 33;
Arrays.fill(CHARS, 2741, 2746, (byte) -19); // Fill 5 of value (byte) -19
Arrays.fill(CHARS, 2746, 2748, (byte) 33); // Fill 2 of value (byte) 33
CHARS[2748] = -87;
CHARS[2749] = -19;
Arrays.fill(CHARS, 2750, 2758, (byte) -87); // Fill 8 of value (byte) -87
CHARS[2758] = 33;
Arrays.fill(CHARS, 2759, 2762, (byte) -87); // Fill 3 of value (byte) -87
CHARS[2762] = 33;
Arrays.fill(CHARS, 2763, 2766, (byte) -87); // Fill 3 of value (byte) -87
Arrays.fill(CHARS, 2766, 2784, (byte) 33); // Fill 18 of value (byte) 33
CHARS[2784] = -19;
Arrays.fill(CHARS, 2785, 2790, (byte) 33); // Fill 5 of value (byte) 33
Arrays.fill(CHARS, 2790, 2800, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 2800, 2817, (byte) 33); // Fill 17 of value (byte) 33
Arrays.fill(CHARS, 2817, 2820, (byte) -87); // Fill 3 of value (byte) -87
CHARS[2820] = 33;
Arrays.fill(CHARS, 2821, 2829, (byte) -19); // Fill 8 of value (byte) -19
Arrays.fill(CHARS, 2829, 2831, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2831, 2833, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 2833, 2835, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2835, 2857, (byte) -19); // Fill 22 of value (byte) -19
CHARS[2857] = 33;
Arrays.fill(CHARS, 2858, 2865, (byte) -19); // Fill 7 of value (byte) -19
CHARS[2865] = 33;
Arrays.fill(CHARS, 2866, 2868, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 2868, 2870, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2870, 2874, (byte) -19); // Fill 4 of value (byte) -19
Arrays.fill(CHARS, 2874, 2876, (byte) 33); // Fill 2 of value (byte) 33
CHARS[2876] = -87;
CHARS[2877] = -19;
Arrays.fill(CHARS, 2878, 2884, (byte) -87); // Fill 6 of value (byte) -87
Arrays.fill(CHARS, 2884, 2887, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 2887, 2889, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 2889, 2891, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 2891, 2894, (byte) -87); // Fill 3 of value (byte) -87
Arrays.fill(CHARS, 2894, 2902, (byte) 33); // Fill 8 of value (byte) 33
Arrays.fill(CHARS, 2902, 2904, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 2904, 2908, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 2908, 2910, (byte) -19); // Fill 2 of value (byte) -19
CHARS[2910] = 33;
Arrays.fill(CHARS, 2911, 2914, (byte) -19); // Fill 3 of value (byte) -19
Arrays.fill(CHARS, 2914, 2918, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 2918, 2928, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 2928, 2946, (byte) 33); // Fill 18 of value (byte) 33
Arrays.fill(CHARS, 2946, 2948, (byte) -87); // Fill 2 of value (byte) -87
CHARS[2948] = 33;
Arrays.fill(CHARS, 2949, 2955, (byte) -19); // Fill 6 of value (byte) -19
Arrays.fill(CHARS, 2955, 2958, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 2958, 2961, (byte) -19); // Fill 3 of value (byte) -19
CHARS[2961] = 33;
Arrays.fill(CHARS, 2962, 2966, (byte) -19); // Fill 4 of value (byte) -19
Arrays.fill(CHARS, 2966, 2969, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 2969, 2971, (byte) -19); // Fill 2 of value (byte) -19
CHARS[2971] = 33;
CHARS[2972] = -19;
CHARS[2973] = 33;
Arrays.fill(CHARS, 2974, 2976, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 2976, 2979, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 2979, 2981, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 2981, 2984, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 2984, 2987, (byte) -19); // Fill 3 of value (byte) -19
Arrays.fill(CHARS, 2987, 2990, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 2990, 2998, (byte) -19); // Fill 8 of value (byte) -19
CHARS[2998] = 33;
Arrays.fill(CHARS, 2999, 3002, (byte) -19); // Fill 3 of value (byte) -19
Arrays.fill(CHARS, 3002, 3006, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 3006, 3011, (byte) -87); // Fill 5 of value (byte) -87
Arrays.fill(CHARS, 3011, 3014, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 3014, 3017, (byte) -87); // Fill 3 of value (byte) -87
CHARS[3017] = 33;
Arrays.fill(CHARS, 3018, 3022, (byte) -87); // Fill 4 of value (byte) -87
Arrays.fill(CHARS, 3022, 3031, (byte) 33); // Fill 9 of value (byte) 33
CHARS[3031] = -87;
Arrays.fill(CHARS, 3032, 3047, (byte) 33); // Fill 15 of value (byte) 33
Arrays.fill(CHARS, 3047, 3056, (byte) -87); // Fill 9 of value (byte) -87
Arrays.fill(CHARS, 3056, 3073, (byte) 33); // Fill 17 of value (byte) 33
Arrays.fill(CHARS, 3073, 3076, (byte) -87); // Fill 3 of value (byte) -87
CHARS[3076] = 33;
Arrays.fill(CHARS, 3077, 3085, (byte) -19); // Fill 8 of value (byte) -19
CHARS[3085] = 33;
Arrays.fill(CHARS, 3086, 3089, (byte) -19); // Fill 3 of value (byte) -19
CHARS[3089] = 33;
Arrays.fill(CHARS, 3090, 3113, (byte) -19); // Fill 23 of value (byte) -19
CHARS[3113] = 33;
Arrays.fill(CHARS, 3114, 3124, (byte) -19); // Fill 10 of value (byte) -19
CHARS[3124] = 33;
Arrays.fill(CHARS, 3125, 3130, (byte) -19); // Fill 5 of value (byte) -19
Arrays.fill(CHARS, 3130, 3134, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 3134, 3141, (byte) -87); // Fill 7 of value (byte) -87
CHARS[3141] = 33;
Arrays.fill(CHARS, 3142, 3145, (byte) -87); // Fill 3 of value (byte) -87
CHARS[3145] = 33;
Arrays.fill(CHARS, 3146, 3150, (byte) -87); // Fill 4 of value (byte) -87
Arrays.fill(CHARS, 3150, 3157, (byte) 33); // Fill 7 of value (byte) 33
Arrays.fill(CHARS, 3157, 3159, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 3159, 3168, (byte) 33); // Fill 9 of value (byte) 33
Arrays.fill(CHARS, 3168, 3170, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 3170, 3174, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 3174, 3184, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 3184, 3202, (byte) 33); // Fill 18 of value (byte) 33
Arrays.fill(CHARS, 3202, 3204, (byte) -87); // Fill 2 of value (byte) -87
CHARS[3204] = 33;
Arrays.fill(CHARS, 3205, 3213, (byte) -19); // Fill 8 of value (byte) -19
CHARS[3213] = 33;
Arrays.fill(CHARS, 3214, 3217, (byte) -19); // Fill 3 of value (byte) -19
CHARS[3217] = 33;
Arrays.fill(CHARS, 3218, 3241, (byte) -19); // Fill 23 of value (byte) -19
CHARS[3241] = 33;
Arrays.fill(CHARS, 3242, 3252, (byte) -19); // Fill 10 of value (byte) -19
CHARS[3252] = 33;
Arrays.fill(CHARS, 3253, 3258, (byte) -19); // Fill 5 of value (byte) -19
Arrays.fill(CHARS, 3258, 3262, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 3262, 3269, (byte) -87); // Fill 7 of value (byte) -87
CHARS[3269] = 33;
Arrays.fill(CHARS, 3270, 3273, (byte) -87); // Fill 3 of value (byte) -87
CHARS[3273] = 33;
Arrays.fill(CHARS, 3274, 3278, (byte) -87); // Fill 4 of value (byte) -87
Arrays.fill(CHARS, 3278, 3285, (byte) 33); // Fill 7 of value (byte) 33
Arrays.fill(CHARS, 3285, 3287, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 3287, 3294, (byte) 33); // Fill 7 of value (byte) 33
CHARS[3294] = -19;
CHARS[3295] = 33;
Arrays.fill(CHARS, 3296, 3298, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 3298, 3302, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 3302, 3312, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 3312, 3330, (byte) 33); // Fill 18 of value (byte) 33
Arrays.fill(CHARS, 3330, 3332, (byte) -87); // Fill 2 of value (byte) -87
CHARS[3332] = 33;
Arrays.fill(CHARS, 3333, 3341, (byte) -19); // Fill 8 of value (byte) -19
CHARS[3341] = 33;
Arrays.fill(CHARS, 3342, 3345, (byte) -19); // Fill 3 of value (byte) -19
CHARS[3345] = 33;
Arrays.fill(CHARS, 3346, 3369, (byte) -19); // Fill 23 of value (byte) -19
CHARS[3369] = 33;
Arrays.fill(CHARS, 3370, 3386, (byte) -19); // Fill 16 of value (byte) -19
Arrays.fill(CHARS, 3386, 3390, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 3390, 3396, (byte) -87); // Fill 6 of value (byte) -87
Arrays.fill(CHARS, 3396, 3398, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 3398, 3401, (byte) -87); // Fill 3 of value (byte) -87
CHARS[3401] = 33;
Arrays.fill(CHARS, 3402, 3406, (byte) -87); // Fill 4 of value (byte) -87
Arrays.fill(CHARS, 3406, 3415, (byte) 33); // Fill 9 of value (byte) 33
CHARS[3415] = -87;
Arrays.fill(CHARS, 3416, 3424, (byte) 33); // Fill 8 of value (byte) 33
Arrays.fill(CHARS, 3424, 3426, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 3426, 3430, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 3430, 3440, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 3440, 3585, (byte) 33); // Fill 145 of value (byte) 33
Arrays.fill(CHARS, 3585, 3631, (byte) -19); // Fill 46 of value (byte) -19
CHARS[3631] = 33;
CHARS[3632] = -19;
CHARS[3633] = -87;
Arrays.fill(CHARS, 3634, 3636, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 3636, 3643, (byte) -87); // Fill 7 of value (byte) -87
Arrays.fill(CHARS, 3643, 3648, (byte) 33); // Fill 5 of value (byte) 33
Arrays.fill(CHARS, 3648, 3654, (byte) -19); // Fill 6 of value (byte) -19
Arrays.fill(CHARS, 3654, 3663, (byte) -87); // Fill 9 of value (byte) -87
CHARS[3663] = 33;
Arrays.fill(CHARS, 3664, 3674, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 3674, 3713, (byte) 33); // Fill 39 of value (byte) 33
Arrays.fill(CHARS, 3713, 3715, (byte) -19); // Fill 2 of value (byte) -19
CHARS[3715] = 33;
CHARS[3716] = -19;
Arrays.fill(CHARS, 3717, 3719, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 3719, 3721, (byte) -19); // Fill 2 of value (byte) -19
CHARS[3721] = 33;
CHARS[3722] = -19;
Arrays.fill(CHARS, 3723, 3725, (byte) 33); // Fill 2 of value (byte) 33
CHARS[3725] = -19;
Arrays.fill(CHARS, 3726, 3732, (byte) 33); // Fill 6 of value (byte) 33
Arrays.fill(CHARS, 3732, 3736, (byte) -19); // Fill 4 of value (byte) -19
CHARS[3736] = 33;
Arrays.fill(CHARS, 3737, 3744, (byte) -19); // Fill 7 of value (byte) -19
CHARS[3744] = 33;
Arrays.fill(CHARS, 3745, 3748, (byte) -19); // Fill 3 of value (byte) -19
CHARS[3748] = 33;
CHARS[3749] = -19;
CHARS[3750] = 33;
CHARS[3751] = -19;
Arrays.fill(CHARS, 3752, 3754, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 3754, 3756, (byte) -19); // Fill 2 of value (byte) -19
CHARS[3756] = 33;
Arrays.fill(CHARS, 3757, 3759, (byte) -19); // Fill 2 of value (byte) -19
CHARS[3759] = 33;
CHARS[3760] = -19;
CHARS[3761] = -87;
Arrays.fill(CHARS, 3762, 3764, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 3764, 3770, (byte) -87); // Fill 6 of value (byte) -87
CHARS[3770] = 33;
Arrays.fill(CHARS, 3771, 3773, (byte) -87); // Fill 2 of value (byte) -87
CHARS[3773] = -19;
Arrays.fill(CHARS, 3774, 3776, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 3776, 3781, (byte) -19); // Fill 5 of value (byte) -19
CHARS[3781] = 33;
CHARS[3782] = -87;
CHARS[3783] = 33;
Arrays.fill(CHARS, 3784, 3790, (byte) -87); // Fill 6 of value (byte) -87
Arrays.fill(CHARS, 3790, 3792, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 3792, 3802, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 3802, 3864, (byte) 33); // Fill 62 of value (byte) 33
Arrays.fill(CHARS, 3864, 3866, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 3866, 3872, (byte) 33); // Fill 6 of value (byte) 33
Arrays.fill(CHARS, 3872, 3882, (byte) -87); // Fill 10 of value (byte) -87
Arrays.fill(CHARS, 3882, 3893, (byte) 33); // Fill 11 of value (byte) 33
CHARS[3893] = -87;
CHARS[3894] = 33;
CHARS[3895] = -87;
CHARS[3896] = 33;
CHARS[3897] = -87;
Arrays.fill(CHARS, 3898, 3902, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 3902, 3904, (byte) -87); // Fill 2 of value (byte) -87
Arrays.fill(CHARS, 3904, 3912, (byte) -19); // Fill 8 of value (byte) -19
CHARS[3912] = 33;
Arrays.fill(CHARS, 3913, 3946, (byte) -19); // Fill 33 of value (byte) -19
Arrays.fill(CHARS, 3946, 3953, (byte) 33); // Fill 7 of value (byte) 33
Arrays.fill(CHARS, 3953, 3973, (byte) -87); // Fill 20 of value (byte) -87
CHARS[3973] = 33;
Arrays.fill(CHARS, 3974, 3980, (byte) -87); // Fill 6 of value (byte) -87
Arrays.fill(CHARS, 3980, 3984, (byte) 33); // Fill 4 of value (byte) 33
Arrays.fill(CHARS, 3984, 3990, (byte) -87); // Fill 6 of value (byte) -87
CHARS[3990] = 33;
CHARS[3991] = -87;
CHARS[3992] = 33;
Arrays.fill(CHARS, 3993, 4014, (byte) -87); // Fill 21 of value (byte) -87
Arrays.fill(CHARS, 4014, 4017, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 4017, 4024, (byte) -87); // Fill 7 of value (byte) -87
CHARS[4024] = 33;
CHARS[4025] = -87;
Arrays.fill(CHARS, 4026, 4256, (byte) 33); // Fill 230 of value (byte) 33
Arrays.fill(CHARS, 4256, 4294, (byte) -19); // Fill 38 of value (byte) -19
Arrays.fill(CHARS, 4294, 4304, (byte) 33); // Fill 10 of value (byte) 33
Arrays.fill(CHARS, 4304, 4343, (byte) -19); // Fill 39 of value (byte) -19
Arrays.fill(CHARS, 4343, 4352, (byte) 33); // Fill 9 of value (byte) 33
CHARS[4352] = -19;
CHARS[4353] = 33;
Arrays.fill(CHARS, 4354, 4356, (byte) -19); // Fill 2 of value (byte) -19
CHARS[4356] = 33;
Arrays.fill(CHARS, 4357, 4360, (byte) -19); // Fill 3 of value (byte) -19
CHARS[4360] = 33;
CHARS[4361] = -19;
CHARS[4362] = 33;
Arrays.fill(CHARS, 4363, 4365, (byte) -19); // Fill 2 of value (byte) -19
CHARS[4365] = 33;
Arrays.fill(CHARS, 4366, 4371, (byte) -19); // Fill 5 of value (byte) -19
Arrays.fill(CHARS, 4371, 4412, (byte) 33); // Fill 41 of value (byte) 33
CHARS[4412] = -19;
CHARS[4413] = 33;
CHARS[4414] = -19;
CHARS[4415] = 33;
CHARS[4416] = -19;
Arrays.fill(CHARS, 4417, 4428, (byte) 33); // Fill 11 of value (byte) 33
CHARS[4428] = -19;
CHARS[4429] = 33;
CHARS[4430] = -19;
CHARS[4431] = 33;
CHARS[4432] = -19;
Arrays.fill(CHARS, 4433, 4436, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 4436, 4438, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 4438, 4441, (byte) 33); // Fill 3 of value (byte) 33
CHARS[4441] = -19;
Arrays.fill(CHARS, 4442, 4447, (byte) 33); // Fill 5 of value (byte) 33
Arrays.fill(CHARS, 4447, 4450, (byte) -19); // Fill 3 of value (byte) -19
CHARS[4450] = 33;
CHARS[4451] = -19;
CHARS[4452] = 33;
CHARS[4453] = -19;
CHARS[4454] = 33;
CHARS[4455] = -19;
CHARS[4456] = 33;
CHARS[4457] = -19;
Arrays.fill(CHARS, 4458, 4461, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 4461, 4463, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 4463, 4466, (byte) 33); // Fill 3 of value (byte) 33
Arrays.fill(CHARS, 4466, 4468, (byte) -19); // Fill 2 of value (byte) -19
CHARS[4468] = 33;
CHARS[4469] = -19;
Arrays.fill(CHARS, 4470, 4510, (byte) 33); // Fill 40 of value (byte) 33
CHARS[4510] = -19;
Arrays.fill(CHARS, 4511, 4520, (byte) 33); // Fill 9 of value (byte) 33
CHARS[4520] = -19;
Arrays.fill(CHARS, 4521, 4523, (byte) 33); // Fill 2 of value (byte) 33
CHARS[4523] = -19;
Arrays.fill(CHARS, 4524, 4526, (byte) 33); // Fill 2 of value (byte) 33
Arrays.fill(CHARS, 4526, 4528, (byte) -19); // Fill 2 of value (byte) -19
Arrays.fill(CHARS, 4528, 4535, (byte) 33); // Fill 7 of value (byte) 33
Arrays.fill(CHARS, 4535, 4537, (byte) -19); // Fill 2 of value (byte) -19
CHARS[4537] = 33;
CHARS[4538] = -19;
CHARS[4539] = 33;
Arrays.fill(CHARS, 4540, 4547, (byte) -19); // Fill 7 of value (byte) -19
Arrays.fill(CHARS, 4547, 4587, (byte) 33); // Fill 40 of value (byte) 33
CHARS[4587] = -19;
Arrays.fill(CHARS, 4588, 4592, (byte) 33); // Fill 4 of value (byte) 33
CHARS[4592] = -19;
Arrays.fill(CHARS, 4593, 4601, (byte) 33); // Fill 8 of value (byte) 33
CHARS[4601] = -19;
Arrays.fill(CHARS, 4602, 7680, (byte) 33); // Fill 3078 of value (byte) 33
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | true |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/ResNameUtils.java | jadx-core/src/main/java/jadx/core/xmlgen/ResNameUtils.java | package jadx.core.xmlgen;
import jadx.core.deobf.NameMapper;
import static jadx.core.deobf.NameMapper.*;
class ResNameUtils {
private ResNameUtils() {
}
/**
* Sanitizes the name so that it can be used as a resource name.
* By resource name is meant that:
* <ul>
* <li>It can be used by aapt2 as a resource entry name.
* <li>It can be converted to a valid R class field name.
* </ul>
* <p>
* If the {@code name} is already a valid resource name, the method returns it unchanged.
* If not, the method creates a valid resource name based on {@code name}, appends the
* {@code postfix}, and returns the result.
*/
static String sanitizeAsResourceName(String name, String postfix, boolean allowNonPrintable) {
if (name.isEmpty()) {
return postfix;
}
final StringBuilder sb = new StringBuilder(name.length() + 1);
boolean nameChanged = false;
int cp = name.codePointAt(0);
if (isValidResourceNameStart(cp, allowNonPrintable)) {
sb.appendCodePoint(cp);
} else {
sb.append('_');
nameChanged = true;
if (isValidResourceNamePart(cp, allowNonPrintable)) {
sb.appendCodePoint(cp);
}
}
for (int i = Character.charCount(cp); i < name.length(); i += Character.charCount(cp)) {
cp = name.codePointAt(i);
if (isValidResourceNamePart(cp, allowNonPrintable)) {
sb.appendCodePoint(cp);
} else {
sb.append('_');
nameChanged = true;
}
}
final String sanitizedName = sb.toString();
if (NameMapper.isReserved(sanitizedName)) {
nameChanged = true;
}
return nameChanged
? sanitizedName + postfix
: sanitizedName;
}
/**
* Converts the resource name to a field name of the R class.
*/
static String convertToRFieldName(String resourceName) {
return resourceName.replace('.', '_');
}
/**
* Determines whether the code point may be part of a resource name as the first character (aapt2 +
* R class gen).
*/
private static boolean isValidResourceNameStart(int codePoint, boolean allowNonPrintable) {
return (allowNonPrintable || isPrintableAsciiCodePoint(codePoint))
&& (isValidAapt2ResourceNameStart(codePoint) && isValidIdentifierStart(codePoint));
}
/**
* Determines whether the code point may be part of a resource name as other than the first
* character
* (aapt2 + R class gen).
*/
private static boolean isValidResourceNamePart(int codePoint, boolean allowNonPrintable) {
return (allowNonPrintable || isPrintableAsciiCodePoint(codePoint))
&& ((isValidAapt2ResourceNamePart(codePoint) && isValidIdentifierPart(codePoint)) || codePoint == '.');
}
/**
* Determines whether the code point may be part of a resource name as the first character (aapt2).
* <p>
* Source: <a href=
* "https://cs.android.com/android/platform/superproject/+/android15-release:frameworks/base/tools/aapt2/text/Unicode.cpp;l=112">aapt2/text/Unicode.cpp#L112</a>
*/
private static boolean isValidAapt2ResourceNameStart(int codePoint) {
return isXidStart(codePoint) || codePoint == '_';
}
/**
* Determines whether the code point may be part of a resource name as other than the first
* character (aapt2).
* <p>
* Source: <a href=
* "https://cs.android.com/android/platform/superproject/+/android15-release:frameworks/base/tools/aapt2/text/Unicode.cpp;l=118">aapt2/text/Unicode.cpp#L118</a>
*/
private static boolean isValidAapt2ResourceNamePart(int codePoint) {
return isXidContinue(codePoint) || codePoint == '.' || codePoint == '-';
}
private static boolean isXidStart(int codePoint) {
// TODO: Need to implement a full check if the code point is XID_Start.
return codePoint < 0x0370 && Character.isUnicodeIdentifierStart(codePoint);
}
private static boolean isXidContinue(int codePoint) {
// TODO: Need to implement a full check if the code point is XID_Continue.
return codePoint < 0x0370
&& (Character.isUnicodeIdentifierPart(codePoint) && !Character.isIdentifierIgnorable(codePoint));
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/ResDecoder.java | jadx-core/src/main/java/jadx/core/xmlgen/ResDecoder.java | package jadx.core.xmlgen;
public class ResDecoder {
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/entry/ValuesParser.java | jadx-core/src/main/java/jadx/core/xmlgen/entry/ValuesParser.java | package jadx.core.xmlgen.entry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.utils.android.AndroidResourcesMap;
import jadx.core.xmlgen.BinaryXMLStrings;
import jadx.core.xmlgen.ParserConstants;
import jadx.core.xmlgen.XmlGenUtils;
public class ValuesParser extends ParserConstants {
private static final Logger LOG = LoggerFactory.getLogger(ValuesParser.class);
private final BinaryXMLStrings strings;
private final Map<Integer, String> resMap;
public ValuesParser(BinaryXMLStrings strings, Map<Integer, String> resMap) {
this.strings = strings;
this.resMap = resMap;
}
@Nullable
public String getSimpleValueString(ResourceEntry ri) {
ProtoValue protoValue = ri.getProtoValue();
if (protoValue != null) {
return protoValue.getValue();
}
RawValue simpleValue = ri.getSimpleValue();
if (simpleValue == null) {
return null;
}
return decodeValue(simpleValue);
}
@Nullable
public String getValueString(ResourceEntry ri) {
ProtoValue protoValue = ri.getProtoValue();
if (protoValue != null) {
if (protoValue.getValue() != null) {
return protoValue.getValue();
}
List<ProtoValue> values = protoValue.getNamedValues();
List<String> strList = new ArrayList<>(values.size());
for (ProtoValue value : values) {
if (value.getName() == null) {
strList.add(value.getValue());
} else {
strList.add(value.getName() + '=' + value.getValue());
}
}
return strList.toString();
}
RawValue simpleValue = ri.getSimpleValue();
if (simpleValue != null) {
return decodeValue(simpleValue);
}
List<RawNamedValue> namedValues = ri.getNamedValues();
List<String> strList = new ArrayList<>(namedValues.size());
for (RawNamedValue value : namedValues) {
String nameStr = decodeNameRef(value.getNameRef());
String valueStr = decodeValue(value.getRawValue());
if (nameStr == null) {
strList.add(valueStr);
} else {
strList.add(nameStr + '=' + valueStr);
}
}
return strList.toString();
}
@Nullable
public String decodeValue(RawValue value) {
int dataType = value.getDataType();
int data = value.getData();
return decodeValue(dataType, data);
}
@Nullable
public String decodeValue(int dataType, int data) {
switch (dataType) {
case TYPE_NULL:
return null;
case TYPE_STRING:
return strings.get(data);
case TYPE_INT_DEC:
return Integer.toString(data);
case TYPE_INT_HEX:
return "0x" + Integer.toHexString(data);
case TYPE_INT_BOOLEAN:
return data == 0 ? "false" : "true";
case TYPE_FLOAT:
return XmlGenUtils.floatToString(Float.intBitsToFloat(data));
case TYPE_INT_COLOR_ARGB8:
return String.format("#%08x", data);
case TYPE_INT_COLOR_RGB8:
return String.format("#%06x", data & 0xFFFFFF);
case TYPE_INT_COLOR_ARGB4:
return String.format("#%04x", data & 0xFFFF);
case TYPE_INT_COLOR_RGB4:
return String.format("#%03x", data & 0xFFF);
case TYPE_DYNAMIC_REFERENCE:
case TYPE_REFERENCE: {
String ri = resMap.get(data);
if (ri == null) {
String androidRi = AndroidResourcesMap.getResName(data);
if (androidRi != null) {
return "@android:" + androidRi;
}
if (data == 0) {
return "0";
}
return "?unknown_ref: " + Integer.toHexString(data);
}
return '@' + ri;
}
case TYPE_ATTRIBUTE: {
String ri = resMap.get(data);
if (ri == null) {
String androidRi = AndroidResourcesMap.getResName(data);
if (androidRi != null) {
return "?android:" + androidRi;
}
return "?unknown_attr_ref: " + Integer.toHexString(data);
}
return '?' + ri;
}
case TYPE_DIMENSION:
return XmlGenUtils.decodeComplex(data, false);
case TYPE_FRACTION:
return XmlGenUtils.decodeComplex(data, true);
case TYPE_DYNAMIC_ATTRIBUTE:
LOG.warn("Data type TYPE_DYNAMIC_ATTRIBUTE not yet supported: {}", data);
return " TYPE_DYNAMIC_ATTRIBUTE: " + data;
default:
LOG.warn("Unknown data type: 0x{} {}", Integer.toHexString(dataType), data);
return " ?0x" + Integer.toHexString(dataType) + ' ' + data;
}
}
public String decodeNameRef(int nameRef) {
int ref = nameRef;
if (isResInternalId(nameRef)) {
ref = nameRef & ATTR_TYPE_ANY;
if (ref == 0) {
return null;
}
}
String ri = resMap.get(ref);
if (ri != null) {
return ri.replace('/', '.');
} else {
String androidRi = AndroidResourcesMap.getResName(ref);
if (androidRi != null) {
return "android:" + androidRi.replace('/', '.');
}
}
return "?0x" + Integer.toHexString(nameRef);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/entry/RawNamedValue.java | jadx-core/src/main/java/jadx/core/xmlgen/entry/RawNamedValue.java | package jadx.core.xmlgen.entry;
public class RawNamedValue {
private final int nameRef;
private final RawValue rawValue;
public RawNamedValue(int nameRef, RawValue rawValue) {
this.nameRef = nameRef;
this.rawValue = rawValue;
}
public int getNameRef() {
return nameRef;
}
public RawValue getRawValue() {
return rawValue;
}
@Override
public String toString() {
return "RawNamedValue{nameRef=" + nameRef + ", rawValue=" + rawValue + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/entry/EntryConfig.java | jadx-core/src/main/java/jadx/core/xmlgen/entry/EntryConfig.java | /**
* Copyright (C) 2018 Ryszard Wiśniewski <brut.alll@gmail.com>
* Copyright (C) 2018 Connor Tumbleson <connor.tumbleson@gmail.com>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jadx.core.xmlgen.entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Original source code can be found
* <a href=
* "https://raw.githubusercontent.com/iBotPeaches/Apktool/master/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResConfigFlags.java">here</a>
*/
public class EntryConfig {
private static final Logger LOG = LoggerFactory.getLogger(EntryConfig.class);
public final short mcc;
public final short mnc;
public final char[] language;
public final char[] region;
public final byte orientation;
public final byte touchscreen;
public final int density;
public final byte keyboard;
public final byte navigation;
public final byte inputFlags;
public final byte grammaticalInflection;
public final short screenWidth;
public final short screenHeight;
public final short sdkVersion;
public final byte screenLayout;
public final byte uiMode;
public final short smallestScreenWidthDp;
public final short screenWidthDp;
public final short screenHeightDp;
private final char[] localeScript;
private final char[] localeVariant;
private final byte screenLayout2;
private final byte colorMode;
public final boolean isInvalid;
private final String mQualifiers;
private final int size;
public EntryConfig(short mcc, short mnc, char[] language,
char[] region, byte orientation,
byte touchscreen, int density, byte keyboard, byte navigation,
byte inputFlags, byte grammaticalInflection, short screenWidth, short screenHeight,
short sdkVersion, byte screenLayout, byte uiMode,
short smallestScreenWidthDp, short screenWidthDp,
short screenHeightDp, char[] localeScript, char[] localeVariant,
byte screenLayout2, byte colorMode, boolean isInvalid, int size) {
if (orientation < 0 || orientation > 3) {
LOG.warn("Invalid orientation value: {}", orientation);
orientation = 0;
isInvalid = true;
}
if (touchscreen < 0 || touchscreen > 3) {
LOG.warn("Invalid touchscreen value: {}", touchscreen);
touchscreen = 0;
isInvalid = true;
}
if (density < -1) {
LOG.warn("Invalid density value: {}", density);
density = 0;
isInvalid = true;
}
if (keyboard < 0 || keyboard > 3) {
LOG.warn("Invalid keyboard value: {}", keyboard);
keyboard = 0;
isInvalid = true;
}
if (navigation < 0 || navigation > 4) {
LOG.warn("Invalid navigation value: {}", navigation);
navigation = 0;
isInvalid = true;
}
if (localeScript != null && localeScript.length != 0) {
if (localeScript[0] == '\00') {
localeScript = null;
}
} else {
localeScript = null;
}
if (localeVariant != null && localeVariant.length != 0) {
if (localeVariant[0] == '\00') {
localeVariant = null;
}
} else {
localeVariant = null;
}
this.mcc = mcc;
this.mnc = mnc;
this.language = language;
this.region = region;
this.orientation = orientation;
this.touchscreen = touchscreen;
this.density = density;
this.keyboard = keyboard;
this.navigation = navigation;
this.inputFlags = inputFlags;
this.grammaticalInflection = grammaticalInflection;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.sdkVersion = sdkVersion;
this.screenLayout = screenLayout;
this.uiMode = uiMode;
this.smallestScreenWidthDp = smallestScreenWidthDp;
this.screenWidthDp = screenWidthDp;
this.screenHeightDp = screenHeightDp;
this.localeScript = localeScript;
this.localeVariant = localeVariant;
this.screenLayout2 = screenLayout2;
this.colorMode = colorMode;
this.isInvalid = isInvalid;
this.size = size;
mQualifiers = generateQualifiers();
}
public String getQualifiers() {
return mQualifiers;
}
private String generateQualifiers() {
StringBuilder ret = new StringBuilder();
if (mcc != 0) {
ret.append("-mcc").append(String.format("%03d", mcc));
if (mnc != MNC_ZERO) {
if (mnc != 0) {
ret.append("-mnc");
if (size <= 32) {
if (mnc > 0 && mnc < 10) {
ret.append(String.format("%02d", mnc));
} else {
ret.append(String.format("%03d", mnc));
}
} else {
ret.append(mnc);
}
}
} else {
ret.append("-mnc00");
}
} else {
if (mnc != 0) {
ret.append("-mnc").append(mnc);
}
}
ret.append(getLocaleString());
switch (grammaticalInflection) {
case GRAMMATICAL_GENDER_NEUTER:
ret.append("-neuter");
break;
case GRAMMATICAL_GENDER_FEMININE:
ret.append("-feminine");
break;
case GRAMMATICAL_GENDER_MASCULINE:
ret.append("-masculine");
break;
}
switch (screenLayout & MASK_LAYOUTDIR) {
case SCREENLAYOUT_LAYOUTDIR_RTL:
ret.append("-ldrtl");
break;
case SCREENLAYOUT_LAYOUTDIR_LTR:
ret.append("-ldltr");
break;
}
if (smallestScreenWidthDp != 0) {
ret.append("-sw").append(smallestScreenWidthDp).append("dp");
}
if (screenWidthDp != 0) {
ret.append("-w").append(screenWidthDp).append("dp");
}
if (screenHeightDp != 0) {
ret.append("-h").append(screenHeightDp).append("dp");
}
switch (screenLayout & MASK_SCREENSIZE) {
case SCREENSIZE_SMALL:
ret.append("-small");
break;
case SCREENSIZE_NORMAL:
ret.append("-normal");
break;
case SCREENSIZE_LARGE:
ret.append("-large");
break;
case SCREENSIZE_XLARGE:
ret.append("-xlarge");
break;
}
switch (screenLayout & MASK_SCREENLONG) {
case SCREENLONG_YES:
ret.append("-long");
break;
case SCREENLONG_NO:
ret.append("-notlong");
break;
}
switch (screenLayout2 & MASK_SCREENROUND) {
case SCREENLAYOUT_ROUND_NO:
ret.append("-notround");
break;
case SCREENLAYOUT_ROUND_YES:
ret.append("-round");
break;
}
switch (colorMode & COLOR_HDR_MASK) {
case COLOR_HDR_YES:
ret.append("-highdr");
break;
case COLOR_HDR_NO:
ret.append("-lowdr");
break;
}
switch (colorMode & COLOR_WIDE_MASK) {
case COLOR_WIDE_YES:
ret.append("-widecg");
break;
case COLOR_WIDE_NO:
ret.append("-nowidecg");
break;
}
switch (orientation) {
case ORIENTATION_PORT:
ret.append("-port");
break;
case ORIENTATION_LAND:
ret.append("-land");
break;
case ORIENTATION_SQUARE:
ret.append("-square");
break;
}
switch (uiMode & MASK_UI_MODE_TYPE) {
case UI_MODE_TYPE_CAR:
ret.append("-car");
break;
case UI_MODE_TYPE_DESK:
ret.append("-desk");
break;
case UI_MODE_TYPE_TELEVISION:
ret.append("-television");
break;
case UI_MODE_TYPE_SMALLUI:
ret.append("-smallui");
break;
case UI_MODE_TYPE_MEDIUMUI:
ret.append("-mediumui");
break;
case UI_MODE_TYPE_LARGEUI:
ret.append("-largeui");
break;
case UI_MODE_TYPE_GODZILLAUI:
ret.append("-godzillaui");
break;
case UI_MODE_TYPE_HUGEUI:
ret.append("-hugeui");
break;
case UI_MODE_TYPE_APPLIANCE:
ret.append("-appliance");
break;
case UI_MODE_TYPE_WATCH:
ret.append("-watch");
break;
case UI_MODE_TYPE_VR_HEADSET:
ret.append("-vrheadset");
break;
}
switch (uiMode & MASK_UI_MODE_NIGHT) {
case UI_MODE_NIGHT_YES:
ret.append("-night");
break;
case UI_MODE_NIGHT_NO:
ret.append("-notnight");
break;
}
switch (density) {
case DENSITY_DEFAULT:
break;
case DENSITY_LOW:
ret.append("-ldpi");
break;
case DENSITY_MEDIUM:
ret.append("-mdpi");
break;
case DENSITY_HIGH:
ret.append("-hdpi");
break;
case DENSITY_TV:
ret.append("-tvdpi");
break;
case DENSITY_XHIGH:
ret.append("-xhdpi");
break;
case DENSITY_XXHIGH:
ret.append("-xxhdpi");
break;
case DENSITY_XXXHIGH:
ret.append("-xxxhdpi");
break;
case DENSITY_ANY:
ret.append("-anydpi");
break;
case DENSITY_NONE:
ret.append("-nodpi");
break;
default:
ret.append('-').append(density).append("dpi");
}
switch (touchscreen) {
case TOUCHSCREEN_NOTOUCH:
ret.append("-notouch");
break;
case TOUCHSCREEN_STYLUS:
ret.append("-stylus");
break;
case TOUCHSCREEN_FINGER:
ret.append("-finger");
break;
}
switch (inputFlags & MASK_KEYSHIDDEN) {
case KEYSHIDDEN_NO:
ret.append("-keysexposed");
break;
case KEYSHIDDEN_YES:
ret.append("-keyshidden");
break;
case KEYSHIDDEN_SOFT:
ret.append("-keyssoft");
break;
}
switch (keyboard) {
case KEYBOARD_NOKEYS:
ret.append("-nokeys");
break;
case KEYBOARD_QWERTY:
ret.append("-qwerty");
break;
case KEYBOARD_12KEY:
ret.append("-12key");
break;
}
switch (inputFlags & MASK_NAVHIDDEN) {
case NAVHIDDEN_NO:
ret.append("-navexposed");
break;
case NAVHIDDEN_YES:
ret.append("-navhidden");
break;
}
switch (navigation) {
case NAVIGATION_NONAV:
ret.append("-nonav");
break;
case NAVIGATION_DPAD:
ret.append("-dpad");
break;
case NAVIGATION_TRACKBALL:
ret.append("-trackball");
break;
case NAVIGATION_WHEEL:
ret.append("-wheel");
break;
}
if (screenWidth != 0 && screenHeight != 0) {
if (screenWidth > screenHeight) {
ret.append(String.format("-%dx%d", screenWidth, screenHeight));
} else {
ret.append(String.format("-%dx%d", screenHeight, screenWidth));
}
}
if (sdkVersion > 0 && sdkVersion >= getNaturalSdkVersionRequirement()) {
ret.append("-v").append(sdkVersion);
}
if (isInvalid) {
ret.append("-ERR").append(sErrCounter++);
}
return ret.toString();
}
private short getNaturalSdkVersionRequirement() {
if ((uiMode & MASK_UI_MODE_TYPE) == UI_MODE_TYPE_VR_HEADSET || (colorMode & COLOR_WIDE_MASK) != 0
|| ((colorMode & COLOR_HDR_MASK) != 0)) {
return SDK_OREO;
}
if ((screenLayout2 & MASK_SCREENROUND) != 0) {
return SDK_MNC;
}
if (density == DENSITY_ANY) {
return SDK_LOLLIPOP;
}
if (smallestScreenWidthDp != 0 || screenWidthDp != 0 || screenHeightDp != 0) {
return SDK_HONEYCOMB_MR2;
}
if ((uiMode & (MASK_UI_MODE_TYPE | MASK_UI_MODE_NIGHT)) != UI_MODE_NIGHT_ANY) {
return SDK_FROYO;
}
if ((screenLayout & (MASK_SCREENSIZE | MASK_SCREENLONG)) != SCREENSIZE_ANY || density != DENSITY_DEFAULT) {
return SDK_DONUT;
}
return 0;
}
private String getLocaleString() {
StringBuilder sb = new StringBuilder();
// check for old style non BCP47 tags
// allows values-xx-rXX, values-xx, values-xxx-rXX
// denies values-xxx, anything else
if (localeVariant == null && localeScript == null && (region[0] != '\00' || language[0] != '\00')
&& region.length != 3) {
sb.append('-').append(language);
if (region[0] != '\00') {
sb.append("-r").append(region);
}
} else { // BCP47
if (language[0] == '\00' && region[0] == '\00') {
return sb.toString(); // early return, no language or region
}
sb.append("-b+");
if (language[0] != '\00') {
sb.append(language);
}
if (localeScript != null && localeScript.length == 4) {
sb.append('+').append(localeScript);
}
if ((region.length == 2 || region.length == 3) && region[0] != '\00') {
sb.append('+').append(region);
}
if (localeVariant != null && localeVariant.length >= 5) {
sb.append('+').append(toUpper(localeVariant));
}
}
return sb.toString();
}
private String toUpper(char[] character) {
StringBuilder sb = new StringBuilder();
for (char ch : character) {
sb.append(Character.toUpperCase(ch));
}
return sb.toString();
}
@Override
public String toString() {
return !getQualifiers().isEmpty() ? getQualifiers() : "[DEFAULT]";
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final EntryConfig other = (EntryConfig) obj;
return this.mQualifiers.equals(other.mQualifiers);
}
@Override
public int hashCode() {
int hash = 17;
hash = 31 * hash + this.mQualifiers.hashCode();
return hash;
}
// TODO: Dirty static hack. This counter should be a part of ResPackage,
// but it would be hard right now and this feature is very rarely used.
private static int sErrCounter = 0;
public static final byte SDK_BASE = 1;
public static final byte SDK_BASE_1_1 = 2;
public static final byte SDK_CUPCAKE = 3;
public static final byte SDK_DONUT = 4;
public static final byte SDK_ECLAIR = 5;
public static final byte SDK_ECLAIR_0_1 = 6;
public static final byte SDK_ECLAIR_MR1 = 7;
public static final byte SDK_FROYO = 8;
public static final byte SDK_GINGERBREAD = 9;
public static final byte SDK_GINGERBREAD_MR1 = 10;
public static final byte SDK_HONEYCOMB = 11;
public static final byte SDK_HONEYCOMB_MR1 = 12;
public static final byte SDK_HONEYCOMB_MR2 = 13;
public static final byte SDK_ICE_CREAM_SANDWICH = 14;
public static final byte SDK_ICE_CREAM_SANDWICH_MR1 = 15;
public static final byte SDK_JELLY_BEAN = 16;
public static final byte SDK_JELLY_BEAN_MR1 = 17;
public static final byte SDK_JELLY_BEAN_MR2 = 18;
public static final byte SDK_KITKAT = 19;
public static final byte SDK_LOLLIPOP = 21;
public static final byte SDK_LOLLIPOP_MR1 = 22;
public static final byte SDK_MNC = 23;
public static final byte SDK_NOUGAT = 24;
public static final byte SDK_NOUGAT_MR1 = 25;
public static final byte SDK_OREO = 26;
public static final byte SDK_OREO_MR1 = 27;
public static final byte SDK_P = 28;
public static final byte ORIENTATION_ANY = 0;
public static final byte ORIENTATION_PORT = 1;
public static final byte ORIENTATION_LAND = 2;
public static final byte ORIENTATION_SQUARE = 3;
public static final byte TOUCHSCREEN_ANY = 0;
public static final byte TOUCHSCREEN_NOTOUCH = 1;
public static final byte TOUCHSCREEN_STYLUS = 2;
public static final byte TOUCHSCREEN_FINGER = 3;
public static final int DENSITY_DEFAULT = 0;
public static final int DENSITY_LOW = 120;
public static final int DENSITY_MEDIUM = 160;
public static final int DENSITY_400 = 190;
public static final int DENSITY_TV = 213;
public static final int DENSITY_HIGH = 240;
public static final int DENSITY_XHIGH = 320;
public static final int DENSITY_XXHIGH = 480;
public static final int DENSITY_XXXHIGH = 640;
public static final int DENSITY_ANY = 0xFFFE;
public static final int DENSITY_NONE = 0xFFFF;
public static final int MNC_ZERO = -1;
public static final short MASK_LAYOUTDIR = 0xc0;
public static final short SCREENLAYOUT_LAYOUTDIR_ANY = 0x00;
public static final short SCREENLAYOUT_LAYOUTDIR_LTR = 0x40;
public static final short SCREENLAYOUT_LAYOUTDIR_RTL = 0x80;
public static final short SCREENLAYOUT_LAYOUTDIR_SHIFT = 0x06;
public static final short MASK_SCREENROUND = 0x03;
public static final short SCREENLAYOUT_ROUND_ANY = 0;
public static final short SCREENLAYOUT_ROUND_NO = 0x1;
public static final short SCREENLAYOUT_ROUND_YES = 0x2;
public static final byte KEYBOARD_ANY = 0;
public static final byte KEYBOARD_NOKEYS = 1;
public static final byte KEYBOARD_QWERTY = 2;
public static final byte KEYBOARD_12KEY = 3;
public static final byte NAVIGATION_ANY = 0;
public static final byte NAVIGATION_NONAV = 1;
public static final byte NAVIGATION_DPAD = 2;
public static final byte NAVIGATION_TRACKBALL = 3;
public static final byte NAVIGATION_WHEEL = 4;
public static final byte MASK_KEYSHIDDEN = 0x3;
public static final byte KEYSHIDDEN_ANY = 0x0;
public static final byte KEYSHIDDEN_NO = 0x1;
public static final byte KEYSHIDDEN_YES = 0x2;
public static final byte KEYSHIDDEN_SOFT = 0x3;
public static final byte MASK_NAVHIDDEN = 0xc;
public static final byte NAVHIDDEN_ANY = 0x0;
public static final byte NAVHIDDEN_NO = 0x4;
public static final byte NAVHIDDEN_YES = 0x8;
public static final byte MASK_SCREENSIZE = 0x0f;
public static final byte SCREENSIZE_ANY = 0x00;
public static final byte SCREENSIZE_SMALL = 0x01;
public static final byte SCREENSIZE_NORMAL = 0x02;
public static final byte SCREENSIZE_LARGE = 0x03;
public static final byte SCREENSIZE_XLARGE = 0x04;
public static final byte MASK_SCREENLONG = 0x30;
public static final byte SCREENLONG_ANY = 0x00;
public static final byte SCREENLONG_NO = 0x10;
public static final byte SCREENLONG_YES = 0x20;
public static final byte MASK_UI_MODE_TYPE = 0x0f;
public static final byte UI_MODE_TYPE_ANY = 0x00;
public static final byte UI_MODE_TYPE_NORMAL = 0x01;
public static final byte UI_MODE_TYPE_DESK = 0x02;
public static final byte UI_MODE_TYPE_CAR = 0x03;
public static final byte UI_MODE_TYPE_TELEVISION = 0x04;
public static final byte UI_MODE_TYPE_APPLIANCE = 0x05;
public static final byte UI_MODE_TYPE_WATCH = 0x06;
public static final byte UI_MODE_TYPE_VR_HEADSET = 0x07;
// start - miui
public static final byte UI_MODE_TYPE_GODZILLAUI = 0x0b;
public static final byte UI_MODE_TYPE_SMALLUI = 0x0c;
public static final byte UI_MODE_TYPE_MEDIUMUI = 0x0d;
public static final byte UI_MODE_TYPE_LARGEUI = 0x0e;
public static final byte UI_MODE_TYPE_HUGEUI = 0x0f;
// end - miui
public static final byte MASK_UI_MODE_NIGHT = 0x30;
public static final byte UI_MODE_NIGHT_ANY = 0x00;
public static final byte UI_MODE_NIGHT_NO = 0x10;
public static final byte UI_MODE_NIGHT_YES = 0x20;
public static final byte COLOR_HDR_MASK = 0xC;
public static final byte COLOR_HDR_NO = 0x4;
public static final byte COLOR_HDR_SHIFT = 0x2;
public static final byte COLOR_HDR_UNDEFINED = 0x0;
public static final byte COLOR_HDR_YES = 0x8;
public static final byte COLOR_UNDEFINED = 0x0;
public static final byte COLOR_WIDE_UNDEFINED = 0x0;
public static final byte COLOR_WIDE_NO = 0x1;
public static final byte COLOR_WIDE_YES = 0x2;
public static final byte COLOR_WIDE_MASK = 0x3;
public static final byte GRAMMATICAL_GENDER_ANY = 0;
public static final byte GRAMMATICAL_GENDER_NEUTER = 1;
public static final byte GRAMMATICAL_GENDER_FEMININE = 2;
public static final byte GRAMMATICAL_GENDER_MASCULINE = 3;
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/entry/ResourceEntry.java | jadx-core/src/main/java/jadx/core/xmlgen/entry/ResourceEntry.java | package jadx.core.xmlgen.entry;
import java.util.List;
public final class ResourceEntry {
private final int id;
private final String pkgName;
private final String typeName;
private final String keyName;
private final String config;
private int parentRef;
private ProtoValue protoValue;
private RawValue simpleValue;
private List<RawNamedValue> namedValues;
public ResourceEntry(int id, String pkgName, String typeName, String keyName, String config) {
this.id = id;
this.pkgName = pkgName;
this.typeName = typeName;
this.keyName = keyName;
this.config = config;
}
public ResourceEntry copy(String newKeyName) {
ResourceEntry copy = new ResourceEntry(id, pkgName, typeName, newKeyName, config);
copy.parentRef = this.parentRef;
copy.protoValue = this.protoValue;
copy.simpleValue = this.simpleValue;
copy.namedValues = this.namedValues;
return copy;
}
public ResourceEntry copyWithId() {
return copy(String.format("%s_res_0x%08x", keyName, id));
}
public int getId() {
return id;
}
public String getPkgName() {
return pkgName;
}
public String getTypeName() {
return typeName;
}
public String getKeyName() {
return keyName;
}
public String getConfig() {
return config;
}
public void setParentRef(int parentRef) {
this.parentRef = parentRef;
}
public int getParentRef() {
return parentRef;
}
public ProtoValue getProtoValue() {
return protoValue;
}
public void setProtoValue(ProtoValue protoValue) {
this.protoValue = protoValue;
}
public RawValue getSimpleValue() {
return simpleValue;
}
public void setSimpleValue(RawValue simpleValue) {
this.simpleValue = simpleValue;
}
public void setNamedValues(List<RawNamedValue> namedValues) {
this.namedValues = namedValues;
}
public List<RawNamedValue> getNamedValues() {
return namedValues;
}
@Override
public String toString() {
return " 0x" + Integer.toHexString(id) + " (" + id + ')' + config + " = " + typeName + '.' + keyName;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/entry/ProtoValue.java | jadx-core/src/main/java/jadx/core/xmlgen/entry/ProtoValue.java | package jadx.core.xmlgen.entry;
import java.util.List;
public class ProtoValue {
private String parent;
private String name;
private String value;
private int type;
private List<ProtoValue> namedValues;
public ProtoValue(String value) {
this.value = value;
}
public ProtoValue() {
}
public int getType() {
return type;
}
public ProtoValue setType(int type) {
this.type = type;
return this;
}
public String getValue() {
return value;
}
public String getParent() {
return parent;
}
public ProtoValue setParent(String parent) {
this.parent = parent;
return this;
}
public ProtoValue setName(String name) {
this.name = name;
return this;
}
public String getName() {
return name;
}
public ProtoValue setNamedValues(List<ProtoValue> namedValues) {
this.namedValues = namedValues;
return this;
}
public List<ProtoValue> getNamedValues() {
return namedValues;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/xmlgen/entry/RawValue.java | jadx-core/src/main/java/jadx/core/xmlgen/entry/RawValue.java | package jadx.core.xmlgen.entry;
public final class RawValue {
private final int dataType;
private final int data;
public RawValue(int dataType, int data) {
this.dataType = dataType;
this.data = data;
}
public int getDataType() {
return dataType;
}
public int getData() {
return data;
}
@Override
public String toString() {
return "RawValue: type=0x" + Integer.toHexString(dataType) + ", value=" + data;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/GsonUtils.java | jadx-core/src/main/java/jadx/core/utils/GsonUtils.java | package jadx.core.utils;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.Strictness;
public class GsonUtils {
public static Gson buildGson() {
return defaultGsonBuilder().create();
}
public static GsonBuilder defaultGsonBuilder() {
return new GsonBuilder()
.disableJdkUnsafe()
.disableInnerClassSerialization()
.setStrictness(Strictness.STRICT)
.setPrettyPrinting();
}
public static <T> InterfaceReplace<T> interfaceReplace(Class<T> replaceCls) {
return new InterfaceReplace<>(replaceCls);
}
public static final class InterfaceReplace<T> implements JsonSerializer<T>, JsonDeserializer<T> {
private final Class<T> replaceCls;
private InterfaceReplace(Class<T> replaceCls) {
this.replaceCls = replaceCls;
}
@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return context.deserialize(json, this.replaceCls);
}
@Override
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src, this.replaceCls);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/EncodedValueUtils.java | jadx-core/src/main/java/jadx/core/utils/EncodedValueUtils.java | package jadx.core.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import jadx.api.plugins.input.data.IMethodHandle;
import jadx.api.plugins.input.data.IMethodProto;
import jadx.api.plugins.input.data.IMethodRef;
import jadx.api.plugins.input.data.MethodHandleType;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.ConstClassNode;
import jadx.core.dex.instructions.ConstStringNode;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.InvokeType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class EncodedValueUtils {
/**
* Return constant literal from {@code jadx.api.plugins.input.data.annotations.EncodedValue}
*
* @return LiteralArg, String, ArgType or null
*/
@Nullable
public static Object convertToConstValue(EncodedValue encodedValue) {
if (encodedValue == null) {
return null;
}
Object value = encodedValue.getValue();
switch (encodedValue.getType()) {
case ENCODED_NULL:
return InsnArg.lit(0, ArgType.OBJECT);
case ENCODED_BOOLEAN:
return Boolean.TRUE.equals(value) ? LiteralArg.litTrue() : LiteralArg.litFalse();
case ENCODED_BYTE:
return InsnArg.lit((Byte) value, ArgType.BYTE);
case ENCODED_SHORT:
return InsnArg.lit((Short) value, ArgType.SHORT);
case ENCODED_CHAR:
return InsnArg.lit((Character) value, ArgType.CHAR);
case ENCODED_INT:
return InsnArg.lit((Integer) value, ArgType.INT);
case ENCODED_LONG:
return InsnArg.lit((Long) value, ArgType.LONG);
case ENCODED_FLOAT:
return InsnArg.lit(Float.floatToIntBits((Float) value), ArgType.FLOAT);
case ENCODED_DOUBLE:
return InsnArg.lit(Double.doubleToLongBits((Double) value), ArgType.DOUBLE);
case ENCODED_STRING:
// noinspection RedundantCast
return (String) value;
case ENCODED_TYPE:
return ArgType.parse((String) value);
default:
return null;
}
}
public static InsnArg convertToInsnArg(RootNode root, EncodedValue value) {
Object obj = value.getValue();
switch (value.getType()) {
case ENCODED_NULL:
case ENCODED_BYTE:
case ENCODED_SHORT:
case ENCODED_CHAR:
case ENCODED_INT:
case ENCODED_LONG:
case ENCODED_FLOAT:
case ENCODED_DOUBLE:
return (InsnArg) convertToConstValue(value);
case ENCODED_BOOLEAN:
return InsnArg.lit(((Boolean) obj) ? 0 : 1, ArgType.BOOLEAN);
case ENCODED_STRING:
return InsnArg.wrapArg(new ConstStringNode((String) obj));
case ENCODED_TYPE:
return InsnArg.wrapArg(new ConstClassNode(ArgType.parse((String) obj)));
case ENCODED_METHOD_TYPE:
return InsnArg.wrapArg(buildMethodType(root, (IMethodProto) obj));
case ENCODED_METHOD_HANDLE:
return InsnArg.wrapArg(buildMethodHandle(root, (IMethodHandle) obj));
}
throw new JadxRuntimeException("Unsupported type for raw invoke-custom: " + value.getType());
}
private static InvokeNode buildMethodType(RootNode root, IMethodProto methodProto) {
ArgType retType = ArgType.parse(methodProto.getReturnType());
List<ArgType> argTypes = Utils.collectionMap(methodProto.getArgTypes(), ArgType::parse);
List<ArgType> callTypes = new ArrayList<>(1 + argTypes.size());
callTypes.add(retType);
callTypes.addAll(argTypes);
ArgType mthType = ArgType.object("java.lang.invoke.MethodType");
ClassInfo cls = ClassInfo.fromType(root, mthType);
MethodInfo mth = MethodInfo.fromDetails(root, cls, "methodType", callTypes, mthType);
InvokeNode invoke = new InvokeNode(mth, InvokeType.STATIC, callTypes.size());
for (ArgType type : callTypes) {
InsnNode argInsn;
if (type.isPrimitive()) {
argInsn = new IndexInsnNode(InsnType.SGET, getTypeField(root, type.getPrimitiveType()), 0);
} else {
argInsn = new ConstClassNode(type);
}
invoke.addArg(InsnArg.wrapArg(argInsn));
}
return invoke;
}
public static FieldInfo getTypeField(RootNode root, PrimitiveType type) {
ArgType boxType = type.getBoxType();
ClassInfo boxCls = ClassInfo.fromType(root, boxType);
return FieldInfo.from(root, boxCls, "TYPE", boxType);
}
/**
* Build `MethodHandles.lookup().find{type}(methodCls, methodName, methodType)`
*/
private static InsnNode buildMethodHandle(RootNode root, IMethodHandle methodHandle) {
if (methodHandle.getType().isField()) {
// TODO: lookup for field
return new ConstStringNode("FIELD:" + methodHandle.getFieldRef());
}
IMethodRef methodRef = methodHandle.getMethodRef();
methodRef.load();
ClassInfo lookupCls = ClassInfo.fromName(root, "java.lang.invoke.MethodHandles.Lookup");
MethodInfo findMethod = MethodInfo.fromDetails(root, lookupCls,
getFindMethodName(methodHandle.getType()),
Arrays.asList(ArgType.CLASS, ArgType.STRING, ArgType.object("java.lang.invoke.MethodType")),
ArgType.object("java.lang.invoke.MethodHandle"));
InvokeNode invoke = new InvokeNode(findMethod, InvokeType.DIRECT, 4);
invoke.addArg(buildLookupArg(root));
invoke.addArg(InsnArg.wrapArg(new ConstClassNode(ArgType.object(methodRef.getParentClassType()))));
invoke.addArg(InsnArg.wrapArg(new ConstStringNode(methodRef.getName())));
invoke.addArg(InsnArg.wrapArg(buildMethodType(root, methodRef)));
return invoke;
}
public static InsnArg buildLookupArg(RootNode root) {
ArgType lookupType = ArgType.object("java.lang.invoke.MethodHandles.Lookup");
ClassInfo cls = ClassInfo.fromName(root, "java.lang.invoke.MethodHandles");
MethodInfo mth = MethodInfo.fromDetails(root, cls, "lookup", Collections.emptyList(), lookupType);
return InsnArg.wrapArg(new InvokeNode(mth, InvokeType.STATIC, 0));
}
private static String getFindMethodName(MethodHandleType type) {
switch (type) {
case INVOKE_STATIC:
return "findStatic";
case INVOKE_CONSTRUCTOR:
return "findConstructor";
case INVOKE_INSTANCE:
case INVOKE_DIRECT:
case INVOKE_INTERFACE:
return "findVirtual";
default:
return "<" + type + '>';
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/CacheStorage.java | jadx-core/src/main/java/jadx/core/utils/CacheStorage.java | package jadx.core.utils;
import java.util.Collections;
import java.util.Set;
public class CacheStorage {
private Set<String> rootPkgs = Collections.emptySet();
public Set<String> getRootPkgs() {
return rootPkgs;
}
public void setRootPkgs(Set<String> rootPkgs) {
this.rootPkgs = rootPkgs;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/ImmutableList.java | jadx-core/src/main/java/jadx/core/utils/ImmutableList.java | package jadx.core.utils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.RandomAccess;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import org.jetbrains.annotations.NotNull;
/**
* Simple immutable list implementation
* Warning: some methods not implemented!
*/
public final class ImmutableList<E> implements List<E>, RandomAccess {
private final E[] arr;
@SuppressWarnings({ "unchecked", "SuspiciousArrayCast" })
public ImmutableList(Collection<E> col) {
this((E[]) Objects.requireNonNull(col).toArray());
}
public ImmutableList(E[] arr) {
this.arr = Objects.requireNonNull(arr);
}
@Override
public int size() {
return arr.length;
}
@Override
public boolean isEmpty() {
return arr.length == 0;
}
@Override
public E get(int index) {
return arr[index];
}
@Override
public int indexOf(Object o) {
int len = arr.length;
for (int i = 0; i < len; i++) {
E e = arr[i];
if (Objects.equals(e, o)) {
return i;
}
}
return -1;
}
@Override
public int lastIndexOf(Object o) {
for (int i = arr.length - 1; i > 0; i--) {
E e = arr[i];
if (Objects.equals(e, o)) {
return i;
}
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public boolean containsAll(@NotNull Collection<?> c) {
for (Object obj : c) {
if (!contains(obj)) {
return false;
}
}
return true;
}
@NotNull
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private final int len = arr.length;
private int index = 0;
@Override
public boolean hasNext() {
return index < len;
}
@Override
public E next() {
try {
return arr[index++];
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException(e.getMessage());
}
}
};
}
@Override
public void forEach(Consumer<? super E> action) {
for (E e : arr) {
action.accept(e);
}
}
@NotNull
@Override
public Object[] toArray() {
return Arrays.copyOf(arr, arr.length);
}
@NotNull
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(@NotNull T[] a) {
return (T[]) Arrays.copyOf(arr, arr.length);
}
@Override
public boolean add(E e) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(@NotNull Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(int index, @NotNull Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(@NotNull Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(@NotNull Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void replaceAll(UnaryOperator<E> operator) {
throw new UnsupportedOperationException();
}
@Override
public void sort(Comparator<? super E> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeIf(Predicate<? super E> filter) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
@Override
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
@Override
public E remove(int index) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public ListIterator<E> listIterator() {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public ListIterator<E> listIterator(int index) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public List<E> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof ImmutableList) {
ImmutableList<?> other = (ImmutableList<?>) o;
return Arrays.equals(arr, other.arr);
}
if (o instanceof List) {
List<?> other = (List<?>) o;
int size = size();
if (size != other.size()) {
return false;
}
for (int i = 0; i < size; i++) {
E e1 = arr[i];
Object e2 = other.get(i);
if (!Objects.equals(e1, e2)) {
return false;
}
}
return true;
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(arr);
}
@Override
public String toString() {
return "ImmutableList{" + Arrays.toString(arr) + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/BlockParentContainer.java | jadx-core/src/main/java/jadx/core/utils/BlockParentContainer.java | package jadx.core.utils;
import java.util.Objects;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IContainer;
public class BlockParentContainer {
private final IContainer parent;
private final IBlock block;
public BlockParentContainer(IContainer parent, IBlock block) {
this.parent = Objects.requireNonNull(parent);
this.block = Objects.requireNonNull(block);
}
public IBlock getBlock() {
return block;
}
public IContainer getParent() {
return parent;
}
@Override
public String toString() {
return "BlockParentContainer{" + block + ", parent=" + parent + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/StringUtils.java | jadx-core/src/main/java/jadx/core/utils/StringUtils.java | package jadx.core.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.IntConsumer;
import org.jetbrains.annotations.Nullable;
import jadx.api.JadxArgs;
import jadx.api.args.IntegerFormat;
import jadx.core.deobf.NameMapper;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class StringUtils {
private static final StringUtils DEFAULT_INSTANCE = new StringUtils(new JadxArgs());
private static final String WHITES = " \t\r\n\f\b";
private static final String WORD_SEPARATORS = WHITES + "(\")<,>{}=+-*/|[]\\:;'.`~!#^&";
public static StringUtils getInstance() {
return DEFAULT_INSTANCE;
}
private final boolean escapeUnicode;
private final IntegerFormat integerFormat;
public StringUtils(JadxArgs args) {
this.escapeUnicode = args.isEscapeUnicode();
this.integerFormat = args.getIntegerFormat();
}
public IntegerFormat getIntegerFormat() {
return integerFormat;
}
public static void visitCodePoints(String str, IntConsumer visitor) {
int len = str.length();
int offset = 0;
while (offset < len) {
int codePoint = str.codePointAt(offset);
visitor.accept(codePoint);
offset += Character.charCount(codePoint);
}
}
public String unescapeString(String str) {
int len = str.length();
if (len == 0) {
return "\"\"";
}
StringBuilder res = new StringBuilder();
res.append('"');
visitCodePoints(str, codePoint -> processCodePoint(codePoint, res));
res.append('"');
return res.toString();
}
private void processCodePoint(int codePoint, StringBuilder res) {
String str = getSpecialStringForCodePoint(codePoint);
if (str != null) {
res.append(str);
return;
}
if (isEscapeNeededForCodePoint(codePoint)) {
res.append("\\u").append(String.format("%04x", codePoint));
} else {
res.appendCodePoint(codePoint);
}
}
private boolean isEscapeNeededForCodePoint(int codePoint) {
if (codePoint < 32) {
return true;
}
if (codePoint < 127) {
return false;
}
if (escapeUnicode) {
return true;
}
return !NameMapper.isPrintableCodePoint(codePoint);
}
/**
* Represent single char the best way possible
*/
public String unescapeChar(char c, boolean explicitCast) {
if (c == '\'') {
return "'\\''";
}
String str = getSpecialStringForCodePoint(c);
if (str != null) {
return '\'' + str + '\'';
}
if (c >= 127 && escapeUnicode) {
return String.format("'\\u%04x'", (int) c);
}
if (NameMapper.isPrintableChar(c)) {
return "'" + c + '\'';
}
String intStr = Integer.toString(c);
return explicitCast ? "(char) " + intStr : intStr;
}
public String unescapeChar(char ch) {
return unescapeChar(ch, false);
}
@Nullable
private String getSpecialStringForCodePoint(int c) {
switch (c) {
case '\n':
return "\\n";
case '\r':
return "\\r";
case '\t':
return "\\t";
case '\b':
return "\\b";
case '\f':
return "\\f";
case '\'':
return "'";
case '"':
return "\\\"";
case '\\':
return "\\\\";
default:
return null;
}
}
public static String escape(String str) {
int len = str.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
switch (c) {
case '.':
case '/':
case ';':
case '$':
case ' ':
case ',':
case '<':
sb.append('_');
break;
case '[':
sb.append('A');
break;
case ']':
case '>':
case '?':
case '*':
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
public static String escapeXML(String str) {
int len = str.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
String replace = escapeXmlChar(c);
if (replace != null) {
sb.append(replace);
} else {
sb.append(c);
}
}
return sb.toString();
}
public static String escapeResValue(String str) {
int len = str.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
commonEscapeAndAppend(sb, c);
}
return sb.toString();
}
public static String escapeResStrValue(String str) {
int len = str.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
switch (c) {
case '"':
sb.append("\\\"");
break;
case '\'':
sb.append("\\'");
break;
default:
commonEscapeAndAppend(sb, c);
break;
}
}
return sb.toString();
}
private static String escapeXmlChar(char c) {
if (c <= 0x1F) {
return "\\" + (int) c;
}
switch (c) {
case '&':
return "&";
case '<':
return "<";
case '>':
return ">";
case '"':
return """;
case '\'':
return "'";
case '\\':
return "\\\\";
default:
return null;
}
}
private static String escapeWhiteSpaceChar(char c) {
switch (c) {
case '\n':
return "\\n";
case '\r':
return "\\r";
case '\t':
return "\\t";
case '\b':
return "\\b";
case '\f':
return "\\f";
default:
return null;
}
}
private static void commonEscapeAndAppend(StringBuilder sb, char c) {
String replace = escapeWhiteSpaceChar(c);
if (replace == null) {
replace = escapeXmlChar(c);
}
if (replace != null) {
sb.append(replace);
} else {
sb.append(c);
}
}
public static boolean notEmpty(String str) {
return str != null && !str.isEmpty();
}
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
public static boolean notBlank(String str) {
return notEmpty(str) && !str.trim().isEmpty();
}
public static int countMatches(String str, String subStr) {
if (str == null || str.isEmpty() || subStr == null || subStr.isEmpty()) {
return 0;
}
int subStrLen = subStr.length();
int count = 0;
int idx = 0;
while ((idx = str.indexOf(subStr, idx)) != -1) {
count++;
idx += subStrLen;
}
return count;
}
public static boolean containsChar(String str, char ch) {
return str.indexOf(ch) != -1;
}
public static String removeChar(String str, char ch) {
int pos = str.indexOf(ch);
if (pos == -1) {
return str;
}
StringBuilder sb = new StringBuilder(str.length());
int cur = 0;
int next = pos;
while (true) {
sb.append(str, cur, next);
cur = next + 1;
next = str.indexOf(ch, cur);
if (next == -1) {
sb.append(str, cur, str.length());
break;
}
}
return sb.toString();
}
/**
* returns how many lines does it have between start to pos in content.
*/
public static int countLinesByPos(String content, int pos, int start) {
if (start >= pos) {
return 0;
}
int count = 0;
int tempPos = start;
do {
tempPos = content.indexOf("\n", tempPos);
if (tempPos == -1) {
break;
}
if (tempPos >= pos) {
break;
}
count += 1;
tempPos += 1;
} while (tempPos < content.length());
return count;
}
/**
* returns lines that contain pos to end if end is not -1.
*/
public static String getLine(String content, int pos, int end) {
if (pos >= content.length()) {
return "";
}
if (end != -1) {
if (end > content.length()) {
end = content.length() - 1;
}
} else {
end = pos + 1;
}
// get to line head
int headPos = content.lastIndexOf("\n", pos);
if (headPos == -1) {
headPos = 0;
}
// get to line end
int endPos = content.indexOf("\n", end);
if (endPos == -1) {
endPos = content.length();
}
return content.substring(headPos, endPos);
}
public static boolean isWhite(char chr) {
return WHITES.indexOf(chr) != -1;
}
public static boolean isWordSeparator(char chr) {
return WORD_SEPARATORS.indexOf(chr) != -1;
}
public static String removeSuffix(String str, String suffix) {
if (str.endsWith(suffix)) {
return str.substring(0, str.length() - suffix.length());
}
return str;
}
public static @Nullable String getPrefix(String str, String delim) {
int idx = str.indexOf(delim);
if (idx != -1) {
return str.substring(0, idx);
}
return null;
}
public static String getDateText() {
return new SimpleDateFormat("HH:mm:ss").format(new Date());
}
private String formatNumber(long number, int bytesLen, boolean cast) {
String numStr;
if (integerFormat.isHexadecimal()) {
String hexStr = Long.toHexString(number);
if (number < 0) {
// cut leading 'f' for negative numbers to match number type length
int len = hexStr.length();
numStr = "0x" + hexStr.substring(len - bytesLen * 2, len);
// force cast, because unsigned negative numbers are bigger
// than signed max value allowed by compiler
cast = true;
} else {
numStr = "0x" + hexStr;
}
} else {
numStr = Long.toString(number);
}
if (bytesLen == 8 && (number == Long.MIN_VALUE || Math.abs(number) >= Integer.MAX_VALUE)) {
// force cast for long values bigger than min/max int
// to resolve compiler error: "integer number too large"
cast = true;
}
if (cast) {
if (bytesLen == 8) {
return numStr + 'L';
}
return getCastStr(bytesLen) + numStr;
}
return numStr;
}
private static String getCastStr(int bytesLen) {
switch (bytesLen) {
case 1:
return "(byte) ";
case 2:
return "(short) ";
case 4:
return "(int) ";
case 8:
return "(long) ";
default:
throw new JadxRuntimeException("Unexpected number type length: " + bytesLen);
}
}
public String formatByte(long l, boolean cast) {
return formatNumber(l, 1, cast);
}
public String formatShort(long l, boolean cast) {
if (integerFormat == IntegerFormat.AUTO) {
switch ((short) l) {
case Short.MAX_VALUE:
return "Short.MAX_VALUE";
case Short.MIN_VALUE:
return "Short.MIN_VALUE";
}
}
return formatNumber(l, 2, cast);
}
public String formatInteger(long l, boolean cast) {
if (integerFormat == IntegerFormat.AUTO) {
switch ((int) l) {
case Integer.MAX_VALUE:
return "Integer.MAX_VALUE";
case Integer.MIN_VALUE:
return "Integer.MIN_VALUE";
}
}
return formatNumber(l, 4, cast);
}
public String formatLong(long l, boolean cast) {
if (integerFormat == IntegerFormat.AUTO) {
if (l == Long.MAX_VALUE) {
return "Long.MAX_VALUE";
}
if (l == Long.MIN_VALUE) {
return "Long.MIN_VALUE";
}
}
return formatNumber(l, 8, cast);
}
public static String formatDouble(double d) {
if (Double.isNaN(d)) {
return "Double.NaN";
}
if (d == Double.NEGATIVE_INFINITY) {
return "Double.NEGATIVE_INFINITY";
}
if (d == Double.POSITIVE_INFINITY) {
return "Double.POSITIVE_INFINITY";
}
if (d == Double.MIN_VALUE) {
return "Double.MIN_VALUE";
}
if (d == Double.MAX_VALUE) {
return "Double.MAX_VALUE";
}
if (d == Double.MIN_NORMAL) {
return "Double.MIN_NORMAL";
}
return Double.toString(d) + 'd';
}
public static String formatFloat(float f) {
if (Float.isNaN(f)) {
return "Float.NaN";
}
if (f == Float.NEGATIVE_INFINITY) {
return "Float.NEGATIVE_INFINITY";
}
if (f == Float.POSITIVE_INFINITY) {
return "Float.POSITIVE_INFINITY";
}
if (f == Float.MIN_VALUE) {
return "Float.MIN_VALUE";
}
if (f == Float.MAX_VALUE) {
return "Float.MAX_VALUE";
}
if (f == Float.MIN_NORMAL) {
return "Float.MIN_NORMAL";
}
return Float.toString(f) + 'f';
}
public static String capitalizeFirstChar(String str) {
if (isEmpty(str)) {
return str;
}
return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/InsnList.java | jadx-core/src/main/java/jadx/core/utils/InsnList.java | package jadx.core.utils;
import java.util.Iterator;
import java.util.List;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
public final class InsnList implements Iterable<InsnNode> {
private final List<InsnNode> list;
public InsnList(List<InsnNode> list) {
this.list = list;
}
public static void remove(List<InsnNode> list, InsnNode insn) {
for (Iterator<InsnNode> iterator = list.iterator(); iterator.hasNext();) {
InsnNode next = iterator.next();
if (next == insn) {
iterator.remove();
return;
}
}
}
public static void remove(BlockNode block, InsnNode insn) {
remove(block.getInstructions(), insn);
}
public static int getIndex(List<InsnNode> list, InsnNode insn) {
return getIndex(list, insn, 0);
}
public static int getIndex(List<InsnNode> list, InsnNode insn, int startOffset) {
int size = list.size();
for (int i = startOffset; i < size; i++) {
if (list.get(i) == insn) {
return i;
}
}
return -1;
}
public static boolean contains(List<InsnNode> list, InsnNode insn) {
return getIndex(list, insn, 0) != -1;
}
public static boolean contains(List<InsnNode> list, InsnNode insn, int startOffset) {
return getIndex(list, insn, startOffset) != -1;
}
public int getIndex(InsnNode insn) {
return getIndex(list, insn);
}
public boolean contains(InsnNode insn) {
return getIndex(insn) != -1;
}
public void remove(InsnNode insn) {
remove(list, insn);
}
public Iterator<InsnNode> iterator() {
return list.iterator();
}
public InsnNode get(int index) {
return list.get(index);
}
public int size() {
return list.size();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/PassMerge.java | jadx-core/src/main/java/jadx/core/utils/PassMerge.java | package jadx.core.utils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import jadx.api.plugins.pass.JadxPass;
import jadx.api.plugins.pass.JadxPassInfo;
import jadx.core.dex.visitors.IDexTreeVisitor;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class PassMerge {
private final List<IDexTreeVisitor> visitors;
private Set<String> mergePassesNames;
private Map<IDexTreeVisitor, String> namesMap;
public PassMerge(List<IDexTreeVisitor> visitors) {
this.visitors = visitors;
}
public void merge(List<JadxPass> customPasses, Function<JadxPass, IDexTreeVisitor> wrap) {
if (Utils.isEmpty(customPasses)) {
return;
}
List<MergePass> mergePasses = ListUtils.map(customPasses, p -> new MergePass(p, wrap.apply(p), p.getInfo()));
linkDeps(mergePasses);
mergePasses.sort(new ExtDepsComparator(visitors).thenComparing(InvertedDepsComparator.INSTANCE));
namesMap = new IdentityHashMap<>();
visitors.forEach(p -> namesMap.put(p, p.getName()));
mergePasses.forEach(p -> namesMap.put(p.getVisitor(), p.getName()));
mergePassesNames = mergePasses.stream().map(MergePass::getName).collect(Collectors.toSet());
for (MergePass mergePass : mergePasses) {
int pos = searchInsertPos(mergePass);
if (pos == -1) {
visitors.add(mergePass.getVisitor());
} else {
visitors.add(pos, mergePass.getVisitor());
}
}
}
private int searchInsertPos(MergePass pass) {
List<String> runAfter = pass.after();
List<String> runBefore = pass.before();
if (runAfter.isEmpty() && runBefore.isEmpty()) {
return -1; // last
}
if (ListUtils.isSingleElement(runAfter, JadxPassInfo.START)) {
return 0;
}
if (ListUtils.isSingleElement(runBefore, JadxPassInfo.END)) {
return -1;
}
int visitorsCount = visitors.size();
Map<String, Integer> namePosMap = new HashMap<>(visitorsCount);
for (int i = 0; i < visitorsCount; i++) {
namePosMap.put(namesMap.get(visitors.get(i)), i);
}
int after = -1;
for (String name : runAfter) {
Integer pos = namePosMap.get(name);
if (pos != null) {
after = Math.max(after, pos);
} else {
if (mergePassesNames.contains(name)) {
// ignore known passes
continue;
}
throw new JadxRuntimeException("Ordering pass not found: " + name
+ ", listed in 'runAfter' of pass: " + pass
+ "\n all passes: " + ListUtils.map(visitors, namesMap::get));
}
}
int before = Integer.MAX_VALUE;
for (String name : runBefore) {
Integer pos = namePosMap.get(name);
if (pos != null) {
before = Math.min(before, pos);
} else {
if (mergePassesNames.contains(name)) {
// ignore known passes
continue;
}
throw new JadxRuntimeException("Ordering pass not found: " + name
+ ", listed in 'runBefore' of pass: " + pass
+ "\n all passes: " + ListUtils.map(visitors, namesMap::get));
}
}
if (before <= after) {
throw new JadxRuntimeException("Conflict order requirements for pass: " + pass
+ "\n run after: " + runAfter
+ "\n run before: " + runBefore
+ "\n passes: " + ListUtils.map(visitors, namesMap::get));
}
if (after == -1) {
if (before == Integer.MAX_VALUE) {
// not ordered, put at last
return -1;
}
return before;
}
int pos = after + 1;
return pos >= visitorsCount ? -1 : pos;
}
private static final class MergePass {
private final JadxPass pass;
private final IDexTreeVisitor visitor;
private final JadxPassInfo info;
// copy dep lists for future modifications
private final List<String> before;
private final List<String> after;
private MergePass(JadxPass pass, IDexTreeVisitor visitor, JadxPassInfo info) {
this.pass = pass;
this.visitor = visitor;
this.info = info;
this.before = new ArrayList<>(info.runBefore());
this.after = new ArrayList<>(info.runAfter());
}
public JadxPass getPass() {
return pass;
}
public IDexTreeVisitor getVisitor() {
return visitor;
}
public String getName() {
return info.getName();
}
public JadxPassInfo getInfo() {
return info;
}
public List<String> before() {
return before;
}
public List<String> after() {
return after;
}
@Override
public String toString() {
return info.getName();
}
}
/**
* Make deps double linked
*/
private static void linkDeps(List<MergePass> mergePasses) {
Map<String, MergePass> map = mergePasses.stream().collect(Collectors.toMap(MergePass::getName, p -> p));
for (MergePass pass : mergePasses) {
for (String after : pass.getInfo().runAfter()) {
MergePass beforePass = map.get(after);
if (beforePass != null) {
beforePass.before().add(pass.getName());
}
}
for (String before : pass.getInfo().runBefore()) {
MergePass afterPass = map.get(before);
if (afterPass != null) {
afterPass.after().add(pass.getName());
}
}
}
}
/**
* Place passes with visitors dependencies before others.
*/
private static class ExtDepsComparator implements Comparator<MergePass> {
private final Set<String> names;
public ExtDepsComparator(List<IDexTreeVisitor> visitors) {
this.names = visitors.stream()
.map(IDexTreeVisitor::getName)
.collect(Collectors.toSet());
}
@Override
public int compare(MergePass first, MergePass second) {
boolean isFirst = containsVisitor(first.before()) || containsVisitor(first.after());
boolean isSecond = containsVisitor(second.before()) || containsVisitor(second.after());
return -Boolean.compare(isFirst, isSecond);
}
private boolean containsVisitor(List<String> deps) {
for (String dep : deps) {
if (names.contains(dep)) {
return true;
}
}
return false;
}
}
/**
* Sort to get inverted dependencies i.e. if pass depends on another place it before.
*/
private static class InvertedDepsComparator implements Comparator<MergePass> {
public static final InvertedDepsComparator INSTANCE = new InvertedDepsComparator();
@Override
public int compare(MergePass first, MergePass second) {
if (first.before().contains(second.getName())
|| first.after().contains(second.getName())) {
return 1;
}
if (second.before().contains(first.getName())
|| second.after().contains(first.getName())) {
return -1;
}
return 0;
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/Utils.java | jadx-core/src/main/java/jadx/core/utils/Utils.java | package jadx.core.utils;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeWriter;
import jadx.api.JadxDecompiler;
import jadx.core.dex.visitors.DepthTraversal;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class Utils {
private static final String JADX_API_PACKAGE = JadxDecompiler.class.getPackage().getName();
private static final String STACKTRACE_STOP_CLS_NAME = DepthTraversal.class.getName();
private Utils() {
}
public static String cleanObjectName(String obj) {
if (obj.charAt(0) == 'L') {
int last = obj.length() - 1;
if (obj.charAt(last) == ';') {
return obj.substring(1, last).replace('/', '.');
}
}
return obj;
}
public static String cutObject(String obj) {
if (obj.charAt(0) == 'L') {
return obj.substring(1, obj.length() - 1);
}
return obj;
}
public static String makeQualifiedObjectName(String obj) {
return 'L' + obj.replace('.', '/') + ';';
}
@SuppressWarnings("StringRepeatCanBeUsed")
public static String strRepeat(String str, int count) {
if (count < 1) {
return "";
}
if (count == 1) {
return str;
}
StringBuilder sb = new StringBuilder(str.length() * count);
for (int i = 0; i < count; i++) {
sb.append(str);
}
return sb.toString();
}
public static String listToString(Iterable<?> objects) {
return listToString(objects, ", ");
}
public static String listToString(Iterable<?> objects, String joiner) {
if (objects == null) {
return "";
}
return listToString(objects, joiner, Objects::toString);
}
public static <T> String listToString(Iterable<T> objects, Function<T, String> toStr) {
return listToString(objects, ", ", toStr);
}
public static <T> String listToString(Iterable<T> objects, String joiner, Function<T, String> toStr) {
StringBuilder sb = new StringBuilder();
listToString(sb, objects, joiner, toStr);
return sb.toString();
}
public static <T> void listToString(StringBuilder sb, Iterable<T> objects, String joiner) {
listToString(sb, objects, joiner, Objects::toString);
}
public static <T> void listToString(StringBuilder sb, Iterable<T> objects, String joiner, Function<T, String> toStr) {
if (objects == null) {
return;
}
Iterator<T> it = objects.iterator();
if (it.hasNext()) {
sb.append(toStr.apply(it.next()));
}
while (it.hasNext()) {
sb.append(joiner).append(toStr.apply(it.next()));
}
}
public static <T> String arrayToStr(T[] arr) {
int len = arr == null ? 0 : arr.length;
if (len == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(arr[0]);
for (int i = 1; i < len; i++) {
sb.append(", ").append(arr[i]);
}
return sb.toString();
}
public static String concatStrings(List<String> list) {
if (isEmpty(list)) {
return "";
}
if (list.size() == 1) {
return list.get(0);
}
StringBuilder sb = new StringBuilder();
list.forEach(sb::append);
return sb.toString();
}
public static String currentStackTrace() {
return getStackTrace(new Exception());
}
public static String currentStackTrace(int skipFrames) {
Exception e = new Exception();
StackTraceElement[] stackTrace = e.getStackTrace();
int len = stackTrace.length;
if (skipFrames < len) {
e.setStackTrace(Arrays.copyOfRange(stackTrace, skipFrames, len));
}
return getStackTrace(e);
}
public static String getFullStackTrace(Throwable throwable) {
return getStackTrace(throwable, false);
}
public static String getStackTrace(Throwable throwable) {
return getStackTrace(throwable, true);
}
private static String getStackTrace(Throwable throwable, boolean filter) {
if (throwable == null) {
return "";
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
if (filter) {
filterRecursive(throwable);
}
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
public static void appendStackTrace(ICodeWriter code, Throwable throwable) {
if (throwable == null) {
return;
}
code.startLine();
OutputStream w = new OutputStream() {
@Override
public void write(int b) {
char c = (char) b;
switch (c) {
case '\n':
code.startLine();
break;
case '\r':
// ignore
break;
default:
code.add(c);
break;
}
}
};
try (PrintWriter pw = new PrintWriter(w, true)) {
filterRecursive(throwable);
throwable.printStackTrace(pw);
pw.flush();
}
}
private static void filterRecursive(Throwable th) {
try {
filter(th);
} catch (Exception e) {
// ignore filter exceptions
}
Throwable cause = th.getCause();
if (cause != null) {
filterRecursive(cause);
}
}
private static void filter(Throwable th) {
StackTraceElement[] stackTrace = th.getStackTrace();
int length = stackTrace.length;
StackTraceElement prevElement = null;
for (int i = 0; i < length; i++) {
StackTraceElement stackTraceElement = stackTrace[i];
String clsName = stackTraceElement.getClassName();
if (clsName.equals(STACKTRACE_STOP_CLS_NAME)
|| clsName.startsWith(JADX_API_PACKAGE)
|| Objects.equals(prevElement, stackTraceElement)) {
th.setStackTrace(Arrays.copyOfRange(stackTrace, 0, i));
return;
}
prevElement = stackTraceElement;
}
// stop condition not found -> just cut tail to any jadx class
for (int i = length - 1; i >= 0; i--) {
String clsName = stackTrace[i].getClassName();
if (clsName.startsWith("jadx.")) {
if (clsName.startsWith("jadx.tests.")) {
continue;
}
th.setStackTrace(Arrays.copyOfRange(stackTrace, 0, i));
return;
}
}
}
public static <T, R> List<R> collectionMap(Collection<T> list, Function<T, R> mapFunc) {
if (list == null || list.isEmpty()) {
return Collections.emptyList();
}
List<R> result = new ArrayList<>(list.size());
for (T t : list) {
result.add(mapFunc.apply(t));
}
return result;
}
public static <T, R> List<R> collectionMapNoNull(Collection<T> list, Function<T, R> mapFunc) {
if (list == null || list.isEmpty()) {
return Collections.emptyList();
}
List<R> result = new ArrayList<>(list.size());
for (T t : list) {
R r = mapFunc.apply(t);
if (r != null) {
result.add(r);
}
}
return result;
}
public static <T> boolean containsInListByRef(List<T> list, T element) {
if (isEmpty(list)) {
return false;
}
for (T t : list) {
if (t == element) {
return true;
}
}
return false;
}
public static <T> int indexInListByRef(List<T> list, T element) {
if (list == null || list.isEmpty()) {
return -1;
}
int size = list.size();
for (int i = 0; i < size; i++) {
T t = list.get(i);
if (t == element) {
return i;
}
}
return -1;
}
public static <T> List<T> lockList(List<T> list) {
if (list.isEmpty()) {
return Collections.emptyList();
}
if (list.size() == 1) {
return Collections.singletonList(list.get(0));
}
return new ImmutableList<>(list);
}
/**
* Sub list from startIndex (inclusive) to list end
*/
public static <T> List<T> listTail(List<T> list, int startIndex) {
if (startIndex == 0) {
return list;
}
int size = list.size();
if (startIndex >= size) {
return Collections.emptyList();
}
return list.subList(startIndex, size);
}
public static <T> List<T> mergeLists(List<T> first, List<T> second) {
if (isEmpty(first)) {
return second;
}
if (isEmpty(second)) {
return first;
}
List<T> result = new ArrayList<>(first.size() + second.size());
result.addAll(first);
result.addAll(second);
return result;
}
public static <T> Set<T> mergeSets(Set<T> first, Set<T> second) {
if (isEmpty(first)) {
return second;
}
if (isEmpty(second)) {
return first;
}
Set<T> result = new HashSet<>(first.size() + second.size());
result.addAll(first);
result.addAll(second);
return result;
}
public static Map<String, String> newConstStringMap(String... parameters) {
int len = parameters.length;
if (len == 0) {
return Collections.emptyMap();
}
if (len % 2 != 0) {
throw new IllegalArgumentException("Incorrect arguments count: " + len);
}
Map<String, String> result = new HashMap<>(len / 2);
for (int i = 0; i < len - 1; i += 2) {
result.put(parameters[i], parameters[i + 1]);
}
return Collections.unmodifiableMap(result);
}
/**
* Merge two maps. Return HashMap as result. Second map will override values from first map.
*/
public static <K, V> Map<K, V> mergeMaps(Map<K, V> first, Map<K, V> second) {
if (isEmpty(first)) {
return second;
}
if (isEmpty(second)) {
return first;
}
Map<K, V> result = new HashMap<>(first.size() + second.size());
result.putAll(first);
result.putAll(second);
return result;
}
/**
* Build map from list of values with value to key mapping function
* <br>
* Similar to:
* <br>
* {@code list.stream().collect(Collectors.toMap(mapKey, Function.identity())); }
*/
public static <K, V> Map<K, V> groupBy(List<V> list, Function<V, K> mapKey) {
Map<K, V> map = new HashMap<>(list.size());
for (V v : list) {
map.put(mapKey.apply(v), v);
}
return map;
}
/**
* Simple DFS visit for tree (cycles not allowed)
*/
public static <T> void treeDfsVisit(T root, Function<T, List<T>> childrenProvider, Consumer<T> visitor) {
multiRootTreeDfsVisit(Collections.singletonList(root), childrenProvider, visitor);
}
public static <T> void multiRootTreeDfsVisit(List<T> roots, Function<T, List<T>> childrenProvider, Consumer<T> visitor) {
Deque<T> queue = new ArrayDeque<>(roots);
while (true) {
T current = queue.pollLast();
if (current == null) {
return;
}
visitor.accept(current);
for (T child : childrenProvider.apply(current)) {
queue.addLast(child);
}
}
}
@Nullable
public static <T> T getOne(@Nullable List<T> list) {
if (list == null || list.size() != 1) {
return null;
}
return list.get(0);
}
@Nullable
public static <T> T getOne(@Nullable Collection<T> collection) {
if (collection == null || collection.size() != 1) {
return null;
}
return collection.iterator().next();
}
public static <T> boolean isSetContainsAny(Set<T> inputSet, Set<T> searchKeys) {
for (T t : inputSet) {
if (searchKeys.contains(t)) {
return true;
}
}
return false;
}
@Nullable
public static <T> T first(List<T> list) {
if (list.isEmpty()) {
return null;
}
return list.get(0);
}
@Nullable
public static <T> T first(Iterable<T> list) {
Iterator<T> it = list.iterator();
if (!it.hasNext()) {
return null;
}
return it.next();
}
@Nullable
public static <T> T last(List<T> list) {
if (list.isEmpty()) {
return null;
}
return list.get(list.size() - 1);
}
@Nullable
public static <T> T last(Iterable<T> list) {
Iterator<T> it = list.iterator();
if (!it.hasNext()) {
return null;
}
while (true) {
T next = it.next();
if (!it.hasNext()) {
return next;
}
}
}
public static <T> T getOrElse(@Nullable T obj, T defaultObj) {
if (obj == null) {
return defaultObj;
}
return obj;
}
public static <T> boolean isEmpty(Collection<T> col) {
return col == null || col.isEmpty();
}
public static <T> boolean notEmpty(Collection<T> col) {
return col != null && !col.isEmpty();
}
public static <K, V> boolean isEmpty(Map<K, V> map) {
return map == null || map.isEmpty();
}
public static <T> boolean isEmpty(T[] arr) {
return arr == null || arr.length == 0;
}
public static <T> boolean notEmpty(T[] arr) {
return arr != null && arr.length != 0;
}
public static void checkThreadInterrupt() {
if (Thread.currentThread().isInterrupted()) {
throw new JadxRuntimeException("Thread interrupted");
}
}
public static ThreadFactory simpleThreadFactory(String name) {
return new SimpleThreadFactory(name);
}
private static final class SimpleThreadFactory implements ThreadFactory {
private static final AtomicInteger POOL = new AtomicInteger(0);
private static final Thread.UncaughtExceptionHandler EXC_HANDLER = new SimpleUncaughtExceptionHandler();
private final AtomicInteger number = new AtomicInteger(0);
private final String name;
public SimpleThreadFactory(String name) {
this.name = name;
}
@Override
public Thread newThread(@NotNull Runnable r) {
Thread thread = new Thread(r, "jadx-" + name
+ '-' + POOL.incrementAndGet()
+ '-' + number.incrementAndGet());
thread.setUncaughtExceptionHandler(EXC_HANDLER);
return thread;
}
private static class SimpleUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(SimpleUncaughtExceptionHandler.class);
@Override
public void uncaughtException(Thread thread, Throwable e) {
if (e instanceof OutOfMemoryError) {
thread.interrupt();
LOG.error("OutOfMemoryError in thread: {}, forcing interrupt", thread.getName());
} else {
LOG.error("Uncaught thread exception, thread: {}", thread.getName(), e);
}
}
}
}
/**
* @deprecated env vars shouldn't be used in core modules.
* Prefer to parse in `app` (use JadxCommonEnv from 'app-commons') and set in jadx args.
*/
@Deprecated
public static boolean getEnvVarBool(String varName, boolean defValue) {
String strValue = System.getenv(varName);
if (strValue == null) {
return defValue;
}
return strValue.equalsIgnoreCase("true");
}
/**
* @deprecated env vars shouldn't be used in core modules.
* Prefer to parse in `app` (use JadxCommonEnv from 'app-commons') and set in jadx args.
*/
@Deprecated
public static int getEnvVarInt(String varName, int defValue) {
String strValue = System.getenv(varName);
if (strValue == null) {
return defValue;
}
return Integer.parseInt(strValue);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/BlockInsnPair.java | jadx-core/src/main/java/jadx/core/utils/BlockInsnPair.java | package jadx.core.utils;
import java.util.Objects;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.InsnNode;
public class BlockInsnPair {
private final IBlock block;
private final InsnNode insn;
public BlockInsnPair(IBlock block, InsnNode insn) {
this.block = block;
this.insn = insn;
}
public IBlock getBlock() {
return block;
}
public InsnNode getInsn() {
return insn;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BlockInsnPair)) {
return false;
}
BlockInsnPair that = (BlockInsnPair) o;
return block.equals(that.block) && insn.equals(that.insn);
}
@Override
public int hashCode() {
return Objects.hash(block, insn);
}
@Override
public String toString() {
return "BlockInsnPair{" + block + ": " + insn + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/DebugUtils.java | jadx-core/src/main/java/jadx/core/utils/DebugUtils.java | package jadx.core.utils;
import java.io.File;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeWriter;
import jadx.api.impl.SimpleCodeWriter;
import jadx.core.codegen.ConditionGen;
import jadx.core.codegen.InsnGen;
import jadx.core.codegen.MethodGen;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.IAttributeNode;
import jadx.core.dex.attributes.nodes.MethodOverrideAttr;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.conditions.IfCondition;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.DotGraphVisitor;
import jadx.core.dex.visitors.IDexTreeVisitor;
import jadx.core.dex.visitors.regions.DepthRegionTraversal;
import jadx.core.dex.visitors.regions.TracedRegionVisitor;
import jadx.core.utils.exceptions.CodegenException;
import jadx.core.utils.exceptions.JadxException;
/**
* Use these methods only for debug purpose.
* CheckStyle will reject usage of this class.
*/
public class DebugUtils {
private static final Logger LOG = LoggerFactory.getLogger(DebugUtils.class);
private DebugUtils() {
}
public static void dump(MethodNode mth) {
dump(mth, "dump");
}
public static void dumpRaw(MethodNode mth, String desc, Predicate<MethodNode> dumpCondition) {
if (dumpCondition.test(mth)) {
dumpRaw(mth, desc);
}
}
public static void dumpRawTest(MethodNode mth, String desc) {
dumpRaw(mth, desc, method -> method.getName().equals("test"));
}
public static void dumpRaw(MethodNode mth, String desc) {
File out = new File("test-graph-" + desc + "-tmp");
DotGraphVisitor.dumpRaw().save(out, mth);
}
public static IDexTreeVisitor dumpRawVisitor(String desc) {
return new AbstractVisitor() {
@Override
public void visit(MethodNode mth) throws JadxException {
dumpRaw(mth, desc);
}
};
}
public static IDexTreeVisitor dumpRawVisitor(String desc, Predicate<MethodNode> filter) {
return new AbstractVisitor() {
@Override
public void visit(MethodNode mth) {
if (filter.test(mth)) {
dumpRaw(mth, desc);
}
}
};
}
public static void dump(MethodNode mth, String desc) {
File out = new File("test-graph-" + desc + "-tmp");
DotGraphVisitor.dump().save(out, mth);
DotGraphVisitor.dumpRaw().save(out, mth);
DotGraphVisitor.dumpRegions().save(out, mth);
}
public static void printRegionsWithBlock(MethodNode mth, BlockNode block) {
Set<IRegion> regions = new LinkedHashSet<>();
DepthRegionTraversal.traverse(mth, new TracedRegionVisitor() {
@Override
public void processBlockTraced(MethodNode mth, IBlock container, IRegion currentRegion) {
if (block.equals(container)) {
regions.add(currentRegion);
}
}
});
LOG.debug(" Found block: {} in regions: {}", block, regions);
}
public static IDexTreeVisitor printRegionsVisitor() {
return new AbstractVisitor() {
@Override
public void visit(MethodNode mth) throws JadxException {
printRegions(mth, true);
}
};
}
public static void printRegions(MethodNode mth) {
printRegions(mth, false);
}
public static void printRegions(MethodNode mth, boolean printInsns) {
Region mthRegion = mth.getRegion();
if (mthRegion == null) {
return;
}
printRegion(mth, mthRegion, printInsns);
}
public static void printRegion(MethodNode mth, IRegion region, boolean printInsns) {
ICodeWriter cw = new SimpleCodeWriter();
cw.startLine('|').add(mth.toString());
printRegion(mth, region, cw, "| ", printInsns);
LOG.debug("{}{}", '\n', cw.finish().getCodeStr());
}
private static void printRegion(MethodNode mth, IRegion region, ICodeWriter cw, String indent, boolean printInsns) {
printWithAttributes(cw, indent, region.toString(), region);
indent += "| ";
printRegionSpecificInfo(cw, indent, mth, region, printInsns);
for (IContainer container : region.getSubBlocks()) {
if (container instanceof IRegion) {
printRegion(mth, (IRegion) container, cw, indent, printInsns);
} else {
printWithAttributes(cw, indent, container.toString(), container);
if (printInsns && container instanceof IBlock) {
IBlock block = (IBlock) container;
printInsns(mth, cw, indent, block);
}
}
}
}
private static void printRegionSpecificInfo(ICodeWriter cw, String indent,
MethodNode mth, IRegion region, boolean printInsns) {
if (region instanceof LoopRegion) {
LoopRegion loop = (LoopRegion) region;
IfCondition condition = loop.getCondition();
if (printInsns && condition != null) {
ConditionGen conditionGen = new ConditionGen(new InsnGen(MethodGen.getFallbackMethodGen(mth), true));
cw.startLine(indent).add("|> ");
try {
conditionGen.add(cw, condition);
} catch (Exception e) {
cw.startLine(indent).add(">!! ").add(condition.toString());
}
}
}
}
private static void printInsns(MethodNode mth, ICodeWriter cw, String indent, IBlock block) {
for (InsnNode insn : block.getInstructions()) {
try {
MethodGen mg = MethodGen.getFallbackMethodGen(mth);
InsnGen ig = new InsnGen(mg, true);
ICodeWriter code = new SimpleCodeWriter();
ig.makeInsn(insn, code);
String codeStr = code.getCodeStr();
List<String> insnStrings = Stream.of(codeStr.split("\\R"))
.filter(StringUtils::notBlank)
.map(s -> "|> " + s)
.collect(Collectors.toList());
Iterator<String> it = insnStrings.iterator();
while (true) {
String insnStr = it.next();
if (it.hasNext()) {
cw.startLine(indent).add(insnStr);
} else {
printWithAttributes(cw, indent, insnStr, insn);
break;
}
}
} catch (CodegenException e) {
cw.startLine(indent).add(">!! ").add(insn.toString());
}
}
}
private static void printWithAttributes(ICodeWriter cw, String indent, String codeStr, IAttributeNode attrNode) {
String str = attrNode.isAttrStorageEmpty() ? codeStr : codeStr + ' ' + attrNode.getAttributesString();
List<String> attrStrings = Stream.of(str.split("\\R"))
.filter(StringUtils::notBlank)
.collect(Collectors.toList());
Iterator<String> it = attrStrings.iterator();
if (!it.hasNext()) {
return;
}
cw.startLine(indent).add(it.next());
while (it.hasNext()) {
cw.startLine(indent).add("|+ ").add(it.next());
}
}
public static void printMap(Map<?, ?> map, String desc) {
LOG.debug("Map {} (size = {}):", desc, map.size());
for (Map.Entry<?, ?> entry : map.entrySet()) {
LOG.debug(" {}: {}", entry.getKey(), entry.getValue());
}
}
public static void printStackTrace(String label) {
LOG.debug("StackTrace: {}\n{}", label, Utils.getFullStackTrace(new Exception()));
}
public static void printMethodOverrideTop(RootNode root) {
LOG.debug("Methods override top 10:");
root.getClasses().stream()
.flatMap(c -> c.getMethods().stream())
.filter(m -> m.contains(AType.METHOD_OVERRIDE))
.map(m -> m.get(AType.METHOD_OVERRIDE))
.filter(o -> !o.getOverrideList().isEmpty())
.filter(distinctByKey(methodOverrideAttr -> methodOverrideAttr.getRelatedMthNodes().size()))
.filter(distinctByKey(MethodOverrideAttr::getRelatedMthNodes))
.sorted(Comparator.comparingInt(o -> -o.getRelatedMthNodes().size()))
.limit(10)
.forEach(o -> LOG.debug(" {} : {}", o.getRelatedMthNodes().size(), Utils.last(o.getOverrideList())));
}
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
private static Map<String, Long> execTimes;
public static void initExecTimes() {
execTimes = new ConcurrentHashMap<>();
}
public static void mergeExecTimeFromStart(String tag, long startTimeMillis) {
mergeExecTime(tag, System.currentTimeMillis() - startTimeMillis);
}
public static void mergeExecTime(String tag, long execTimeMillis) {
execTimes.merge(tag, execTimeMillis, Long::sum);
}
public static void printExecTimes() {
System.out.println("Exec times:");
execTimes.forEach((tag, time) -> System.out.println(" " + tag + ": " + time + "ms"));
}
public static void printExecTimesWithTotal(long totalMillis) {
System.out.println("Exec times: total " + totalMillis + "ms");
execTimes.forEach((tag, time) -> System.out.println(" " + tag + ": " + time + "ms"
+ String.format(" (%.2f%%)", time * 100. / (double) totalMillis)));
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/ErrorsCounter.java | jadx-core/src/main/java/jadx/core/utils/ErrorsCounter.java | package jadx.core.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.Consts;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.IAttributeNode;
import jadx.core.dex.attributes.nodes.JadxError;
import jadx.core.dex.nodes.IDexNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.exceptions.JadxOverflowException;
public class ErrorsCounter {
private static final Logger LOG = LoggerFactory.getLogger(ErrorsCounter.class);
private static final boolean PRINT_MTH_SIZE = Consts.DEBUG;
private final Set<IAttributeNode> errorNodes = new HashSet<>();
private int errorsCount;
private final Set<IAttributeNode> warnNodes = new HashSet<>();
private int warnsCount;
public static <N extends IDexNode & IAttributeNode> String error(N node, String warnMsg, Throwable th) {
return node.root().getErrorsCounter().addError(node, warnMsg, th);
}
public static <N extends IDexNode & IAttributeNode> void warning(N node, String warnMsg) {
node.root().getErrorsCounter().addWarning(node, warnMsg);
}
public static String formatMsg(IDexNode node, String msg) {
return msg + " in " + node.typeName() + ": " + node + ", file: " + node.getInputFileName();
}
private synchronized <N extends IDexNode & IAttributeNode> String addError(N node, String error, @Nullable Throwable e) {
errorNodes.add(node);
errorsCount++;
String msg = formatMsg(node, error);
if (PRINT_MTH_SIZE && node instanceof MethodNode) {
String mthSize = "[" + ((MethodNode) node).getInsnsCount() + "] ";
msg = mthSize + msg;
error = mthSize + error;
}
if (e == null) {
LOG.error(msg);
} else if (e instanceof StackOverflowError) {
LOG.error("{}, error: StackOverflowError", msg);
} else if (e instanceof JadxOverflowException) {
// don't print full stack trace
String details = e.getMessage();
e = new JadxOverflowException(details);
if (details == null || details.isEmpty()) {
LOG.error("{}", msg);
} else {
LOG.error("{}, details: {}", msg, details);
}
} else {
LOG.error(msg, e);
}
node.addAttr(AType.JADX_ERROR, new JadxError(error, e));
return msg;
}
private synchronized <N extends IDexNode & IAttributeNode> void addWarning(N node, String warn) {
warnNodes.add(node);
warnsCount++;
LOG.warn(formatMsg(node, warn));
}
public void printReport() {
if (getErrorCount() > 0) {
LOG.error("{} errors occurred in following nodes:", getErrorCount());
List<String> errors = new ArrayList<>(errorNodes.size());
for (IAttributeNode node : errorNodes) {
String nodeName = node.getClass().getSimpleName().replace("Node", "");
errors.add(nodeName + ": " + node);
}
Collections.sort(errors);
for (String err : errors) {
LOG.error(" {}", err);
}
}
if (getWarnsCount() > 0) {
LOG.warn("{} warnings in {} nodes", getWarnsCount(), warnNodes.size());
}
}
public int getErrorCount() {
return errorsCount;
}
public int getWarnsCount() {
return warnsCount;
}
public Set<IAttributeNode> getErrorNodes() {
return errorNodes;
}
public Set<IAttributeNode> getWarnNodes() {
return warnNodes;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/DebugChecksPass.java | jadx-core/src/main/java/jadx/core/utils/DebugChecksPass.java | package jadx.core.utils;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.utils.exceptions.JadxException;
public class DebugChecksPass extends AbstractVisitor {
private final String visitorName;
public DebugChecksPass(String visitorName) {
this.visitorName = visitorName;
}
@Override
public String getName() {
return "Checks-for-" + visitorName;
}
@Override
public void visit(MethodNode mth) throws JadxException {
if (!mth.contains(AType.JADX_ERROR)) {
try {
DebugChecks.runChecksAfterVisitor(mth, visitorName);
} catch (Exception e) {
mth.addError("Check error", e);
}
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/BetterName.java | jadx-core/src/main/java/jadx/core/utils/BetterName.java | package jadx.core.utils;
import java.util.HashSet;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.deobf.NameMapper;
public class BetterName {
private static final Logger LOG = LoggerFactory.getLogger(BetterName.class);
private static final boolean DEBUG = false;
private static final double TOLERANCE = 0.001;
/**
* Compares two class names and returns the "better" one.
* If both names are equally good, {@code firstName} is returned.
*/
public static String getBetterClassName(String firstName, String secondName) {
return getBetterName(firstName, secondName);
}
/**
* Compares two resource names and returns the "better" one.
* If both names are equally good, {@code firstName} is returned.
*/
public static String getBetterResourceName(String firstName, String secondName) {
return getBetterName(firstName, secondName);
}
private static String getBetterName(String firstName, String secondName) {
if (Objects.equals(firstName, secondName)) {
return firstName;
}
if (StringUtils.isEmpty(firstName) || StringUtils.isEmpty(secondName)) {
return StringUtils.notEmpty(firstName)
? firstName
: secondName;
}
final var firstResult = analyze(firstName);
final var secondResult = analyze(secondName);
if (firstResult.digitCount != 0 || secondResult.digitCount != 0) {
final var firstRatio = (float) firstResult.digitCount / firstResult.length;
final var secondRatio = (float) secondResult.digitCount / secondResult.length;
if (Math.abs(secondRatio - firstRatio) >= TOLERANCE) {
return firstRatio <= secondRatio
? firstName
: secondName;
}
}
return firstResult.length >= secondResult.length
? firstName
: secondName;
}
private static AnalyzeResult analyze(String name) {
final var result = new AnalyzeResult();
StringUtils.visitCodePoints(name, cp -> {
if (Character.isDigit(cp)) {
result.digitCount++;
}
result.length++;
});
return result;
}
private static class AnalyzeResult {
private int length;
private int digitCount;
}
/**
* @deprecated Use {@link #getBetterClassName(String, String)} or
* {@link #getBetterResourceName(String, String)} instead.
*/
@Deprecated
public static String compareAndGet(String first, String second) {
if (Objects.equals(first, second)) {
return first;
}
int firstRating = calcRating(first);
int secondRating = calcRating(second);
boolean firstBetter = firstRating >= secondRating;
if (DEBUG) {
if (firstBetter) {
LOG.debug("Better name: '{}' > '{}' ({} > {})", first, second, firstRating, secondRating);
} else {
LOG.debug("Better name: '{}' > '{}' ({} > {})", second, first, secondRating, firstRating);
}
}
return firstBetter ? first : second;
}
/**
* @deprecated This function is an implementation detail of deprecated
* {@link #compareAndGet(String, String)} and should not be used outside tests.
*/
@Deprecated
public static int calcRating(String str) {
int rating = str.length() * 3;
rating += differentCharsCount(str) * 20;
if (NameMapper.isAllCharsPrintable(str)) {
rating += 100;
}
if (NameMapper.isValidIdentifier(str)) {
rating += 50;
}
if (str.contains("_")) {
// rare in obfuscated names
rating += 100;
}
return rating;
}
@Deprecated
private static int differentCharsCount(String str) {
String lower = str.toLowerCase(Locale.ROOT);
Set<Integer> chars = new HashSet<>();
StringUtils.visitCodePoints(lower, chars::add);
return chars.size();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/BlockUtils.java | jadx-core/src/main/java/jadx/core/utils/BlockUtils.java | package jadx.core.utils;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.LoopInfo;
import jadx.core.dex.attributes.nodes.PhiListAttr;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.mods.TernaryInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.conditions.IfCondition;
import jadx.core.dex.trycatch.CatchAttr;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.utils.blocks.BlockSet;
import jadx.core.utils.blocks.DFSIteration;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class BlockUtils {
private BlockUtils() {
}
public static BlockNode getBlockByOffset(int offset, Iterable<BlockNode> casesBlocks) {
for (BlockNode block : casesBlocks) {
if (block.getStartOffset() == offset) {
return block;
}
}
throw new JadxRuntimeException("Can't find block by offset: "
+ InsnUtils.formatOffset(offset)
+ " in list " + casesBlocks);
}
public static BlockNode selectOther(BlockNode node, List<BlockNode> blocks) {
List<BlockNode> list = blocks;
if (list.size() > 2) {
list = cleanBlockList(list);
}
if (list.size() != 2) {
throw new JadxRuntimeException("Incorrect nodes count for selectOther: " + node + " in " + list);
}
BlockNode first = list.get(0);
if (first != node) {
return first;
} else {
return list.get(1);
}
}
public static BlockNode selectOtherSafe(BlockNode node, List<BlockNode> blocks) {
int size = blocks.size();
if (size == 1) {
BlockNode first = blocks.get(0);
return first != node ? first : null;
}
if (size == 2) {
BlockNode first = blocks.get(0);
return first != node ? first : blocks.get(1);
}
return null;
}
public static boolean isExceptionHandlerPath(BlockNode b) {
if (b.contains(AType.EXC_HANDLER)
|| b.contains(AFlag.EXC_BOTTOM_SPLITTER)
|| b.contains(AFlag.REMOVE)) {
return true;
}
if (b.contains(AFlag.SYNTHETIC)) {
List<BlockNode> s = b.getSuccessors();
return s.size() == 1 && s.get(0).contains(AType.EXC_HANDLER);
}
return false;
}
/**
* Remove exception handlers from block nodes list
*/
private static List<BlockNode> cleanBlockList(List<BlockNode> list) {
List<BlockNode> ret = new ArrayList<>(list.size());
for (BlockNode block : list) {
if (!isExceptionHandlerPath(block)) {
ret.add(block);
}
}
return ret;
}
/**
* Remove exception handlers from block nodes bitset
*/
public static void cleanBitSet(MethodNode mth, BitSet bs) {
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
BlockNode block = mth.getBasicBlocks().get(i);
if (isExceptionHandlerPath(block)) {
bs.clear(i);
}
}
}
public static boolean isBackEdge(BlockNode from, BlockNode to) {
if (to == null) {
return false;
}
if (from.getCleanSuccessors().contains(to)) {
return false; // already checked
}
return from.getSuccessors().contains(to);
}
public static boolean isFollowBackEdge(BlockNode block) {
if (block == null) {
return false;
}
if (block.contains(AFlag.LOOP_START)) {
List<BlockNode> predecessors = block.getPredecessors();
if (predecessors.size() == 1) {
BlockNode loopEndBlock = predecessors.get(0);
if (loopEndBlock.contains(AFlag.LOOP_END)) {
List<LoopInfo> loops = loopEndBlock.getAll(AType.LOOP);
for (LoopInfo loop : loops) {
if (loop.getStart().equals(block) && loop.getEnd().equals(loopEndBlock)) {
return true;
}
}
}
}
}
return false;
}
/**
* Check if instruction contains in block (use == for comparison, not equals)
*/
public static boolean blockContains(BlockNode block, InsnNode insn) {
for (InsnNode bi : block.getInstructions()) {
if (bi == insn) {
return true;
}
}
return false;
}
public static boolean checkFirstInsn(IBlock block, Predicate<InsnNode> predicate) {
InsnNode insn = getFirstInsn(block);
return insn != null && predicate.test(insn);
}
public static boolean checkLastInsnType(IBlock block, InsnType expectedType) {
InsnNode insn = getLastInsn(block);
return insn != null && insn.getType() == expectedType;
}
public static InsnNode getLastInsnWithType(IBlock block, InsnType expectedType) {
InsnNode insn = getLastInsn(block);
if (insn != null && insn.getType() == expectedType) {
return insn;
}
return null;
}
public static int getFirstSourceLine(IBlock block) {
for (InsnNode insn : block.getInstructions()) {
int line = insn.getSourceLine();
if (line != 0) {
return line;
}
}
return 0;
}
@Nullable
public static InsnNode getFirstInsn(@Nullable IBlock block) {
if (block == null) {
return null;
}
List<InsnNode> insns = block.getInstructions();
if (insns.isEmpty()) {
return null;
}
return insns.get(0);
}
@Nullable
public static InsnNode getLastInsn(@Nullable IBlock block) {
if (block == null) {
return null;
}
List<InsnNode> insns = block.getInstructions();
if (insns.isEmpty()) {
return null;
}
return insns.get(insns.size() - 1);
}
public static boolean isExitBlock(MethodNode mth, BlockNode block) {
if (block == mth.getExitBlock()) {
return true;
}
return isExitBlock(block);
}
public static boolean isExitBlock(BlockNode block) {
List<BlockNode> successors = block.getSuccessors();
if (successors.isEmpty()) {
return true;
}
if (successors.size() == 1) {
BlockNode next = successors.get(0);
return next.getSuccessors().isEmpty();
}
return false;
}
public static boolean containsExitInsn(IBlock block) {
InsnNode lastInsn = BlockUtils.getLastInsn(block);
if (lastInsn == null) {
return false;
}
InsnType type = lastInsn.getType();
return type == InsnType.RETURN
|| type == InsnType.THROW
|| type == InsnType.BREAK
|| type == InsnType.CONTINUE;
}
public static @Nullable BlockNode getBlockByInsn(MethodNode mth, @Nullable InsnNode insn) {
return getBlockByInsn(mth, insn, mth.getBasicBlocks());
}
public static @Nullable BlockNode getBlockByInsn(MethodNode mth, @Nullable InsnNode insn, List<BlockNode> blocks) {
if (insn == null) {
return null;
}
if (insn instanceof PhiInsn) {
return searchBlockWithPhi(mth, (PhiInsn) insn);
}
if (insn.contains(AFlag.WRAPPED)) {
return getBlockByWrappedInsn(mth, insn);
}
for (BlockNode bn : blocks) {
if (blockContains(bn, insn)) {
return bn;
}
}
return null;
}
public static BlockNode searchBlockWithPhi(MethodNode mth, PhiInsn insn) {
for (BlockNode block : mth.getBasicBlocks()) {
PhiListAttr phiListAttr = block.get(AType.PHI_LIST);
if (phiListAttr != null) {
for (PhiInsn phiInsn : phiListAttr.getList()) {
if (phiInsn == insn) {
return block;
}
}
}
}
return null;
}
private static BlockNode getBlockByWrappedInsn(MethodNode mth, InsnNode insn) {
for (BlockNode bn : mth.getBasicBlocks()) {
for (InsnNode bi : bn.getInstructions()) {
if (bi == insn || foundWrappedInsn(bi, insn) != null) {
return bn;
}
}
}
return null;
}
public static InsnNode searchInsnParent(MethodNode mth, InsnNode insn) {
InsnArg insnArg = searchWrappedInsnParent(mth, insn);
if (insnArg == null) {
return null;
}
return insnArg.getParentInsn();
}
public static InsnArg searchWrappedInsnParent(MethodNode mth, InsnNode insn) {
if (!insn.contains(AFlag.WRAPPED)) {
return null;
}
for (BlockNode bn : mth.getBasicBlocks()) {
for (InsnNode bi : bn.getInstructions()) {
InsnArg res = foundWrappedInsn(bi, insn);
if (res != null) {
return res;
}
}
}
return null;
}
private static InsnArg foundWrappedInsn(InsnNode container, InsnNode insn) {
for (InsnArg arg : container.getArguments()) {
if (arg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
if (wrapInsn == insn) {
return arg;
}
InsnArg res = foundWrappedInsn(wrapInsn, insn);
if (res != null) {
return res;
}
}
}
if (container instanceof TernaryInsn) {
return foundWrappedInsnInCondition(((TernaryInsn) container).getCondition(), insn);
}
return null;
}
private static InsnArg foundWrappedInsnInCondition(IfCondition cond, InsnNode insn) {
if (cond.isCompare()) {
IfNode cmpInsn = cond.getCompare().getInsn();
return foundWrappedInsn(cmpInsn, insn);
}
for (IfCondition nestedCond : cond.getArgs()) {
InsnArg res = foundWrappedInsnInCondition(nestedCond, insn);
if (res != null) {
return res;
}
}
return null;
}
public static BitSet newBlocksBitSet(MethodNode mth) {
return new BitSet(mth.getBasicBlocks().size());
}
public static BitSet copyBlocksBitSet(MethodNode mth, BitSet bitSet) {
BitSet copy = new BitSet(mth.getBasicBlocks().size());
if (!bitSet.isEmpty()) {
copy.or(bitSet);
}
return copy;
}
public static BitSet blocksToBitSet(MethodNode mth, Collection<BlockNode> blocks) {
BitSet bs = newBlocksBitSet(mth);
for (BlockNode block : blocks) {
bs.set(block.getId());
}
return bs;
}
@Nullable
public static BlockNode bitSetToOneBlock(MethodNode mth, BitSet bs) {
if (bs == null || bs.cardinality() != 1) {
return null;
}
return mth.getBasicBlocks().get(bs.nextSetBit(0));
}
public static List<BlockNode> bitSetToBlocks(MethodNode mth, BitSet bs) {
if (bs == null || bs == EmptyBitSet.EMPTY) {
return Collections.emptyList();
}
int size = bs.cardinality();
if (size == 0) {
return Collections.emptyList();
}
List<BlockNode> blocks = new ArrayList<>(size);
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
BlockNode block = mth.getBasicBlocks().get(i);
blocks.add(block);
}
return blocks;
}
public static void forEachBlockFromBitSet(MethodNode mth, BitSet bs, Consumer<BlockNode> consumer) {
if (bs == null || bs == EmptyBitSet.EMPTY || bs.isEmpty()) {
return;
}
List<BlockNode> blocks = mth.getBasicBlocks();
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
consumer.accept(blocks.get(i));
}
}
/**
* Return first successor which not exception handler and not follow loop back edge
*/
@Nullable
public static BlockNode getNextBlock(BlockNode block) {
List<BlockNode> s = block.getCleanSuccessors();
return s.isEmpty() ? null : s.get(0);
}
@Nullable
public static BlockNode getPrevBlock(BlockNode block) {
List<BlockNode> preds = block.getPredecessors();
return preds.size() == 1 ? preds.get(0) : null;
}
/**
* Return successor on path to 'pathEnd' block
*/
public static BlockNode getNextBlockToPath(BlockNode block, BlockNode pathEnd) {
List<BlockNode> successors = block.getCleanSuccessors();
if (successors.contains(pathEnd)) {
return pathEnd;
}
Set<BlockNode> path = getAllPathsBlocks(block, pathEnd);
for (BlockNode s : successors) {
if (path.contains(s)) {
return s;
}
}
return null;
}
/**
* Return predecessor on path from 'pathStart' block
*/
public static @Nullable BlockNode getPrevBlockOnPath(MethodNode mth, BlockNode block, BlockNode pathStart) {
BlockSet preds = BlockSet.from(mth, block.getPredecessors());
if (preds.contains(pathStart)) {
return pathStart;
}
DFSIteration dfs = new DFSIteration(mth, pathStart, BlockNode::getCleanSuccessors);
while (true) {
BlockNode next = dfs.next();
if (next == null) {
return null;
}
if (preds.contains(next)) {
return next;
}
}
}
/**
* Visit blocks on any path from start to end.
* Only one path will be visited!
*/
public static boolean visitBlocksOnPath(MethodNode mth, BlockNode start, BlockNode end, Consumer<BlockNode> visitor) {
visitor.accept(start);
if (start == end) {
return true;
}
if (start.getCleanSuccessors().contains(end)) {
visitor.accept(end);
return true;
}
// DFS on clean successors
BitSet visited = newBlocksBitSet(mth);
Deque<BlockNode> queue = new ArrayDeque<>();
queue.addLast(start);
while (true) {
BlockNode current = queue.peekLast();
if (current == null) {
return false;
}
boolean added = false;
for (BlockNode next : current.getCleanSuccessors()) {
if (next == end) {
queue.removeFirst(); // start already visited
queue.addLast(next);
queue.forEach(visitor);
return true;
}
int id = next.getId();
if (!visited.get(id)) {
visited.set(id);
queue.addLast(next);
added = true;
break;
}
}
if (!added) {
queue.pollLast();
if (queue.isEmpty()) {
return false;
}
}
}
}
public static List<BlockNode> collectAllSuccessors(MethodNode mth, BlockNode startBlock, boolean clean) {
List<BlockNode> list = new ArrayList<>(mth.getBasicBlocks().size());
Function<BlockNode, List<BlockNode>> nextFunc = clean ? BlockNode::getCleanSuccessors : BlockNode::getSuccessors;
visitDFS(mth, startBlock, nextFunc, list::add);
return list;
}
public static void visitDFS(MethodNode mth, Consumer<BlockNode> visitor) {
visitDFS(mth, mth.getEnterBlock(), BlockNode::getSuccessors, visitor);
}
public static void visitReverseDFS(MethodNode mth, Consumer<BlockNode> visitor) {
visitDFS(mth, mth.getExitBlock(), BlockNode::getPredecessors, visitor);
}
private static void visitDFS(MethodNode mth, BlockNode startBlock,
Function<BlockNode, List<BlockNode>> nextFunc, Consumer<BlockNode> visitor) {
DFSIteration dfsIteration = new DFSIteration(mth, startBlock, nextFunc);
while (true) {
BlockNode next = dfsIteration.next();
if (next == null) {
return;
}
visitor.accept(next);
}
}
public static List<BlockNode> collectPredecessors(MethodNode mth, BlockNode start, Collection<BlockNode> stopBlocks) {
BitSet bs = newBlocksBitSet(mth);
if (!stopBlocks.isEmpty()) {
bs.or(blocksToBitSet(mth, stopBlocks));
}
List<BlockNode> list = new ArrayList<>();
traversePredecessors(start, bs, block -> {
list.add(block);
return false;
});
return list;
}
public static void visitPredecessorsUntil(MethodNode mth, BlockNode start, Predicate<BlockNode> visitor) {
traversePredecessors(start, newBlocksBitSet(mth), visitor);
}
/**
* Up BFS.
* To stop return true from predicate
*/
private static void traversePredecessors(BlockNode start, BitSet visited, Predicate<BlockNode> visitor) {
Queue<BlockNode> queue = new ArrayDeque<>();
queue.add(start);
while (true) {
BlockNode current = queue.poll();
if (current == null || visitor.test(current)) {
return;
}
for (BlockNode next : current.getPredecessors()) {
int id = next.getId();
if (!visited.get(id)) {
visited.set(id);
queue.add(next);
}
}
}
}
/**
* Collect blocks from all possible execution paths from 'start' to 'end'
*/
public static Set<BlockNode> getAllPathsBlocks(BlockNode start, BlockNode end) {
Set<BlockNode> set = new HashSet<>();
set.add(start);
if (start != end) {
addPredecessors(set, end, start);
}
return set;
}
private static void addPredecessors(Set<BlockNode> set, BlockNode from, BlockNode until) {
set.add(from);
for (BlockNode pred : from.getPredecessors()) {
if (pred != until && !set.contains(pred)) {
addPredecessors(set, pred, until);
}
}
}
private static boolean traverseSuccessorsUntil(BlockNode from, BlockNode until, BitSet visited, boolean clean) {
List<BlockNode> nodes = clean ? from.getCleanSuccessors() : from.getSuccessors();
for (BlockNode s : nodes) {
if (s == until) {
return true;
}
if (s == from) {
// ignore possible block self loop
continue;
}
int id = s.getPos();
if (!visited.get(id)) {
visited.set(id);
if (until.isDominator(s)) {
return true;
}
if (traverseSuccessorsUntil(s, until, visited, clean)) {
return true;
}
}
}
return false;
}
/**
* Search at least one path from startBlocks to end
*/
public static boolean atLeastOnePathExists(Collection<BlockNode> startBlocks, BlockNode end) {
for (BlockNode startBlock : startBlocks) {
if (isPathExists(startBlock, end)) {
return true;
}
}
return false;
}
/**
* Check if exist path from every startBlocks to end
*/
public static boolean isAllPathExists(Collection<BlockNode> startBlocks, BlockNode end) {
for (BlockNode startBlock : startBlocks) {
if (!isPathExists(startBlock, end)) {
return false;
}
}
return true;
}
public static boolean isPathExists(BlockNode start, BlockNode end) {
if (start == end
|| end.isDominator(start)
|| start.getCleanSuccessors().contains(end)) {
return true;
}
if (start.getPredecessors().contains(end)) {
return false;
}
return traverseSuccessorsUntil(start, end, new BitSet(), true);
}
public static boolean isAnyPathExists(BlockNode start, BlockNode end) {
if (start == end
|| end.isDominator(start)
|| start.getSuccessors().contains(end)) {
return true;
}
if (start.getPredecessors().contains(end)) {
return false;
}
return traverseSuccessorsUntil(start, end, new BitSet(), false);
}
public static BlockNode getTopBlock(List<BlockNode> blocks) {
if (blocks.size() == 1) {
return blocks.get(0);
}
for (BlockNode from : blocks) {
boolean top = true;
for (BlockNode to : blocks) {
if (from != to && !isAnyPathExists(from, to)) {
top = false;
break;
}
}
if (top) {
return from;
}
}
return null;
}
/**
* Search last block in control flow graph from input set.
*/
@Nullable
public static BlockNode getBottomBlock(List<BlockNode> blocks) {
if (blocks.size() == 1) {
return blocks.get(0);
}
for (BlockNode bottomCandidate : blocks) {
boolean bottom = true;
for (BlockNode from : blocks) {
if (bottomCandidate != from && !isAnyPathExists(from, bottomCandidate)) {
bottom = false;
break;
}
}
if (bottom) {
return bottomCandidate;
}
}
return null;
}
public static boolean isOnlyOnePathExists(BlockNode start, BlockNode end) {
if (start == end) {
return true;
}
if (!end.isDominator(start)) {
return false;
}
BlockNode currentNode = start;
while (currentNode.getCleanSuccessors().size() == 1) {
currentNode = currentNode.getCleanSuccessors().get(0);
if (currentNode == end) {
return true;
}
}
return false;
}
/**
* Search for first node which not dominated by dom, starting from start
*/
public static BlockNode traverseWhileDominates(BlockNode dom, BlockNode start) {
for (BlockNode node : start.getCleanSuccessors()) {
if (!node.isDominator(dom)) {
return node;
} else {
BlockNode out = traverseWhileDominates(dom, node);
if (out != null) {
return out;
}
}
}
return null;
}
/**
* Search the lowest common ancestor in dominator tree for input set.
*/
@Nullable
public static BlockNode getCommonDominator(MethodNode mth, List<BlockNode> blocks) {
BitSet doms = newBlocksBitSet(mth);
// collect all dominators from input set
doms.set(0, mth.getBasicBlocks().size());
blocks.forEach(b -> doms.and(b.getDoms()));
// exclude all dominators of immediate dominator (including self)
BitSet combine = newBlocksBitSet(mth);
combine.or(doms);
forEachBlockFromBitSet(mth, doms, block -> {
BlockNode idom = block.getIDom();
if (idom != null) {
combine.andNot(idom.getDoms());
combine.clear(idom.getId());
}
});
return bitSetToOneBlock(mth, combine);
}
/**
* Return common cross block for input set.
*
* @return could be one of the giving blocks. null if cross is a method exit block.
*/
@Nullable
public static BlockNode getPathCross(MethodNode mth, Collection<BlockNode> blocks) {
BitSet domFrontBS = newBlocksBitSet(mth);
BitSet tmpBS = newBlocksBitSet(mth); // store block itself and its domFrontier
boolean first = true;
for (BlockNode b : blocks) {
tmpBS.clear();
tmpBS.set(b.getId());
tmpBS.or(b.getDomFrontier());
if (first) {
domFrontBS.or(tmpBS);
first = false;
} else {
domFrontBS.and(tmpBS);
}
}
domFrontBS.clear(mth.getExitBlock().getId());
if (domFrontBS.isEmpty()) {
return null;
}
BlockNode oneBlock = bitSetToOneBlock(mth, domFrontBS);
if (oneBlock != null) {
return oneBlock;
}
BitSet excluded = newBlocksBitSet(mth);
// exclude method exit and loop start blocks
excluded.set(mth.getExitBlock().getId());
// exclude loop start blocks
mth.getLoops().forEach(l -> excluded.set(l.getStart().getId()));
if (!mth.isNoExceptionHandlers()) {
// exclude exception handlers paths
mth.getExceptionHandlers().forEach(h -> addExcHandler(mth, h, excluded));
}
domFrontBS.andNot(excluded);
oneBlock = bitSetToOneBlock(mth, domFrontBS);
if (oneBlock != null) {
return oneBlock;
}
BitSet combinedDF = newBlocksBitSet(mth);
int k = mth.getBasicBlocks().size();
while (true) {
// collect dom frontier blocks from current set until only one block left
forEachBlockFromBitSet(mth, domFrontBS, block -> {
BitSet domFrontier = block.getDomFrontier();
if (!domFrontier.isEmpty()) {
combinedDF.or(domFrontier);
}
});
combinedDF.andNot(excluded);
int cardinality = combinedDF.cardinality();
if (cardinality == 1) {
return bitSetToOneBlock(mth, combinedDF);
}
if (cardinality == 0) {
return null;
}
if (k-- < 0) {
mth.addWarnComment("Path cross not found for " + blocks + ", limit reached: " + mth.getBasicBlocks().size());
return null;
}
// replace domFrontBS with combinedDF
domFrontBS.clear();
domFrontBS.or(combinedDF);
combinedDF.clear();
}
}
private static void addExcHandler(MethodNode mth, ExceptionHandler handler, BitSet set) {
BlockNode handlerBlock = handler.getHandlerBlock();
if (handlerBlock == null) {
mth.addDebugComment("Null handler block in: " + handler);
return;
}
set.set(handlerBlock.getId());
}
public static BlockNode getPathCross(MethodNode mth, BlockNode b1, BlockNode b2) {
if (b1 == b2) {
return b1;
}
if (b1 == null || b2 == null) {
return null;
}
return getPathCross(mth, Arrays.asList(b1, b2));
}
/**
* Collect all block dominated by 'dominator', starting from 'start'
*/
public static List<BlockNode> collectBlocksDominatedBy(MethodNode mth, BlockNode dominator, BlockNode start) {
List<BlockNode> result = new ArrayList<>();
collectWhileDominates(dominator, start, result, newBlocksBitSet(mth), false);
return result;
}
/**
* Collect all block dominated by 'dominator', starting from 'start', including exception handlers
*/
public static Set<BlockNode> collectBlocksDominatedByWithExcHandlers(MethodNode mth, BlockNode dominator, BlockNode start) {
Set<BlockNode> result = new LinkedHashSet<>();
collectWhileDominates(dominator, start, result, newBlocksBitSet(mth), true);
return result;
}
private static void collectWhileDominates(BlockNode dominator, BlockNode child, Collection<BlockNode> result,
BitSet visited, boolean includeExcHandlers) {
if (visited.get(child.getId())) {
return;
}
visited.set(child.getId());
List<BlockNode> successors = includeExcHandlers ? child.getSuccessors() : child.getCleanSuccessors();
for (BlockNode node : successors) {
if (node.isDominator(dominator)) {
result.add(node);
collectWhileDominates(dominator, node, result, visited, includeExcHandlers);
}
}
}
/**
* Visit blocks on path without branching or merging paths.
*/
public static void visitSinglePath(BlockNode startBlock, Consumer<BlockNode> visitor) {
if (startBlock == null) {
return;
}
visitor.accept(startBlock);
BlockNode next = getNextSinglePathBlock(startBlock);
while (next != null) {
visitor.accept(next);
next = getNextSinglePathBlock(next);
}
}
@Nullable
public static BlockNode getNextSinglePathBlock(BlockNode block) {
if (block == null || block.getPredecessors().size() > 1) {
return null;
}
List<BlockNode> successors = block.getSuccessors();
return successors.size() == 1 ? successors.get(0) : null;
}
public static List<BlockNode> buildSimplePath(BlockNode block) {
if (block == null) {
return Collections.emptyList();
}
List<BlockNode> list = new ArrayList<>();
if (block.getCleanSuccessors().size() >= 2) {
return Collections.emptyList();
}
list.add(block);
BlockNode currentBlock = getNextBlock(block);
while (currentBlock != null
&& currentBlock.getCleanSuccessors().size() < 2
&& currentBlock.getPredecessors().size() == 1) {
list.add(currentBlock);
currentBlock = getNextBlock(currentBlock);
}
return list;
}
/**
* Set 'SKIP' flag for all synthetic predecessors from start block.
*/
public static void skipPredSyntheticPaths(BlockNode block) {
for (BlockNode pred : block.getPredecessors()) {
if (pred.contains(AFlag.SYNTHETIC)
&& !pred.contains(AFlag.EXC_TOP_SPLITTER)
&& !pred.contains(AFlag.EXC_BOTTOM_SPLITTER)
&& pred.getInstructions().isEmpty()) {
pred.add(AFlag.DONT_GENERATE);
skipPredSyntheticPaths(pred);
}
}
}
/**
* Follow empty blocks and return end of path block (first not empty).
* Return start block if no such path.
*/
public static BlockNode followEmptyPath(BlockNode start) {
while (true) {
BlockNode next = getNextBlockOnEmptyPath(start);
if (next == null) {
return start;
}
start = next;
}
}
public static void visitBlocksOnEmptyPath(BlockNode start, Consumer<BlockNode> visitor) {
while (true) {
BlockNode next = getNextBlockOnEmptyPath(start);
if (next == null) {
return;
}
visitor.accept(next);
start = next;
}
}
@Nullable
private static BlockNode getNextBlockOnEmptyPath(BlockNode block) {
if (!block.getInstructions().isEmpty() || block.getPredecessors().size() > 1) {
return null;
}
List<BlockNode> successors = block.getCleanSuccessors();
if (successors.size() != 1) {
return null;
}
return successors.get(0);
}
/**
* Return true if on path from start to end no instructions and no branches.
*/
public static boolean isEmptySimplePath(BlockNode start, BlockNode end) {
if (start == end && start.getInstructions().isEmpty()) {
return true;
}
if (!start.getInstructions().isEmpty() || start.getCleanSuccessors().size() != 1) {
return false;
}
BlockNode block = getNextBlock(start);
while (block != null
&& block != end
&& block.getCleanSuccessors().size() < 2
&& block.getPredecessors().size() == 1
&& block.getInstructions().isEmpty()) {
block = getNextBlock(block);
}
return block == end;
}
/**
* Return predecessor of synthetic block or same block otherwise.
*/
public static BlockNode skipSyntheticPredecessor(BlockNode block) {
if (block.isSynthetic()
&& block.getInstructions().isEmpty()
&& block.getPredecessors().size() == 1) {
return block.getPredecessors().get(0);
}
return block;
}
public static boolean isAllBlocksEmpty(List<BlockNode> blocks) {
if (Utils.isEmpty(blocks)) {
return true;
}
for (BlockNode block : blocks) {
if (!block.getInstructions().isEmpty()) {
return false;
}
}
return true;
}
public static List<InsnNode> collectAllInsns(List<BlockNode> blocks) {
List<InsnNode> insns = new ArrayList<>();
blocks.forEach(block -> insns.addAll(block.getInstructions()));
return insns;
}
/**
* Return limited number of instructions from method.
* Return empty list if method contains more than limit.
*/
public static List<InsnNode> collectInsnsWithLimit(List<BlockNode> blocks, int limit) {
List<InsnNode> insns = new ArrayList<>(limit);
for (BlockNode block : blocks) {
List<InsnNode> blockInsns = block.getInstructions();
int blockSize = blockInsns.size();
if (blockSize == 0) {
continue;
}
if (insns.size() + blockSize > limit) {
return Collections.emptyList();
}
insns.addAll(blockInsns);
}
return insns;
}
/**
* Return insn if it is only one instruction in this method. Return null otherwise.
*/
@Nullable
public static InsnNode getOnlyOneInsnFromMth(MethodNode mth) {
if (mth.isNoCode()) {
return null;
}
InsnNode insn = null;
for (BlockNode block : mth.getBasicBlocks()) {
List<InsnNode> blockInsns = block.getInstructions();
int blockSize = blockInsns.size();
if (blockSize == 0) {
continue;
}
if (blockSize > 1) {
return null;
}
if (insn != null) {
return null;
}
insn = blockInsns.get(0);
}
return insn;
}
public static boolean isFirstInsn(MethodNode mth, InsnNode insn) {
BlockNode startBlock = followEmptyPath(mth.getEnterBlock());
if (startBlock != null && !startBlock.getInstructions().isEmpty()) {
return startBlock.getInstructions().get(0) == insn;
}
// handle branching with empty blocks
BlockNode block = getBlockByInsn(mth, insn);
if (block == null) {
throw new JadxRuntimeException("Insn not found in method: " + insn);
}
if (block.getInstructions().get(0) != insn) {
return false;
}
Set<BlockNode> allPathsBlocks = getAllPathsBlocks(mth.getEnterBlock(), block);
for (BlockNode pathBlock : allPathsBlocks) {
if (!pathBlock.getInstructions().isEmpty() && pathBlock != block) {
return false;
}
}
return true;
}
/**
* Replace insn by index i in block,
* for proper copy attributes, assume attributes are not overlap
*/
public static void replaceInsn(MethodNode mth, BlockNode block, int i, InsnNode insn) {
InsnNode prevInsn = block.getInstructions().get(i);
insn.copyAttributesFrom(prevInsn);
insn.inheritMetadata(prevInsn);
insn.setOffset(prevInsn.getOffset());
block.getInstructions().set(i, insn);
RegisterArg result = insn.getResult();
RegisterArg prevResult = prevInsn.getResult();
if (result != null && prevResult != null && result.sameRegAndSVar(prevResult)) {
// Don't unbind result for same register.
// Unbind will remove arg from PHI and not add it back on rebind.
InsnRemover.unbindAllArgs(mth, prevInsn);
} else {
InsnRemover.unbindInsn(mth, prevInsn);
}
insn.rebindArgs();
}
public static boolean replaceInsn(MethodNode mth, BlockNode block, InsnNode oldInsn, InsnNode newInsn) {
List<InsnNode> instructions = block.getInstructions();
int size = instructions.size();
for (int i = 0; i < size; i++) {
InsnNode instruction = instructions.get(i);
if (instruction == oldInsn) {
replaceInsn(mth, block, i, newInsn);
return true;
}
}
return false;
}
public static boolean insertBeforeInsn(BlockNode block, InsnNode insn, InsnNode newInsn) {
int index = getInsnIndexInBlock(block, insn);
if (index == -1) {
return false;
}
block.getInstructions().add(index, newInsn);
return true;
}
public static boolean insertAfterInsn(BlockNode block, InsnNode insn, InsnNode newInsn) {
int index = getInsnIndexInBlock(block, insn);
if (index == -1) {
return false;
}
block.getInstructions().add(index + 1, newInsn);
return true;
}
public static int getInsnIndexInBlock(BlockNode block, InsnNode insn) {
List<InsnNode> instructions = block.getInstructions();
int size = instructions.size();
for (int i = 0; i < size; i++) {
if (instructions.get(i) == insn) {
return i;
}
}
return -1;
}
public static boolean replaceInsn(MethodNode mth, InsnNode oldInsn, InsnNode newInsn) {
for (BlockNode block : mth.getBasicBlocks()) {
if (replaceInsn(mth, block, oldInsn, newInsn)) {
return true;
}
}
return false;
}
public static BlockNode getTopSplitterForHandler(BlockNode handlerBlock) {
BlockNode block = getBlockWithFlag(handlerBlock.getPredecessors(), AFlag.EXC_TOP_SPLITTER);
if (block == null) {
throw new JadxRuntimeException("Can't find top splitter block for handler:" + handlerBlock);
}
return block;
}
@Nullable
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | true |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/InsnUtils.java | jadx-core/src/main/java/jadx/core/utils/InsnUtils.java | package jadx.core.utils;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.api.plugins.input.data.attributes.JadxAttrType;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.ConstClassNode;
import jadx.core.dex.instructions.ConstStringNode;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
public class InsnUtils {
private static final Logger LOG = LoggerFactory.getLogger(InsnUtils.class);
private InsnUtils() {
}
public static String formatOffset(int offset) {
if (offset < 0) {
return "?";
}
return String.format("0x%04x", offset);
}
public static String insnTypeToString(InsnType type) {
return type + " ";
}
public static String indexToString(Object index) {
if (index == null) {
return "";
}
if (index instanceof String) {
return "\"" + index + '"';
}
return index.toString();
}
/**
* Search constant assigned to provided arg.
*
* @return LiteralArg, String, ArgType or null
*/
public static Object getConstValueByArg(RootNode root, InsnArg arg) {
if (arg.isLiteral()) {
return arg;
}
if (arg.isRegister()) {
RegisterArg reg = (RegisterArg) arg;
InsnNode parInsn = reg.getAssignInsn();
if (parInsn == null) {
return null;
}
if (parInsn.getType() == InsnType.MOVE) {
return getConstValueByArg(root, parInsn.getArg(0));
}
return getConstValueByInsn(root, parInsn);
}
if (arg.isInsnWrap()) {
InsnNode insn = ((InsnWrapArg) arg).getWrapInsn();
return getConstValueByInsn(root, insn);
}
return null;
}
/**
* Return constant value from insn or null if not constant.
*
* @return LiteralArg, String, ArgType or null
*/
@Nullable
public static Object getConstValueByInsn(RootNode root, InsnNode insn) {
switch (insn.getType()) {
case CONST:
return insn.getArg(0);
case CONST_STR:
return ((ConstStringNode) insn).getString();
case CONST_CLASS:
return ((ConstClassNode) insn).getClsType();
case SGET:
FieldInfo f = (FieldInfo) ((IndexInsnNode) insn).getIndex();
FieldNode fieldNode = root.resolveField(f);
if (fieldNode == null) {
LOG.warn("Field {} not found", f);
return null;
}
EncodedValue constVal = fieldNode.get(JadxAttrType.CONSTANT_VALUE);
if (constVal != null) {
return EncodedValueUtils.convertToConstValue(constVal);
}
return null;
default:
return null;
}
}
@Nullable
public static InsnNode searchSingleReturnInsn(MethodNode mth, Predicate<InsnNode> test) {
if (!mth.isNoCode() && mth.getPreExitBlocks().size() == 1) {
return searchInsn(mth, InsnType.RETURN, test);
}
return null;
}
/**
* Search instruction of specific type and condition in method.
* This method support inlined instructions.
*/
@Nullable
public static InsnNode searchInsn(MethodNode mth, InsnType insnType, Predicate<InsnNode> test) {
if (mth.isNoCode()) {
return null;
}
for (BlockNode block : mth.getBasicBlocks()) {
for (InsnNode insn : block.getInstructions()) {
InsnNode foundInsn = recursiveInsnCheck(insn, insnType, test);
if (foundInsn != null) {
return foundInsn;
}
}
}
return null;
}
public static void replaceInsns(MethodNode mth, Function<InsnNode, InsnNode> replaceFunction) {
for (BlockNode block : mth.getBasicBlocks()) {
List<InsnNode> insns = block.getInstructions();
int insnsCount = insns.size();
for (int i = 0; i < insnsCount; i++) {
InsnNode insn = insns.get(i);
replaceInsnsInInsn(mth, insn, replaceFunction);
InsnNode replace = replaceFunction.apply(insn);
if (replace != null) {
BlockUtils.replaceInsn(mth, block, i, replace);
}
}
}
}
public static void replaceInsnsInInsn(MethodNode mth, InsnNode insn, Function<InsnNode, InsnNode> replaceFunction) {
int argsCount = insn.getArgsCount();
for (int i = 0; i < argsCount; i++) {
InsnArg arg = insn.getArg(i);
if (arg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
replaceInsnsInInsn(mth, wrapInsn, replaceFunction);
InsnNode replace = replaceFunction.apply(wrapInsn);
if (replace != null) {
InsnRemover.unbindArgUsage(mth, arg);
insn.setArg(i, InsnArg.wrapInsnIntoArg(replace));
}
}
}
}
@Nullable
public static RegisterArg getRegFromInsn(List<RegisterArg> regs, InsnType insnType) {
for (RegisterArg reg : regs) {
InsnNode parentInsn = reg.getParentInsn();
if (parentInsn != null && parentInsn.getType() == insnType) {
return reg;
}
}
return null;
}
private static InsnNode recursiveInsnCheck(InsnNode insn, InsnType insnType, Predicate<InsnNode> test) {
if (insn.getType() == insnType && test.test(insn)) {
return insn;
}
for (InsnArg arg : insn.getArguments()) {
if (arg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
InsnNode foundInsn = recursiveInsnCheck(wrapInsn, insnType, test);
if (foundInsn != null) {
return foundInsn;
}
}
}
return null;
}
@Nullable
public static InsnArg getSingleArg(InsnNode insn) {
if (insn != null && insn.getArgsCount() == 1) {
return insn.getArg(0);
}
return null;
}
@Nullable
public static InsnNode checkInsnType(@Nullable InsnNode insn, InsnType insnType) {
if (insn != null && insn.getType() == insnType) {
return insn;
}
return null;
}
public static boolean isInsnType(@Nullable InsnNode insn, InsnType insnType) {
return insn != null && insn.getType() == insnType;
}
@Nullable
public static InsnNode getWrappedInsn(InsnArg arg) {
if (arg != null && arg.isInsnWrap()) {
return ((InsnWrapArg) arg).getWrapInsn();
}
return null;
}
public static boolean isWrapped(InsnArg arg, InsnType insnType) {
if (arg != null && arg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
return wrapInsn.getType() == insnType;
}
return false;
}
public static boolean dontGenerateIfNotUsed(InsnNode insn) {
RegisterArg resArg = insn.getResult();
if (resArg != null) {
SSAVar ssaVar = resArg.getSVar();
for (RegisterArg arg : ssaVar.getUseList()) {
InsnNode parentInsn = arg.getParentInsn();
if (parentInsn != null
&& !parentInsn.contains(AFlag.DONT_GENERATE)) {
return false;
}
}
}
insn.add(AFlag.DONT_GENERATE);
return true;
}
public static <T extends InsnArg> boolean containsVar(List<T> list, RegisterArg arg) {
if (list == null || list.isEmpty()) {
return false;
}
for (InsnArg insnArg : list) {
if (insnArg == arg || arg.sameRegAndSVar(insnArg)) {
return true;
}
}
return false;
}
public static boolean containsVar(InsnNode insn, RegisterArg arg) {
if (insn == null) {
return false;
}
RegisterArg result = insn.getResult();
if (result != null && result.sameRegAndSVar(arg)) {
return true;
}
if (insn.getArgsCount() == 0) {
return false;
}
for (InsnArg insnArg : insn.getArguments()) {
if (containsVar(insnArg, arg)) {
return true;
}
}
return false;
}
public static boolean containsVar(InsnArg insnArg, RegisterArg arg) {
if (insnArg.isRegister()) {
return ((RegisterArg) insnArg).sameRegAndSVar(arg);
}
if (insnArg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) insnArg).getWrapInsn();
return containsVar(wrapInsn, arg);
}
return false;
}
public static boolean contains(InsnNode insn, AFlag flag) {
return insn != null && insn.contains(flag);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/InsnRemover.java | jadx-core/src/main/java/jadx/core/utils/InsnRemover.java | package jadx.core.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.jetbrains.annotations.Nullable;
import jadx.core.Consts;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
import static jadx.core.utils.InsnUtils.isInsnType;
import static jadx.core.utils.ListUtils.allMatch;
/**
* Helper class for correct instructions removing,
* can be used while iterating over instructions list
*/
public class InsnRemover {
private final MethodNode mth;
private final List<InsnNode> toRemove;
@Nullable
private List<InsnNode> instrList;
public InsnRemover(MethodNode mth) {
this(mth, null);
}
public InsnRemover(MethodNode mth, BlockNode block) {
this.mth = mth;
this.toRemove = new ArrayList<>();
if (block != null) {
this.instrList = block.getInstructions();
}
}
public void setBlock(BlockNode block) {
this.instrList = block.getInstructions();
}
public void addAndUnbind(InsnNode insn) {
toRemove.add(insn);
unbindInsn(mth, insn);
}
public void addWithoutUnbind(InsnNode insn) {
toRemove.add(insn);
}
public void perform() {
if (toRemove.isEmpty()) {
return;
}
if (instrList == null) {
for (InsnNode remInsn : toRemove) {
remove(mth, remInsn);
}
} else {
unbindInsns(mth, toRemove);
removeAll(instrList, toRemove);
}
toRemove.clear();
}
public void performForBlock(BlockNode block) {
if (toRemove.isEmpty()) {
return;
}
instrList = Objects.requireNonNull(block.getInstructions());
unbindInsns(mth, toRemove);
removeAll(instrList, toRemove);
toRemove.clear();
}
public static void unbindInsn(@Nullable MethodNode mth, InsnNode insn) {
unbindAllArgs(mth, insn);
unbindResult(mth, insn);
insn.add(AFlag.DONT_GENERATE);
}
public static void unbindInsns(@Nullable MethodNode mth, List<InsnNode> insns) {
// remove all usage first so on result unbind we can remove unused ssa vars
insns.forEach(insn -> unbindAllArgs(mth, insn));
insns.forEach(insn -> {
unbindResult(mth, insn);
insn.add(AFlag.DONT_GENERATE);
});
}
public static void unbindAllArgs(@Nullable MethodNode mth, InsnNode insn) {
for (InsnArg arg : insn.getArguments()) {
unbindArgUsage(mth, arg);
}
if (insn.getType() == InsnType.PHI) {
for (InsnArg arg : insn.getArguments()) {
if (arg instanceof RegisterArg) {
((RegisterArg) arg).getSVar().updateUsedInPhiList();
}
}
}
insn.add(AFlag.REMOVE);
insn.add(AFlag.DONT_GENERATE);
}
public static void unbindResult(@Nullable MethodNode mth, InsnNode insn) {
RegisterArg r = insn.getResult();
if (r == null) {
return;
}
if (mth != null) {
SSAVar ssaVar = r.getSVar();
if (ssaVar != null && ssaVar.getAssignInsn() == insn /* can be already reassigned */) {
removeSsaVar(mth, ssaVar);
}
}
insn.setResult(null);
}
private static void removeSsaVar(MethodNode mth, SSAVar ssaVar) {
int useCount = ssaVar.getUseCount();
if (useCount == 0) {
mth.removeSVar(ssaVar);
return;
}
// check if all usage only in PHI insns
if (allMatch(ssaVar.getUseList(), arg -> isInsnType(arg.getParentInsn(), InsnType.PHI))) {
for (RegisterArg arg : new ArrayList<>(ssaVar.getUseList())) {
InsnNode parentInsn = arg.getParentInsn();
if (parentInsn != null) {
((PhiInsn) parentInsn).removeArg(arg);
}
}
mth.removeSVar(ssaVar);
return;
}
// check if all usage only in not generated instructions
if (allMatch(ssaVar.getUseList(),
arg -> arg.contains(AFlag.DONT_GENERATE) || (InsnUtils.contains(arg.getParentInsn(), AFlag.DONT_GENERATE)))) {
for (RegisterArg arg : ssaVar.getUseList()) {
arg.resetSSAVar();
}
mth.removeSVar(ssaVar);
return;
}
throw new JadxRuntimeException("Can't remove SSA var: " + ssaVar + ", still in use, count: " + useCount
+ ", list:\n " + ssaVar.getUseList().stream()
.map(arg -> arg + " from " + arg.getParentInsn())
.collect(Collectors.joining("\n ")));
}
public static void unbindArgUsage(@Nullable MethodNode mth, InsnArg arg) {
if (arg instanceof RegisterArg) {
RegisterArg reg = (RegisterArg) arg;
SSAVar sVar = reg.getSVar();
if (sVar != null) {
sVar.removeUse(reg);
}
} else if (arg instanceof InsnWrapArg) {
InsnWrapArg wrap = (InsnWrapArg) arg;
unbindInsn(mth, wrap.getWrapInsn());
}
}
// Don't use 'instrList.removeAll(toRemove)' because it will remove instructions by content
// and here can be several instructions with same content
private static void removeAll(List<InsnNode> insns, List<InsnNode> toRemove) {
if (toRemove == null || toRemove.isEmpty()) {
return;
}
for (InsnNode rem : toRemove) {
int insnsCount = insns.size();
boolean found = false;
for (int i = 0; i < insnsCount; i++) {
if (insns.get(i) == rem) {
insns.remove(i);
found = true;
break;
}
}
if (!found && Consts.DEBUG_WITH_ERRORS) {
throw new JadxRuntimeException("Can't remove insn:"
+ "\n " + rem
+ "\n not found in list:"
+ "\n " + Utils.listToString(insns, "\n "));
}
}
}
public static void remove(MethodNode mth, @Nullable InsnNode insn) {
if (insn == null) {
return;
}
if (insn.contains(AFlag.WRAPPED)) {
unbindInsn(mth, insn);
return;
}
BlockNode block = BlockUtils.getBlockByInsn(mth, insn);
if (block != null) {
remove(mth, block, insn);
} else {
insn.add(AFlag.DONT_GENERATE);
mth.addWarnComment("Not found block with instruction: " + insn);
}
}
public static void remove(MethodNode mth, BlockNode block, InsnNode insn) {
unbindInsn(mth, insn);
removeWithoutUnbind(mth, block, insn);
}
public static boolean removeWithoutUnbind(MethodNode mth, BlockNode block, InsnNode insn) {
// remove by pointer (don't use equals)
Iterator<InsnNode> it = block.getInstructions().iterator();
while (it.hasNext()) {
InsnNode ir = it.next();
if (ir == insn) {
it.remove();
return true;
}
}
if (!insn.contains(AFlag.WRAPPED)) {
mth.addWarnComment("Failed to remove instruction: " + insn + " from block: " + block);
}
return false;
}
public static void removeAllAndUnbind(MethodNode mth, BlockNode block, List<InsnNode> insns) {
unbindInsns(mth, insns);
removeAll(block.getInstructions(), insns);
}
public static void removeAllAndUnbind(MethodNode mth, IContainer container, List<InsnNode> insns) {
unbindInsns(mth, insns);
RegionUtils.visitBlocks(mth, container, b -> removeAll(b.getInstructions(), insns));
}
public static void removeAllAndUnbind(MethodNode mth, List<InsnNode> insns) {
unbindInsns(mth, insns);
for (BlockNode block : mth.getBasicBlocks()) {
removeAll(block.getInstructions(), insns);
}
}
public static void removeAllWithoutUnbind(BlockNode block, List<InsnNode> insns) {
removeAll(block.getInstructions(), insns);
}
public static void removeAllMarked(MethodNode mth) {
InsnRemover insnRemover = new InsnRemover(mth);
for (BlockNode blockNode : mth.getBasicBlocks()) {
for (InsnNode insn : blockNode.getInstructions()) {
if (insn.contains(AFlag.REMOVE)) {
insnRemover.addWithoutUnbind(insn);
}
}
insnRemover.setBlock(blockNode);
insnRemover.perform();
}
}
public static void remove(MethodNode mth, BlockNode block, int index) {
List<InsnNode> instructions = block.getInstructions();
unbindInsn(mth, instructions.get(index));
instructions.remove(index);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/DebugChecks.java | jadx-core/src/main/java/jadx/core/utils/DebugChecks.java | package jadx.core.utils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.PhiListAttr;
import jadx.core.dex.attributes.nodes.TmpEdgeAttr;
import jadx.core.dex.instructions.IfNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.PhiInsn;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.args.SSAVar;
import jadx.core.dex.instructions.mods.TernaryInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.IDexTreeVisitor;
import jadx.core.utils.exceptions.JadxRuntimeException;
/**
* Check invariants and information consistency for blocks, instructions, registers, SSA variables.
* These checks are very expensive and executed only in tests.
*/
public class DebugChecks {
private static final Set<String> IGNORE_CHECKS = new HashSet<>(List.of(
"PrepareForCodeGen",
"RenameVisitor",
"DotGraphVisitor"));
public static List<IDexTreeVisitor> insertPasses(List<IDexTreeVisitor> passes) {
int size = passes.size();
List<IDexTreeVisitor> list = new ArrayList<>(size * 2);
for (IDexTreeVisitor pass : passes) {
list.add(pass);
String name = pass.getName();
if (!IGNORE_CHECKS.contains(name)) {
list.add(new DebugChecksPass(name));
}
}
return list;
}
public static void runChecksAfterVisitor(MethodNode mth, String visitor) {
try {
checkMethod(mth);
} catch (Exception e) {
mth.addError("Debug check failed after visitor: " + visitor, e);
}
}
public static void checkMethod(MethodNode mth) {
List<BlockNode> basicBlocks = mth.getBasicBlocks();
if (Utils.isEmpty(basicBlocks)) {
return;
}
for (BlockNode block : basicBlocks) {
for (InsnNode insn : block.getInstructions()) {
checkInsn(mth, block, insn);
}
}
checkSSAVars(mth);
// checkPHI(mth);
}
private static void checkInsn(MethodNode mth, BlockNode block, InsnNode insn) {
if (insn.getResult() != null) {
checkVar(mth, insn, insn.getResult());
}
for (InsnArg arg : insn.getArguments()) {
if (arg instanceof RegisterArg) {
checkVar(mth, insn, (RegisterArg) arg);
} else if (arg.isInsnWrap()) {
InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn();
checkInsn(mth, block, wrapInsn);
}
}
switch (insn.getType()) {
case TERNARY:
TernaryInsn ternaryInsn = (TernaryInsn) insn;
for (RegisterArg arg : ternaryInsn.getCondition().getRegisterArgs()) {
checkVar(mth, insn, arg);
}
break;
case IF:
IfNode ifNode = (IfNode) insn;
if (!ifNode.getThenBlock().equals(ifNode.getElseBlock())) {
// exclude temp edges
int branches = (int) block.getSuccessors().stream().filter(b -> !hasTmpEdge(block, b)).count();
if (branches != 2) {
DebugUtils.dumpRaw(mth, "error");
throw new JadxRuntimeException(
"Incorrect if block successors count: " + branches + " (expect 2), block: " + block);
}
}
checkBlock(mth, ifNode.getThenBlock(), () -> "then block in if insn: " + ifNode);
checkBlock(mth, ifNode.getElseBlock(), () -> "else block in if insn: " + ifNode);
break;
}
}
private static boolean hasTmpEdge(BlockNode start, BlockNode end) {
TmpEdgeAttr tmpEdgeAttr = end.get(AType.TMP_EDGE);
if (tmpEdgeAttr == null) {
return false;
}
return tmpEdgeAttr.getBlock().equals(start);
}
private static void checkBlock(MethodNode mth, BlockNode block, Supplier<String> source) {
if (!mth.getBasicBlocks().contains(block)) {
throw new JadxRuntimeException("Block not registered in method: " + block + " from " + source.get());
}
}
private static void checkVar(MethodNode mth, InsnNode insn, RegisterArg reg) {
checkRegisterArg(mth, reg);
SSAVar sVar = reg.getSVar();
if (sVar == null) {
if (reg.contains(AFlag.DONT_GENERATE) || insn.contains(AFlag.DONT_GENERATE)) {
return;
}
if (Utils.notEmpty(mth.getSVars())) {
throw new JadxRuntimeException("Null SSA var in " + reg + " at " + insn);
}
return;
}
if (Utils.indexInListByRef(mth.getSVars(), sVar) == -1) {
throw new JadxRuntimeException("SSA var not present in method vars list, var: " + sVar + " from insn: " + insn);
}
RegisterArg resArg = insn.getResult();
List<RegisterArg> useList = sVar.getUseList();
if (resArg == reg) {
if (sVar.getAssignInsn() != insn) {
throw new JadxRuntimeException("Incorrect assign in ssa var: " + sVar
+ "\n expected: " + sVar.getAssignInsn()
+ "\n got: " + insn);
}
} else {
if (!Utils.containsInListByRef(useList, reg)) {
throw new JadxRuntimeException("Incorrect use list in ssa var: " + sVar + ", register not listed."
+ "\n insn: " + insn);
}
}
for (RegisterArg useArg : useList) {
checkRegisterArg(mth, useArg);
}
}
private static void checkSSAVars(MethodNode mth) {
for (SSAVar ssaVar : mth.getSVars()) {
RegisterArg assignArg = ssaVar.getAssign();
if (assignArg.contains(AFlag.REMOVE)) {
// ignore removed vars
continue;
}
InsnNode assignInsn = assignArg.getParentInsn();
if (assignInsn != null) {
if (insnMissing(mth, assignInsn)) {
throw new JadxRuntimeException("Insn not found for assign arg in SSAVar: " + ssaVar + ", insn: " + assignInsn);
}
RegisterArg resArg = assignInsn.getResult();
if (resArg == null) {
throw new JadxRuntimeException("SSA assign insn result missing. SSAVar: " + ssaVar + ", insn: " + assignInsn);
}
SSAVar assignVar = resArg.getSVar();
if (!assignVar.equals(ssaVar)) {
throw new JadxRuntimeException("Unexpected SSAVar in assign. "
+ "Expected: " + ssaVar + ", got: " + assignVar + ", insn: " + assignInsn);
}
}
for (RegisterArg arg : ssaVar.getUseList()) {
InsnNode useInsn = arg.getParentInsn();
if (useInsn == null) {
throw new JadxRuntimeException("Parent insn can't be null for arg in use list of SSAVar: " + ssaVar);
}
if (insnMissing(mth, useInsn)) {
throw new JadxRuntimeException("Insn not found for use arg for SSAVar: " + ssaVar + ", insn: " + useInsn);
}
int argIndex = useInsn.getArgIndex(arg);
if (argIndex == -1) {
throw new JadxRuntimeException("Use arg not found in insn for SSAVar: " + ssaVar + ", insn: " + useInsn);
}
InsnArg foundArg = useInsn.getArg(argIndex);
if (!foundArg.equals(arg)) {
throw new JadxRuntimeException(
"Incorrect use arg in insn for SSAVar: " + ssaVar + ", insn: " + useInsn + ", arg: " + foundArg);
}
}
}
}
private static boolean insnMissing(MethodNode mth, InsnNode insn) {
if (insn.contains(AFlag.HIDDEN)) {
// skip search
return false;
}
BlockNode block = BlockUtils.getBlockByInsn(mth, insn);
return block == null;
}
private static void checkRegisterArg(MethodNode mth, RegisterArg reg) {
InsnNode parentInsn = reg.getParentInsn();
if (parentInsn == null) {
if (reg.contains(AFlag.METHOD_ARGUMENT)) {
return;
}
throw new JadxRuntimeException("Null parentInsn for reg: " + reg);
}
if (!parentInsn.contains(AFlag.HIDDEN)) {
if (parentInsn.getResult() != reg && !parentInsn.containsArg(reg)) {
throw new JadxRuntimeException("Incorrect parentInsn: " + parentInsn + ", must contains arg: " + reg);
}
BlockNode parentInsnBlock = BlockUtils.getBlockByInsn(mth, parentInsn);
if (parentInsnBlock == null) {
throw new JadxRuntimeException("Parent insn not found in blocks tree for: " + reg
+ "\n insn: " + parentInsn);
}
}
}
private static void checkPHI(MethodNode mth) {
for (BlockNode block : mth.getBasicBlocks()) {
List<PhiInsn> phis = new ArrayList<>();
for (InsnNode insn : block.getInstructions()) {
if (insn.getType() == InsnType.PHI) {
PhiInsn phi = (PhiInsn) insn;
phis.add(phi);
if (phi.getArgsCount() == 0) {
throw new JadxRuntimeException("No args and binds in PHI");
}
for (InsnArg arg : insn.getArguments()) {
if (arg instanceof RegisterArg) {
BlockNode b = phi.getBlockByArg((RegisterArg) arg);
if (b == null) {
throw new JadxRuntimeException("Predecessor block not found");
}
} else {
throw new JadxRuntimeException("Not register in phi insn");
}
}
}
}
PhiListAttr phiListAttr = block.get(AType.PHI_LIST);
if (phiListAttr == null) {
if (!phis.isEmpty()) {
throw new JadxRuntimeException("Missing PHI list attribute");
}
} else {
List<PhiInsn> phiList = phiListAttr.getList();
if (phiList.isEmpty()) {
throw new JadxRuntimeException("Empty PHI list attribute");
}
if (!phis.containsAll(phiList) || !phiList.containsAll(phis)) {
throw new JadxRuntimeException("Instructions not match");
}
}
}
for (SSAVar ssaVar : mth.getSVars()) {
for (PhiInsn usedInPhi : ssaVar.getUsedInPhi()) {
boolean found = false;
for (RegisterArg useArg : ssaVar.getUseList()) {
InsnNode parentInsn = useArg.getParentInsn();
if (parentInsn != null && parentInsn == usedInPhi) {
found = true;
break;
}
}
if (!found) {
throw new JadxRuntimeException("Used in phi incorrect");
}
}
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/ListUtils.java | jadx-core/src/main/java/jadx/core/utils/ListUtils.java | package jadx.core.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import org.jetbrains.annotations.Nullable;
public class ListUtils {
public static <T> boolean isSingleElement(@Nullable List<T> list, T obj) {
if (list == null || list.size() != 1) {
return false;
}
return Objects.equals(list.get(0), obj);
}
public static <T> boolean unorderedEquals(List<T> first, List<T> second) {
if (first.size() != second.size()) {
return false;
}
return first.containsAll(second);
}
public static <T, U> boolean orderedEquals(List<T> list1, List<U> list2, BiPredicate<T, U> comparer) {
if (list1 == list2) {
return true;
}
if (list1.size() != list2.size()) {
return false;
}
final Iterator<T> iter1 = list1.iterator();
final Iterator<U> iter2 = list2.iterator();
while (iter1.hasNext() && iter2.hasNext()) {
final T item1 = iter1.next();
final U item2 = iter2.next();
if (!comparer.test(item1, item2)) {
return false;
}
}
return !iter1.hasNext() && !iter2.hasNext();
}
public static <T, R> List<R> map(Collection<T> list, Function<T, R> mapFunc) {
if (list == null || list.isEmpty()) {
return Collections.emptyList();
}
List<R> result = new ArrayList<>(list.size());
for (T t : list) {
result.add(mapFunc.apply(t));
}
return result;
}
public static <T> T first(List<T> list) {
return list.get(0);
}
public static <T> @Nullable T last(List<T> list) {
if (list == null || list.isEmpty()) {
return null;
}
return list.get(list.size() - 1);
}
public static <T> @Nullable T removeLast(List<T> list) {
int size = list.size();
if (size == 0) {
return null;
}
return list.remove(size - 1);
}
public static <T extends Comparable<T>> List<T> distinctMergeSortedLists(List<T> first, List<T> second) {
if (first.isEmpty()) {
return second;
}
if (second.isEmpty()) {
return first;
}
Set<T> set = new TreeSet<>(first);
set.addAll(second);
return new ArrayList<>(set);
}
public static <T> List<T> distinctList(List<T> list) {
return new ArrayList<>(new LinkedHashSet<>(list));
}
public static <T> List<T> concat(T first, T[] values) {
List<T> list = new ArrayList<>(1 + values.length);
list.add(first);
list.addAll(Arrays.asList(values));
return list;
}
/**
* Replace old element to new one.
* Support null and empty immutable list (created by Collections.emptyList())
*/
public static <T> List<T> safeReplace(List<T> list, T oldObj, T newObj) {
if (list == null || list.isEmpty()) {
// immutable empty list
List<T> newList = new ArrayList<>(1);
newList.add(newObj);
return newList;
}
int idx = list.indexOf(oldObj);
if (idx != -1) {
list.set(idx, newObj);
} else {
list.add(newObj);
}
return list;
}
public static <T> void safeRemove(List<T> list, T obj) {
if (list != null && !list.isEmpty()) {
list.remove(obj);
}
}
public static <T> List<T> safeRemoveAndTrim(List<T> list, T obj) {
if (list == null || list.isEmpty()) {
return list;
}
if (list.remove(obj)) {
if (list.isEmpty()) {
return Collections.emptyList();
}
}
return list;
}
public static <T> List<T> safeAdd(List<T> list, T obj) {
if (list == null || list.isEmpty()) {
List<T> newList = new ArrayList<>(1);
newList.add(obj);
return newList;
}
list.add(obj);
return list;
}
public static <T> List<T> filter(Collection<T> list, Predicate<T> filter) {
if (list == null || list.isEmpty()) {
return Collections.emptyList();
}
List<T> result = new ArrayList<>();
for (T element : list) {
if (filter.test(element)) {
result.add(element);
}
}
return result;
}
/**
* Search exactly one element in list by filter
*
* @return null if found not exactly one element (zero or more than one)
*/
@Nullable
public static <T> T filterOnlyOne(List<T> list, Predicate<T> filter) {
if (list == null || list.isEmpty()) {
return null;
}
T found = null;
for (T element : list) {
if (filter.test(element)) {
if (found != null) {
// found second
return null;
}
found = element;
}
}
return found;
}
public static <T> boolean allMatch(Collection<T> list, Predicate<T> test) {
if (list == null || list.isEmpty()) {
return false;
}
for (T element : list) {
if (!test.test(element)) {
return false;
}
}
return true;
}
public static <T> boolean noneMatch(Collection<T> list, Predicate<T> test) {
return !anyMatch(list, test);
}
public static <T> boolean anyMatch(Collection<T> list, Predicate<T> test) {
if (list == null || list.isEmpty()) {
return false;
}
for (T element : list) {
if (test.test(element)) {
return true;
}
}
return false;
}
public static <T> List<T> enumerationToList(Enumeration<T> enumeration) {
if (enumeration == null || enumeration == Collections.emptyEnumeration()) {
return Collections.emptyList();
}
List<T> list = new ArrayList<>();
while (enumeration.hasMoreElements()) {
list.add(enumeration.nextElement());
}
return list;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/DecompilerScheduler.java | jadx-core/src/main/java/jadx/core/utils/DecompilerScheduler.java | package jadx.core.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.IDecompileScheduler;
import jadx.api.JavaClass;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class DecompilerScheduler implements IDecompileScheduler {
private static final Logger LOG = LoggerFactory.getLogger(DecompilerScheduler.class);
private static final int MERGED_BATCH_SIZE = 16;
private static final boolean DEBUG_BATCHES = false;
@Override
public List<List<JavaClass>> buildBatches(List<JavaClass> classes) {
try {
long start = System.currentTimeMillis();
List<List<JavaClass>> result = internalBatches(classes);
if (LOG.isDebugEnabled()) {
LOG.debug("Build decompilation batches in {}ms for {} classes",
System.currentTimeMillis() - start, classes.size());
}
if (DEBUG_BATCHES) {
check(result, classes);
}
return result;
} catch (Exception e) {
LOG.warn("Build batches failed (continue with fallback)", e);
return buildFallback(classes);
}
}
/**
* Put classes with many dependencies at the end.
* Build batches for dependencies of single class to avoid locking from another thread.
*/
public List<List<JavaClass>> internalBatches(List<JavaClass> classes) {
List<DepInfo> deps = sumDependencies(classes);
Set<JavaClass> added = new HashSet<>(classes.size());
Comparator<JavaClass> cmpDepSize = Comparator.comparingInt(JavaClass::getTotalDepsCount);
List<List<JavaClass>> result = new ArrayList<>();
List<JavaClass> mergedBatch = new ArrayList<>(MERGED_BATCH_SIZE);
for (DepInfo depInfo : deps) {
JavaClass cls = depInfo.getCls();
if (!added.add(cls)) {
continue;
}
int depsSize = cls.getTotalDepsCount();
if (depsSize == 0) {
// add classes without dependencies in merged batch
mergedBatch.add(cls);
if (mergedBatch.size() >= MERGED_BATCH_SIZE) {
result.add(mergedBatch);
mergedBatch = new ArrayList<>(MERGED_BATCH_SIZE);
}
} else {
List<JavaClass> batch = new ArrayList<>();
for (JavaClass dep : cls.getDependencies()) {
JavaClass topDep = dep.getTopParentClass();
if (!added.contains(topDep)) {
batch.add(topDep);
added.add(topDep);
}
}
batch.sort(cmpDepSize);
batch.add(cls);
result.add(Utils.lockList(batch));
}
}
if (!mergedBatch.isEmpty()) {
result.add(mergedBatch);
}
if (DEBUG_BATCHES) {
dumpBatchesStats(classes, result, deps);
}
return result;
}
private static List<DepInfo> sumDependencies(List<JavaClass> classes) {
List<DepInfo> deps = new ArrayList<>(classes.size());
for (JavaClass cls : classes) {
int count = 0;
for (JavaClass dep : cls.getDependencies()) {
count += 1 + dep.getTotalDepsCount();
}
deps.add(new DepInfo(cls, count));
}
Collections.sort(deps);
return deps;
}
private static final class DepInfo implements Comparable<DepInfo> {
private final JavaClass cls;
private final int depsCount;
private DepInfo(JavaClass cls, int depsCount) {
this.cls = cls;
this.depsCount = depsCount;
}
public JavaClass getCls() {
return cls;
}
public int getDepsCount() {
return depsCount;
}
@Override
public int compareTo(@NotNull DecompilerScheduler.DepInfo o) {
int deps = Integer.compare(depsCount, o.depsCount);
if (deps == 0) {
return cls.getClassNode().compareTo(o.cls.getClassNode());
}
return deps;
}
@Override
public String toString() {
return cls + ":" + depsCount;
}
}
private static List<List<JavaClass>> buildFallback(List<JavaClass> classes) {
return classes.stream()
.sorted(Comparator.comparingInt(c -> c.getClassNode().getTotalDepsCount()))
.map(Collections::singletonList)
.collect(Collectors.toList());
}
private void dumpBatchesStats(List<JavaClass> classes, List<List<JavaClass>> result, List<DepInfo> deps) {
int clsInBatches = result.stream().mapToInt(List::size).sum();
double avg = result.stream().mapToInt(List::size).average().orElse(-1);
int maxSingleDeps = classes.stream().mapToInt(JavaClass::getTotalDepsCount).max().orElse(-1);
int maxSubDeps = deps.stream().mapToInt(DepInfo::getDepsCount).max().orElse(-1);
LOG.info("Batches stats:"
+ "\n input classes: " + classes.size()
+ ",\n classes in batches: " + clsInBatches
+ ",\n batches: " + result.size()
+ ",\n average batch size: " + String.format("%.2f", avg)
+ ",\n max single deps count: " + maxSingleDeps
+ ",\n max sub deps count: " + maxSubDeps);
}
private static void check(List<List<JavaClass>> result, List<JavaClass> classes) {
int classInBatches = result.stream().mapToInt(List::size).sum();
if (classes.size() != classInBatches) {
throw new JadxRuntimeException(
"Incorrect number of classes in result batch: " + classInBatches + ", expected: " + classes.size());
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/FileSignature.java | jadx-core/src/main/java/jadx/core/utils/FileSignature.java | package jadx.core.utils;
public class FileSignature {
private final byte[] signatureBytes;
private final String fileType;
public FileSignature(String fileType, String signatureHex) {
this.fileType = fileType;
String[] parts = signatureHex.split(" ");
this.signatureBytes = new byte[parts.length];
for (int i = 0; i < parts.length; i++) {
if (parts[i].length() != 2) {
throw new RuntimeException(signatureHex);
}
if (!parts[i].equals("??")) {
this.signatureBytes[i] = (byte) Integer.parseInt(parts[i], 16);
}
}
}
public static boolean matches(FileSignature sig, byte[] data) {
if (data.length < sig.signatureBytes.length) {
return false;
}
for (int i = 0; i < sig.signatureBytes.length; i++) {
byte b = sig.signatureBytes[i];
if (b != data[i]) {
return false;
}
}
return true;
}
public String getFileType() {
return fileType;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/RegionUtils.java | jadx-core/src/main/java/jadx/core/utils/RegionUtils.java | package jadx.core.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.AttrList;
import jadx.core.dex.attributes.nodes.LoopInfo;
import jadx.core.dex.attributes.nodes.LoopLabelAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IBranchRegion;
import jadx.core.dex.nodes.IConditionRegion;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.trycatch.CatchAttr;
import jadx.core.dex.trycatch.ExceptionHandler;
import jadx.core.dex.trycatch.TryCatchBlockAttr;
import jadx.core.dex.visitors.regions.AbstractRegionVisitor;
import jadx.core.dex.visitors.regions.DepthRegionTraversal;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class RegionUtils {
private RegionUtils() {
}
public static boolean hasExitEdge(IContainer container) {
if (container instanceof IBlock) {
return BlockUtils.containsExitInsn((IBlock) container);
}
if (container instanceof IBranchRegion) {
// all branches must have exit edge
for (IContainer br : ((IBranchRegion) container).getBranches()) {
if (br == null || !hasExitEdge(br)) {
return false;
}
}
return true;
}
if (container instanceof IRegion) {
IContainer last = Utils.last(((IRegion) container).getSubBlocks());
return last != null && hasExitEdge(last);
}
throw new JadxRuntimeException(unknownContainerType(container));
}
@Nullable
public static InsnNode getFirstInsn(IContainer container) {
if (container instanceof IBlock) {
IBlock block = (IBlock) container;
List<InsnNode> insnList = block.getInstructions();
if (insnList.isEmpty()) {
return null;
}
return insnList.get(0);
} else if (container instanceof IBranchRegion) {
return null;
} else if (container instanceof IRegion) {
IRegion region = (IRegion) container;
List<IContainer> blocks = region.getSubBlocks();
if (blocks.isEmpty()) {
return null;
}
return getFirstInsn(blocks.get(0));
} else {
throw new JadxRuntimeException(unknownContainerType(container));
}
}
public static @Nullable BlockNode getFirstBlockNode(IContainer container) {
if (container instanceof IBlock) {
if (container instanceof BlockNode) {
return (BlockNode) container;
}
return null;
}
if (container instanceof IBranchRegion) {
return null;
}
if (container instanceof IRegion) {
List<IContainer> blocks = ((IRegion) container).getSubBlocks();
if (blocks.isEmpty()) {
return null;
}
return getFirstBlockNode(blocks.get(0));
}
throw new JadxRuntimeException(unknownContainerType(container));
}
public static int getFirstSourceLine(IContainer container) {
if (container instanceof IBlock) {
return BlockUtils.getFirstSourceLine((IBlock) container);
}
if (container instanceof IConditionRegion) {
return ((IConditionRegion) container).getConditionSourceLine();
}
if (container instanceof IBranchRegion) {
IBranchRegion branchRegion = (IBranchRegion) container;
return getFirstSourceLine(branchRegion.getBranches());
}
if (container instanceof IRegion) {
IRegion region = (IRegion) container;
return getFirstSourceLine(region.getSubBlocks());
}
return 0;
}
private static int getFirstSourceLine(List<IContainer> containers) {
if (containers.isEmpty()) {
return 0;
}
for (IContainer container : containers) {
int line = getFirstSourceLine(container);
if (line != 0) {
return line;
}
}
return 0;
}
public static InsnNode getLastInsn(IContainer container) {
if (container instanceof IBlock) {
IBlock block = (IBlock) container;
List<InsnNode> insnList = block.getInstructions();
if (insnList.isEmpty()) {
return null;
}
return insnList.get(insnList.size() - 1);
} else if (container instanceof IBranchRegion) {
return null;
} else if (container instanceof IRegion) {
IRegion region = (IRegion) container;
List<IContainer> blocks = region.getSubBlocks();
if (blocks.isEmpty()) {
return null;
}
return getLastInsn(blocks.get(blocks.size() - 1));
} else {
throw new JadxRuntimeException(unknownContainerType(container));
}
}
public static BlockInsnPair getLastInsnWithBlock(IContainer container) {
if (container instanceof IBlock) {
IBlock block = (IBlock) container;
InsnNode lastInsn = ListUtils.last(block.getInstructions());
if (lastInsn == null) {
return null;
}
return new BlockInsnPair(block, lastInsn);
}
if (container instanceof IBranchRegion) {
List<IContainer> branches = ((IBranchRegion) container).getBranches();
long count = branches.stream().filter(Objects::nonNull).count();
if (count == 1) {
// single branch
for (IContainer branch : branches) {
if (branch != null) {
return getLastInsnWithBlock(branch);
}
}
}
// several last instructions
return null;
}
if (container instanceof IRegion) {
IRegion region = (IRegion) container;
List<IContainer> blocks = region.getSubBlocks();
if (blocks.isEmpty()) {
return null;
}
return getLastInsnWithBlock(ListUtils.last(blocks));
}
throw new JadxRuntimeException(unknownContainerType(container));
}
public static IBlock getLastBlock(IContainer container) {
if (container instanceof IBlock) {
return (IBlock) container;
} else if (container instanceof IBranchRegion) {
return null;
} else if (container instanceof IRegion) {
List<IContainer> blocks = ((IRegion) container).getSubBlocks();
if (blocks.isEmpty()) {
return null;
}
return getLastBlock(blocks.get(blocks.size() - 1));
} else {
throw new JadxRuntimeException(unknownContainerType(container));
}
}
public static boolean isExitBlock(MethodNode mth, IContainer container) {
if (container instanceof BlockNode) {
return BlockUtils.isExitBlock(mth, (BlockNode) container);
}
return false;
}
/**
* Return true if last block in region has no successors or jump out insn (return or break)
*/
public static boolean hasExitBlock(IContainer container) {
if (container == null) {
return false;
}
return hasExitBlock(container, container);
}
private static boolean hasExitBlock(IContainer rootContainer, IContainer container) {
if (container instanceof BlockNode) {
BlockNode blockNode = (BlockNode) container;
if (BlockUtils.isExitBlock(blockNode)) {
return true;
}
return isInsnExitContainer(rootContainer, (IBlock) container);
}
if (container instanceof IBranchRegion) {
IBranchRegion branchRegion = (IBranchRegion) container;
return ListUtils.allMatch(branchRegion.getBranches(), RegionUtils::hasExitBlock);
}
if (container instanceof IBlock) {
return isInsnExitContainer(rootContainer, (IBlock) container);
}
if (container instanceof IRegion) {
List<IContainer> blocks = ((IRegion) container).getSubBlocks();
return !blocks.isEmpty()
&& hasExitBlock(rootContainer, blocks.get(blocks.size() - 1));
}
throw new JadxRuntimeException(unknownContainerType(container));
}
private static boolean isInsnExitContainer(IContainer rootContainer, IBlock block) {
InsnNode lastInsn = BlockUtils.getLastInsn(block);
if (lastInsn == null) {
return false;
}
InsnType insnType = lastInsn.getType();
if (insnType == InsnType.RETURN) {
return true;
}
if (insnType == InsnType.THROW) {
// check if after throw execution can continue in current container
CatchAttr catchAttr = lastInsn.get(AType.EXC_CATCH);
if (catchAttr != null) {
for (ExceptionHandler handler : catchAttr.getHandlers()) {
if (RegionUtils.isRegionContainsBlock(rootContainer, handler.getHandlerBlock())) {
return false;
}
}
}
return true;
}
if (insnType == InsnType.BREAK) {
AttrList<LoopInfo> loopInfoAttrList = lastInsn.get(AType.LOOP);
if (loopInfoAttrList != null) {
for (LoopInfo loopInfo : loopInfoAttrList.getList()) {
if (!RegionUtils.isRegionContainsBlock(rootContainer, loopInfo.getStart())) {
return true;
}
}
}
LoopLabelAttr loopLabelAttr = lastInsn.get(AType.LOOP_LABEL);
if (loopLabelAttr != null
&& !RegionUtils.isRegionContainsBlock(rootContainer, loopLabelAttr.getLoop().getStart())) {
return true;
}
}
return false;
}
public static boolean hasBreakInsn(IContainer container) {
if (container instanceof IBlock) {
return BlockUtils.checkLastInsnType((IBlock) container, InsnType.BREAK);
} else if (container instanceof IRegion) {
List<IContainer> blocks = ((IRegion) container).getSubBlocks();
return !blocks.isEmpty()
&& hasBreakInsn(blocks.get(blocks.size() - 1));
} else {
throw new JadxRuntimeException("Unknown container type: " + container);
}
}
public static int insnsCount(IContainer container) {
if (container instanceof IBlock) {
List<InsnNode> insnList = ((IBlock) container).getInstructions();
int count = 0;
for (InsnNode insn : insnList) {
if (insn.contains(AFlag.DONT_GENERATE)) {
continue;
}
count++;
}
return count;
}
if (container instanceof IRegion) {
IRegion region = (IRegion) container;
int count = 0;
for (IContainer block : region.getSubBlocks()) {
count += insnsCount(block);
}
return count;
}
throw new JadxRuntimeException(unknownContainerType(container));
}
public static List<InsnNode> collectInsns(MethodNode mth, IContainer container) {
List<InsnNode> list = new ArrayList<>();
visitBlocks(mth, container, block -> list.addAll(block.getInstructions()));
return list;
}
public static boolean isEmpty(IContainer container) {
return !notEmpty(container);
}
public static boolean notEmpty(@Nullable IContainer container) {
if (container == null) {
return false;
}
if (container instanceof IBlock) {
List<InsnNode> insnList = ((IBlock) container).getInstructions();
for (InsnNode insnNode : insnList) {
if (!insnNode.contains(AFlag.DONT_GENERATE)) {
return true;
}
}
return false;
}
if (container instanceof LoopRegion) {
return true;
}
if (container instanceof IRegion) {
IRegion region = (IRegion) container;
for (IContainer block : region.getSubBlocks()) {
if (notEmpty(block)) {
return true;
}
}
return false;
}
throw new JadxRuntimeException(unknownContainerType(container));
}
public static void getAllRegionBlocks(IContainer container, Set<IBlock> blocks) {
if (container instanceof IBlock) {
blocks.add((IBlock) container);
} else if (container instanceof IRegion) {
IRegion region = (IRegion) container;
for (IContainer block : region.getSubBlocks()) {
getAllRegionBlocks(block, blocks);
}
} else {
throw new JadxRuntimeException(unknownContainerType(container));
}
}
public static boolean isRegionContainsBlock(IContainer container, BlockNode block) {
if (container instanceof IBlock) {
return container == block;
} else if (container instanceof IRegion) {
IRegion region = (IRegion) container;
for (IContainer b : region.getSubBlocks()) {
if (isRegionContainsBlock(b, block)) {
return true;
}
}
return false;
} else {
throw new JadxRuntimeException(unknownContainerType(container));
}
}
public static IContainer getSingleSubBlock(IContainer container) {
if (container instanceof Region) {
List<IContainer> subBlocks = ((Region) container).getSubBlocks();
if (subBlocks.size() == 1) {
return ignoreSimpleRegionWrapper(subBlocks.get(0));
}
}
return null;
}
private static IContainer ignoreSimpleRegionWrapper(IContainer container) {
while (true) {
if (container instanceof Region) {
List<IContainer> subBlocks = ((Region) container).getSubBlocks();
if (subBlocks.size() != 1) {
return container;
}
container = subBlocks.get(0);
} else {
return container;
}
}
}
public static List<IContainer> getExcHandlersForRegion(IContainer region) {
TryCatchBlockAttr tb = region.get(AType.TRY_BLOCK);
if (tb != null) {
List<IContainer> list = new ArrayList<>(tb.getHandlersCount());
for (ExceptionHandler eh : tb.getHandlers()) {
list.add(eh.getHandlerRegion());
}
return list;
}
return Collections.emptyList();
}
private static boolean isRegionContainsExcHandlerRegion(IContainer container, IRegion region) {
if (container == region) {
return true;
}
if (container instanceof IRegion) {
IRegion r = (IRegion) container;
// process sub blocks
for (IContainer b : r.getSubBlocks()) {
// process try block
TryCatchBlockAttr tb = b.get(AType.TRY_BLOCK);
if (tb != null && b instanceof IRegion) {
for (ExceptionHandler eh : tb.getHandlers()) {
if (isRegionContainsRegion(eh.getHandlerRegion(), region)) {
return true;
}
}
}
if (isRegionContainsRegion(b, region)) {
return true;
}
}
}
return false;
}
/**
* Check if {@code region} contains in {@code container}.
* <br>
* For simple region (not from exception handlers) search in parents
* otherwise run recursive search because exception handlers can have several parents
*/
public static boolean isRegionContainsRegion(IContainer container, IRegion region) {
if (container == region) {
return true;
}
if (region == null) {
return false;
}
IRegion parent = region.getParent();
while (container != parent) {
if (parent == null) {
if (region.contains(AType.EXC_HANDLER)) {
return isRegionContainsExcHandlerRegion(container, region);
}
return false;
}
region = parent;
parent = region.getParent();
}
return true;
}
public static IContainer getBlockContainer(IContainer container, IBlock block) {
if (container instanceof IBlock) {
return container == block ? container : null;
}
if (container instanceof IRegion) {
IRegion region = (IRegion) container;
for (IContainer c : region.getSubBlocks()) {
IContainer res = getBlockContainer(c, block);
if (res != null) {
return res instanceof IBlock ? region : res;
}
}
return null;
}
throw new JadxRuntimeException(unknownContainerType(container));
}
/**
* Check if two blocks in same region on same level
* TODO: Add 'region' annotation to all blocks to speed up checks
*/
public static boolean isBlocksInSameRegion(MethodNode mth, BlockNode firstBlock, BlockNode secondBlock) {
Region region = mth.getRegion();
if (region == null) {
return false;
}
IContainer firstContainer = getBlockContainer(region, firstBlock);
if (firstContainer instanceof IRegion) {
if (firstContainer instanceof IBranchRegion) {
return false;
}
List<IContainer> subBlocks = ((IRegion) firstContainer).getSubBlocks();
return subBlocks.contains(secondBlock);
}
return false;
}
public static boolean isDominatedBy(BlockNode dom, IContainer cont) {
if (dom == cont) {
return true;
}
if (cont instanceof BlockNode) {
BlockNode block = (BlockNode) cont;
return block.isDominator(dom);
} else if (cont instanceof IBlock) {
return false;
} else if (cont instanceof IRegion) {
IRegion region = (IRegion) cont;
for (IContainer c : region.getSubBlocks()) {
if (!isDominatedBy(dom, c)) {
return false;
}
}
return true;
} else {
throw new JadxRuntimeException(unknownContainerType(cont));
}
}
public static boolean hasPathThroughBlock(BlockNode block, IContainer cont) {
if (block == cont) {
return true;
}
if (cont instanceof BlockNode) {
return BlockUtils.isPathExists(block, (BlockNode) cont);
}
if (cont instanceof IBlock) {
return false;
}
if (cont instanceof IRegion) {
IRegion region = (IRegion) cont;
for (IContainer c : region.getSubBlocks()) {
if (hasPathThroughBlock(block, c)) {
return true;
}
}
return false;
}
throw new JadxRuntimeException(unknownContainerType(cont));
}
protected static String unknownContainerType(IContainer container) {
if (container == null) {
return "Null container variable";
}
return "Unknown container type: " + container.getClass();
}
public static void visitBlocks(MethodNode mth, IContainer container, Consumer<IBlock> visitor) {
DepthRegionTraversal.traverse(mth, container, new AbstractRegionVisitor() {
@Override
public void processBlock(MethodNode mth, IBlock block) {
visitor.accept(block);
}
});
}
public static void visitBlockNodes(MethodNode mth, IContainer container, Consumer<BlockNode> visitor) {
DepthRegionTraversal.traverse(mth, container, new AbstractRegionVisitor() {
@Override
public void processBlock(MethodNode mth, IBlock block) {
if (block instanceof BlockNode) {
visitor.accept((BlockNode) block);
}
}
});
}
public static void visitRegions(MethodNode mth, IContainer container, Predicate<IRegion> visitor) {
DepthRegionTraversal.traverse(mth, container, new AbstractRegionVisitor() {
@Override
public boolean enterRegion(MethodNode mth, IRegion region) {
return visitor.test(region);
}
});
}
public static @Nullable IContainer getNextContainer(MethodNode mth, IRegion region) {
IRegion parent = region.getParent();
List<IContainer> subBlocks = parent.getSubBlocks();
int index = subBlocks.indexOf(region);
if (index == -1 || index + 1 >= subBlocks.size()) {
return null;
}
return subBlocks.get(index + 1);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/EmptyBitSet.java | jadx-core/src/main/java/jadx/core/utils/EmptyBitSet.java | package jadx.core.utils;
import java.util.BitSet;
public final class EmptyBitSet extends BitSet {
private static final long serialVersionUID = -1194884945157778639L;
public static final BitSet EMPTY = new EmptyBitSet();
public EmptyBitSet() {
super(0);
}
@Override
public int cardinality() {
return 0;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public int nextSetBit(int fromIndex) {
return -1;
}
@Override
public int length() {
return 0;
}
@Override
public int size() {
return 0;
}
@Override
public void set(int bitIndex) {
throw new UnsupportedOperationException();
}
@Override
public void set(int bitIndex, boolean value) {
throw new UnsupportedOperationException();
}
@Override
public void set(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}
@Override
public void set(int fromIndex, int toIndex, boolean value) {
throw new UnsupportedOperationException();
}
@Override
public boolean get(int bitIndex) {
return false;
}
@Override
public BitSet get(int fromIndex, int toIndex) {
return EMPTY;
}
@Override
public void and(BitSet set) {
throw new UnsupportedOperationException();
}
@Override
public void or(BitSet set) {
throw new UnsupportedOperationException();
}
@Override
public void xor(BitSet set) {
throw new UnsupportedOperationException();
}
@Override
public void andNot(BitSet set) {
throw new UnsupportedOperationException();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/tasks/TaskExecutor.java | jadx-core/src/main/java/jadx/core/utils/tasks/TaskExecutor.java | package jadx.core.utils.tasks;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.JadxArgs;
import jadx.api.utils.tasks.ITaskExecutor;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class TaskExecutor implements ITaskExecutor {
private static final Logger LOG = LoggerFactory.getLogger(TaskExecutor.class);
private enum ExecType {
PARALLEL,
SEQUENTIAL,
}
private static final class ExecStage {
private final ExecType type;
private final List<? extends Runnable> tasks;
private ExecStage(ExecType type, List<? extends Runnable> tasks) {
this.type = type;
this.tasks = tasks;
}
public ExecType getType() {
return type;
}
public List<? extends Runnable> getTasks() {
return tasks;
}
}
private final List<ExecStage> stages = new ArrayList<>();
private final AtomicInteger threadsCount = new AtomicInteger(JadxArgs.DEFAULT_THREADS_COUNT);
private final AtomicInteger progress = new AtomicInteger(0);
private final AtomicBoolean running = new AtomicBoolean(false);
private final AtomicBoolean terminating = new AtomicBoolean(false);
private final Object executorSync = new Object();
private @Nullable ExecutorService executor;
private int tasksCount = 0;
private @Nullable Error terminateError;
@Override
public void addParallelTasks(List<? extends Runnable> parallelTasks) {
if (parallelTasks.isEmpty()) {
return;
}
tasksCount += parallelTasks.size();
stages.add(new ExecStage(ExecType.PARALLEL, parallelTasks));
}
@Override
public void addSequentialTasks(List<? extends Runnable> seqTasks) {
if (seqTasks.isEmpty()) {
return;
}
tasksCount += seqTasks.size();
stages.add(new ExecStage(ExecType.SEQUENTIAL, seqTasks));
}
@Override
public void addSequentialTask(Runnable seqTask) {
addSequentialTasks(Collections.singletonList(seqTask));
}
@Override
public int getThreadsCount() {
return threadsCount.get();
}
@Override
public void setThreadsCount(int count) {
threadsCount.set(count);
}
@Override
public int getTasksCount() {
return tasksCount;
}
@Override
public int getProgress() {
return progress.get();
}
@Override
public void execute() {
synchronized (executorSync) {
if (running.get() || executor != null) {
throw new IllegalStateException("Already executing");
}
executor = Executors.newFixedThreadPool(1, Utils.simpleThreadFactory("task-s"));
running.set(true);
terminating.set(false);
progress.set(0);
executor.execute(this::runStages);
}
}
private void stopExecution() {
synchronized (executorSync) {
running.set(false);
terminating.set(true);
if (executor != null) {
executor.shutdown();
executor = null;
}
}
}
@Override
public void awaitTermination() {
ExecutorService activeExecutor = executor;
if (activeExecutor != null && running.get()) {
awaitExecutorTermination(activeExecutor);
}
Error error = terminateError;
if (error != null) {
throw error;
}
}
@Override
public void terminate() {
terminating.set(true);
}
@SuppressWarnings("DataFlowIssue")
private void terminateWithError(Error error) {
if (terminating.get()) {
return;
}
terminateError = error;
terminate();
executor.shutdownNow();
}
@Override
public boolean isTerminating() {
return terminating.get();
}
@Override
public boolean isRunning() {
return running.get();
}
@Override
public @Nullable ExecutorService getInternalExecutor() {
return executor;
}
private void runStages() {
try {
for (ExecStage stage : stages) {
int threads = Math.min(stage.getTasks().size(), threadsCount.get());
if (stage.getType() == ExecType.SEQUENTIAL || threads == 1) {
for (Runnable task : stage.getTasks()) {
wrapTask(task);
}
} else {
ExecutorService parallelExecutor = Executors.newFixedThreadPool(
threads, Utils.simpleThreadFactory("task-p"));
for (Runnable task : stage.getTasks()) {
parallelExecutor.execute(() -> wrapTask(task));
}
parallelExecutor.shutdown();
awaitExecutorTermination(parallelExecutor);
}
if (terminating.get()) {
break;
}
}
} finally {
stopExecution();
}
}
private void wrapTask(Runnable task) {
if (terminating.get()) {
return;
}
try {
task.run();
progress.incrementAndGet();
} catch (Error e) {
terminateWithError(e);
} catch (Exception e) {
LOG.error("Unhandled task exception:", e);
}
}
public static void awaitExecutorTermination(ExecutorService executor) {
try {
boolean complete = executor.awaitTermination(10, TimeUnit.DAYS);
if (!complete) {
throw new JadxRuntimeException("Executor timeout");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/exceptions/JadxArgsValidateException.java | jadx-core/src/main/java/jadx/core/utils/exceptions/JadxArgsValidateException.java | package jadx.core.utils.exceptions;
public class JadxArgsValidateException extends RuntimeException {
private static final long serialVersionUID = -7457621776087311909L;
public JadxArgsValidateException(String message) {
super(message);
}
public JadxArgsValidateException(String message, Throwable cause) {
super(message, cause);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/exceptions/DecodeException.java | jadx-core/src/main/java/jadx/core/utils/exceptions/DecodeException.java | package jadx.core.utils.exceptions;
import jadx.core.dex.nodes.MethodNode;
public class DecodeException extends JadxException {
private static final long serialVersionUID = -6611189094923499636L;
public DecodeException(String message) {
super(message);
}
public DecodeException(String message, Throwable cause) {
super(message, cause);
}
public DecodeException(MethodNode mth, String msg) {
super(mth, msg, null);
}
public DecodeException(MethodNode mth, String msg, Throwable th) {
super(mth, msg, th);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/exceptions/CodegenException.java | jadx-core/src/main/java/jadx/core/utils/exceptions/CodegenException.java | package jadx.core.utils.exceptions;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.MethodNode;
public class CodegenException extends JadxException {
private static final long serialVersionUID = 39344288912966824L;
public CodegenException(String message) {
super(message);
}
public CodegenException(String message, Throwable cause) {
super(message, cause);
}
public CodegenException(ClassNode mth, String msg) {
super(mth, msg, null);
}
public CodegenException(ClassNode mth, String msg, Throwable th) {
super(mth, msg, th);
}
public CodegenException(MethodNode mth, String msg) {
super(mth, msg, null);
}
public CodegenException(MethodNode mth, String msg, Throwable th) {
super(mth, msg, th);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/exceptions/InvalidDataException.java | jadx-core/src/main/java/jadx/core/utils/exceptions/InvalidDataException.java | package jadx.core.utils.exceptions;
public class InvalidDataException extends JadxRuntimeException {
public InvalidDataException(String message) {
super(message);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/exceptions/JadxOverflowException.java | jadx-core/src/main/java/jadx/core/utils/exceptions/JadxOverflowException.java | package jadx.core.utils.exceptions;
public class JadxOverflowException extends JadxRuntimeException {
private static final long serialVersionUID = 2568659798680154204L;
public JadxOverflowException(String message) {
super(message);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/exceptions/JadxException.java | jadx-core/src/main/java/jadx/core/utils/exceptions/JadxException.java | package jadx.core.utils.exceptions;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.ErrorsCounter;
public class JadxException extends Exception {
private static final long serialVersionUID = 3577449089978463557L;
public JadxException(String message) {
super(message);
}
public JadxException(String message, Throwable cause) {
super(message, cause);
}
public JadxException(ClassNode cls, String msg, Throwable th) {
super(ErrorsCounter.formatMsg(cls, msg), th);
}
public JadxException(MethodNode mth, String msg, Throwable th) {
super(ErrorsCounter.formatMsg(mth, msg), th);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/exceptions/JadxRuntimeException.java | jadx-core/src/main/java/jadx/core/utils/exceptions/JadxRuntimeException.java | package jadx.core.utils.exceptions;
public class JadxRuntimeException extends RuntimeException {
private static final long serialVersionUID = -7410848445429898248L;
public JadxRuntimeException() {
super();
}
public JadxRuntimeException(String message) {
super(message);
}
public JadxRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/blocks/DFSIteration.java | jadx-core/src/main/java/jadx/core/utils/blocks/DFSIteration.java | package jadx.core.utils.blocks;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.function.Function;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.MethodNode;
public class DFSIteration {
private final Function<BlockNode, List<BlockNode>> nextFunc;
private final Deque<BlockNode> queue;
private final BlockSet visited;
public DFSIteration(MethodNode mth, BlockNode startBlock, Function<BlockNode, List<BlockNode>> next) {
nextFunc = next;
queue = new ArrayDeque<>();
visited = new BlockSet(mth);
queue.addLast(startBlock);
visited.add(startBlock);
}
public @Nullable BlockNode next() {
BlockNode current = queue.pollLast();
if (current == null) {
return null;
}
List<BlockNode> nextBlocks = nextFunc.apply(current);
int count = nextBlocks.size();
for (int i = count - 1; i >= 0; i--) { // to preserve order in queue
BlockNode next = nextBlocks.get(i);
if (!visited.addChecked(next)) {
queue.addLast(next);
}
}
return current;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/blocks/BlockSet.java | jadx-core/src/main/java/jadx/core/utils/blocks/BlockSet.java | package jadx.core.utils.blocks;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.EmptyBitSet;
/**
* BlockNode set implementation based on BitSet.
*/
public class BlockSet implements Iterable<BlockNode> {
public static BlockSet empty(MethodNode mth) {
return new BlockSet(mth);
}
public static BlockSet from(MethodNode mth, Collection<BlockNode> blocks) {
BlockSet newBS = new BlockSet(mth);
newBS.addAll(blocks);
return newBS;
}
private final MethodNode mth;
private final BitSet bs;
public BlockSet(MethodNode mth) {
this.mth = mth;
this.bs = new BitSet(mth.getBasicBlocks().size());
}
public boolean contains(BlockNode block) {
return bs.get(block.getPos());
}
public void add(BlockNode block) {
bs.set(block.getPos());
}
public void addAll(Collection<BlockNode> blocks) {
blocks.forEach(this::add);
}
public void addAll(BlockSet otherBlockSet) {
bs.or(otherBlockSet.bs);
}
public void remove(BlockNode block) {
bs.clear(block.getPos());
}
public void remove(Collection<BlockNode> blocks) {
blocks.forEach(this::remove);
}
public boolean addChecked(BlockNode block) {
int id = block.getPos();
boolean state = bs.get(id);
bs.set(id);
return state;
}
public boolean containsAll(List<BlockNode> blocks) {
for (BlockNode block : blocks) {
if (!contains(block)) {
return false;
}
}
return true;
}
public boolean intersects(List<BlockNode> blocks) {
for (BlockNode block : blocks) {
if (contains(block)) {
return true;
}
}
return false;
}
public BlockSet intersect(List<BlockNode> blocks) {
BlockSet input = from(mth, blocks);
BlockSet result = new BlockSet(mth);
BitSet resultBS = result.bs;
resultBS.or(this.bs);
resultBS.and(input.bs);
return result;
}
public boolean isEmpty() {
return bs.isEmpty();
}
public int size() {
return bs.cardinality();
}
public void remove() {
bs.clear();
}
public @Nullable BlockNode getOne() {
if (bs.cardinality() == 1) {
return mth.getBasicBlocks().get(bs.nextSetBit(0));
}
return null;
}
public BlockNode getFirst() {
return mth.getBasicBlocks().get(bs.nextSetBit(0));
}
@Override
public void forEach(Consumer<? super BlockNode> consumer) {
if (bs.isEmpty()) {
return;
}
List<BlockNode> blocks = mth.getBasicBlocks();
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
consumer.accept(blocks.get(i));
}
}
@Override
public @NotNull Iterator<BlockNode> iterator() {
return new BlockSetIterator(bs, size(), mth.getBasicBlocks());
}
@Override
public Spliterator<BlockNode> spliterator() {
int size = size();
BlockSetIterator iterator = new BlockSetIterator(bs, size, mth.getBasicBlocks());
return Spliterators.spliterator(iterator, size, Spliterator.ORDERED | Spliterator.DISTINCT);
}
public List<BlockNode> toList() {
if (bs == null || bs == EmptyBitSet.EMPTY) {
return Collections.emptyList();
}
int size = bs.cardinality();
if (size == 0) {
return Collections.emptyList();
}
List<BlockNode> mthBlocks = mth.getBasicBlocks();
List<BlockNode> blocks = new ArrayList<>(size);
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
blocks.add(mthBlocks.get(i));
}
return blocks;
}
@Override
public String toString() {
return toList().toString();
}
private static final class BlockSetIterator implements Iterator<BlockNode> {
private final BitSet bs;
private final int size;
private final List<BlockNode> blocks;
private int cursor;
private int start;
public BlockSetIterator(BitSet bs, int size, List<BlockNode> blocks) {
this.bs = bs;
this.size = size;
this.blocks = blocks;
}
@Override
public boolean hasNext() {
return cursor != size;
}
@Override
public BlockNode next() {
int pos = bs.nextSetBit(start);
if (pos == -1) {
throw new NoSuchElementException();
}
start = pos + 1;
cursor++;
return blocks.get(pos);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/blocks/BlockPair.java | jadx-core/src/main/java/jadx/core/utils/blocks/BlockPair.java | package jadx.core.utils.blocks;
import jadx.core.dex.nodes.BlockNode;
public class BlockPair {
private final BlockNode first;
private final BlockNode second;
public BlockPair(BlockNode first, BlockNode second) {
this.first = first;
this.second = second;
}
public BlockNode getFirst() {
return first;
}
public BlockNode getSecond() {
return second;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BlockPair)) {
return false;
}
BlockPair other = (BlockPair) o;
return first.equals(other.first) && second.equals(other.second);
}
@Override
public int hashCode() {
return first.hashCode() + 31 * second.hashCode();
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/files/FileUtils.java | jadx-core/src/main/java/jadx/core/utils/files/FileUtils.java | package jadx.core.utils.files;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.plugins.files.IJadxFilesGetter;
import jadx.core.utils.ListUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class FileUtils {
private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class);
public static final int READ_BUFFER_SIZE = 8 * 1024;
private static final int MAX_FILENAME_LENGTH = 128;
public static final String JADX_TMP_INSTANCE_PREFIX = "jadx-instance-";
public static final String JADX_TMP_PREFIX = "jadx-tmp-";
private static Path tempRootDir = createTempRootDir();
private FileUtils() {
// utility class
}
public static synchronized Path updateTempRootDir(Path newTempRootDir) {
try {
makeDirs(newTempRootDir);
Path dir = Files.createTempDirectory(newTempRootDir, JADX_TMP_INSTANCE_PREFIX);
tempRootDir = dir;
dir.toFile().deleteOnExit();
return dir;
} catch (Exception e) {
throw new JadxRuntimeException("Failed to update temp root directory", e);
}
}
private static Path createTempRootDir() {
try {
Path dir = Files.createTempDirectory(JADX_TMP_INSTANCE_PREFIX);
dir.toFile().deleteOnExit();
return dir;
} catch (Exception e) {
throw new JadxRuntimeException("Failed to create temp root directory", e);
}
}
public static List<Path> expandDirs(List<Path> paths) {
List<Path> files = new ArrayList<>(paths.size());
for (Path path : paths) {
if (Files.isDirectory(path)) {
expandDir(path, files);
} else {
files.add(path);
}
}
return files;
}
private static void expandDir(Path dir, List<Path> files) {
try (Stream<Path> walk = Files.walk(dir, FileVisitOption.FOLLOW_LINKS)) {
walk.filter(Files::isRegularFile).forEach(files::add);
} catch (Exception e) {
LOG.error("Failed to list files in directory: {}", dir, e);
}
}
public static void addFileToJar(JarOutputStream jar, File source, String entryName) throws IOException {
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) {
JarEntry entry = new JarEntry(entryName);
entry.setTime(source.lastModified());
jar.putNextEntry(entry);
copyStream(in, jar);
jar.closeEntry();
}
}
public static void makeDirsForFile(Path path) {
if (path != null) {
makeDirs(path.toAbsolutePath().getParent().toFile());
}
}
public static void makeDirsForFile(File file) {
if (file != null) {
makeDirs(file.getParentFile());
}
}
private static final Object MKDIR_SYNC = new Object();
public static void makeDirs(@Nullable File dir) {
if (dir != null) {
synchronized (MKDIR_SYNC) {
if (!dir.mkdirs() && !dir.isDirectory()) {
throw new JadxRuntimeException("Can't create directory " + dir);
}
}
}
}
public static void makeDirs(@Nullable Path dir) {
if (dir != null) {
makeDirs(dir.toFile());
}
}
public static void deleteFileIfExists(Path filePath) throws IOException {
Files.deleteIfExists(filePath);
}
public static boolean deleteDir(File dir) {
deleteDir(dir.toPath());
return true;
}
public static void deleteDirIfExists(Path dir) {
if (Files.exists(dir)) {
try {
deleteDir(dir);
} catch (Exception e) {
LOG.error("Failed to delete dir: {}", dir.toAbsolutePath(), e);
}
}
}
private static void deleteDir(Path dir) {
deleteDir(dir, false);
}
private static void deleteDir(Path dir, boolean keepRootDir) {
try {
List<Path> files = new ArrayList<>();
List<Path> directories = new ArrayList<>();
Files.walkFileTree(dir, Collections.emptySet(), Integer.MAX_VALUE, new SimpleFileVisitor<>() {
@Override
public @NotNull FileVisitResult visitFile(@NotNull Path file, @NotNull BasicFileAttributes attrs) {
files.add(file);
return FileVisitResult.CONTINUE;
}
@Override
public @NotNull FileVisitResult postVisitDirectory(@NotNull Path directory, IOException exc) {
directories.add(directory);
return FileVisitResult.CONTINUE;
}
});
// delete files in parallel
if (!files.isEmpty()) {
files.parallelStream().forEach(path -> {
try {
Files.delete(path);
} catch (Exception e) {
LOG.warn("Failed to delete file {}", path.toAbsolutePath(), e);
}
});
}
// after all files are deleted, remove empty directories
if (keepRootDir) {
// root dir always last
ListUtils.removeLast(directories);
}
for (Path directory : directories) {
try {
Files.delete(directory);
} catch (IOException e) {
LOG.warn("Failed to delete directory {}", directory.toAbsolutePath(), e);
}
}
} catch (Exception e) {
throw new JadxRuntimeException("Failed to delete directory " + dir, e);
}
}
public static void clearTempRootDir() {
if (Files.isDirectory(tempRootDir)) {
clearDir(tempRootDir);
}
}
public static void clearDir(Path clearDir) {
try {
deleteDir(clearDir, true);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to clear directory " + clearDir, e);
}
}
/**
* Deprecated.
* Migrate to {@link IJadxFilesGetter} from jadx args to get temp dir
*/
@Deprecated
public static Path createTempDir(String prefix) {
try {
Path dir = Files.createTempDirectory(tempRootDir, prefix);
dir.toFile().deleteOnExit();
return dir;
} catch (Exception e) {
throw new JadxRuntimeException("Failed to create temp directory with suffix: " + prefix, e);
}
}
/**
* Deprecated.
* Migrate to {@link IJadxFilesGetter} from jadx args to get temp dir
*/
@Deprecated
public static Path createTempFile(String suffix) {
try {
Path path = Files.createTempFile(tempRootDir, JADX_TMP_PREFIX, suffix);
path.toFile().deleteOnExit();
return path;
} catch (Exception e) {
throw new JadxRuntimeException("Failed to create temp file with suffix: " + suffix, e);
}
}
/**
* Deprecated.
* Prefer {@link IJadxFilesGetter} from jadx args to get temp dir
*/
@Deprecated
public static Path createTempFileNoDelete(String suffix) {
try {
return Files.createTempFile(Files.createTempDirectory("jadx-persist"), "jadx-", suffix);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to create temp file with suffix: " + suffix, e);
}
}
/**
* Deprecated.
* Migrate to {@link IJadxFilesGetter} from jadx args to get temp dir
*/
@Deprecated
public static Path createTempFileNonPrefixed(String fileName) {
try {
Path path = Files.createFile(tempRootDir.resolve(fileName));
path.toFile().deleteOnExit();
return path;
} catch (Exception e) {
throw new JadxRuntimeException("Failed to create non-prefixed temp file: " + fileName, e);
}
}
public static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[READ_BUFFER_SIZE];
while (true) {
int count = input.read(buffer);
if (count == -1) {
break;
}
output.write(buffer, 0, count);
}
}
public static byte[] streamToByteArray(InputStream input) throws IOException {
return input.readAllBytes();
}
public static String streamToString(InputStream input) throws IOException {
return new String(streamToByteArray(input), StandardCharsets.UTF_8);
}
public static void close(Closeable c) {
if (c == null) {
return;
}
try {
c.close();
} catch (IOException e) {
LOG.error("Close exception for {}", c, e);
}
}
public static void writeFile(Path file, String data) throws IOException {
FileUtils.makeDirsForFile(file);
Files.writeString(file, data, StandardCharsets.UTF_8,
StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
public static void writeFile(Path file, byte[] data) throws IOException {
FileUtils.makeDirsForFile(file);
Files.write(file, data, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
public static void writeFile(Path file, InputStream is) throws IOException {
FileUtils.makeDirsForFile(file);
Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
}
public static String readFile(Path textFile) throws IOException {
return Files.readString(textFile);
}
public static boolean renameFile(Path sourcePath, Path targetPath) {
try {
Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (NoSuchFileException e) {
LOG.error("File to rename not found {}", sourcePath, e);
} catch (FileAlreadyExistsException e) {
LOG.error("File with that name already exists {}", targetPath, e);
} catch (IOException e) {
LOG.error("Error renaming file {}", e.getMessage(), e);
}
return false;
}
@NotNull
public static File prepareFile(File file) {
File saveFile = cutFileName(file);
makeDirsForFile(saveFile);
return saveFile;
}
private static File cutFileName(File file) {
String name = file.getName();
if (name.length() <= MAX_FILENAME_LENGTH) {
return file;
}
int dotIndex = name.indexOf('.');
int cutAt = MAX_FILENAME_LENGTH - name.length() + dotIndex - 1;
if (cutAt <= 0) {
name = name.substring(0, MAX_FILENAME_LENGTH - 1);
} else {
name = name.substring(0, cutAt) + name.substring(dotIndex);
}
return new File(file.getParentFile(), name);
}
private static final byte[] HEX_ARRAY = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII);
public static String bytesToHex(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return "";
}
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
/**
* Zero padded hex string for first byte
*/
public static String byteToHex(int value) {
int v = value & 0xFF;
byte[] hexChars = new byte[] { HEX_ARRAY[v >>> 4], HEX_ARRAY[v & 0x0F] };
return new String(hexChars, StandardCharsets.US_ASCII);
}
/**
* Zero padded hex string for int value
*/
public static String intToHex(int value) {
byte[] hexChars = new byte[8];
int v = value;
for (int i = 7; i >= 0; i--) {
hexChars[i] = HEX_ARRAY[v & 0x0F];
v >>>= 4;
}
return new String(hexChars, StandardCharsets.US_ASCII);
}
private static final byte[] ZIP_FILE_MAGIC = { 0x50, 0x4B, 0x03, 0x04 };
public static boolean isZipFile(File file) {
try (InputStream is = new FileInputStream(file)) {
int len = ZIP_FILE_MAGIC.length;
byte[] headers = new byte[len];
int read = is.read(headers);
return read == len && Arrays.equals(headers, ZIP_FILE_MAGIC);
} catch (Exception e) {
LOG.error("Failed to read zip file: {}", file.getAbsolutePath(), e);
return false;
}
}
public static String getPathBaseName(Path file) {
String fileName = file.getFileName().toString();
int extEndIndex = fileName.lastIndexOf('.');
if (extEndIndex == -1) {
return fileName;
}
return fileName.substring(0, extEndIndex);
}
public static File toFile(String path) {
if (path == null) {
return null;
}
return new File(path);
}
public static List<Path> toPaths(List<File> files) {
return files.stream().map(File::toPath).collect(Collectors.toList());
}
public static List<Path> toPaths(File[] files) {
return Stream.of(files).map(File::toPath).collect(Collectors.toList());
}
public static List<Path> toPathsWithTrim(File[] files) {
return Stream.of(files).map(FileUtils::toPathWithTrim).collect(Collectors.toList());
}
public static Path toPathWithTrim(File file) {
return toPathWithTrim(file.getPath());
}
public static Path toPathWithTrim(String file) {
return Path.of(file.trim());
}
public static List<Path> fileNamesToPaths(List<String> fileNames) {
return fileNames.stream().map(Paths::get).collect(Collectors.toList());
}
public static List<File> toFiles(List<Path> paths) {
return paths.stream().map(Path::toFile).collect(Collectors.toList());
}
public static String md5Sum(String str) {
return md5Sum(str.getBytes(StandardCharsets.UTF_8));
}
public static String md5Sum(byte[] data) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(data);
return bytesToHex(md.digest());
} catch (Exception e) {
throw new JadxRuntimeException("Failed to build hash", e);
}
}
/**
* Hash timestamps of input files
*/
public static String buildInputsHash(List<Path> inputPaths) {
try (ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(bout)) {
List<Path> inputFiles = FileUtils.expandDirs(inputPaths);
Collections.sort(inputFiles);
data.write(inputPaths.size());
data.write(inputFiles.size());
for (Path inputFile : inputFiles) {
FileTime modifiedTime = Files.getLastModifiedTime(inputFile);
data.writeLong(modifiedTime.toMillis());
}
return FileUtils.md5Sum(bout.toByteArray());
} catch (Exception e) {
throw new JadxRuntimeException("Failed to build hash for inputs", e);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/input/InsnDataUtils.java | jadx-core/src/main/java/jadx/core/utils/input/InsnDataUtils.java | package jadx.core.utils.input;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import jadx.api.plugins.input.data.ICallSite;
import jadx.api.plugins.input.data.IMethodHandle;
import jadx.api.plugins.input.data.IMethodRef;
import jadx.api.plugins.input.data.annotations.EncodedType;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.api.plugins.input.insns.InsnData;
import jadx.api.plugins.input.insns.InsnIndexType;
import jadx.api.plugins.input.insns.custom.ICustomPayload;
public class InsnDataUtils {
@Nullable
public static ICallSite getCallSite(InsnData insnData) {
if (insnData.getIndexType() != InsnIndexType.CALL_SITE) {
return null;
}
ICustomPayload payload = insnData.getPayload();
if (payload != null) {
return (ICallSite) payload;
}
return insnData.getIndexAsCallSite();
}
@Nullable
public static IMethodRef getMethodRef(InsnData insnData) {
if (insnData.getIndexType() != InsnIndexType.METHOD_REF) {
return null;
}
ICustomPayload payload = insnData.getPayload();
if (payload != null) {
return (IMethodRef) payload;
}
return insnData.getIndexAsMethod();
}
@Nullable
public static IMethodHandle getMethodHandleAt(ICallSite callSite, int argNum) {
if (callSite == null) {
return null;
}
List<EncodedValue> values = callSite.getValues();
if (argNum < values.size()) {
EncodedValue encodedValue = values.get(argNum);
if (encodedValue.getType() == EncodedType.ENCODED_METHOD_HANDLE) {
return (IMethodHandle) encodedValue.getValue();
}
}
return null;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/log/LogUtils.java | jadx-core/src/main/java/jadx/core/utils/log/LogUtils.java | package jadx.core.utils.log;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
/**
* Escape input from untrusted source before pass to logger.
* Suggested by CodeQL: https://codeql.github.com/codeql-query-help/java/java-log-injection/
*/
public class LogUtils {
private static final Pattern ALFA_NUMERIC = Pattern.compile("\\w*");
public static String escape(String input) {
if (input == null) {
return "null";
}
if (ALFA_NUMERIC.matcher(input).matches()) {
return input;
}
return input.replaceAll("\\W", ".");
}
public static String escape(byte[] input) {
if (input == null) {
return "null";
}
return escape(new String(input, StandardCharsets.UTF_8));
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/android/TextResMapFile.java | jadx-core/src/main/java/jadx/core/utils/android/TextResMapFile.java | package jadx.core.utils.android;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class TextResMapFile {
private static final int SPLIT_POS = 8;
public static Map<Integer, String> read(InputStream is) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
Map<Integer, String> resMap = new HashMap<>();
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
parseLine(resMap, line);
}
return resMap;
} catch (Exception e) {
throw new JadxRuntimeException("Failed to read res-map file", e);
}
}
private static void parseLine(Map<Integer, String> resMap, String line) {
int id = Integer.parseInt(line.substring(0, SPLIT_POS), 16);
String name = line.substring(SPLIT_POS + 1);
resMap.put(id, name);
}
public static Map<Integer, String> read(Path resMapFile) {
try (InputStream in = Files.newInputStream(resMapFile)) {
return read(in);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to read res-map file", e);
}
}
public static void write(Path resMapFile, Map<Integer, String> inputResMap) {
try {
Map<Integer, String> resMap = new TreeMap<>(inputResMap);
List<String> lines = new ArrayList<>(resMap.size());
for (Map.Entry<Integer, String> entry : resMap.entrySet()) {
lines.add(String.format("%08x=%s", entry.getKey(), entry.getValue()));
}
Files.write(resMapFile, lines, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to write res-map file", e);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/android/AppAttribute.java | jadx-core/src/main/java/jadx/core/utils/android/AppAttribute.java | package jadx.core.utils.android;
public enum AppAttribute {
APPLICATION_LABEL,
MIN_SDK_VERSION,
COMPILE_SDK_VERSION,
TARGET_SDK_VERSION,
VERSION_CODE,
VERSION_NAME,
MAIN_ACTIVITY,
APPLICATION,
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/android/Res9patchStreamDecoder.java | jadx-core/src/main/java/jadx/core/utils/android/Res9patchStreamDecoder.java | /**
* Copyright 2014 Ryszard Wiśniewski <brut.alll@gmail.com>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jadx.core.utils.android;
import java.awt.image.BufferedImage;
import java.io.DataInput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import org.jetbrains.annotations.Nullable;
import jadx.core.utils.exceptions.JadxRuntimeException;
/**
* @author Ryszard Wiśniewski "brut.alll@gmail.com"
*/
public class Res9patchStreamDecoder {
public boolean decode(InputStream in, OutputStream out) {
try {
BufferedImage im = ImageIO.read(in);
NinePatch np = getNinePatch(in);
if (np == null) {
return false;
}
int w = im.getWidth();
int h = im.getHeight();
BufferedImage im2 = new BufferedImage(w + 2, h + 2, BufferedImage.TYPE_INT_ARGB);
im2.createGraphics().drawImage(im, 1, 1, w, h, null);
drawHLine(im2, h + 1, np.padLeft + 1, w - np.padRight);
drawVLine(im2, w + 1, np.padTop + 1, h - np.padBottom);
int[] xDivs = np.xDivs;
for (int i = 0; i < xDivs.length - 1; i += 2) {
drawHLine(im2, 0, xDivs[i] + 1, xDivs[i + 1]);
}
int[] yDivs = np.yDivs;
for (int i = 0; i < yDivs.length - 1; i += 2) {
drawVLine(im2, 0, yDivs[i] + 1, yDivs[i + 1]);
}
ImageIO.write(im2, "png", out);
return true;
} catch (Exception e) {
throw new JadxRuntimeException("9patch image decode error", e);
}
}
@Nullable
private NinePatch getNinePatch(InputStream in) throws IOException {
ExtDataInput di = new ExtDataInput(in);
if (!find9patchChunk(di)) {
return null;
}
return NinePatch.decode(di);
}
private boolean find9patchChunk(DataInput di) throws IOException {
di.skipBytes(8);
while (true) {
int size;
try {
size = di.readInt();
} catch (IOException ex) {
return false;
}
if (di.readInt() == NP_CHUNK_TYPE) {
return true;
}
di.skipBytes(size + 4);
}
}
private void drawHLine(BufferedImage im, int y, int x1, int x2) {
for (int x = x1; x <= x2; x++) {
im.setRGB(x, y, NP_COLOR);
}
}
private void drawVLine(BufferedImage im, int x, int y1, int y2) {
for (int y = y1; y <= y2; y++) {
im.setRGB(x, y, NP_COLOR);
}
}
private static final int NP_CHUNK_TYPE = 0x6e705463; // npTc
private static final int NP_COLOR = 0xff000000;
private static class NinePatch {
public final int padLeft;
public final int padRight;
public final int padTop;
public final int padBottom;
public final int[] xDivs;
public final int[] yDivs;
public NinePatch(int padLeft, int padRight, int padTop, int padBottom,
int[] xDivs, int[] yDivs) {
this.padLeft = padLeft;
this.padRight = padRight;
this.padTop = padTop;
this.padBottom = padBottom;
this.xDivs = xDivs;
this.yDivs = yDivs;
}
public static NinePatch decode(ExtDataInput di) throws IOException {
di.skipBytes(1);
byte numXDivs = di.readByte();
byte numYDivs = di.readByte();
di.skipBytes(1);
di.skipBytes(8);
int padLeft = di.readInt();
int padRight = di.readInt();
int padTop = di.readInt();
int padBottom = di.readInt();
di.skipBytes(4);
int[] xDivs = di.readIntArray(numXDivs);
int[] yDivs = di.readIntArray(numYDivs);
return new NinePatch(padLeft, padRight, padTop, padBottom, xDivs, yDivs);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/android/AndroidManifestParser.java | jadx-core/src/main/java/jadx/core/utils/android/AndroidManifestParser.java | package jadx.core.utils.android;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import jadx.api.ResourceFile;
import jadx.api.ResourceType;
import jadx.api.security.IJadxSecurity;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.xmlgen.ResContainer;
public class AndroidManifestParser {
private final Document androidManifest;
private final @Nullable Document appStrings;
private final EnumSet<AppAttribute> parseAttrs;
private final IJadxSecurity security;
public AndroidManifestParser(ResourceFile androidManifestRes, EnumSet<AppAttribute> parseAttrs, IJadxSecurity security) {
this(androidManifestRes, null, parseAttrs, security);
}
public AndroidManifestParser(ResourceFile androidManifestRes, @Nullable ResContainer appStrings,
EnumSet<AppAttribute> parseAttrs, IJadxSecurity security) {
this.parseAttrs = parseAttrs;
this.security = Objects.requireNonNull(security);
this.androidManifest = parseAndroidManifest(androidManifestRes);
this.appStrings = parseAppStrings(appStrings);
}
public boolean isManifestFound() {
return androidManifest != null;
}
@Nullable
public static ResourceFile getAndroidManifest(List<ResourceFile> resources) {
return resources.stream()
.filter(resourceFile -> resourceFile.getType() == ResourceType.MANIFEST)
.findFirst()
.orElse(null);
}
public ApplicationParams parse() {
if (!isManifestFound()) {
throw new JadxRuntimeException("AndroidManifest.xml is missing");
}
return parseAttributes();
}
private ApplicationParams parseAttributes() {
String applicationLabel = null;
Integer minSdkVersion = null;
Integer targetSdkVersion = null;
Integer compileSdkVersion = null;
Integer versionCode = null;
String versionName = null;
String mainActivity = null;
String application = null;
@Nullable
Element manifest = (Element) androidManifest.getElementsByTagName("manifest").item(0);
@Nullable
Element usesSdk = (Element) androidManifest.getElementsByTagName("uses-sdk").item(0);
if (parseAttrs.contains(AppAttribute.APPLICATION_LABEL)) {
applicationLabel = getApplicationLabel();
}
if (usesSdk != null) {
if (parseAttrs.contains(AppAttribute.MIN_SDK_VERSION)) {
minSdkVersion = Integer.valueOf(usesSdk.getAttribute("android:minSdkVersion"));
}
if (parseAttrs.contains(AppAttribute.TARGET_SDK_VERSION)) {
String stringTargetSdk = usesSdk.getAttribute("android:targetSdkVersion");
if (!stringTargetSdk.isEmpty()) {
targetSdkVersion = Integer.valueOf(stringTargetSdk);
} else {
if (minSdkVersion == null) {
minSdkVersion = Integer.valueOf(usesSdk.getAttribute("android:minSdkVersion"));
}
targetSdkVersion = minSdkVersion;
}
}
if (parseAttrs.contains(AppAttribute.COMPILE_SDK_VERSION)) {
String stringCompileSdk = usesSdk.getAttribute("android:compileSdkVersion");
if (!stringCompileSdk.isEmpty()) {
compileSdkVersion = Integer.valueOf(stringCompileSdk);
} else {
compileSdkVersion = targetSdkVersion;
}
}
}
if (manifest != null) {
if (parseAttrs.contains(AppAttribute.VERSION_CODE)) {
versionCode = Integer.valueOf(manifest.getAttribute("android:versionCode"));
}
if (parseAttrs.contains(AppAttribute.VERSION_NAME)) {
versionName = manifest.getAttribute("android:versionName");
}
}
if (parseAttrs.contains(AppAttribute.MAIN_ACTIVITY)) {
mainActivity = getMainActivityName();
}
if (parseAttrs.contains(AppAttribute.APPLICATION)) {
application = getApplicationName();
}
return new ApplicationParams(applicationLabel, minSdkVersion, targetSdkVersion, compileSdkVersion,
versionCode, versionName, mainActivity, application);
}
private String getApplicationLabel() {
Element application = (Element) androidManifest.getElementsByTagName("application").item(0);
if (application.hasAttribute("android:label")) {
String appLabelName = application.getAttribute("android:label");
if (appLabelName.startsWith("@string")) {
if (appStrings == null) {
throw new IllegalArgumentException("APPLICATION_LABEL attribute requires non null appStrings");
}
appLabelName = appLabelName.split("/")[1];
NodeList strings = appStrings.getElementsByTagName("string");
for (int i = 0; i < strings.getLength(); i++) {
String stringName = strings.item(i)
.getAttributes()
.getNamedItem("name")
.getNodeValue();
if (stringName.equals(appLabelName)) {
return strings.item(i).getTextContent();
}
}
} else {
return appLabelName;
}
}
return "UNKNOWN";
}
private String getMainActivityName() {
String mainActivityName = getMainActivityNameThroughActivityTag();
if (mainActivityName == null) {
mainActivityName = getMainActivityNameThroughActivityAliasTag();
}
return mainActivityName;
}
private String getApplicationName() {
Element application = (Element) androidManifest.getElementsByTagName("application").item(0);
if (application.hasAttribute("android:name")) {
return application.getAttribute("android:name");
}
return null;
}
private String getMainActivityNameThroughActivityAliasTag() {
NodeList activityAliasNodes = androidManifest.getElementsByTagName("activity-alias");
for (int i = 0; i < activityAliasNodes.getLength(); i++) {
Element activityElement = (Element) activityAliasNodes.item(i);
if (isMainActivityElement(activityElement)) {
return activityElement.getAttribute("android:targetActivity");
}
}
return null;
}
private String getMainActivityNameThroughActivityTag() {
NodeList activityNodes = androidManifest.getElementsByTagName("activity");
for (int i = 0; i < activityNodes.getLength(); i++) {
Element activityElement = (Element) activityNodes.item(i);
if (isMainActivityElement(activityElement)) {
return activityElement.getAttribute("android:name");
}
}
return null;
}
private boolean isMainActivityElement(Element element) {
NodeList intentFilterNodes = element.getElementsByTagName("intent-filter");
for (int j = 0; j < intentFilterNodes.getLength(); j++) {
Element intentFilterElement = (Element) intentFilterNodes.item(j);
NodeList actionNodes = intentFilterElement.getElementsByTagName("action");
NodeList categoryNodes = intentFilterElement.getElementsByTagName("category");
boolean isMainAction = false;
boolean isLauncherCategory = false;
for (int k = 0; k < actionNodes.getLength(); k++) {
Element actionElement = (Element) actionNodes.item(k);
String actionName = actionElement.getAttribute("android:name");
if ("android.intent.action.MAIN".equals(actionName)) {
isMainAction = true;
break;
}
}
for (int k = 0; k < categoryNodes.getLength(); k++) {
Element categoryElement = (Element) categoryNodes.item(k);
String categoryName = categoryElement.getAttribute("android:name");
if ("android.intent.category.LAUNCHER".equals(categoryName)) {
isLauncherCategory = true;
break;
}
}
if (isMainAction && isLauncherCategory) {
return true;
}
}
return false;
}
private Document parseXml(String xmlContent) {
try (InputStream xmlStream = new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8))) {
Document document = security.parseXml(xmlStream);
document.getDocumentElement().normalize();
return document;
} catch (Exception e) {
throw new JadxRuntimeException("Can not parse xml content", e);
}
}
private Document parseAppStrings(ResContainer appStrings) {
if (appStrings == null) {
return null;
}
String content = appStrings.getText().getCodeStr();
return parseXml(content);
}
private Document parseAndroidManifest(ResourceFile androidManifest) {
if (androidManifest == null) {
return null;
}
String content = androidManifest.loadContent().getText().getCodeStr();
return parseXml(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/core/utils/android/DataInputDelegate.java | jadx-core/src/main/java/jadx/core/utils/android/DataInputDelegate.java | /**
* Copyright 2014 Ryszard Wiśniewski <brut.alll@gmail.com>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jadx.core.utils.android;
import java.io.DataInput;
import java.io.IOException;
/**
* @author Ryszard Wiśniewski "brut.alll@gmail.com"
*/
public abstract class DataInputDelegate implements DataInput {
protected final DataInput mDelegate;
public DataInputDelegate(DataInput delegate) {
this.mDelegate = delegate;
}
public int skipBytes(int n) throws IOException {
return mDelegate.skipBytes(n);
}
public int readUnsignedShort() throws IOException {
return mDelegate.readUnsignedShort();
}
public int readUnsignedByte() throws IOException {
return mDelegate.readUnsignedByte();
}
public String readUTF() throws IOException {
return mDelegate.readUTF();
}
public short readShort() throws IOException {
return mDelegate.readShort();
}
public long readLong() throws IOException {
return mDelegate.readLong();
}
public String readLine() throws IOException {
return mDelegate.readLine();
}
public int readInt() throws IOException {
return mDelegate.readInt();
}
public void readFully(byte[] b, int off, int len) throws IOException {
mDelegate.readFully(b, off, len);
}
public void readFully(byte[] b) throws IOException {
mDelegate.readFully(b);
}
public float readFloat() throws IOException {
return mDelegate.readFloat();
}
public double readDouble() throws IOException {
return mDelegate.readDouble();
}
public char readChar() throws IOException {
return mDelegate.readChar();
}
public byte readByte() throws IOException {
return mDelegate.readByte();
}
public boolean readBoolean() throws IOException {
return mDelegate.readBoolean();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/android/ApplicationParams.java | jadx-core/src/main/java/jadx/core/utils/android/ApplicationParams.java | package jadx.core.utils.android;
import jadx.api.JadxDecompiler;
import jadx.api.JavaClass;
public class ApplicationParams {
private final String applicationLabel;
private final Integer minSdkVersion;
private final Integer targetSdkVersion;
private final Integer compileSdkVersion;
private final Integer versionCode;
private final String versionName;
private final String mainActivity;
private final String application;
public ApplicationParams(String applicationLabel, Integer minSdkVersion, Integer targetSdkVersion, Integer compileSdkVersion,
Integer versionCode, String versionName, String mainActivity, String application) {
this.applicationLabel = applicationLabel;
this.minSdkVersion = minSdkVersion;
this.targetSdkVersion = targetSdkVersion;
this.compileSdkVersion = compileSdkVersion;
this.versionCode = versionCode;
this.versionName = versionName;
this.mainActivity = mainActivity;
this.application = application;
}
public String getApplicationName() {
return applicationLabel;
}
public Integer getMinSdkVersion() {
return minSdkVersion;
}
public Integer getTargetSdkVersion() {
return targetSdkVersion;
}
public Integer getCompileSdkVersion() {
return compileSdkVersion;
}
public Integer getVersionCode() {
return versionCode;
}
public String getVersionName() {
return versionName;
}
public String getMainActivity() {
return mainActivity;
}
public JavaClass getMainActivityJavaClass(JadxDecompiler decompiler) {
return decompiler.searchJavaClassByOrigFullName(mainActivity);
}
public String getApplication() {
return application;
}
public JavaClass getApplicationJavaClass(JadxDecompiler decompiler) {
return decompiler.searchJavaClassByOrigFullName(application);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/android/AndroidResourcesMap.java | jadx-core/src/main/java/jadx/core/utils/android/AndroidResourcesMap.java | package jadx.core.utils.android;
import java.io.InputStream;
import java.util.Map;
import org.jetbrains.annotations.Nullable;
import jadx.core.utils.exceptions.JadxRuntimeException;
/**
* Store resources id to name mapping
*/
public class AndroidResourcesMap {
private static final Map<Integer, String> RES_MAP = loadBundled();
public static @Nullable String getResName(int resId) {
return RES_MAP.get(resId);
}
public static Map<Integer, String> getMap() {
return RES_MAP;
}
private static Map<Integer, String> loadBundled() {
try (InputStream is = AndroidResourcesMap.class.getResourceAsStream("/android/res-map.txt")) {
return TextResMapFile.read(is);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to load android resource file (res-map.txt)", e);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/android/AndroidResourcesUtils.java | jadx-core/src/main/java/jadx/core/utils/android/AndroidResourcesUtils.java | package jadx.core.utils.android;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeWriter;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.api.plugins.input.data.annotations.EncodedType;
import jadx.api.plugins.input.data.annotations.EncodedValue;
import jadx.core.codegen.ClassGen;
import jadx.core.deobf.NameMapper;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.ConstStorage;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.xmlgen.ResourceStorage;
import jadx.core.xmlgen.entry.ResourceEntry;
/**
* Android resources specific handlers
*/
public class AndroidResourcesUtils {
private static final Logger LOG = LoggerFactory.getLogger(AndroidResourcesUtils.class);
private AndroidResourcesUtils() {
}
public static ClassNode searchAppResClass(RootNode root, ResourceStorage resStorage) {
String appPackage = root.getAppPackage();
String fullName = appPackage != null ? appPackage + ".R" : "R";
ClassInfo clsInfo = ClassInfo.fromName(root, fullName);
ClassNode resCls = root.resolveClass(clsInfo);
if (resCls != null) {
addResourceFields(resCls, resStorage, true);
return resCls;
}
LOG.debug("Can't find 'R' class in app package: {}", appPackage);
List<ClassNode> candidates = root.searchClassByShortName("R");
if (candidates.size() == 1) {
ClassNode resClsCandidate = candidates.get(0);
addResourceFields(resClsCandidate, resStorage, true);
return resClsCandidate;
}
if (!candidates.isEmpty()) {
LOG.info("Found several 'R' class candidates: {}", candidates);
}
LOG.info("App 'R' class not found, put all resources ids into : '{}'", fullName);
ClassNode rCls = ClassNode.addSyntheticClass(root, clsInfo, AccessFlags.PUBLIC | AccessFlags.FINAL);
rCls.addInfoComment("This class is generated by JADX");
addResourceFields(rCls, resStorage, false);
return rCls;
}
public static boolean handleAppResField(ICodeWriter code, ClassGen clsGen, ClassInfo declClass) {
ClassInfo parentClass = declClass.getParentClass();
if (parentClass != null && parentClass.getShortName().equals("R")) {
clsGen.useClass(code, parentClass);
code.add('.');
code.add(declClass.getAliasShortName());
return true;
}
return false;
}
/**
* Force hex format for Android resources ids
*/
public static boolean isResourceFieldValue(ClassNode cls, ArgType type) {
return type.equals(ArgType.INT) && isResourceClass(cls);
}
public static boolean isResourceClass(ClassNode cls) {
ClassNode parentClass = cls.getParentClass();
return parentClass != null && parentClass.getAlias().equals("R");
}
private static final class ResClsInfo {
private final ClassNode typeCls;
private final Map<String, FieldNode> fieldsMap = new HashMap<>();
private ResClsInfo(ClassNode typeCls) {
this.typeCls = typeCls;
}
public ClassNode getTypeCls() {
return typeCls;
}
public Map<String, FieldNode> getFieldsMap() {
return fieldsMap;
}
}
private static void addResourceFields(ClassNode resCls, ResourceStorage resStorage, boolean rClsExists) {
Map<Integer, FieldNode> resFieldsMap = fillResFieldsMap(resCls);
Map<String, ResClsInfo> innerClsMap = new TreeMap<>();
if (rClsExists) {
for (ClassNode innerClass : resCls.getInnerClasses()) {
ResClsInfo innerResCls = new ResClsInfo(innerClass);
innerClass.getFields().forEach(field -> innerResCls.getFieldsMap().put(field.getName(), field));
innerClsMap.put(innerClass.getAlias(), innerResCls);
}
}
for (ResourceEntry resource : resStorage.getResources()) {
String resTypeName = resource.getTypeName();
String resName = resource.getKeyName().replace('.', '_');
ResClsInfo typeClsInfo = innerClsMap.computeIfAbsent(
resTypeName,
name -> getClassForResType(resCls, rClsExists, name));
typeClsInfo.getFieldsMap().computeIfAbsent(resName, name -> {
ClassNode typeCls = typeClsInfo.getTypeCls();
FieldInfo rFieldInfo = FieldInfo.from(typeCls.root(), typeCls.getClassInfo(), resName, ArgType.INT);
FieldNode newResField = new FieldNode(typeCls, rFieldInfo,
AccessFlags.PUBLIC | AccessFlags.STATIC | AccessFlags.FINAL);
newResField.addAttr(new EncodedValue(EncodedType.ENCODED_INT, resource.getId()));
typeCls.addField(newResField);
if (rClsExists) {
newResField.addInfoComment("Added by JADX");
}
return newResField;
});
FieldNode fieldNode = resFieldsMap.get(resource.getId());
if (fieldNode != null
&& !fieldNode.getName().equals(resName)
&& NameMapper.isValidAndPrintable(resName)
&& resCls.root().getArgs().isRenameValid()) {
fieldNode.add(AFlag.DONT_RENAME);
fieldNode.getFieldInfo().setAlias(resName);
}
}
}
private static ResClsInfo getClassForResType(ClassNode resCls, boolean rClsExists, String typeName) {
RootNode root = resCls.root();
String typeClsFullName = resCls.getClassInfo().makeRawFullName() + '$' + typeName;
ClassInfo clsInfo = ClassInfo.fromName(root, typeClsFullName);
ClassNode existCls = root.resolveClass(clsInfo);
if (existCls != null) {
ResClsInfo resClsInfo = new ResClsInfo(existCls);
existCls.getFields().forEach(field -> resClsInfo.getFieldsMap().put(field.getName(), field));
return resClsInfo;
}
ClassNode newTypeCls = ClassNode.addSyntheticClass(root, clsInfo,
AccessFlags.PUBLIC | AccessFlags.STATIC | AccessFlags.FINAL);
if (rClsExists) {
newTypeCls.addInfoComment("Added by JADX");
}
return new ResClsInfo(newTypeCls);
}
@NotNull
private static Map<Integer, FieldNode> fillResFieldsMap(ClassNode resCls) {
Map<Integer, FieldNode> resFieldsMap = new HashMap<>();
ConstStorage constStorage = resCls.root().getConstValues();
constStorage.getGlobalConstFields().forEach((key, field) -> {
if (field.getFieldInfo().getType().equals(ArgType.INT)
&& field instanceof FieldNode
&& key instanceof Integer) {
FieldNode fldNode = (FieldNode) field;
AccessInfo accessFlags = fldNode.getAccessFlags();
if (accessFlags.isStatic() && accessFlags.isFinal()) {
resFieldsMap.put((Integer) key, fldNode);
}
}
});
return resFieldsMap;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/utils/android/ExtDataInput.java | jadx-core/src/main/java/jadx/core/utils/android/ExtDataInput.java | /**
* Copyright 2014 Ryszard Wiśniewski <brut.alll@gmail.com>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jadx.core.utils.android;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Ryszard Wiśniewski "brut.alll@gmail.com"
*/
public class ExtDataInput extends DataInputDelegate {
public ExtDataInput(InputStream in) {
this((DataInput) new DataInputStream(in));
}
public ExtDataInput(DataInput delegate) {
super(delegate);
}
public int[] readIntArray(int length) throws IOException {
int[] array = new int[length];
for (int i = 0; i < length; i++) {
array[i] = readInt();
}
return array;
}
public void skipInt() throws IOException {
skipBytes(4);
}
public void skipCheckInt(int expected) throws IOException {
int got = readInt();
if (got != expected) {
throw new IOException(String.format("Expected: 0x%08x, got: 0x%08x", expected, got));
}
}
public void skipCheckShort(short expected) throws IOException {
short got = readShort();
if (got != expected) {
throw new IOException(String.format("Expected: 0x%08x, got: 0x%08x", expected, got));
}
}
public void skipCheckByte(byte expected) throws IOException {
byte got = readByte();
if (got != expected) {
throw new IOException(String.format("Expected: 0x%08x, got: 0x%08x", expected, got));
}
}
public void skipCheckChunkTypeInt(int expected, int possible) throws IOException {
int got = readInt();
if (got == possible) {
skipCheckChunkTypeInt(expected, -1);
} else if (got != expected) {
throw new IOException(String.format("Expected: 0x%08x, got: 0x%08x", expected, got));
}
}
/**
* The general contract of DataInput doesn't guarantee all the bytes requested will be skipped
* and failure can occur for many reasons. We override this to try harder to skip all the bytes
* requested (this is similar to DataInputStream's wrapper).
*/
@Override
@SuppressWarnings("InnerAssignment")
public final int skipBytes(int n) throws IOException {
int total = 0;
int cur;
while ((total < n) && ((cur = super.skipBytes(n - total)) > 0)) {
total += cur;
}
return total;
}
public String readNullEndedString(int length, boolean fixed) throws IOException {
StringBuilder string = new StringBuilder(16);
while (length-- != 0) {
short ch = readShort();
if (ch == 0) {
break;
}
string.append((char) ch);
}
if (fixed) {
skipBytes(length * 2);
}
return string.toString();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.