repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/AppContext.java
jadx-core/src/main/java/jadx/core/plugins/AppContext.java
package jadx.core.plugins; import java.util.Objects; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.gui.JadxGuiContext; import jadx.core.plugins.files.IJadxFilesGetter; public class AppContext { private @Nullable JadxGuiContext guiContext; private IJadxFilesGetter filesGetter; public @Nullable JadxGuiContext getGuiContext() { return guiContext; } public void setGuiContext(@Nullable JadxGuiContext guiContext) { this.guiContext = guiContext; } public IJadxFilesGetter getFilesGetter() { return Objects.requireNonNull(filesGetter); } public void setFilesGetter(IJadxFilesGetter filesGetter) { this.filesGetter = filesGetter; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/JadxPluginManager.java
jadx-core/src/main/java/jadx/core/plugins/JadxPluginManager.java
package jadx.core.plugins; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.function.Consumer; import java.util.stream.Collectors; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxDecompiler; import jadx.api.plugins.JadxPlugin; import jadx.api.plugins.input.JadxCodeInput; import jadx.api.plugins.loader.JadxPluginLoader; import jadx.api.plugins.options.JadxPluginOptions; import jadx.api.plugins.options.OptionDescription; import jadx.core.plugins.versions.VerifyRequiredVersion; public class JadxPluginManager { private static final Logger LOG = LoggerFactory.getLogger(JadxPluginManager.class); private final JadxDecompiler decompiler; private final JadxPluginsData pluginsData; private final Set<String> disabledPlugins; private final SortedSet<PluginContext> allPlugins = new TreeSet<>(); private final SortedSet<PluginContext> resolvedPlugins = new TreeSet<>(); private final Map<String, String> provideSuggestions = new TreeMap<>(); private final List<Consumer<PluginContext>> addPluginListeners = new ArrayList<>(); public JadxPluginManager(JadxDecompiler decompiler) { this.decompiler = decompiler; this.pluginsData = new JadxPluginsData(decompiler, this); this.disabledPlugins = decompiler.getArgs().getDisabledPlugins(); } /** * Add suggestion how to resolve conflicting plugins */ public void providesSuggestion(String provides, String pluginId) { provideSuggestions.put(provides, pluginId); } public void load(JadxPluginLoader pluginLoader) { allPlugins.clear(); VerifyRequiredVersion verifyRequiredVersion = new VerifyRequiredVersion(); for (JadxPlugin plugin : pluginLoader.load()) { addPlugin(plugin, verifyRequiredVersion); } resolve(); } public void register(JadxPlugin plugin) { Objects.requireNonNull(plugin); PluginContext addedPlugin = addPlugin(plugin, new VerifyRequiredVersion()); if (addedPlugin == null) { LOG.debug("Can't register plugin, it was disabled: {}", plugin.getPluginInfo().getPluginId()); return; } LOG.debug("Register plugin: {}", addedPlugin.getPluginId()); resolve(); } private @Nullable PluginContext addPlugin(JadxPlugin plugin, VerifyRequiredVersion verifyRequiredVersion) { PluginContext pluginContext = new PluginContext(decompiler, pluginsData, plugin); if (disabledPlugins.contains(pluginContext.getPluginId())) { return null; } String requiredJadxVersion = pluginContext.getPluginInfo().getRequiredJadxVersion(); if (!verifyRequiredVersion.isCompatible(requiredJadxVersion)) { LOG.warn("Plugin '{}' not loaded: requires '{}' jadx version which it is not compatible with current: {}", pluginContext, requiredJadxVersion, verifyRequiredVersion.getJadxVersion()); return null; } LOG.debug("Loading plugin: {}", pluginContext); if (!allPlugins.add(pluginContext)) { throw new IllegalArgumentException("Duplicate plugin id: " + pluginContext + ", class " + plugin.getClass()); } addPluginListeners.forEach(l -> l.accept(pluginContext)); return pluginContext; } public boolean unload(String pluginId) { boolean result = allPlugins.removeIf(context -> { if (context.getPluginId().equals(pluginId)) { LOG.debug("Unload plugin: {}", pluginId); return true; } return false; }); resolve(); return result; } public SortedSet<PluginContext> getAllPluginContexts() { return allPlugins; } public SortedSet<PluginContext> getResolvedPluginContexts() { return resolvedPlugins; } private synchronized void resolve() { Map<String, List<PluginContext>> provides = allPlugins.stream() .collect(Collectors.groupingBy(p -> p.getPluginInfo().getProvides())); List<PluginContext> resolved = new ArrayList<>(provides.size()); provides.forEach((provide, list) -> { if (list.size() == 1) { resolved.add(list.get(0)); } else { String suggestion = provideSuggestions.get(provide); if (suggestion != null) { list.stream().filter(p -> p.getPluginId().equals(suggestion)) .findFirst() .ifPresent(resolved::add); } else { PluginContext selected = list.get(0); resolved.add(selected); LOG.debug("Select providing '{}' plugin '{}', candidates: {}", provide, selected, list); } } }); resolvedPlugins.clear(); resolvedPlugins.addAll(resolved); } public void initAll() { init(allPlugins); } public void initResolved() { init(resolvedPlugins); } public void init(SortedSet<PluginContext> pluginContexts) { AppContext defAppContext = buildDefaultAppContext(); for (PluginContext context : pluginContexts) { try { if (context.getAppContext() == null) { context.setAppContext(defAppContext); } context.init(); } catch (Exception e) { LOG.warn("Failed to init plugin: {}", context.getPluginId(), e); } } for (PluginContext context : pluginContexts) { JadxPluginOptions options = context.getOptions(); if (options != null) { verifyOptions(context, options); } } } public void unloadAll() { unload(allPlugins); } public void unloadResolved() { unload(resolvedPlugins); } public void unload(SortedSet<PluginContext> pluginContexts) { for (PluginContext context : pluginContexts) { try { context.unload(); } catch (Exception e) { LOG.warn("Failed to unload plugin: {}", context.getPluginId(), e); } } } private AppContext buildDefaultAppContext() { AppContext appContext = new AppContext(); appContext.setGuiContext(null); appContext.setFilesGetter(decompiler.getArgs().getFilesGetter()); return appContext; } private void verifyOptions(PluginContext pluginContext, JadxPluginOptions options) { String pluginId = pluginContext.getPluginId(); List<OptionDescription> descriptions = options.getOptionsDescriptions(); if (descriptions == null) { throw new IllegalArgumentException("Null option descriptions in plugin id: " + pluginId); } String prefix = pluginId + '.'; descriptions.forEach(descObj -> { String optName = descObj.name(); if (optName == null || !optName.startsWith(prefix)) { throw new IllegalArgumentException("Plugin option name should start with plugin id: '" + prefix + "', option: " + optName); } String desc = descObj.description(); if (desc == null || desc.isEmpty()) { throw new IllegalArgumentException("Plugin option description not set, plugin: " + pluginId); } List<String> values = descObj.values(); if (values == null) { throw new IllegalArgumentException("Plugin option values is null, option: " + optName + ", plugin: " + pluginId); } }); } public List<JadxCodeInput> getCodeInputs() { return getResolvedPluginContexts() .stream() .flatMap(p -> p.getCodeInputs().stream()) .collect(Collectors.toList()); } public void registerAddPluginListener(Consumer<PluginContext> listener) { this.addPluginListeners.add(listener); // run for already added plugins getAllPluginContexts().forEach(listener); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/JadxPluginsData.java
jadx-core/src/main/java/jadx/core/plugins/JadxPluginsData.java
package jadx.core.plugins; import jadx.api.JadxDecompiler; import jadx.api.plugins.JadxPlugin; import jadx.api.plugins.data.IJadxPlugins; import jadx.api.plugins.data.JadxPluginRuntimeData; import jadx.core.utils.exceptions.JadxRuntimeException; public class JadxPluginsData implements IJadxPlugins { private final JadxDecompiler decompiler; private final JadxPluginManager pluginManager; public JadxPluginsData(JadxDecompiler decompiler, JadxPluginManager pluginManager) { this.decompiler = decompiler; this.pluginManager = pluginManager; } @Override public JadxPluginRuntimeData getById(String pluginId) { return pluginManager.getResolvedPluginContexts() .stream() .filter(p -> p.getPluginId().equals(pluginId)) .findFirst() .orElseThrow(() -> new JadxRuntimeException("Plugin with id '" + pluginId + "' not found")); } @Override public JadxPluginRuntimeData getProviding(String provideId) { return pluginManager.getResolvedPluginContexts() .stream() .filter(p -> p.getPluginInfo().getProvides().equals(provideId)) .findFirst() .orElseThrow(() -> new JadxRuntimeException("Plugin providing '" + provideId + "' not found")); } @SuppressWarnings("unchecked") @Override public <P extends JadxPlugin> P getInstance(Class<P> pluginCls) { return pluginManager.getResolvedPluginContexts() .stream() .filter(p -> p.getPluginInstance().getClass().equals(pluginCls)) .map(p -> (P) p.getPluginInstance()) .findFirst() .orElseThrow(() -> new JadxRuntimeException("Plugin class '" + pluginCls + "' not found")); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/PluginContext.java
jadx-core/src/main/java/jadx/core/plugins/PluginContext.java
package jadx.core.plugins; import java.io.Closeable; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Supplier; import org.jetbrains.annotations.Nullable; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.api.plugins.JadxPlugin; import jadx.api.plugins.JadxPluginContext; import jadx.api.plugins.JadxPluginInfo; import jadx.api.plugins.data.IJadxFiles; import jadx.api.plugins.data.IJadxPlugins; import jadx.api.plugins.data.JadxPluginRuntimeData; import jadx.api.plugins.events.IJadxEvents; import jadx.api.plugins.gui.JadxGuiContext; import jadx.api.plugins.input.ICodeLoader; import jadx.api.plugins.input.JadxCodeInput; import jadx.api.plugins.input.data.impl.MergeCodeLoader; import jadx.api.plugins.options.JadxPluginOptions; import jadx.api.plugins.options.OptionDescription; import jadx.api.plugins.options.OptionFlag; import jadx.api.plugins.pass.JadxPass; import jadx.api.plugins.resources.IResourcesLoader; import jadx.core.plugins.files.JadxFilesData; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.zip.ZipReader; public class PluginContext implements JadxPluginContext, JadxPluginRuntimeData, Comparable<PluginContext> { private final JadxDecompiler decompiler; private final JadxPluginsData pluginsData; private final JadxPlugin plugin; private final JadxPluginInfo pluginInfo; private AppContext appContext; private final List<JadxCodeInput> codeInputs = new ArrayList<>(); private @Nullable JadxPluginOptions options; private @Nullable Supplier<String> inputsHashSupplier; private boolean initialized; PluginContext(JadxDecompiler decompiler, JadxPluginsData pluginsData, JadxPlugin plugin) { this.decompiler = decompiler; this.pluginsData = pluginsData; this.plugin = plugin; this.pluginInfo = plugin.getPluginInfo(); } public void init() { plugin.init(this); initialized = true; } public void unload() { if (initialized) { plugin.unload(); } } @Override public boolean isInitialized() { return initialized; } @Override public JadxArgs getArgs() { return decompiler.getArgs(); } @Override public JadxDecompiler getDecompiler() { return decompiler; } @Override public void addPass(JadxPass pass) { decompiler.addCustomPass(pass); } @Override public void addCodeInput(JadxCodeInput codeInput) { this.codeInputs.add(codeInput); } @Override public List<JadxCodeInput> getCodeInputs() { return codeInputs; } @Override public void registerOptions(JadxPluginOptions options) { try { this.options = Objects.requireNonNull(options); options.setOptions(getArgs().getPluginOptions()); } catch (Exception e) { throw new JadxRuntimeException("Failed to apply options for plugin: " + getPluginId(), e); } } @Override public void registerInputsHashSupplier(Supplier<String> supplier) { this.inputsHashSupplier = supplier; } @Override public String getInputsHash() { if (inputsHashSupplier == null) { return defaultOptionsHash(); } try { return inputsHashSupplier.get(); } catch (Exception e) { throw new JadxRuntimeException("Failed to get inputs hash for plugin: " + getPluginId(), e); } } private String defaultOptionsHash() { if (options == null) { return ""; } Map<String, String> allOptions = getArgs().getPluginOptions(); StringBuilder sb = new StringBuilder(); for (OptionDescription optDesc : options.getOptionsDescriptions()) { if (!optDesc.getFlags().contains(OptionFlag.NOT_CHANGING_CODE)) { sb.append(':').append(allOptions.get(optDesc.name())); } } return FileUtils.md5Sum(sb.toString()); } @Override public IJadxEvents events() { return decompiler.events(); } @Override public IResourcesLoader getResourcesLoader() { return decompiler.getResourcesLoader(); } public AppContext getAppContext() { return appContext; } public void setAppContext(AppContext appContext) { this.appContext = appContext; } @Override public @Nullable JadxGuiContext getGuiContext() { return appContext.getGuiContext(); } @Override public JadxPlugin getPluginInstance() { return plugin; } @Override public JadxPluginInfo getPluginInfo() { return pluginInfo; } @Override public String getPluginId() { return pluginInfo.getPluginId(); } @Override public @Nullable JadxPluginOptions getOptions() { return options; } @Override public IJadxPlugins plugins() { return pluginsData; } @Override public IJadxFiles files() { return new JadxFilesData(pluginInfo, appContext.getFilesGetter()); } @Override public ICodeLoader loadCodeFiles(List<Path> files, @Nullable Closeable closeable) { return new MergeCodeLoader( Utils.collectionMap(codeInputs, codeInput -> codeInput.loadFiles(files)), closeable); } @Override public ZipReader getZipReader() { return decompiler.getZipReader(); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof PluginContext)) { return false; } return this.getPluginId().equals(((PluginContext) other).getPluginId()); } @Override public int hashCode() { return getPluginId().hashCode(); } @Override public int compareTo(PluginContext other) { return this.getPluginId().compareTo(other.getPluginId()); } @Override public String toString() { return getPluginId(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/files/IJadxFilesGetter.java
jadx-core/src/main/java/jadx/core/plugins/files/IJadxFilesGetter.java
package jadx.core.plugins.files; import java.nio.file.Path; public interface IJadxFilesGetter { Path getConfigDir(); Path getCacheDir(); Path getTempDir(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/files/JadxFilesData.java
jadx-core/src/main/java/jadx/core/plugins/files/JadxFilesData.java
package jadx.core.plugins.files; import java.nio.file.Path; import jadx.api.plugins.JadxPluginInfo; import jadx.api.plugins.data.IJadxFiles; import jadx.core.utils.files.FileUtils; public class JadxFilesData implements IJadxFiles { private static final String PLUGINS_DATA_DIR = "plugins-data"; private final JadxPluginInfo pluginInfo; private final IJadxFilesGetter filesGetter; public JadxFilesData(JadxPluginInfo pluginInfo, IJadxFilesGetter filesGetter) { this.pluginInfo = pluginInfo; this.filesGetter = filesGetter; } @Override public Path getPluginCacheDir() { return toPluginPath(filesGetter.getCacheDir()); } @Override public Path getPluginConfigDir() { return toPluginPath(filesGetter.getConfigDir()); } @Override public Path getPluginTempDir() { return toPluginPath(filesGetter.getTempDir()); } private Path toPluginPath(Path dir) { Path dirPath = dir.resolve(PLUGINS_DATA_DIR).resolve(pluginInfo.getPluginId()); FileUtils.makeDirs(dirPath); return dirPath; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/files/TempFilesGetter.java
jadx-core/src/main/java/jadx/core/plugins/files/TempFilesGetter.java
package jadx.core.plugins.files; import java.nio.file.Files; import java.nio.file.Path; import jadx.core.utils.files.FileUtils; public class TempFilesGetter implements IJadxFilesGetter { public static final TempFilesGetter INSTANCE = new TempFilesGetter(); private static final class TempRootHolder { public static final Path TEMP_ROOT_DIR; static { try { TEMP_ROOT_DIR = Files.createTempDirectory("jadx-temp-"); TEMP_ROOT_DIR.toFile().deleteOnExit(); } catch (Exception e) { throw new RuntimeException("Failed to create temp directory", e); } } } private TempFilesGetter() { } @Override public Path getConfigDir() { return makeSubDir("config"); } @Override public Path getCacheDir() { return makeSubDir("cache"); } @Override public Path getTempDir() { return makeSubDir("tmp"); } private Path makeSubDir(String subDir) { Path dir = TempRootHolder.TEMP_ROOT_DIR.resolve(subDir); FileUtils.makeDirs(dir); return dir; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/files/SingleDirFilesGetter.java
jadx-core/src/main/java/jadx/core/plugins/files/SingleDirFilesGetter.java
package jadx.core.plugins.files; import java.nio.file.Path; import jadx.core.utils.files.FileUtils; /** * Use single directory for all jadx files */ public class SingleDirFilesGetter implements IJadxFilesGetter { private final Path baseDir; public SingleDirFilesGetter(Path baseDir) { this.baseDir = baseDir; } @Override public Path getConfigDir() { return makeSubDir("config"); } @Override public Path getCacheDir() { return makeSubDir("cache"); } @Override public Path getTempDir() { return makeSubDir("temp"); } private Path makeSubDir(String subDir) { Path dir = baseDir.resolve(subDir); FileUtils.makeDirs(dir); return dir; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/events/JadxEventsImpl.java
jadx-core/src/main/java/jadx/core/plugins/events/JadxEventsImpl.java
package jadx.core.plugins.events; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.plugins.events.IJadxEvent; import jadx.api.plugins.events.IJadxEvents; import jadx.api.plugins.events.JadxEventType; import jadx.core.Consts; public class JadxEventsImpl implements IJadxEvents { private static final Logger LOG = LoggerFactory.getLogger(JadxEventsImpl.class); private final JadxEventsManager manager = new JadxEventsManager(); @Override public void send(IJadxEvent event) { if (Consts.DEBUG_EVENTS) { LOG.debug("Sending event: {}", event); } manager.send(event); } @Override public <E extends IJadxEvent> void addListener(JadxEventType<E> eventType, Consumer<E> listener) { manager.addListener(eventType, listener); if (Consts.DEBUG_EVENTS) { LOG.debug("add listener for: {}, stats: {}", eventType, manager.listenersDebugStats()); } } @Override public <E extends IJadxEvent> void removeListener(JadxEventType<E> eventType, Consumer<E> listener) { manager.removeListener(eventType, listener); if (Consts.DEBUG_EVENTS) { LOG.debug("remove listener for: {}, stats: {}", eventType, manager.listenersDebugStats()); } } @Override public void reset() { manager.reset(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/events/JadxEventsManager.java
jadx-core/src/main/java/jadx/core/plugins/events/JadxEventsManager.java
package jadx.core.plugins.events; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import jadx.api.plugins.events.IJadxEvent; import jadx.api.plugins.events.JadxEventType; /** * Handle events sending and receiving */ public class JadxEventsManager { private final Map<JadxEventType<?>, List<Consumer<IJadxEvent>>> listeners = new IdentityHashMap<>(); private final ExecutorService eventsThreadPool; public JadxEventsManager() { // TODO: allow to change threading strategy this.eventsThreadPool = Executors.newSingleThreadExecutor(makeThreadFactory()); } @SuppressWarnings("unchecked") public synchronized <E extends IJadxEvent> void addListener(JadxEventType<E> eventType, Consumer<E> listener) { listeners.computeIfAbsent(eventType, et -> new ArrayList<>()) .add((Consumer<IJadxEvent>) listener); } public synchronized <E extends IJadxEvent> boolean removeListener(JadxEventType<E> eventType, Consumer<E> listener) { List<Consumer<IJadxEvent>> eventListeners = listeners.get(eventType); if (eventListeners != null) { return eventListeners.remove(listener); } return false; } public synchronized void send(IJadxEvent event) { List<Consumer<IJadxEvent>> consumers = listeners.get(event.getType()); if (consumers != null) { for (Consumer<IJadxEvent> consumer : consumers) { eventsThreadPool.execute(() -> consumer.accept(event)); } } } public synchronized void reset() { listeners.clear(); } private static ThreadFactory makeThreadFactory() { return new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(0); @Override public Thread newThread(@NotNull Runnable r) { return new Thread(r, "jadx-events-thread-" + threadNumber.incrementAndGet()); } }; } public String listenersDebugStats() { return listeners.entrySet() .stream() .filter(p -> !p.getValue().isEmpty()) .map(p -> p.getKey() + ":" + p.getValue().size()) .collect(Collectors.joining(", ", "[", "]")); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/versions/VersionComparator.java
jadx-core/src/main/java/jadx/core/plugins/versions/VersionComparator.java
package jadx.core.plugins.versions; public class VersionComparator { private VersionComparator() { } public static int checkAndCompare(String str1, String str2) { return compare(clean(str1), clean(str2)); } private static String clean(String str) { if (str == null || str.isEmpty()) { return ""; } String result = str.trim().toLowerCase(); if (result.startsWith("jadx-gui-")) { result = result.substring(9); } if (result.startsWith("jadx-")) { result = result.substring(5); } if (result.charAt(0) == 'v') { result = result.substring(1); } if (result.charAt(0) == 'r') { result = result.substring(1); int dot = result.indexOf('.'); if (dot != -1) { result = result.substring(0, dot); } } // treat a package version as part of version result = result.replace('-', '.'); return result; } private static int compare(String str1, String str2) { String[] s1 = str1.split("\\."); int l1 = s1.length; String[] s2 = str2.split("\\."); int l2 = s2.length; int i = 0; // skip equals parts while (i < l1 && i < l2) { if (!s1[i].equals(s2[i])) { break; } i++; } // compare first non-equal ordinal number if (i < l1 && i < l2) { return Integer.valueOf(s1[i]).compareTo(Integer.valueOf(s2[i])); } boolean checkFirst = l1 > l2; boolean zeroTail = isZeroTail(checkFirst ? s1 : s2, i); if (zeroTail) { return 0; } return checkFirst ? 1 : -1; } private static boolean isZeroTail(String[] arr, int pos) { for (int i = pos; i < arr.length; i++) { if (Integer.parseInt(arr[i]) != 0) { return false; } } return true; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/plugins/versions/VerifyRequiredVersion.java
jadx-core/src/main/java/jadx/core/plugins/versions/VerifyRequiredVersion.java
package jadx.core.plugins.versions; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jetbrains.annotations.Nullable; import jadx.core.Jadx; public class VerifyRequiredVersion { public static boolean isJadxCompatible(@Nullable String reqVersionStr) { return new VerifyRequiredVersion().isCompatible(reqVersionStr); } public static void verify(String requiredJadxVersion) { try { parse(requiredJadxVersion); } catch (Exception e) { throw new IllegalArgumentException("Malformed 'requiredJadxVersion': " + e.getMessage(), e); } } private final String jadxVersion; private final boolean unstable; private final boolean dev; public VerifyRequiredVersion() { this(Jadx.getVersion()); } public VerifyRequiredVersion(String jadxVersion) { this.jadxVersion = jadxVersion; this.unstable = jadxVersion.startsWith("r"); this.dev = jadxVersion.equals(Jadx.VERSION_DEV); } public boolean isCompatible(@Nullable String reqVersionStr) { if (reqVersionStr == null || reqVersionStr.isEmpty()) { return true; } RequiredVersionData reqVer = parse(reqVersionStr); if (dev) { // keep version str parsing for verification return true; } if (unstable) { return VersionComparator.checkAndCompare(jadxVersion, reqVer.getUnstableRev()) >= 0; } return VersionComparator.checkAndCompare(jadxVersion, reqVer.getReleaseVer()) >= 0; } public String getJadxVersion() { return jadxVersion; } private static final Pattern REQ_VER_FORMAT = Pattern.compile("(\\d+\\.\\d+\\.\\d+),\\s+(r\\d+)"); private static RequiredVersionData parse(String reqVersionStr) { Matcher matcher = REQ_VER_FORMAT.matcher(reqVersionStr); if (!matcher.matches()) { throw new RuntimeException("Expect format: " + REQ_VER_FORMAT + ", got: " + reqVersionStr); } return new RequiredVersionData(matcher.group(1), matcher.group(2)); } private static final class RequiredVersionData { private final String releaseVer; private final String unstableRev; private RequiredVersionData(String releaseVer, String unstableRev) { this.releaseVer = releaseVer; this.unstableRev = unstableRev; } public String getReleaseVer() { return releaseVer; } public String getUnstableRev() { return unstableRev; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/NameMapper.java
jadx-core/src/main/java/jadx/core/deobf/NameMapper.java
package jadx.core.deobf; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import jadx.core.utils.StringUtils; import static jadx.core.utils.StringUtils.notEmpty; public class NameMapper { public static final Pattern VALID_JAVA_IDENTIFIER = Pattern.compile( "\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*"); private static final Pattern VALID_JAVA_FULL_IDENTIFIER = Pattern.compile( "(" + VALID_JAVA_IDENTIFIER + "\\.)*" + VALID_JAVA_IDENTIFIER); private static final Set<String> RESERVED_NAMES = new HashSet<>( Arrays.asList( "_", "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while")); public static boolean isReserved(String str) { return RESERVED_NAMES.contains(str); } public static boolean isValidIdentifier(String str) { return notEmpty(str) && !isReserved(str) && VALID_JAVA_IDENTIFIER.matcher(str).matches(); } public static boolean isValidFullIdentifier(String str) { return notEmpty(str) && !isReserved(str) && VALID_JAVA_FULL_IDENTIFIER.matcher(str).matches(); } public static boolean isValidAndPrintable(String str) { return isValidIdentifier(str) && isAllCharsPrintable(str); } public static boolean isValidIdentifierStart(int codePoint) { return Character.isJavaIdentifierStart(codePoint); } public static boolean isValidIdentifierPart(int codePoint) { return Character.isJavaIdentifierPart(codePoint); } public static boolean isPrintableChar(char c) { return 32 <= c && c <= 126; } public static boolean isPrintableAsciiCodePoint(int c) { return 32 <= c && c <= 126; } public static boolean isPrintableCodePoint(int codePoint) { if (Character.isISOControl(codePoint)) { return false; } if (Character.isWhitespace(codePoint)) { // don't print whitespaces other than standard one return codePoint == ' '; } switch (Character.getType(codePoint)) { case Character.CONTROL: case Character.FORMAT: case Character.PRIVATE_USE: case Character.SURROGATE: case Character.UNASSIGNED: return false; } return true; } public static boolean isAllCharsPrintable(String str) { int len = str.length(); int offset = 0; while (offset < len) { int codePoint = str.codePointAt(offset); if (!isPrintableAsciiCodePoint(codePoint)) { return false; } offset += Character.charCount(codePoint); } return true; } /** * Return modified string with removed: * <ul> * <li>not printable chars (including unicode) * <li>chars not valid for java identifier part * </ul> * Note: this 'middle' method must be used with prefixed string: * <ul> * <li>can leave invalid chars for java identifier start (i.e numbers) * <li>result not checked for reserved words * </ul> */ public static String removeInvalidCharsMiddle(String name) { if (isValidIdentifier(name) && isAllCharsPrintable(name)) { return name; } int len = name.length(); StringBuilder sb = new StringBuilder(len); StringUtils.visitCodePoints(name, codePoint -> { if (isPrintableAsciiCodePoint(codePoint) && isValidIdentifierPart(codePoint)) { sb.appendCodePoint(codePoint); } }); return sb.toString(); } /** * Return string with removed invalid chars, see {@link #removeInvalidCharsMiddle} * <p> * Prepend prefix if first char is not valid as java identifier start char. */ public static String removeInvalidChars(String name, String prefix) { String result = removeInvalidCharsMiddle(name); if (!result.isEmpty()) { int codePoint = result.codePointAt(0); if (!isValidIdentifierStart(codePoint)) { return prefix + result; } } return result; } public static String removeNonPrintableCharacters(String name) { StringBuilder sb = new StringBuilder(name.length()); StringUtils.visitCodePoints(name, codePoint -> { if (isPrintableAsciiCodePoint(codePoint)) { sb.appendCodePoint(codePoint); } }); return sb.toString(); } private NameMapper() { } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/DeobfuscatorVisitor.java
jadx-core/src/main/java/jadx/core/deobf/DeobfuscatorVisitor.java
package jadx.core.deobf; import jadx.api.JadxArgs; import jadx.api.deobf.IAliasProvider; import jadx.api.deobf.IRenameCondition; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.PackageNode; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.visitors.AbstractVisitor; import jadx.core.utils.exceptions.JadxException; public class DeobfuscatorVisitor extends AbstractVisitor { @Override public void init(RootNode root) throws JadxException { JadxArgs args = root.getArgs(); if (!args.isDeobfuscationOn()) { return; } DeobfPresets mapping = DeobfPresets.build(root); if (args.getGeneratedRenamesMappingFileMode().shouldRead()) { if (mapping.load()) { mapping.apply(root); } } IAliasProvider aliasProvider = args.getAliasProvider(); IRenameCondition renameCondition = args.getRenameCondition(); mapping.initIndexes(aliasProvider); process(root, renameCondition, aliasProvider); } public static void process(RootNode root, IRenameCondition renameCondition, IAliasProvider aliasProvider) { boolean pkgUpdated = false; for (PackageNode pkg : root.getPackages()) { if (renameCondition.shouldRename(pkg)) { String alias = aliasProvider.forPackage(pkg); if (alias != null) { pkg.rename(alias, false); pkgUpdated = true; } } } if (pkgUpdated) { root.runPackagesUpdate(); } for (ClassNode cls : root.getClasses()) { if (renameCondition.shouldRename(cls)) { String clsAlias = aliasProvider.forClass(cls); if (clsAlias != null) { cls.rename(clsAlias); } } for (FieldNode fld : cls.getFields()) { if (renameCondition.shouldRename(fld)) { String fldAlias = aliasProvider.forField(fld); if (fldAlias != null) { fld.rename(fldAlias); } } } for (MethodNode mth : cls.getMethods()) { if (renameCondition.shouldRename(mth)) { String mthAlias = aliasProvider.forMethod(mth); if (mthAlias != null) { mth.rename(mthAlias); } } } } } @Override public String getName() { return "DeobfuscatorVisitor"; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/DeobfAliasProvider.java
jadx-core/src/main/java/jadx/core/deobf/DeobfAliasProvider.java
package jadx.core.deobf; import jadx.api.deobf.IAliasProvider; import jadx.core.dex.attributes.AType; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.PackageNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.StringUtils; public class DeobfAliasProvider implements IAliasProvider { private int pkgIndex = 0; private int clsIndex = 0; private int fldIndex = 0; private int mthIndex = 0; private int maxLength; @Override public void init(RootNode root) { this.maxLength = root.getArgs().getDeobfuscationMaxLength(); } @Override public void initIndexes(int pkg, int cls, int fld, int mth) { pkgIndex = pkg; clsIndex = cls; fldIndex = fld; mthIndex = mth; } @Override public String forPackage(PackageNode pkg) { return String.format("p%03d%s", pkgIndex++, prepareNamePart(pkg.getPkgInfo().getName())); } @Override public String forClass(ClassNode cls) { String prefix = makeClsPrefix(cls); return String.format("%sC%04d%s", prefix, clsIndex++, prepareNamePart(cls.getName())); } @Override public String forField(FieldNode fld) { return String.format("f%d%s", fldIndex++, prepareNamePart(fld.getName())); } @Override public String forMethod(MethodNode mth) { String prefix = mth.contains(AType.METHOD_OVERRIDE) ? "mo" : "m"; return String.format("%s%d%s", prefix, mthIndex++, prepareNamePart(mth.getName())); } private String prepareNamePart(String name) { if (name.length() > maxLength) { return 'x' + Integer.toHexString(name.hashCode()); } return NameMapper.removeInvalidCharsMiddle(name); } /** * Generate a prefix for a class name that bases on certain class properties, certain * extended superclasses or implemented interfaces. */ private String makeClsPrefix(ClassNode cls) { if (cls.isEnum()) { return "Enum"; } StringBuilder result = new StringBuilder(); if (cls.getAccessFlags().isInterface()) { result.append("Interface"); } else if (cls.getAccessFlags().isAbstract()) { result.append("Abstract"); } result.append(getBaseName(cls)); return result.toString(); } /** * Process current class and all super classes to get meaningful parent name */ private static String getBaseName(ClassNode cls) { ClassNode currentCls = cls; while (currentCls != null) { ArgType superCls = currentCls.getSuperClass(); if (superCls != null) { String superClsName = superCls.getObject(); if (superClsName.startsWith("android.app.") // e.g. Activity or Fragment || superClsName.startsWith("android.os.") // e.g. AsyncTask ) { return getClsName(superClsName); } } for (ArgType interfaceType : cls.getInterfaces()) { String name = interfaceType.getObject(); if (name.equals("java.lang.Runnable")) { return "Runnable"; } if (name.startsWith("java.util.concurrent.") // e.g. Callable || name.startsWith("android.view.") // e.g. View.OnClickListener || name.startsWith("android.content.") // e.g. DialogInterface.OnClickListener ) { return getClsName(name); } } if (superCls == null) { break; } currentCls = cls.root().resolveClass(superCls); } return ""; } private static String getClsName(String name) { int pgkEnd = name.lastIndexOf('.'); String clsName = name.substring(pgkEnd + 1); return StringUtils.removeChar(clsName, '$'); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/DeobfPresets.java
jadx-core/src/main/java/jadx/core/deobf/DeobfPresets.java
package jadx.core.deobf; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxArgs; import jadx.api.args.GeneratedRenamesMappingFileMode; import jadx.api.deobf.IAliasProvider; import jadx.api.deobf.impl.AlwaysRename; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.FieldInfo; 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.PackageNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.files.FileUtils; import static java.nio.charset.StandardCharsets.UTF_8; public class DeobfPresets { private static final Logger LOG = LoggerFactory.getLogger(DeobfPresets.class); private static final Charset MAP_FILE_CHARSET = UTF_8; private final Path deobfMapFile; private final Map<String, String> pkgPresetMap = new HashMap<>(); private final Map<String, String> clsPresetMap = new HashMap<>(); private final Map<String, String> fldPresetMap = new HashMap<>(); private final Map<String, String> mthPresetMap = new HashMap<>(); public static DeobfPresets build(RootNode root) { Path deobfMapPath = getPathDeobfMapPath(root); if (root.getArgs().getGeneratedRenamesMappingFileMode() != GeneratedRenamesMappingFileMode.IGNORE) { LOG.debug("Deobfuscation map file set to: {}", deobfMapPath); } return new DeobfPresets(deobfMapPath); } private static Path getPathDeobfMapPath(RootNode root) { JadxArgs jadxArgs = root.getArgs(); File deobfMapFile = jadxArgs.getGeneratedRenamesMappingFile(); if (deobfMapFile != null) { return deobfMapFile.toPath(); } Path inputFilePath = jadxArgs.getInputFiles().get(0).toPath().toAbsolutePath(); String baseName = FileUtils.getPathBaseName(inputFilePath); return inputFilePath.getParent().resolve(baseName + ".jobf"); } private DeobfPresets(Path deobfMapFile) { this.deobfMapFile = deobfMapFile; } /** * Loads deobfuscator presets */ public boolean load() { if (!Files.exists(deobfMapFile)) { return false; } LOG.info("Loading obfuscation map from: {}", deobfMapFile.toAbsolutePath()); try { List<String> lines = Files.readAllLines(deobfMapFile, MAP_FILE_CHARSET); for (String l : lines) { l = l.trim(); if (l.isEmpty() || l.startsWith("#")) { continue; } String[] va = splitAndTrim(l); if (va.length != 2) { continue; } String origName = va[0]; String alias = va[1]; switch (l.charAt(0)) { case 'p': pkgPresetMap.put(origName, alias); break; case 'c': clsPresetMap.put(origName, alias); break; case 'f': fldPresetMap.put(origName, alias); break; case 'm': mthPresetMap.put(origName, alias); break; case 'v': // deprecated break; } } return true; } catch (Exception e) { LOG.error("Failed to load deobfuscation map file '{}'", deobfMapFile.toAbsolutePath(), e); return false; } } private static String[] splitAndTrim(String str) { String[] v = str.substring(2).split("="); for (int i = 0; i < v.length; i++) { v[i] = v[i].trim(); } return v; } public void save() throws IOException { List<String> list = new ArrayList<>(); for (Map.Entry<String, String> pkgEntry : pkgPresetMap.entrySet()) { list.add(String.format("p %s = %s", pkgEntry.getKey(), pkgEntry.getValue())); } for (Map.Entry<String, String> clsEntry : clsPresetMap.entrySet()) { list.add(String.format("c %s = %s", clsEntry.getKey(), clsEntry.getValue())); } for (Map.Entry<String, String> fldEntry : fldPresetMap.entrySet()) { list.add(String.format("f %s = %s", fldEntry.getKey(), fldEntry.getValue())); } for (Map.Entry<String, String> mthEntry : mthPresetMap.entrySet()) { list.add(String.format("m %s = %s", mthEntry.getKey(), mthEntry.getValue())); } Collections.sort(list); if (list.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Deobfuscation map is empty, not saving it"); } return; } Files.write(deobfMapFile, list, MAP_FILE_CHARSET, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); LOG.info("Deobfuscation map file saved as: {}", deobfMapFile); } public void fill(RootNode root) { for (PackageNode pkg : root.getPackages()) { if (pkg.isLeaf()) { // ignore middle packages if (pkg.hasParentAlias()) { pkgPresetMap.put(pkg.getPkgInfo().getFullName(), pkg.getAliasPkgInfo().getFullName()); } else if (pkg.hasAlias()) { pkgPresetMap.put(pkg.getPkgInfo().getFullName(), pkg.getAliasPkgInfo().getName()); } } } for (ClassNode cls : root.getClasses()) { ClassInfo classInfo = cls.getClassInfo(); if (classInfo.hasAlias()) { clsPresetMap.put(classInfo.makeRawFullName(), classInfo.getAliasShortName()); } for (FieldNode fld : cls.getFields()) { FieldInfo fieldInfo = fld.getFieldInfo(); if (fieldInfo.hasAlias()) { fldPresetMap.put(fieldInfo.getRawFullId(), fld.getAlias()); } } for (MethodNode mth : cls.getMethods()) { MethodInfo methodInfo = mth.getMethodInfo(); if (methodInfo.hasAlias()) { mthPresetMap.put(methodInfo.getRawFullId(), methodInfo.getAlias()); } } } } public void apply(RootNode root) { DeobfuscatorVisitor.process(root, AlwaysRename.INSTANCE, new IAliasProvider() { @Override public String forPackage(PackageNode pkg) { return pkgPresetMap.get(pkg.getPkgInfo().getFullName()); } @Override public String forClass(ClassNode cls) { return getForCls(cls.getClassInfo()); } @Override public String forField(FieldNode fld) { return getForFld(fld.getFieldInfo()); } @Override public String forMethod(MethodNode mth) { return getForMth(mth.getMethodInfo()); } }); } public void initIndexes(IAliasProvider aliasProvider) { aliasProvider.initIndexes(pkgPresetMap.size(), clsPresetMap.size(), fldPresetMap.size(), mthPresetMap.size()); } public String getForCls(ClassInfo cls) { if (clsPresetMap.isEmpty()) { return null; } return clsPresetMap.get(cls.makeRawFullName()); } public String getForFld(FieldInfo fld) { if (fldPresetMap.isEmpty()) { return null; } return fldPresetMap.get(fld.getRawFullId()); } public String getForMth(MethodInfo mth) { if (mthPresetMap.isEmpty()) { return null; } return mthPresetMap.get(mth.getRawFullId()); } public void clear() { pkgPresetMap.clear(); clsPresetMap.clear(); fldPresetMap.clear(); mthPresetMap.clear(); } public Path getDeobfMapFile() { return deobfMapFile; } public Map<String, String> getPkgPresetMap() { return pkgPresetMap; } public Map<String, String> getClsPresetMap() { return clsPresetMap; } public Map<String, String> getFldPresetMap() { return fldPresetMap; } public Map<String, String> getMthPresetMap() { return mthPresetMap; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/SaveDeobfMapping.java
jadx-core/src/main/java/jadx/core/deobf/SaveDeobfMapping.java
package jadx.core.deobf; import java.nio.file.Files; import java.nio.file.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxArgs; import jadx.api.args.GeneratedRenamesMappingFileMode; import jadx.core.codegen.json.JsonMappingGen; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.visitors.AbstractVisitor; import jadx.core.utils.exceptions.JadxException; public class SaveDeobfMapping extends AbstractVisitor { private static final Logger LOG = LoggerFactory.getLogger(SaveDeobfMapping.class); @Override public void init(RootNode root) throws JadxException { JadxArgs args = root.getArgs(); if (args.isDeobfuscationOn() || !args.isJsonOutput()) { saveMappings(root); } if (args.isJsonOutput()) { JsonMappingGen.dump(root); } } private void saveMappings(RootNode root) { GeneratedRenamesMappingFileMode mode = root.getArgs().getGeneratedRenamesMappingFileMode(); if (!mode.shouldWrite()) { return; } DeobfPresets mapping = DeobfPresets.build(root); Path deobfMapFile = mapping.getDeobfMapFile(); if (mode == GeneratedRenamesMappingFileMode.READ_OR_SAVE && Files.exists(deobfMapFile)) { return; } try { mapping.clear(); mapping.fill(root); mapping.save(); } catch (Exception e) { LOG.error("Failed to save deobfuscation map file '{}'", deobfMapFile.toAbsolutePath(), e); } } @Override public String getName() { return "SaveDeobfMapping"; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/FileTypeDetector.java
jadx-core/src/main/java/jadx/core/deobf/FileTypeDetector.java
package jadx.core.deobf; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import jadx.core.utils.FileSignature; import jadx.core.utils.StringUtils; public class FileTypeDetector { private static final Pattern DOCTYPE_PATTERN = Pattern.compile("\\s*<!doctype *(\\w+)[ >]", Pattern.CASE_INSENSITIVE); private static final List<FileSignature> FILE_SIGNATURES = new ArrayList<>(); static { register("png", "89 50 4E 47"); register("jpg", "FF D8 FF"); register("gif", "47 49 46 38"); register("webp", "52 49 46 46 ?? ?? ?? ?? 57 45 42 50 56 50 38"); register("bmp", "42 4D"); register("bmp", "42 41"); register("bmp", "43 49"); register("bmp", "43 50"); register("bmp", "49 43"); register("bmp", "50 54"); register("mp4", "00 00 00 ?? 66 74 79 70 69 73 6F 36"); register("mp4", "00 00 00 ?? 66 74 79 70 6D 70 34 32"); register("m4a", "00 00 00 ?? 66 74 79 70 4D 34 41 20"); register("mp3", "49 44 33"); register("ogg", "4F 67 67 53"); register("wav", "52 49 46 46 ?? ?? ?? ?? 57 41 56 45"); register("ttf", "00 01 00 00"); register("ttc", "74 74 63 66"); register("otf", "4F 54 54 4F"); register("xml", "03 00 08 00"); } public static void register(String fileType, String signature) { FILE_SIGNATURES.add(new FileSignature(fileType, signature)); } private static String detectByHeaders(byte[] data) { for (FileSignature sig : FILE_SIGNATURES) { if (FileSignature.matches(sig, data)) { if (sig.getFileType().equals("png") && isNinePatch(data)) { return ".9.png"; } return "." + sig.getFileType(); } } return null; } public static String detectFileExtension(byte[] data) { // detect ext by headers String extByHeaders = detectByHeaders(data); if (!StringUtils.isEmpty(extByHeaders)) { return extByHeaders; } // detect ext by readable text String text = new String(data, StandardCharsets.UTF_8); if (text.startsWith("-----BEGIN CERTIFICATE-----")) { return ".cer"; } if (text.startsWith("-----BEGIN PRIVATE KEY-----")) { return ".key"; } if (text.contains("<html>")) { return ".html"; } Matcher m = DOCTYPE_PATTERN.matcher(text); if (m.lookingAt()) { return "." + m.group(1).toLowerCase(); } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new java.io.ByteArrayInputStream(data)); String rootTag = doc.getDocumentElement().getNodeName(); if ("svg".equalsIgnoreCase(rootTag)) { return ".svg"; } if ("plist".equalsIgnoreCase(rootTag)) { return ".plist"; } if ("kml".equalsIgnoreCase(rootTag)) { return ".kml"; } return ".xml"; } catch (Exception ignored) { } return null; } private static int readInt(byte[] data, int offset) { return (data[offset] & 0xFF) << 24 | (data[offset + 1] & 0xFF) << 16 | (data[offset + 2] & 0xFF) << 8 | (data[offset + 3] & 0xFF); } private static boolean isNinePatch(byte[] data) { int offset = 8; while (offset + 8 < data.length) { int chunkLength = readInt(data, offset); int chunkType = readInt(data, offset + 4); if (chunkType == 0x6e705463) { // 'npTc' return true; } offset += 8 + chunkLength + 4; // chunk + data + CRC } return false; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/conditions/ExcludePackageWithTLDNames.java
jadx-core/src/main/java/jadx/core/deobf/conditions/ExcludePackageWithTLDNames.java
package jadx.core.deobf.conditions; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Set; import java.util.stream.Collectors; import jadx.core.dex.nodes.PackageNode; import jadx.core.utils.exceptions.JadxRuntimeException; /** * Provides a list of all top level domains, so we can exclude them from deobfuscation. */ public class ExcludePackageWithTLDNames extends AbstractDeobfCondition { /** * Lazy load TLD set */ private static class TldHolder { private static final Set<String> TLD_SET = loadTldSet(); } private static Set<String> loadTldSet() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(TldHolder.class.getResourceAsStream("tlds.txt")))) { return reader.lines() .filter(line -> !line.startsWith("#") && !line.isEmpty()) .collect(Collectors.toSet()); } catch (Exception e) { throw new JadxRuntimeException("Failed to load top level domain list file: tlds.txt", e); } } @Override public Action check(PackageNode pkg) { if (pkg.isRoot() && TldHolder.TLD_SET.contains(pkg.getName())) { return Action.FORBID_RENAME; } return Action.NO_ACTION; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/conditions/DeobfWhitelist.java
jadx-core/src/main/java/jadx/core/deobf/conditions/DeobfWhitelist.java
package jadx.core.deobf.conditions; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.PackageNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.Utils; public class DeobfWhitelist extends AbstractDeobfCondition { public static final List<String> DEFAULT_LIST = Arrays.asList( "android.support.v4.*", "android.support.v7.*", "android.support.v4.os.*", "android.support.annotation.Px", "androidx.core.os.*", "androidx.annotation.Px"); public static final String DEFAULT_STR = Utils.listToString(DEFAULT_LIST, " "); private final Set<String> packages = new HashSet<>(); private final Set<String> classes = new HashSet<>(); @Override public void init(RootNode root) { packages.clear(); classes.clear(); for (String whitelistItem : root.getArgs().getDeobfuscationWhitelist()) { if (!whitelistItem.isEmpty()) { if (whitelistItem.endsWith(".*")) { packages.add(whitelistItem.substring(0, whitelistItem.length() - 2)); } else { classes.add(whitelistItem); } } } } @Override public Action check(PackageNode pkg) { if (packages.contains(pkg.getPkgInfo().getFullName())) { return Action.FORBID_RENAME; } return Action.NO_ACTION; } @Override public Action check(ClassNode cls) { if (classes.contains(cls.getClassInfo().getFullName())) { return Action.FORBID_RENAME; } return Action.NO_ACTION; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/conditions/AbstractDeobfCondition.java
jadx-core/src/main/java/jadx/core/deobf/conditions/AbstractDeobfCondition.java
package jadx.core.deobf.conditions; import jadx.api.deobf.IDeobfCondition; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.PackageNode; import jadx.core.dex.nodes.RootNode; public abstract class AbstractDeobfCondition implements IDeobfCondition { @Override public void init(RootNode root) { } @Override public Action check(PackageNode pkg) { return Action.NO_ACTION; } @Override public Action check(ClassNode cls) { return Action.NO_ACTION; } @Override public Action check(FieldNode fld) { return Action.NO_ACTION; } @Override public Action check(MethodNode mth) { return Action.NO_ACTION; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/conditions/JadxRenameConditions.java
jadx-core/src/main/java/jadx/core/deobf/conditions/JadxRenameConditions.java
package jadx.core.deobf.conditions; import java.util.ArrayList; import java.util.List; import jadx.api.deobf.IDeobfCondition; import jadx.api.deobf.IRenameCondition; import jadx.api.deobf.impl.CombineDeobfConditions; public class JadxRenameConditions { /** * This method provides a mutable list of default deobfuscation conditions used by jadx. * To build {@link IRenameCondition} use {@link CombineDeobfConditions#combine(List)} method. */ public static List<IDeobfCondition> buildDefaultDeobfConditions() { List<IDeobfCondition> list = new ArrayList<>(); list.add(new BaseDeobfCondition()); list.add(new DeobfWhitelist()); list.add(new ExcludePackageWithTLDNames()); list.add(new ExcludeAndroidRClass()); list.add(new AvoidClsAndPkgNamesCollision()); list.add(new DeobfLengthCondition()); return list; } public static IRenameCondition buildDefault() { return CombineDeobfConditions.combine(buildDefaultDeobfConditions()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/conditions/BaseDeobfCondition.java
jadx-core/src/main/java/jadx/core/deobf/conditions/BaseDeobfCondition.java
package jadx.core.deobf.conditions; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.PackageNode; /** * Disable deobfuscation for nodes: * - with 'DONT_RENAME' flag * - already renamed */ public class BaseDeobfCondition extends AbstractDeobfCondition { @Override public Action check(PackageNode pkg) { if (pkg.contains(AFlag.DONT_RENAME) || pkg.hasAlias()) { return Action.FORBID_RENAME; } return Action.NO_ACTION; } @Override public Action check(ClassNode cls) { if (cls.contains(AFlag.DONT_RENAME) || cls.getClassInfo().hasAlias()) { return Action.FORBID_RENAME; } return Action.NO_ACTION; } @Override public Action check(MethodNode mth) { if (mth.contains(AFlag.DONT_RENAME) || mth.getMethodInfo().hasAlias() || mth.isConstructor()) { return Action.FORBID_RENAME; } return Action.NO_ACTION; } @Override public Action check(FieldNode fld) { if (fld.contains(AFlag.DONT_RENAME) || fld.getFieldInfo().hasAlias()) { return Action.FORBID_RENAME; } return Action.NO_ACTION; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/conditions/DeobfLengthCondition.java
jadx-core/src/main/java/jadx/core/deobf/conditions/DeobfLengthCondition.java
package jadx.core.deobf.conditions; import jadx.api.JadxArgs; import jadx.api.deobf.IDeobfCondition; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.PackageNode; import jadx.core.dex.nodes.RootNode; public class DeobfLengthCondition implements IDeobfCondition { private int minLength; private int maxLength; @Override public void init(RootNode root) { JadxArgs args = root.getArgs(); this.minLength = args.getDeobfuscationMinLength(); this.maxLength = args.getDeobfuscationMaxLength(); } private Action checkName(String s) { int len = s.length(); if (len < minLength || len > maxLength) { return Action.FORCE_RENAME; } return Action.NO_ACTION; } @Override public Action check(PackageNode pkg) { return checkName(pkg.getName()); } @Override public Action check(ClassNode cls) { return checkName(cls.getName()); } @Override public Action check(FieldNode fld) { return checkName(fld.getName()); } @Override public Action check(MethodNode mth) { return checkName(mth.getName()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/conditions/AvoidClsAndPkgNamesCollision.java
jadx-core/src/main/java/jadx/core/deobf/conditions/AvoidClsAndPkgNamesCollision.java
package jadx.core.deobf.conditions; import java.util.HashSet; import java.util.Set; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.PackageNode; import jadx.core.dex.nodes.RootNode; public class AvoidClsAndPkgNamesCollision extends AbstractDeobfCondition { private final Set<String> avoidClsNames = new HashSet<>(); @Override public void init(RootNode root) { avoidClsNames.clear(); for (PackageNode pkg : root.getPackages()) { avoidClsNames.add(pkg.getName()); } } @Override public Action check(ClassNode cls) { if (avoidClsNames.contains(cls.getAlias())) { return Action.FORCE_RENAME; } return Action.NO_ACTION; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/deobf/conditions/ExcludeAndroidRClass.java
jadx-core/src/main/java/jadx/core/deobf/conditions/ExcludeAndroidRClass.java
package jadx.core.deobf.conditions; import jadx.core.dex.attributes.AFlag; 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; public class ExcludeAndroidRClass extends AbstractDeobfCondition { @Override public Action check(ClassNode cls) { if (isR(cls.getTopParentClass())) { return Action.FORBID_RENAME; } return Action.NO_ACTION; } private static boolean isR(ClassNode cls) { if (cls.contains(AFlag.ANDROID_R_CLASS)) { return true; } if (!cls.getClassInfo().getShortName().equals("R")) { return false; } if (!cls.getMethods().isEmpty() || !cls.getFields().isEmpty()) { return false; } for (ClassNode inner : cls.getInnerClasses()) { for (MethodNode m : inner.getMethods()) { if (!m.getMethodInfo().isConstructor() && !m.getMethodInfo().isClassInit()) { return false; } } for (FieldNode field : cls.getFields()) { ArgType type = field.getType(); if (type != ArgType.INT && (!type.isArray() || type.getArrayElement() != ArgType.INT)) { return false; } } } cls.add(AFlag.ANDROID_R_CLASS); 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/clsp/ClspGraph.java
jadx-core/src/main/java/jadx/core/clsp/ClspGraph.java
package jadx.core.clsp; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.Consts; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.IMethodDetails; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.exceptions.DecodeException; import jadx.core.utils.exceptions.JadxRuntimeException; /** * Classes hierarchy graph with methods additional info */ public class ClspGraph { private static final Logger LOG = LoggerFactory.getLogger(ClspGraph.class); private final RootNode root; private Map<String, ClspClass> nameMap; private Map<String, Set<String>> superTypesCache; private Map<String, List<String>> implementsCache; private final Set<String> missingClasses = new HashSet<>(); public ClspGraph(RootNode rootNode) { this.root = rootNode; } public void loadClsSetFile() throws IOException, DecodeException { ClsSet set = new ClsSet(root); set.loadFromClstFile(); addClasspath(set); } public void addClasspath(ClsSet set) { if (nameMap == null) { nameMap = new HashMap<>(set.getClassesCount()); set.addToMap(nameMap); } else { throw new JadxRuntimeException("Classpath already loaded"); } } public void addApp(List<ClassNode> classes) { if (nameMap == null) { nameMap = new HashMap<>(classes.size()); } for (ClassNode cls : classes) { addClass(cls); } } public void initCache() { fillSuperTypesCache(); fillImplementsCache(); } public boolean isClsKnown(String fullName) { return nameMap.containsKey(fullName); } public ClspClass getClsDetails(ArgType type) { return nameMap.get(type.getObject()); } @Nullable public IMethodDetails getMethodDetails(MethodInfo methodInfo) { ClspClass cls = nameMap.get(methodInfo.getDeclClass().getRawName()); if (cls == null) { return null; } ClspMethod clspMethod = getMethodFromClass(cls, methodInfo); if (clspMethod != null) { return clspMethod; } // deep search for (ArgType parent : cls.getParents()) { ClspClass clspParent = getClspClass(parent); if (clspParent != null) { ClspMethod methodFromParent = getMethodFromClass(clspParent, methodInfo); if (methodFromParent != null) { return methodFromParent; } } } // unknown method return new SimpleMethodDetails(methodInfo); } private ClspMethod getMethodFromClass(ClspClass cls, MethodInfo methodInfo) { return cls.getMethodsMap().get(methodInfo.getShortId()); } private void addClass(ClassNode cls) { ArgType clsType = cls.getClassInfo().getType(); String rawName = clsType.getObject(); ClspClass clspClass = new ClspClass(clsType, -1, cls.getAccessFlags().rawValue(), ClspClassSource.APP); clspClass.setParents(ClsSet.makeParentsArray(cls)); nameMap.put(rawName, clspClass); } /** * @return {@code clsName} instanceof {@code implClsName} */ public boolean isImplements(String clsName, String implClsName) { Set<String> anc = getSuperTypes(clsName); return anc.contains(implClsName); } public List<String> getImplementations(String clsName) { List<String> list = implementsCache.get(clsName); return list == null ? Collections.emptyList() : list; } private void fillImplementsCache() { Map<String, List<String>> map = new HashMap<>(nameMap.size()); List<String> classes = new ArrayList<>(nameMap.keySet()); Collections.sort(classes); for (String cls : classes) { for (String st : getSuperTypes(cls)) { map.computeIfAbsent(st, v -> new ArrayList<>()).add(cls); } } implementsCache = map; } public String getCommonAncestor(String clsName, String implClsName) { if (clsName.equals(implClsName)) { return clsName; } ClspClass cls = nameMap.get(implClsName); if (cls == null) { missingClasses.add(clsName); return null; } if (isImplements(clsName, implClsName)) { return implClsName; } Set<String> anc = getSuperTypes(clsName); return searchCommonParent(anc, cls); } private String searchCommonParent(Set<String> anc, ClspClass cls) { for (ArgType p : cls.getParents()) { String name = p.getObject(); if (anc.contains(name)) { return name; } ClspClass nCls = getClspClass(p); if (nCls != null) { String r = searchCommonParent(anc, nCls); if (r != null) { return r; } } } return null; } public Set<String> getSuperTypes(String clsName) { Set<String> result = superTypesCache.get(clsName); return result == null ? Collections.emptySet() : result; } private static final Set<String> OBJECT_SINGLE_SET = Collections.singleton(Consts.CLASS_OBJECT); private void fillSuperTypesCache() { Map<String, Set<String>> map = new HashMap<>(nameMap.size()); Set<String> tmpSet = new HashSet<>(); for (Map.Entry<String, ClspClass> entry : nameMap.entrySet()) { ClspClass cls = entry.getValue(); tmpSet.clear(); addSuperTypes(cls, tmpSet); Set<String> result; int size = tmpSet.size(); switch (size) { case 0: { result = Collections.emptySet(); break; } case 1: { String supCls = tmpSet.iterator().next(); if (supCls.equals(Consts.CLASS_OBJECT)) { result = OBJECT_SINGLE_SET; } else { result = Collections.singleton(supCls); } break; } default: { result = new HashSet<>(tmpSet); break; } } map.put(cls.getName(), result); } superTypesCache = map; } private void addSuperTypes(ClspClass cls, Set<String> result) { for (ArgType parentType : cls.getParents()) { if (parentType == null) { continue; } ClspClass parentCls = getClspClass(parentType); if (parentCls != null) { boolean isNew = result.add(parentCls.getName()); if (isNew) { addSuperTypes(parentCls, result); } } else { // parent type is unknown result.add(parentType.getObject()); } } } @Nullable private ClspClass getClspClass(ArgType clsType) { ClspClass clspClass = nameMap.get(clsType.getObject()); if (clspClass == null) { missingClasses.add(clsType.getObject()); } return clspClass; } public void printMissingClasses() { int count = missingClasses.size(); if (count == 0) { return; } LOG.warn("Found {} references to unknown classes", count); if (LOG.isDebugEnabled()) { List<String> clsNames = new ArrayList<>(missingClasses); Collections.sort(clsNames); for (String cls : clsNames) { LOG.debug(" {}", cls); } } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/clsp/ClsSet.java
jadx-core/src/main/java/jadx/core/clsp/ClsSet.java
package jadx.core.clsp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Stream; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.exceptions.DecodeException; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; /** * Classes list for import into classpath graph */ public class ClsSet { private static final Logger LOG = LoggerFactory.getLogger(ClsSet.class); private static final String CLST_EXTENSION = ".jcst"; private static final String CLST_FILENAME = "core" + CLST_EXTENSION; private static final String CLST_PATH = "/clst/" + CLST_FILENAME; private static final String JADX_CLS_SET_HEADER = "jadx-cst"; private static final int VERSION = 5; private static final String STRING_CHARSET = "US-ASCII"; private static final ArgType[] EMPTY_ARGTYPE_ARRAY = new ArgType[0]; private static final ArgType[] OBJECT_ARGTYPE_ARRAY = new ArgType[] { ArgType.OBJECT }; private final RootNode root; private int androidApiLevel; public ClsSet(RootNode root) { this.root = root; } private enum TypeEnum { WILDCARD, GENERIC, GENERIC_TYPE_VARIABLE, OUTER_GENERIC, OBJECT, ARRAY, PRIMITIVE } private ClspClass[] classes; public void loadFromClstFile() throws IOException, DecodeException { long startTime = System.currentTimeMillis(); try (InputStream input = ClsSet.class.getResourceAsStream(CLST_PATH)) { if (input == null) { throw new JadxRuntimeException("Can't load classpath file: " + CLST_PATH); } load(input); } if (LOG.isDebugEnabled()) { long time = System.currentTimeMillis() - startTime; int methodsCount = Stream.of(classes).mapToInt(clspClass -> clspClass.getMethodsMap().size()).sum(); LOG.debug("Clst file loaded in {}ms, android api: {}, classes: {}, methods: {}", time, androidApiLevel, classes.length, methodsCount); } } public void loadFrom(RootNode root) { List<ClassNode> list = root.getClasses(true); Map<String, ClspClass> names = new HashMap<>(list.size()); int k = 0; for (ClassNode cls : list) { ArgType clsType = cls.getClassInfo().getType(); String clsRawName = clsType.getObject(); cls.load(); ClspClassSource source = getClspClassSource(cls); ClspClass nClass = new ClspClass(clsType, k, cls.getAccessFlags().rawValue(), source); if (names.put(clsRawName, nClass) != null) { throw new JadxRuntimeException("Duplicate class: " + clsRawName); } k++; nClass.setTypeParameters(cls.getGenericTypeParameters()); nClass.setMethods(getMethodsDetails(cls)); } classes = new ClspClass[k]; k = 0; for (ClassNode cls : list) { ClspClass nClass = getCls(cls, names); if (nClass == null) { throw new JadxRuntimeException("Missing class: " + cls); } nClass.setParents(makeParentsArray(cls)); classes[k] = nClass; k++; } } private static ClspClassSource getClspClassSource(ClassNode cls) { String inputFileName = cls.getClsData().getInputFileName(); int idx = inputFileName.indexOf(':'); String sourceFile = inputFileName.substring(0, idx); ClspClassSource source = ClspClassSource.getClspClassSource(sourceFile); if (source == ClspClassSource.APP) { throw new JadxRuntimeException("Unexpected input file: " + inputFileName); } return source; } private List<ClspMethod> getMethodsDetails(ClassNode cls) { List<MethodNode> methodsList = cls.getMethods(); List<ClspMethod> methods = new ArrayList<>(methodsList.size()); for (MethodNode mth : methodsList) { processMethodDetails(mth, methods); } return methods; } private void processMethodDetails(MethodNode mth, List<ClspMethod> methods) { AccessInfo accessFlags = mth.getAccessFlags(); if (accessFlags.isPrivate() || accessFlags.isSynthetic() || accessFlags.isBridge()) { return; } ClspMethod clspMethod = new ClspMethod(mth.getMethodInfo(), mth.getArgTypes(), mth.getReturnType(), mth.getTypeParameters(), mth.getThrows(), accessFlags.rawValue()); methods.add(clspMethod); } public static ArgType[] makeParentsArray(ClassNode cls) { ArgType superClass = cls.getSuperClass(); if (superClass == null) { // cls is java.lang.Object return EMPTY_ARGTYPE_ARRAY; } int interfacesCount = cls.getInterfaces().size(); if (interfacesCount == 0 && superClass == ArgType.OBJECT) { return OBJECT_ARGTYPE_ARRAY; } ArgType[] parents = new ArgType[1 + interfacesCount]; parents[0] = superClass; int k = 1; for (ArgType iface : cls.getInterfaces()) { parents[k] = iface; k++; } return parents; } private static ClspClass getCls(ClassNode cls, Map<String, ClspClass> names) { return getCls(cls.getRawName(), names); } private static ClspClass getCls(ArgType clsType, Map<String, ClspClass> names) { return getCls(clsType.getObject(), names); } private static ClspClass getCls(String fullName, Map<String, ClspClass> names) { ClspClass cls = names.get(fullName); if (cls == null) { LOG.debug("Class not found: {}", fullName); } return cls; } public void save(Path path) throws IOException { FileUtils.makeDirsForFile(path); String outputName = path.getFileName().toString(); if (outputName.endsWith(CLST_EXTENSION)) { try (BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(path))) { save(outputStream); } } else { throw new JadxRuntimeException("Unknown file format: " + outputName); } } private void save(OutputStream output) throws IOException { DataOutputStream out = new DataOutputStream(output); out.writeBytes(JADX_CLS_SET_HEADER); out.writeByte(VERSION); out.writeInt(androidApiLevel); Map<String, ClspClass> names = new HashMap<>(classes.length); out.writeInt(classes.length); for (ClspClass cls : classes) { out.writeInt(cls.getAccFlags()); writeUnsignedByte(out, cls.getSource().ordinal()); String clsName = cls.getName(); writeString(out, clsName); names.put(clsName, cls); } for (ClspClass cls : classes) { writeArgTypesArray(out, cls.getParents(), names); writeArgTypesList(out, cls.getTypeParameters(), names); List<ClspMethod> methods = cls.getSortedMethodsList(); out.writeShort(methods.size()); for (ClspMethod method : methods) { writeMethod(out, method, names); } } int methodsCount = Stream.of(classes).mapToInt(c -> c.getMethodsMap().size()).sum(); LOG.info("Classes: {}, methods: {}, file size: {} bytes", classes.length, methodsCount, out.size()); } private static void writeMethod(DataOutputStream out, ClspMethod method, Map<String, ClspClass> names) throws IOException { MethodInfo methodInfo = method.getMethodInfo(); writeString(out, methodInfo.getName()); writeArgTypesList(out, methodInfo.getArgumentsTypes(), names); writeArgType(out, methodInfo.getReturnType(), names); writeArgTypesList(out, method.containsGenericArgs() ? method.getArgTypes() : Collections.emptyList(), names); writeArgType(out, method.getReturnType(), names); writeArgTypesList(out, method.getTypeParameters(), names); out.writeInt(method.getRawAccessFlags()); writeArgTypesList(out, method.getThrows(), names); } private static void writeArgTypesList(DataOutputStream out, List<ArgType> list, Map<String, ClspClass> names) throws IOException { int size = list.size(); writeUnsignedByte(out, size); if (size != 0) { for (ArgType type : list) { writeArgType(out, type, names); } } } private static void writeArgTypesArray(DataOutputStream out, @Nullable ArgType[] arr, Map<String, ClspClass> names) throws IOException { if (arr == null) { out.writeByte(-1); return; } if (arr == OBJECT_ARGTYPE_ARRAY) { out.writeByte(-2); return; } int size = arr.length; out.writeByte(size); if (size != 0) { for (ArgType type : arr) { writeArgType(out, type, names); } } } private static void writeArgType(DataOutputStream out, ArgType argType, Map<String, ClspClass> names) throws IOException { if (argType == null) { out.writeByte(-1); return; } if (argType.isPrimitive()) { out.writeByte(TypeEnum.PRIMITIVE.ordinal()); out.writeByte(argType.getPrimitiveType().getShortName().charAt(0)); } else if (argType.getOuterType() != null) { out.writeByte(TypeEnum.OUTER_GENERIC.ordinal()); writeArgType(out, argType.getOuterType(), names); writeArgType(out, argType.getInnerType(), names); } else if (argType.getWildcardType() != null) { out.writeByte(TypeEnum.WILDCARD.ordinal()); ArgType.WildcardBound bound = argType.getWildcardBound(); out.writeByte(bound.getNum()); if (bound != ArgType.WildcardBound.UNBOUND) { writeArgType(out, argType.getWildcardType(), names); } } else if (argType.isGeneric()) { out.writeByte(TypeEnum.GENERIC.ordinal()); out.writeInt(getCls(argType, names).getId()); writeArgTypesList(out, argType.getGenericTypes(), names); } else if (argType.isGenericType()) { out.writeByte(TypeEnum.GENERIC_TYPE_VARIABLE.ordinal()); writeString(out, argType.getObject()); writeArgTypesList(out, argType.getExtendTypes(), names); } else if (argType.isObject()) { out.writeByte(TypeEnum.OBJECT.ordinal()); out.writeInt(getCls(argType, names).getId()); } else if (argType.isArray()) { out.writeByte(TypeEnum.ARRAY.ordinal()); writeArgType(out, argType.getArrayElement(), names); } else { throw new JadxRuntimeException("Cannot save type: " + argType); } } private void load(InputStream input) throws IOException, DecodeException { try (DataInputStream in = new DataInputStream(new BufferedInputStream(input))) { byte[] header = new byte[JADX_CLS_SET_HEADER.length()]; int readHeaderLength = in.read(header); if (readHeaderLength != JADX_CLS_SET_HEADER.length() || !JADX_CLS_SET_HEADER.equals(new String(header, STRING_CHARSET))) { throw new DecodeException("Wrong jadx class set header"); } int version = in.readByte(); if (version != VERSION) { throw new DecodeException("Wrong jadx class set version, got: " + version + ", expect: " + VERSION); } androidApiLevel = in.readInt(); int clsCount = in.readInt(); classes = new ClspClass[clsCount]; for (int i = 0; i < clsCount; i++) { int accFlags = in.readInt(); ClspClassSource clsSource = readClsSource(in); String name = readString(in); classes[i] = new ClspClass(ArgType.object(name), i, accFlags, clsSource); } for (int i = 0; i < clsCount; i++) { ClspClass nClass = classes[i]; ClassInfo clsInfo = ClassInfo.fromType(root, nClass.getClsType()); nClass.setParents(readArgTypesArray(in)); nClass.setTypeParameters(readArgTypesList(in)); nClass.setMethods(readClsMethods(in, clsInfo)); } } } private static ClspClassSource readClsSource(DataInputStream in) throws IOException, DecodeException { int source = readUnsignedByte(in); ClspClassSource[] clspClassSources = ClspClassSource.values(); if (source < 0 || source > clspClassSources.length) { throw new DecodeException("Wrong jadx source identifier: " + source); } return clspClassSources[source]; } private List<ClspMethod> readClsMethods(DataInputStream in, ClassInfo clsInfo) throws IOException { int mCount = in.readShort(); List<ClspMethod> methods = new ArrayList<>(mCount); for (int j = 0; j < mCount; j++) { methods.add(readMethod(in, clsInfo)); } return methods; } private ClspMethod readMethod(DataInputStream in, ClassInfo clsInfo) throws IOException { String name = readString(in); List<ArgType> argTypes = readArgTypesList(in); ArgType retType = readArgType(in); List<ArgType> genericArgTypes = readArgTypesList(in); if (genericArgTypes.isEmpty() || Objects.equals(genericArgTypes, argTypes)) { genericArgTypes = argTypes; } ArgType genericRetType = readArgType(in); if (Objects.equals(genericRetType, retType)) { genericRetType = retType; } List<ArgType> typeParameters = readArgTypesList(in); int accFlags = in.readInt(); List<ArgType> throwList = readArgTypesList(in); MethodInfo methodInfo = MethodInfo.fromDetails(root, clsInfo, name, argTypes, retType); return new ClspMethod(methodInfo, genericArgTypes, genericRetType, typeParameters, throwList, accFlags); } private List<ArgType> readArgTypesList(DataInputStream in) throws IOException { int count = in.readByte(); if (count == 0) { return Collections.emptyList(); } List<ArgType> list = new ArrayList<>(count); for (int i = 0; i < count; i++) { list.add(readArgType(in)); } return list; } @Nullable private ArgType[] readArgTypesArray(DataInputStream in) throws IOException { int count = in.readByte(); switch (count) { case -1: return null; case -2: return OBJECT_ARGTYPE_ARRAY; case 0: return EMPTY_ARGTYPE_ARRAY; default: ArgType[] arr = new ArgType[count]; for (int i = 0; i < count; i++) { arr[i] = readArgType(in); } return arr; } } private ArgType readArgType(DataInputStream in) throws IOException { int ordinal = in.readByte(); if (ordinal == -1) { return null; } switch (TypeEnum.values()[ordinal]) { case WILDCARD: ArgType.WildcardBound bound = ArgType.WildcardBound.getByNum(in.readByte()); if (bound == ArgType.WildcardBound.UNBOUND) { return ArgType.WILDCARD; } ArgType objType = readArgType(in); return ArgType.wildcard(objType, bound); case OUTER_GENERIC: ArgType outerType = readArgType(in); ArgType innerType = readArgType(in); return ArgType.outerGeneric(outerType, innerType); case GENERIC: ArgType clsType = classes[in.readInt()].getClsType(); return ArgType.generic(clsType, readArgTypesList(in)); case GENERIC_TYPE_VARIABLE: String typeVar = readString(in); List<ArgType> extendTypes = readArgTypesList(in); return ArgType.genericType(typeVar, extendTypes); case OBJECT: return classes[in.readInt()].getClsType(); case ARRAY: return ArgType.array(Objects.requireNonNull(readArgType(in))); case PRIMITIVE: char shortName = (char) in.readByte(); return ArgType.parse(shortName); default: throw new JadxRuntimeException("Unsupported Arg Type: " + ordinal); } } private static void writeString(DataOutputStream out, String name) throws IOException { byte[] bytes = name.getBytes(STRING_CHARSET); int len = bytes.length; if (len >= 0xFF) { throw new JadxRuntimeException("String is too long: " + name); } writeUnsignedByte(out, bytes.length); out.write(bytes); } private static String readString(DataInputStream in) throws IOException { int len = readUnsignedByte(in); return readString(in, len); } private static String readString(DataInputStream in, int len) throws IOException { byte[] bytes = new byte[len]; int count = in.read(bytes); while (count != len) { int res = in.read(bytes, count, len - count); if (res == -1) { throw new IOException("String read error"); } else { count += res; } } return new String(bytes, STRING_CHARSET); } private static void writeUnsignedByte(DataOutputStream out, int value) throws IOException { if (value < 0 || value >= 0xFF) { throw new JadxRuntimeException("Unsigned byte value is too big: " + value); } out.writeByte(value); } private static int readUnsignedByte(DataInputStream in) throws IOException { return ((int) in.readByte()) & 0xFF; } public int getClassesCount() { return classes.length; } public void addToMap(Map<String, ClspClass> nameMap) { for (ClspClass cls : classes) { nameMap.put(cls.getName(), cls); } } public int getAndroidApiLevel() { return androidApiLevel; } public void setAndroidApiLevel(int androidApiLevel) { this.androidApiLevel = androidApiLevel; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/clsp/ClspMethod.java
jadx-core/src/main/java/jadx/core/clsp/ClspMethod.java
package jadx.core.clsp; import java.util.List; import java.util.Objects; import org.jetbrains.annotations.NotNull; import jadx.api.plugins.input.data.AccessFlags; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.IMethodDetails; import jadx.core.utils.Utils; /** * Method node in classpath graph. */ public class ClspMethod implements IMethodDetails, Comparable<ClspMethod> { private final MethodInfo methodInfo; private final List<ArgType> argTypes; private final ArgType returnType; private final List<ArgType> typeParameters; private final List<ArgType> throwList; private final int accFlags; public ClspMethod(MethodInfo methodInfo, List<ArgType> argTypes, ArgType returnType, List<ArgType> typeParameters, List<ArgType> throwList, int accFlags) { this.methodInfo = methodInfo; this.argTypes = argTypes; this.returnType = returnType; this.typeParameters = typeParameters; this.throwList = throwList; this.accFlags = accFlags; } @Override public MethodInfo getMethodInfo() { return methodInfo; } @Override public ArgType getReturnType() { return returnType; } @Override public List<ArgType> getArgTypes() { return argTypes; } public boolean containsGenericArgs() { return !Objects.equals(argTypes, methodInfo.getArgumentsTypes()); } public int getArgsCount() { return argTypes.size(); } @Override public List<ArgType> getTypeParameters() { return typeParameters; } @Override public List<ArgType> getThrows() { return throwList; } @Override public boolean isVarArg() { return (accFlags & AccessFlags.VARARGS) != 0; } @Override public int getRawAccessFlags() { return accFlags; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ClspMethod)) { return false; } ClspMethod other = (ClspMethod) o; return methodInfo.equals(other.methodInfo); } @Override public int hashCode() { return methodInfo.hashCode(); } @Override public int compareTo(@NotNull ClspMethod other) { return this.methodInfo.compareTo(other.methodInfo); } @Override public String toAttrString() { return IMethodDetails.super.toAttrString() + " (c)"; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ClspMth{"); if (Utils.notEmpty(getTypeParameters())) { sb.append('<'); sb.append(Utils.listToString(getTypeParameters())); sb.append("> "); } sb.append(getMethodInfo().getFullName()); sb.append('('); sb.append(Utils.listToString(getArgTypes())); sb.append("):"); sb.append(getReturnType()); if (isVarArg()) { sb.append(" VARARG"); } List<ArgType> throwsList = getThrows(); if (Utils.notEmpty(throwsList)) { sb.append(" throws ").append(Utils.listToString(throwsList)); } sb.append('}'); 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/clsp/ClspClass.java
jadx-core/src/main/java/jadx/core/clsp/ClspClass.java
package jadx.core.clsp; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.intellij.lang.annotations.MagicConstant; import jadx.api.plugins.input.data.AccessFlags; import jadx.core.dex.instructions.args.ArgType; /** * Class node in classpath graph */ public class ClspClass { private final ArgType clsType; private final int id; private final int accFlags; private ArgType[] parents; private Map<String, ClspMethod> methodsMap = Collections.emptyMap(); private List<ArgType> typeParameters = Collections.emptyList(); private final ClspClassSource source; public ClspClass(ArgType clsType, int id, int accFlags, ClspClassSource source) { this.clsType = clsType; this.id = id; this.accFlags = accFlags; this.source = source; } public String getName() { return clsType.getObject(); } public ArgType getClsType() { return clsType; } public int getId() { return id; } public int getAccFlags() { return accFlags; } public boolean isInterface() { return AccessFlags.hasFlag(accFlags, AccessFlags.INTERFACE); } public boolean hasAccFlag(@MagicConstant(flagsFromClass = AccessFlags.class) int flags) { return AccessFlags.hasFlag(accFlags, flags); } public ArgType[] getParents() { return parents; } public void setParents(ArgType[] parents) { this.parents = parents; } public Map<String, ClspMethod> getMethodsMap() { return methodsMap; } public List<ClspMethod> getSortedMethodsList() { List<ClspMethod> list = new ArrayList<>(methodsMap.size()); list.addAll(methodsMap.values()); Collections.sort(list); return list; } public void setMethodsMap(Map<String, ClspMethod> methodsMap) { this.methodsMap = Objects.requireNonNull(methodsMap); } public void setMethods(List<ClspMethod> methods) { Map<String, ClspMethod> map = new HashMap<>(methods.size()); for (ClspMethod mth : methods) { map.put(mth.getMethodInfo().getShortId(), mth); } setMethodsMap(map); } public List<ArgType> getTypeParameters() { return typeParameters; } public void setTypeParameters(List<ArgType> typeParameters) { this.typeParameters = typeParameters; } public ClspClassSource getSource() { return this.source; } @Override public int hashCode() { return clsType.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClspClass nClass = (ClspClass) o; return clsType.equals(nClass.clsType); } @Override public String toString() { return clsType.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/clsp/ClspClassSource.java
jadx-core/src/main/java/jadx/core/clsp/ClspClassSource.java
package jadx.core.clsp; public enum ClspClassSource { APP(""), CORE("android.jar"), ANDROID_CAR("android.car.jar"), APACHE_HTTP_LEGACY_CLIENT("org.apache.http.legacy.jar"); private final String jarFile; ClspClassSource(String jarFile) { this.jarFile = jarFile; } public String getJarFile() { return jarFile; } public static ClspClassSource getClspClassSource(String jarFile) { for (ClspClassSource classSource : ClspClassSource.values()) { if (classSource.getJarFile().equals(jarFile)) { return classSource; } } return APP; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/clsp/SimpleMethodDetails.java
jadx-core/src/main/java/jadx/core/clsp/SimpleMethodDetails.java
package jadx.core.clsp; import java.util.Collections; import java.util.List; import jadx.api.plugins.input.data.AccessFlags; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.IMethodDetails; /** * Method details build from MethodInfo. * Note: some fields have unknown values. */ public class SimpleMethodDetails implements IMethodDetails { private final MethodInfo methodInfo; public SimpleMethodDetails(MethodInfo methodInfo) { this.methodInfo = methodInfo; } @Override public MethodInfo getMethodInfo() { return methodInfo; } @Override public ArgType getReturnType() { return methodInfo.getReturnType(); } @Override public List<ArgType> getArgTypes() { return methodInfo.getArgumentsTypes(); } @Override public List<ArgType> getTypeParameters() { return Collections.emptyList(); } @Override public List<ArgType> getThrows() { return Collections.emptyList(); } @Override public boolean isVarArg() { return false; } @Override public int getRawAccessFlags() { return AccessFlags.PUBLIC; } @Override public String toAttrString() { return IMethodDetails.super.toAttrString() + " (s)"; } @Override public String toString() { return "SimpleMethodDetails{" + methodInfo + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/export/ExportGradleType.java
jadx-core/src/main/java/jadx/core/export/ExportGradleType.java
package jadx.core.export; public enum ExportGradleType { AUTO("Auto"), ANDROID_APP("Android App"), ANDROID_LIBRARY("Android Library"), SIMPLE_JAVA("Simple Java"); private final String desc; ExportGradleType(String desc) { this.desc = desc; } public String getDesc() { return desc; } @Override public String toString() { return desc; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/export/OutDirs.java
jadx-core/src/main/java/jadx/core/export/OutDirs.java
package jadx.core.export; import java.io.File; import jadx.core.utils.files.FileUtils; public class OutDirs { private final File srcOutDir; private final File resOutDir; public OutDirs(File srcOutDir, File resOutDir) { this.srcOutDir = srcOutDir; this.resOutDir = resOutDir; } public File getSrcOutDir() { return srcOutDir; } public File getResOutDir() { return resOutDir; } public void makeDirs() { FileUtils.makeDirs(srcOutDir); FileUtils.makeDirs(resOutDir); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/export/GradleInfoStorage.java
jadx-core/src/main/java/jadx/core/export/GradleInfoStorage.java
package jadx.core.export; public class GradleInfoStorage { private boolean vectorPathData; private boolean vectorFillType; private boolean useApacheHttpLegacy; private boolean nonFinalResIds; public boolean isVectorPathData() { return vectorPathData; } public void setVectorPathData(boolean vectorPathData) { this.vectorPathData = vectorPathData; } public boolean isVectorFillType() { return vectorFillType; } public void setVectorFillType(boolean vectorFillType) { this.vectorFillType = vectorFillType; } public boolean isUseApacheHttpLegacy() { return useApacheHttpLegacy; } public void setUseApacheHttpLegacy(boolean useApacheHttpLegacy) { this.useApacheHttpLegacy = useApacheHttpLegacy; } public boolean isNonFinalResIds() { return nonFinalResIds; } public void setNonFinalResIds(boolean nonFinalResIds) { this.nonFinalResIds = nonFinalResIds; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/export/TemplateFile.java
jadx-core/src/main/java/jadx/core/export/TemplateFile.java
package jadx.core.export; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.Nullable; import jadx.core.utils.exceptions.JadxRuntimeException; /** * Simple template engine * Syntax for replace variable with value: '{{variable}}' */ public class TemplateFile { private enum State { NONE, START, VARIABLE, END } private static class ParserState { private State state = State.NONE; private StringBuilder curVariable; private boolean skip; } private final String templateName; private final InputStream template; private final Map<String, String> values = new HashMap<>(); public static TemplateFile fromResources(String path) throws FileNotFoundException { InputStream res = TemplateFile.class.getResourceAsStream(path); if (res == null) { throw new FileNotFoundException("Resource not found: " + path); } return new TemplateFile(path, res); } private TemplateFile(String name, InputStream in) { this.templateName = name; this.template = in; } public void add(String name, @Nullable Object value) { values.put(name, String.valueOf(value)); } public String build() throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { process(out); return out.toString(); } } public void save(File outFile) throws IOException { try (OutputStream out = new FileOutputStream(outFile)) { process(out); } } private void process(OutputStream out) throws IOException { if (template.available() == 0) { throw new IOException("Template already processed"); } try (InputStream in = new BufferedInputStream(template)) { ParserState state = new ParserState(); while (true) { int ch = in.read(); if (ch == -1) { break; } String str = process(state, (char) ch); if (str != null) { out.write(str.getBytes()); } else if (!state.skip) { out.write(ch); } } } } @Nullable private String process(ParserState parser, char ch) { State state = parser.state; switch (ch) { case '{': switch (state) { case START: parser.state = State.VARIABLE; parser.curVariable = new StringBuilder(); break; default: parser.state = State.START; break; } parser.skip = true; return null; case '}': switch (state) { case VARIABLE: parser.state = State.END; parser.skip = true; return null; case END: parser.state = State.NONE; String varName = parser.curVariable.toString(); parser.curVariable = new StringBuilder(); return processVar(varName); } break; default: switch (state) { case VARIABLE: parser.curVariable.append(ch); parser.skip = true; return null; case START: parser.state = State.NONE; return "{" + ch; case END: throw new JadxRuntimeException("Expected variable end: '" + parser.curVariable + "' (missing second '}')"); } break; } parser.skip = false; return null; } private String processVar(String varName) { String str = values.get(varName); if (str == null) { throw new JadxRuntimeException("Unknown variable: '" + varName + "' in template: " + templateName); } return str; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/export/ExportGradle.java
jadx-core/src/main/java/jadx/core/export/ExportGradle.java
package jadx.core.export; import java.io.File; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ResourceFile; import jadx.api.ResourceType; import jadx.core.dex.nodes.RootNode; import jadx.core.export.gen.AndroidGradleGenerator; import jadx.core.export.gen.IExportGradleGenerator; import jadx.core.export.gen.SimpleJavaGradleGenerator; import jadx.core.utils.android.AndroidManifestParser; import jadx.core.utils.exceptions.JadxRuntimeException; public class ExportGradle { private static final Logger LOG = LoggerFactory.getLogger(ExportGradle.class); private final RootNode root; private final File projectDir; private final List<ResourceFile> resources; private IExportGradleGenerator generator; public ExportGradle(RootNode root, File projectDir, List<ResourceFile> resources) { this.root = root; this.projectDir = projectDir; this.resources = resources; } public OutDirs init() { ExportGradleType exportType = getExportGradleType(); LOG.info("Export Gradle project using '{}' template", exportType); switch (exportType) { case ANDROID_APP: case ANDROID_LIBRARY: generator = new AndroidGradleGenerator(root, projectDir, resources, exportType); break; case SIMPLE_JAVA: generator = new SimpleJavaGradleGenerator(root, projectDir, resources); break; default: throw new JadxRuntimeException("Unexpected export type: " + exportType); } generator.init(); OutDirs outDirs = generator.getOutDirs(); outDirs.makeDirs(); return outDirs; } private ExportGradleType getExportGradleType() { ExportGradleType argsExportType = root.getArgs().getExportGradleType(); ExportGradleType detectedType = detectExportType(root, resources); if (argsExportType == null || argsExportType == ExportGradleType.AUTO || argsExportType == detectedType) { return detectedType; } return argsExportType; } public static ExportGradleType detectExportType(RootNode root, List<ResourceFile> resources) { ResourceFile androidManifest = AndroidManifestParser.getAndroidManifest(resources); if (androidManifest != null) { if (resources.stream().anyMatch(r -> r.getOriginalName().equals("classes.jar"))) { return ExportGradleType.ANDROID_LIBRARY; } if (resources.stream().anyMatch(r -> r.getType() == ResourceType.ARSC)) { return ExportGradleType.ANDROID_APP; } } return ExportGradleType.SIMPLE_JAVA; } public void generateGradleFiles() { generator.generateFiles(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/export/gen/SimpleJavaGradleGenerator.java
jadx-core/src/main/java/jadx/core/export/gen/SimpleJavaGradleGenerator.java
package jadx.core.export.gen; import java.io.File; import java.io.IOException; import java.util.List; import jadx.api.ResourceFile; import jadx.core.dex.nodes.RootNode; import jadx.core.export.OutDirs; import jadx.core.export.TemplateFile; import jadx.core.utils.exceptions.JadxRuntimeException; public class SimpleJavaGradleGenerator implements IExportGradleGenerator { private final RootNode root; private final File projectDir; private final List<ResourceFile> resources; private OutDirs outDirs; private File appDir; public SimpleJavaGradleGenerator(RootNode root, File projectDir, List<ResourceFile> resources) { this.root = root; this.projectDir = projectDir; this.resources = resources; } @Override public void init() { appDir = new File(projectDir, "app"); File srcOutDir = new File(appDir, "src/main/java"); File resOutDir = new File(appDir, "src/main/resources"); outDirs = new OutDirs(srcOutDir, resOutDir); } @Override public void generateFiles() { try { saveSettingsGradle(); saveBuildGradle(); } catch (Exception e) { throw new JadxRuntimeException("Failed to generate gradle files", e); } } private void saveSettingsGradle() throws IOException { TemplateFile tmpl = TemplateFile.fromResources("/export/java/settings.gradle.kts.tmpl"); tmpl.add("projectName", GradleGeneratorTools.guessProjectName(root)); tmpl.save(new File(projectDir, "settings.gradle.kts")); } private void saveBuildGradle() throws IOException { TemplateFile tmpl = TemplateFile.fromResources("/export/java/build.gradle.kts.tmpl"); tmpl.save(new File(appDir, "build.gradle.kts")); } @Override public OutDirs getOutDirs() { return outDirs; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/export/gen/IExportGradleGenerator.java
jadx-core/src/main/java/jadx/core/export/gen/IExportGradleGenerator.java
package jadx.core.export.gen; import jadx.core.export.OutDirs; public interface IExportGradleGenerator { void init(); OutDirs getOutDirs(); void generateFiles(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/export/gen/AndroidGradleGenerator.java
jadx-core/src/main/java/jadx/core/export/gen/AndroidGradleGenerator.java
package jadx.core.export.gen; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ResourceFile; import jadx.api.ResourceType; import jadx.api.security.IJadxSecurity; import jadx.core.dex.nodes.RootNode; import jadx.core.export.ExportGradleType; import jadx.core.export.GradleInfoStorage; import jadx.core.export.OutDirs; import jadx.core.export.TemplateFile; import jadx.core.utils.Utils; import jadx.core.utils.android.AndroidManifestParser; import jadx.core.utils.android.AppAttribute; import jadx.core.utils.android.ApplicationParams; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.xmlgen.ResContainer; public class AndroidGradleGenerator implements IExportGradleGenerator { private static final Logger LOG = LoggerFactory.getLogger(AndroidGradleGenerator.class); private static final Pattern ILLEGAL_GRADLE_CHARS = Pattern.compile("[/\\\\:>\"?*|]"); private static final ApplicationParams UNKNOWN_APP_PARAMS = new ApplicationParams("UNKNOWN", 0, 0, 0, 0, "UNKNOWN", "UNKNOWN", "UNKNOWN"); private final RootNode root; private final File projectDir; private final List<ResourceFile> resources; private final boolean exportApp; private OutDirs outDirs; private File baseDir; private ApplicationParams applicationParams; public AndroidGradleGenerator(RootNode root, File projectDir, List<ResourceFile> resources, ExportGradleType exportType) { this.root = root; this.projectDir = projectDir; this.resources = resources; this.exportApp = exportType == ExportGradleType.ANDROID_APP; } @Override public void init() { String moduleDir = exportApp ? "app" : "lib"; baseDir = new File(projectDir, moduleDir); outDirs = new OutDirs(new File(baseDir, "src/main/java"), new File(baseDir, "src/main")); applicationParams = parseApplicationParams(); } @Override public void generateFiles() { try { saveProjectBuildGradle(); if (exportApp) { saveApplicationBuildGradle(); } else { saveLibraryBuildGradle(); } saveSettingsGradle(); saveGradleProperties(); } catch (Exception e) { throw new JadxRuntimeException("Gradle export failed", e); } } @Override public OutDirs getOutDirs() { return outDirs; } private ApplicationParams parseApplicationParams() { try { ResourceFile androidManifest = AndroidManifestParser.getAndroidManifest(resources); if (androidManifest == null) { LOG.warn("AndroidManifest.xml not found, exported files will contains 'UNKNOWN' fields"); return UNKNOWN_APP_PARAMS; } ResContainer strings = null; if (exportApp) { ResourceFile arscFile = resources.stream() .filter(resourceFile -> resourceFile.getType() == ResourceType.ARSC) .findFirst().orElse(null); if (arscFile != null) { List<ResContainer> resContainers = arscFile.loadContent().getSubFiles(); strings = resContainers .stream() .filter(resContainer -> resContainer.getName().contains("values/strings.xml")) .findFirst() .orElseGet(() -> resContainers.stream() .filter(resContainer -> resContainer.getName().contains("strings.xml")) .findFirst().orElse(null)); } } EnumSet<AppAttribute> attrs = EnumSet.noneOf(AppAttribute.class); attrs.add(AppAttribute.MIN_SDK_VERSION); if (exportApp) { attrs.add(AppAttribute.APPLICATION_LABEL); attrs.add(AppAttribute.TARGET_SDK_VERSION); attrs.add(AppAttribute.COMPILE_SDK_VERSION); attrs.add(AppAttribute.VERSION_NAME); attrs.add(AppAttribute.VERSION_CODE); } IJadxSecurity security = root.getArgs().getSecurity(); AndroidManifestParser parser = new AndroidManifestParser(androidManifest, strings, attrs, security); return parser.parse(); } catch (Exception t) { LOG.warn("Failed to parse AndroidManifest.xml", t); return UNKNOWN_APP_PARAMS; } } private void saveGradleProperties() throws IOException { GradleInfoStorage gradleInfo = root.getGradleInfoStorage(); /* * For Android Gradle Plugin >=8.0.0 the property "android.nonFinalResIds=false" has to be set in * "gradle.properties" when resource identifiers are used as constant expressions. */ if (gradleInfo.isNonFinalResIds()) { File gradlePropertiesFile = new File(projectDir, "gradle.properties"); try (FileOutputStream fos = new FileOutputStream(gradlePropertiesFile)) { fos.write("android.nonFinalResIds=false".getBytes(StandardCharsets.UTF_8)); } } } private void saveProjectBuildGradle() throws IOException { TemplateFile tmpl = TemplateFile.fromResources("/export/android/build.gradle.tmpl"); tmpl.save(new File(projectDir, "build.gradle")); } private void saveSettingsGradle() throws IOException { TemplateFile tmpl = TemplateFile.fromResources("/export/android/settings.gradle.tmpl"); String appName = applicationParams.getApplicationName(); String projectName; if (appName != null) { projectName = ILLEGAL_GRADLE_CHARS.matcher(appName).replaceAll(""); } else { projectName = GradleGeneratorTools.guessProjectName(root); } tmpl.add("projectName", projectName); tmpl.add("mainModuleName", baseDir.getName()); tmpl.save(new File(projectDir, "settings.gradle")); } private void saveApplicationBuildGradle() throws IOException { String appPackage = Utils.getOrElse(root.getAppPackage(), "UNKNOWN"); int minSdkVersion = Utils.getOrElse(applicationParams.getMinSdkVersion(), 0); TemplateFile tmpl = TemplateFile.fromResources("/export/android/app.build.gradle.tmpl"); tmpl.add("applicationId", appPackage); tmpl.add("minSdkVersion", minSdkVersion); tmpl.add("compileSdkVersion", applicationParams.getCompileSdkVersion()); tmpl.add("targetSdkVersion", applicationParams.getTargetSdkVersion()); tmpl.add("versionCode", applicationParams.getVersionCode()); tmpl.add("versionName", applicationParams.getVersionName()); tmpl.add("additionalOptions", genAdditionalAndroidPluginOptions(minSdkVersion)); tmpl.save(new File(baseDir, "build.gradle")); } private void saveLibraryBuildGradle() throws IOException { String pkg = Utils.getOrElse(root.getAppPackage(), "UNKNOWN"); int minSdkVersion = Utils.getOrElse(applicationParams.getMinSdkVersion(), 0); TemplateFile tmpl = TemplateFile.fromResources("/export/android/lib.build.gradle.tmpl"); tmpl.add("packageId", pkg); tmpl.add("minSdkVersion", minSdkVersion); tmpl.add("compileSdkVersion", applicationParams.getCompileSdkVersion()); tmpl.add("additionalOptions", genAdditionalAndroidPluginOptions(minSdkVersion)); tmpl.save(new File(baseDir, "build.gradle")); } private String genAdditionalAndroidPluginOptions(int minSdkVersion) { List<String> additionalOptions = new ArrayList<>(); GradleInfoStorage gradleInfo = root.getGradleInfoStorage(); if (gradleInfo.isVectorPathData() && minSdkVersion < 21 || gradleInfo.isVectorFillType() && minSdkVersion < 24) { additionalOptions.add("vectorDrawables.useSupportLibrary = true"); } if (gradleInfo.isUseApacheHttpLegacy()) { additionalOptions.add("useLibrary 'org.apache.http.legacy'"); } StringBuilder sb = new StringBuilder(); for (String additionalOption : additionalOptions) { sb.append(" ").append(additionalOption).append('\n'); } 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/export/gen/GradleGeneratorTools.java
jadx-core/src/main/java/jadx/core/export/gen/GradleGeneratorTools.java
package jadx.core.export.gen; import java.io.File; import java.util.List; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.files.FileUtils; public class GradleGeneratorTools { public static String guessProjectName(RootNode root) { List<File> inputFiles = root.getArgs().getInputFiles(); if (inputFiles.size() == 1) { return FileUtils.getPathBaseName(inputFiles.get(0).toPath()); } // default return "PROJECT_NAME"; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/trycatch/ExceptionHandler.java
jadx-core/src/main/java/jadx/core/dex/trycatch/ExceptionHandler.java
package jadx.core.dex.trycatch; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import org.jetbrains.annotations.Nullable; import jadx.core.Consts; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.IContainer; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.InsnUtils; import jadx.core.utils.Utils; public class ExceptionHandler { private final List<ClassInfo> catchTypes = new ArrayList<>(1); private final int handlerOffset; private BlockNode handlerBlock; private final List<BlockNode> blocks = new ArrayList<>(); private IContainer handlerRegion; private InsnArg arg; private TryCatchBlockAttr tryBlock; private boolean isFinally; private boolean removed = false; public static ExceptionHandler build(MethodNode mth, int addr, @Nullable ClassInfo type) { ExceptionHandler eh = new ExceptionHandler(addr); eh.addCatchType(mth, type); return eh; } private ExceptionHandler(int addr) { this.handlerOffset = addr; } /** * Add exception type to catch block * * @param type - null for 'all' or 'Throwable' handler */ public boolean addCatchType(MethodNode mth, @Nullable ClassInfo type) { if (type != null) { if (catchTypes.contains(type)) { return false; } return catchTypes.add(type); } if (!this.catchTypes.isEmpty()) { mth.addDebugComment("Throwable added to exception handler: '" + catchTypeStr() + "', keep only Throwable"); catchTypes.clear(); return true; } return false; } public void addCatchTypes(MethodNode mth, Collection<ClassInfo> types) { for (ClassInfo type : types) { addCatchType(mth, type); } } public List<ClassInfo> getCatchTypes() { return catchTypes; } public ArgType getArgType() { if (isCatchAll()) { return ArgType.THROWABLE; } List<ClassInfo> types = getCatchTypes(); if (types.size() == 1) { return types.iterator().next().getType(); } else { return ArgType.THROWABLE; } } public boolean isCatchAll() { if (catchTypes.isEmpty()) { return true; } for (ClassInfo classInfo : catchTypes) { if (classInfo.getFullName().equals(Consts.CLASS_THROWABLE)) { return true; } } return false; } public int getHandlerOffset() { return handlerOffset; } public BlockNode getHandlerBlock() { return handlerBlock; } public void setHandlerBlock(BlockNode handlerBlock) { this.handlerBlock = handlerBlock; } public List<BlockNode> getBlocks() { return blocks; } public void addBlock(BlockNode node) { blocks.add(node); } public IContainer getHandlerRegion() { return handlerRegion; } public void setHandlerRegion(IContainer handlerRegion) { this.handlerRegion = handlerRegion; } public InsnArg getArg() { return arg; } public void setArg(InsnArg arg) { this.arg = arg; } public void setTryBlock(TryCatchBlockAttr tryBlock) { this.tryBlock = tryBlock; } public TryCatchBlockAttr getTryBlock() { return tryBlock; } public boolean isFinally() { return isFinally; } public void setFinally(boolean isFinally) { this.isFinally = isFinally; } public boolean isRemoved() { return removed; } public void markForRemove() { this.removed = true; this.blocks.forEach(b -> b.add(AFlag.REMOVE)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExceptionHandler that = (ExceptionHandler) o; return handlerOffset == that.handlerOffset && catchTypes.equals(that.catchTypes) && Objects.equals(tryBlock, that.tryBlock); } @Override public int hashCode() { return Objects.hash(catchTypes, handlerOffset /* , tryBlock */); } public String catchTypeStr() { return catchTypes.isEmpty() ? "all" : Utils.listToString(catchTypes, " | ", ClassInfo::getShortName); } @Override public String toString() { return catchTypeStr() + " -> " + InsnUtils.formatOffset(handlerOffset); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/trycatch/CatchAttr.java
jadx-core/src/main/java/jadx/core/dex/trycatch/CatchAttr.java
package jadx.core.dex.trycatch; import java.util.Comparator; import java.util.List; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.utils.Utils; public class CatchAttr implements IJadxAttribute { public static CatchAttr build(List<ExceptionHandler> handlers) { handlers.sort(Comparator.comparingInt(ExceptionHandler::getHandlerOffset)); return new CatchAttr(handlers); } private final List<ExceptionHandler> handlers; private CatchAttr(List<ExceptionHandler> handlers) { this.handlers = handlers; } public List<ExceptionHandler> getHandlers() { return handlers; } @Override public AType<CatchAttr> getAttrType() { return AType.EXC_CATCH; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CatchAttr)) { return false; } CatchAttr catchAttr = (CatchAttr) o; return getHandlers().equals(catchAttr.getHandlers()); } @Override public int hashCode() { return getHandlers().hashCode(); } @Override public String toString() { return "Catch: " + Utils.listToString(getHandlers()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/trycatch/TryCatchBlockAttr.java
jadx-core/src/main/java/jadx/core/dex/trycatch/TryCatchBlockAttr.java
package jadx.core.dex.trycatch; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jadx.api.plugins.input.data.attributes.IJadxAttrType; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.Utils; public class TryCatchBlockAttr implements IJadxAttribute { private final int id; private final List<ExceptionHandler> handlers; private List<BlockNode> blocks; private TryCatchBlockAttr outerTryBlock; private List<TryCatchBlockAttr> innerTryBlocks = Collections.emptyList(); private boolean merged = false; private BlockNode topSplitter; public TryCatchBlockAttr(int id, List<ExceptionHandler> handlers, List<BlockNode> blocks) { this.id = id; this.handlers = handlers; this.blocks = blocks; handlers.forEach(h -> h.setTryBlock(this)); } public boolean isAllHandler() { return handlers.size() == 1 && handlers.get(0).isCatchAll(); } public boolean isThrowOnly() { boolean throwFound = false; for (BlockNode block : blocks) { List<InsnNode> insns = block.getInstructions(); if (insns.size() != 1) { return false; } InsnNode insn = insns.get(0); switch (insn.getType()) { case MOVE_EXCEPTION: case MONITOR_EXIT: // allowed instructions break; case THROW: throwFound = true; break; default: return false; } } return throwFound; } public int getId() { return id; } public List<ExceptionHandler> getHandlers() { return handlers; } public int getHandlersCount() { return handlers.size(); } public List<BlockNode> getBlocks() { return blocks; } public void setBlocks(List<BlockNode> blocks) { this.blocks = blocks; } public void clear() { blocks.clear(); handlers.forEach(ExceptionHandler::markForRemove); handlers.clear(); } public void removeBlock(BlockNode block) { blocks.remove(block); } public void removeHandler(ExceptionHandler handler) { handlers.remove(handler); handler.markForRemove(); } public List<TryCatchBlockAttr> getInnerTryBlocks() { return innerTryBlocks; } public void addInnerTryBlock(TryCatchBlockAttr inner) { if (this.innerTryBlocks.isEmpty()) { this.innerTryBlocks = new ArrayList<>(); } this.innerTryBlocks.add(inner); } public TryCatchBlockAttr getOuterTryBlock() { return outerTryBlock; } public void setOuterTryBlock(TryCatchBlockAttr outerTryBlock) { this.outerTryBlock = outerTryBlock; } public BlockNode getTopSplitter() { return topSplitter; } public void setTopSplitter(BlockNode topSplitter) { this.topSplitter = topSplitter; } public boolean isMerged() { return merged; } public void setMerged(boolean merged) { this.merged = merged; } public int id() { return id; } @Override public IJadxAttrType<? extends IJadxAttribute> getAttrType() { return AType.TRY_BLOCK; } @Override public int hashCode() { return handlers.hashCode() + 31 * blocks.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } TryCatchBlockAttr other = (TryCatchBlockAttr) obj; return id == other.id && handlers.equals(other.handlers) && blocks.equals(other.blocks); } @Override public String toString() { if (merged) { return "Merged into " + outerTryBlock; } StringBuilder sb = new StringBuilder(); sb.append("TryCatch #").append(id).append(" {").append(Utils.listToString(handlers)); sb.append(", blocks: (").append(Utils.listToString(blocks)).append(')'); if (topSplitter != null) { sb.append(", top: ").append(topSplitter); } if (outerTryBlock != null) { sb.append(", outer: #").append(outerTryBlock.id); } if (!innerTryBlocks.isEmpty()) { sb.append(", inners: ").append(Utils.listToString(innerTryBlocks, inner -> "#" + inner.id)); } sb.append(" }"); return sb.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/trycatch/ExcHandlerAttr.java
jadx-core/src/main/java/jadx/core/dex/trycatch/ExcHandlerAttr.java
package jadx.core.dex.trycatch; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; public class ExcHandlerAttr implements IJadxAttribute { private final ExceptionHandler handler; public ExcHandlerAttr(ExceptionHandler handler) { this.handler = handler; } @Override public AType<ExcHandlerAttr> getAttrType() { return AType.EXC_HANDLER; } public TryCatchBlockAttr getTryBlock() { return handler.getTryBlock(); } public ExceptionHandler getHandler() { return handler; } @Override public String toString() { return "ExcHandler: " + handler; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/BaseInvokeNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/BaseInvokeNode.java
package jadx.core.dex.instructions; import org.jetbrains.annotations.Nullable; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.nodes.InsnNode; public abstract class BaseInvokeNode extends InsnNode { public BaseInvokeNode(InsnType type, int argsCount) { super(type, argsCount); } public abstract MethodInfo getCallMth(); @Nullable public abstract InsnArg getInstanceArg(); public abstract boolean isStaticCall(); /** * Return offset to match method args from {@link #getCallMth()} */ public abstract int getFirstArgOffset(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/InvokeNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/InvokeNode.java
package jadx.core.dex.instructions; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.nodes.InsnNode; public class InvokeNode extends BaseInvokeNode { private final InvokeType type; private final MethodInfo mth; public InvokeNode(MethodInfo mthInfo, InsnData insn, InvokeType invokeType, boolean isRange) { this(mthInfo, insn, invokeType, invokeType != InvokeType.STATIC, isRange); } public InvokeNode(MethodInfo mth, InsnData insn, InvokeType type, boolean instanceCall, boolean isRange) { super(InsnType.INVOKE, mth.getArgsCount() + (instanceCall ? 1 : 0)); this.mth = mth; this.type = type; int k = isRange ? insn.getReg(0) : 0; if (instanceCall) { int r = isRange ? k : insn.getReg(k); addReg(r, mth.getDeclClass().getType()); k++; } for (ArgType arg : mth.getArgumentsTypes()) { addReg(isRange ? k : insn.getReg(k), arg); k += arg.getRegCount(); } int resReg = insn.getResultReg(); if (resReg != -1) { setResult(InsnArg.reg(resReg, mth.getReturnType())); } } public InvokeNode(MethodInfo mth, InvokeType invokeType, int argsCount) { super(InsnType.INVOKE, argsCount); this.mth = mth; this.type = invokeType; } public InvokeType getInvokeType() { return type; } @Override public MethodInfo getCallMth() { return mth; } @Override @Nullable public InsnArg getInstanceArg() { if (type != InvokeType.STATIC && getArgsCount() > 0) { return getArg(0); } return null; } @Override public boolean isStaticCall() { return type == InvokeType.STATIC; } public boolean isPolymorphicCall() { if (type == InvokeType.POLYMORPHIC) { return true; } // java bytecode uses virtual call with modified method info if (type == InvokeType.VIRTUAL && mth.getDeclClass().getFullName().equals("java.lang.invoke.MethodHandle") && (mth.getName().equals("invoke") || mth.getName().equals("invokeExact"))) { return true; } return false; } public int getFirstArgOffset() { return type == InvokeType.STATIC ? 0 : 1; } @Override public InsnNode copy() { return copyCommonParams(new InvokeNode(mth, type, getArgsCount())); } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof InvokeNode) || !super.isSame(obj)) { return false; } InvokeNode other = (InvokeNode) obj; return type == other.type && mth.equals(other.mth); } @Override public String toString() { return baseString() + " " + type + " call: " + mth + attributesString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/InvokeType.java
jadx-core/src/main/java/jadx/core/dex/instructions/InvokeType.java
package jadx.core.dex.instructions; public enum InvokeType { STATIC, DIRECT, VIRTUAL, INTERFACE, SUPER, POLYMORPHIC, CUSTOM, CUSTOM_RAW, }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/TargetInsnNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/TargetInsnNode.java
package jadx.core.dex.instructions; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.InsnNode; public abstract class TargetInsnNode extends InsnNode { public TargetInsnNode(InsnType type, int argsCount) { super(type, argsCount); } public void initBlocks(BlockNode curBlock) { } public boolean replaceTargetBlock(BlockNode origin, BlockNode replace) { return false; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/ArithOp.java
jadx-core/src/main/java/jadx/core/dex/instructions/ArithOp.java
package jadx.core.dex.instructions; public enum ArithOp { ADD("+"), SUB("-"), MUL("*"), DIV("/"), REM("%"), AND("&"), OR("|"), XOR("^"), SHL("<<"), SHR(">>"), USHR(">>>"); private final String symbol; ArithOp(String symbol) { this.symbol = symbol; } public String getSymbol() { return this.symbol; } public boolean isBitOp() { switch (this) { case AND: case OR: case XOR: return true; default: return false; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/ConstClassNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/ConstClassNode.java
package jadx.core.dex.instructions; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.InsnNode; public final class ConstClassNode extends InsnNode { private final ArgType clsType; public ConstClassNode(ArgType clsType) { super(InsnType.CONST_CLASS, 0); this.clsType = clsType; } public ArgType getClsType() { return clsType; } @Override public InsnNode copy() { return copyCommonParams(new ConstClassNode(clsType)); } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof ConstClassNode) || !super.isSame(obj)) { return false; } ConstClassNode other = (ConstClassNode) obj; return clsType.equals(other.clsType); } @Override public String toString() { return super.toString() + ' ' + clsType + ".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/dex/instructions/NewArrayNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/NewArrayNode.java
package jadx.core.dex.instructions; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.InsnNode; public class NewArrayNode extends InsnNode { private final ArgType arrType; public NewArrayNode(ArgType arrType, int argsCount) { super(InsnType.NEW_ARRAY, argsCount); this.arrType = arrType; } public ArgType getArrayType() { return arrType; } public int getDimension() { return arrType.getArrayDimension(); } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof NewArrayNode) || !super.isSame(obj)) { return false; } NewArrayNode other = (NewArrayNode) obj; return arrType == other.arrType; } @Override public InsnNode copy() { return copyCommonParams(new NewArrayNode(arrType, getArgsCount())); } @Override public String toString() { return super.toString() + " type: " + arrType; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/ConstStringNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/ConstStringNode.java
package jadx.core.dex.instructions; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.StringUtils; public final class ConstStringNode extends InsnNode { private final String str; public ConstStringNode(String str) { super(InsnType.CONST_STR, 0); this.str = str; } public String getString() { return str; } @Override public InsnNode copy() { return copyCommonParams(new ConstStringNode(str)); } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof ConstStringNode) || !super.isSame(obj)) { return false; } ConstStringNode other = (ConstStringNode) obj; return str.equals(other.str); } @Override public String toString() { return super.toString() + ' ' + StringUtils.getInstance().unescapeString(str); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/GotoNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/GotoNode.java
package jadx.core.dex.instructions; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; public class GotoNode extends TargetInsnNode { protected final int target; public GotoNode(int target) { this(InsnType.GOTO, target, 0); } protected GotoNode(InsnType type, int target, int argsCount) { super(type, argsCount); this.target = target; } public int getTarget() { return target; } @Override public InsnNode copy() { return copyCommonParams(new GotoNode(target)); } @Override public String toString() { return super.toString() + "-> " + InsnUtils.formatOffset(target); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/InsnType.java
jadx-core/src/main/java/jadx/core/dex/instructions/InsnType.java
package jadx.core.dex.instructions; public enum InsnType { CONST, CONST_STR, CONST_CLASS, ARITH, NEG, NOT, MOVE, MOVE_MULTI, CAST, RETURN, GOTO, THROW, MOVE_EXCEPTION, CMP_L, CMP_G, IF, SWITCH, SWITCH_DATA, MONITOR_ENTER, MONITOR_EXIT, CHECK_CAST, INSTANCE_OF, ARRAY_LENGTH, FILL_ARRAY, FILL_ARRAY_DATA, FILLED_NEW_ARRAY, AGET, APUT, NEW_ARRAY, NEW_INSTANCE, IGET, IPUT, SGET, SPUT, INVOKE, MOVE_RESULT, // *** Additional instructions *** // replacement for removed instructions NOP, TERNARY, CONSTRUCTOR, BREAK, CONTINUE, // strings concatenation STR_CONCAT, // just generate one argument ONE_ARG, PHI, // fake insn to keep arguments which will be used in regions codegen REGION_ARG, // Java specific dynamic jump instructions JAVA_JSR, JAVA_RET, }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/InsnDecoder.java
jadx-core/src/main/java/jadx/core/dex/instructions/InsnDecoder.java
package jadx.core.dex.instructions; import java.util.List; import java.util.Objects; import jadx.api.plugins.input.data.ICodeReader; import jadx.api.plugins.input.data.IMethodProto; import jadx.api.plugins.input.data.IMethodRef; import jadx.api.plugins.input.insns.InsnData; import jadx.api.plugins.input.insns.custom.IArrayPayload; import jadx.api.plugins.input.insns.custom.ICustomPayload; import jadx.api.plugins.input.insns.custom.ISwitchPayload; import jadx.core.Consts; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.CodeFeaturesAttr; import jadx.core.dex.attributes.nodes.CodeFeaturesAttr.CodeFeature; import jadx.core.dex.attributes.nodes.JadxError; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.instructions.args.LiteralArg; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.instructions.java.JsrNode; 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.Utils; import jadx.core.utils.exceptions.DecodeException; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.input.InsnDataUtils; public class InsnDecoder { private final MethodNode method; private final RootNode root; public InsnDecoder(MethodNode mthNode) { this.method = mthNode; this.root = method.root(); } public InsnNode[] process(ICodeReader codeReader) { InsnNode[] instructions = new InsnNode[codeReader.getUnitsCount()]; codeReader.visitInstructions(rawInsn -> { int offset = rawInsn.getOffset(); InsnNode insn; try { rawInsn.decode(); insn = decode(rawInsn); } catch (Exception e) { boolean mthWithErrors = method.contains(AType.JADX_ERROR); method.addError("Failed to decode insn: " + rawInsn, e); if (mthWithErrors) { // second error in this method => abort processing throw new JadxRuntimeException("Failed to decode insn: " + rawInsn, e); } insn = new InsnNode(InsnType.NOP, 0); insn.addAttr(AType.JADX_ERROR, new JadxError("decode failed: " + e.getMessage(), e)); } insn.setOffset(offset); instructions[offset] = insn; }); return instructions; } protected InsnNode decode(InsnData insn) throws DecodeException { switch (insn.getOpcode()) { case NOP: return new InsnNode(InsnType.NOP, 0); // move-result will be process in invoke and filled-new-array instructions case MOVE_RESULT: return insn(InsnType.MOVE_RESULT, InsnArg.reg(insn, 0, ArgType.UNKNOWN)); case CONST: LiteralArg narrowLitArg = InsnArg.lit(insn, ArgType.NARROW); return insn(InsnType.CONST, InsnArg.reg(insn, 0, narrowLitArg.getType()), narrowLitArg); case CONST_WIDE: LiteralArg wideLitArg = InsnArg.lit(insn, ArgType.WIDE); return insn(InsnType.CONST, InsnArg.reg(insn, 0, wideLitArg.getType()), wideLitArg); case CONST_STRING: InsnNode constStrInsn = new ConstStringNode(insn.getIndexAsString()); constStrInsn.setResult(InsnArg.reg(insn, 0, ArgType.STRING)); return constStrInsn; case CONST_CLASS: { ArgType clsType = ArgType.parse(insn.getIndexAsType()); InsnNode constClsInsn = new ConstClassNode(clsType); constClsInsn.setResult(InsnArg.reg(insn, 0, ArgType.generic(Consts.CLASS_CLASS, clsType))); return constClsInsn; } case MOVE: return insn(InsnType.MOVE, InsnArg.reg(insn, 0, ArgType.NARROW), InsnArg.reg(insn, 1, ArgType.NARROW)); case MOVE_MULTI: int len = insn.getRegsCount(); InsnNode mmv = new InsnNode(InsnType.MOVE_MULTI, len); for (int i = 0; i < len; i++) { mmv.addArg(InsnArg.reg(insn, i, ArgType.UNKNOWN)); } return mmv; case MOVE_WIDE: return insn(InsnType.MOVE, InsnArg.reg(insn, 0, ArgType.WIDE), InsnArg.reg(insn, 1, ArgType.WIDE)); case MOVE_OBJECT: return insn(InsnType.MOVE, InsnArg.reg(insn, 0, ArgType.UNKNOWN_OBJECT), InsnArg.reg(insn, 1, ArgType.UNKNOWN_OBJECT)); case ADD_INT: return arith(insn, ArithOp.ADD, ArgType.INT); case ADD_DOUBLE: return arith(insn, ArithOp.ADD, ArgType.DOUBLE); case ADD_FLOAT: return arith(insn, ArithOp.ADD, ArgType.FLOAT); case ADD_LONG: return arith(insn, ArithOp.ADD, ArgType.LONG); case ADD_INT_LIT: return arithLit(insn, ArithOp.ADD, ArgType.INT); case SUB_INT: return arith(insn, ArithOp.SUB, ArgType.INT); case RSUB_INT: return new ArithNode(ArithOp.SUB, InsnArg.reg(insn, 0, ArgType.INT), InsnArg.lit(insn, ArgType.INT), InsnArg.reg(insn, 1, ArgType.INT)); case SUB_LONG: return arith(insn, ArithOp.SUB, ArgType.LONG); case SUB_FLOAT: return arith(insn, ArithOp.SUB, ArgType.FLOAT); case SUB_DOUBLE: return arith(insn, ArithOp.SUB, ArgType.DOUBLE); case MUL_INT: return arith(insn, ArithOp.MUL, ArgType.INT); case MUL_DOUBLE: return arith(insn, ArithOp.MUL, ArgType.DOUBLE); case MUL_FLOAT: return arith(insn, ArithOp.MUL, ArgType.FLOAT); case MUL_LONG: return arith(insn, ArithOp.MUL, ArgType.LONG); case MUL_INT_LIT: return arithLit(insn, ArithOp.MUL, ArgType.INT); case DIV_INT: return arith(insn, ArithOp.DIV, ArgType.INT); case REM_INT: return arith(insn, ArithOp.REM, ArgType.INT); case REM_LONG: return arith(insn, ArithOp.REM, ArgType.LONG); case REM_FLOAT: return arith(insn, ArithOp.REM, ArgType.FLOAT); case REM_DOUBLE: return arith(insn, ArithOp.REM, ArgType.DOUBLE); case DIV_DOUBLE: return arith(insn, ArithOp.DIV, ArgType.DOUBLE); case DIV_FLOAT: return arith(insn, ArithOp.DIV, ArgType.FLOAT); case DIV_LONG: return arith(insn, ArithOp.DIV, ArgType.LONG); case DIV_INT_LIT: return arithLit(insn, ArithOp.DIV, ArgType.INT); case REM_INT_LIT: return arithLit(insn, ArithOp.REM, ArgType.INT); case AND_INT: return arith(insn, ArithOp.AND, ArgType.INT); case AND_INT_LIT: return arithLit(insn, ArithOp.AND, ArgType.INT); case XOR_INT_LIT: return arithLit(insn, ArithOp.XOR, ArgType.INT); case AND_LONG: return arith(insn, ArithOp.AND, ArgType.LONG); case OR_INT: return arith(insn, ArithOp.OR, ArgType.INT); case OR_INT_LIT: return arithLit(insn, ArithOp.OR, ArgType.INT); case XOR_INT: return arith(insn, ArithOp.XOR, ArgType.INT); case OR_LONG: return arith(insn, ArithOp.OR, ArgType.LONG); case XOR_LONG: return arith(insn, ArithOp.XOR, ArgType.LONG); case USHR_INT: return arith(insn, ArithOp.USHR, ArgType.INT); case USHR_LONG: return arith(insn, ArithOp.USHR, ArgType.LONG); case SHL_INT: return arith(insn, ArithOp.SHL, ArgType.INT); case SHL_LONG: return arith(insn, ArithOp.SHL, ArgType.LONG); case SHR_INT: return arith(insn, ArithOp.SHR, ArgType.INT); case SHR_LONG: return arith(insn, ArithOp.SHR, ArgType.LONG); case SHL_INT_LIT: return arithLit(insn, ArithOp.SHL, ArgType.INT); case SHR_INT_LIT: return arithLit(insn, ArithOp.SHR, ArgType.INT); case USHR_INT_LIT: return arithLit(insn, ArithOp.USHR, ArgType.INT); case NEG_INT: return neg(insn, ArgType.INT); case NEG_LONG: return neg(insn, ArgType.LONG); case NEG_FLOAT: return neg(insn, ArgType.FLOAT); case NEG_DOUBLE: return neg(insn, ArgType.DOUBLE); case NOT_INT: return not(insn, ArgType.INT); case NOT_LONG: return not(insn, ArgType.LONG); case INT_TO_BYTE: return cast(insn, ArgType.INT, ArgType.BYTE); case INT_TO_CHAR: return cast(insn, ArgType.INT, ArgType.CHAR); case INT_TO_SHORT: return cast(insn, ArgType.INT, ArgType.SHORT); case INT_TO_FLOAT: return cast(insn, ArgType.INT, ArgType.FLOAT); case INT_TO_DOUBLE: return cast(insn, ArgType.INT, ArgType.DOUBLE); case INT_TO_LONG: return cast(insn, ArgType.INT, ArgType.LONG); case FLOAT_TO_INT: return cast(insn, ArgType.FLOAT, ArgType.INT); case FLOAT_TO_DOUBLE: return cast(insn, ArgType.FLOAT, ArgType.DOUBLE); case FLOAT_TO_LONG: return cast(insn, ArgType.FLOAT, ArgType.LONG); case DOUBLE_TO_INT: return cast(insn, ArgType.DOUBLE, ArgType.INT); case DOUBLE_TO_FLOAT: return cast(insn, ArgType.DOUBLE, ArgType.FLOAT); case DOUBLE_TO_LONG: return cast(insn, ArgType.DOUBLE, ArgType.LONG); case LONG_TO_INT: return cast(insn, ArgType.LONG, ArgType.INT); case LONG_TO_FLOAT: return cast(insn, ArgType.LONG, ArgType.FLOAT); case LONG_TO_DOUBLE: return cast(insn, ArgType.LONG, ArgType.DOUBLE); case IF_EQ: case IF_EQZ: return new IfNode(insn, IfOp.EQ); case IF_NE: case IF_NEZ: return new IfNode(insn, IfOp.NE); case IF_GT: case IF_GTZ: return new IfNode(insn, IfOp.GT); case IF_GE: case IF_GEZ: return new IfNode(insn, IfOp.GE); case IF_LT: case IF_LTZ: return new IfNode(insn, IfOp.LT); case IF_LE: case IF_LEZ: return new IfNode(insn, IfOp.LE); case CMP_LONG: return cmp(insn, InsnType.CMP_L, ArgType.LONG); case CMPL_FLOAT: return cmp(insn, InsnType.CMP_L, ArgType.FLOAT); case CMPL_DOUBLE: return cmp(insn, InsnType.CMP_L, ArgType.DOUBLE); case CMPG_FLOAT: return cmp(insn, InsnType.CMP_G, ArgType.FLOAT); case CMPG_DOUBLE: return cmp(insn, InsnType.CMP_G, ArgType.DOUBLE); case GOTO: return new GotoNode(insn.getTarget()); case JAVA_JSR: method.add(AFlag.RESOLVE_JAVA_JSR); JsrNode jsr = new JsrNode(insn.getTarget()); jsr.setResult(InsnArg.reg(insn, 0, ArgType.UNKNOWN_INT)); return jsr; case JAVA_RET: method.add(AFlag.RESOLVE_JAVA_JSR); return insn(InsnType.JAVA_RET, null, InsnArg.reg(insn, 0, ArgType.UNKNOWN_INT)); case THROW: return insn(InsnType.THROW, null, InsnArg.reg(insn, 0, ArgType.THROWABLE)); case MOVE_EXCEPTION: return insn(InsnType.MOVE_EXCEPTION, InsnArg.reg(insn, 0, ArgType.UNKNOWN_OBJECT_NO_ARRAY)); case RETURN_VOID: return new InsnNode(InsnType.RETURN, 0); case RETURN: return insn(InsnType.RETURN, null, InsnArg.reg(insn, 0, method.getReturnType())); case INSTANCE_OF: InsnNode instInsn = new IndexInsnNode(InsnType.INSTANCE_OF, ArgType.parse(insn.getIndexAsType()), 1); instInsn.setResult(InsnArg.reg(insn, 0, ArgType.BOOLEAN)); instInsn.addArg(InsnArg.reg(insn, 1, ArgType.UNKNOWN_OBJECT)); return instInsn; case CHECK_CAST: ArgType castType = ArgType.parse(insn.getIndexAsType()); InsnNode checkCastInsn = new IndexInsnNode(InsnType.CHECK_CAST, castType, 1); checkCastInsn.setResult(InsnArg.reg(insn, 0, castType)); checkCastInsn.addArg(InsnArg.reg(insn, insn.getRegsCount() == 2 ? 1 : 0, ArgType.UNKNOWN_OBJECT)); return checkCastInsn; case IGET: FieldInfo igetFld = FieldInfo.fromRef(root, insn.getIndexAsField()); InsnNode igetInsn = new IndexInsnNode(InsnType.IGET, igetFld, 1); igetInsn.setResult(InsnArg.reg(insn, 0, tryResolveFieldType(igetFld))); igetInsn.addArg(InsnArg.reg(insn, 1, igetFld.getDeclClass().getType())); return igetInsn; case IPUT: FieldInfo iputFld = FieldInfo.fromRef(root, insn.getIndexAsField()); InsnNode iputInsn = new IndexInsnNode(InsnType.IPUT, iputFld, 2); iputInsn.addArg(InsnArg.reg(insn, 0, tryResolveFieldType(iputFld))); iputInsn.addArg(InsnArg.reg(insn, 1, iputFld.getDeclClass().getType())); return iputInsn; case SGET: FieldInfo sgetFld = FieldInfo.fromRef(root, insn.getIndexAsField()); InsnNode sgetInsn = new IndexInsnNode(InsnType.SGET, sgetFld, 0); sgetInsn.setResult(InsnArg.reg(insn, 0, tryResolveFieldType(sgetFld))); return sgetInsn; case SPUT: FieldInfo sputFld = FieldInfo.fromRef(root, insn.getIndexAsField()); InsnNode sputInsn = new IndexInsnNode(InsnType.SPUT, sputFld, 1); sputInsn.addArg(InsnArg.reg(insn, 0, tryResolveFieldType(sputFld))); return sputInsn; case ARRAY_LENGTH: InsnNode arrLenInsn = new InsnNode(InsnType.ARRAY_LENGTH, 1); arrLenInsn.setResult(InsnArg.reg(insn, 0, ArgType.INT)); arrLenInsn.addArg(InsnArg.reg(insn, 1, ArgType.array(ArgType.UNKNOWN))); return arrLenInsn; case AGET: return arrayGet(insn, ArgType.INT_FLOAT, ArgType.NARROW_NUMBERS_NO_BOOL); case AGET_BOOLEAN: return arrayGet(insn, ArgType.BOOLEAN); case AGET_BYTE: return arrayGet(insn, ArgType.BYTE, ArgType.NARROW_INTEGRAL); case AGET_BYTE_BOOLEAN: return arrayGet(insn, ArgType.BYTE_BOOLEAN); case AGET_CHAR: return arrayGet(insn, ArgType.CHAR); case AGET_SHORT: return arrayGet(insn, ArgType.SHORT); case AGET_WIDE: return arrayGet(insn, ArgType.WIDE); case AGET_OBJECT: return arrayGet(insn, ArgType.UNKNOWN_OBJECT); case APUT: return arrayPut(insn, ArgType.INT_FLOAT, ArgType.NARROW_NUMBERS_NO_BOOL); case APUT_BOOLEAN: return arrayPut(insn, ArgType.BOOLEAN); case APUT_BYTE: return arrayPut(insn, ArgType.BYTE); case APUT_BYTE_BOOLEAN: return arrayPut(insn, ArgType.BYTE_BOOLEAN); case APUT_CHAR: return arrayPut(insn, ArgType.CHAR); case APUT_SHORT: return arrayPut(insn, ArgType.SHORT); case APUT_WIDE: return arrayPut(insn, ArgType.WIDE); case APUT_OBJECT: return arrayPut(insn, ArgType.UNKNOWN_OBJECT); case INVOKE_STATIC: return invoke(insn, InvokeType.STATIC, false); case INVOKE_STATIC_RANGE: return invoke(insn, InvokeType.STATIC, true); case INVOKE_DIRECT: return invoke(insn, InvokeType.DIRECT, false); case INVOKE_INTERFACE: return invoke(insn, InvokeType.INTERFACE, false); case INVOKE_SUPER: return invoke(insn, InvokeType.SUPER, false); case INVOKE_VIRTUAL: return invoke(insn, InvokeType.VIRTUAL, false); case INVOKE_CUSTOM: return invokeCustom(insn, false); case INVOKE_SPECIAL: return invokeSpecial(insn); case INVOKE_POLYMORPHIC: return invokePolymorphic(insn, false); case INVOKE_DIRECT_RANGE: return invoke(insn, InvokeType.DIRECT, true); case INVOKE_INTERFACE_RANGE: return invoke(insn, InvokeType.INTERFACE, true); case INVOKE_SUPER_RANGE: return invoke(insn, InvokeType.SUPER, true); case INVOKE_VIRTUAL_RANGE: return invoke(insn, InvokeType.VIRTUAL, true); case INVOKE_CUSTOM_RANGE: return invokeCustom(insn, true); case INVOKE_POLYMORPHIC_RANGE: return invokePolymorphic(insn, true); case NEW_INSTANCE: ArgType clsType = ArgType.parse(insn.getIndexAsType()); IndexInsnNode newInstInsn = new IndexInsnNode(InsnType.NEW_INSTANCE, clsType, 0); newInstInsn.setResult(InsnArg.reg(insn, 0, clsType)); return newInstInsn; case NEW_ARRAY: return makeNewArray(insn); case FILL_ARRAY_DATA: return new FillArrayInsn(InsnArg.reg(insn, 0, ArgType.UNKNOWN_ARRAY), insn.getTarget()); case FILL_ARRAY_DATA_PAYLOAD: return new FillArrayData(((IArrayPayload) Objects.requireNonNull(insn.getPayload()))); case FILLED_NEW_ARRAY: return filledNewArray(insn, false); case FILLED_NEW_ARRAY_RANGE: return filledNewArray(insn, true); case PACKED_SWITCH: return makeSwitch(insn, true); case SPARSE_SWITCH: return makeSwitch(insn, false); case PACKED_SWITCH_PAYLOAD: case SPARSE_SWITCH_PAYLOAD: return new SwitchData(((ISwitchPayload) insn.getPayload())); case MONITOR_ENTER: return insn(InsnType.MONITOR_ENTER, null, InsnArg.reg(insn, 0, ArgType.UNKNOWN_OBJECT)); case MONITOR_EXIT: return insn(InsnType.MONITOR_EXIT, null, InsnArg.reg(insn, 0, ArgType.UNKNOWN_OBJECT)); default: throw new DecodeException("Unknown instruction: '" + insn + '\''); } } private SwitchInsn makeSwitch(InsnData insn, boolean packed) { SwitchInsn swInsn = new SwitchInsn(InsnArg.reg(insn, 0, ArgType.UNKNOWN), insn.getTarget(), packed); ICustomPayload payload = insn.getPayload(); if (payload != null) { swInsn.attachSwitchData(new SwitchData((ISwitchPayload) payload), insn.getTarget()); } method.add(AFlag.COMPUTE_POST_DOM); CodeFeaturesAttr.add(method, CodeFeature.SWITCH); return swInsn; } private InsnNode makeNewArray(InsnData insn) { ArgType indexType = ArgType.parse(insn.getIndexAsType()); int dim = (int) insn.getLiteral(); ArgType arrType; if (dim == 0) { arrType = indexType; } else { if (indexType.isArray()) { // java bytecode can pass array as a base type arrType = indexType; } else { arrType = ArgType.array(indexType, dim); } } int regsCount = insn.getRegsCount(); NewArrayNode newArr = new NewArrayNode(arrType, regsCount - 1); newArr.setResult(InsnArg.reg(insn, 0, arrType)); for (int i = 1; i < regsCount; i++) { newArr.addArg(InsnArg.typeImmutableReg(insn, i, ArgType.INT)); } CodeFeaturesAttr.add(method, CodeFeature.NEW_ARRAY); return newArr; } private ArgType tryResolveFieldType(FieldInfo igetFld) { FieldNode fieldNode = root.resolveField(igetFld); if (fieldNode != null) { return fieldNode.getType(); } return igetFld.getType(); } private InsnNode filledNewArray(InsnData insn, boolean isRange) { ArgType arrType = ArgType.parse(insn.getIndexAsType()); ArgType elType = arrType.getArrayElement(); boolean typeImmutable = elType.isPrimitive(); int regsCount = insn.getRegsCount(); InsnArg[] regs = new InsnArg[regsCount]; if (isRange) { int r = insn.getReg(0); for (int i = 0; i < regsCount; i++) { regs[i] = InsnArg.reg(r, elType, typeImmutable); r++; } } else { for (int i = 0; i < regsCount; i++) { int regNum = insn.getReg(i); regs[i] = InsnArg.reg(regNum, elType, typeImmutable); } } InsnNode node = new FilledNewArrayNode(elType, regs.length); // node.setResult(resReg == -1 ? null : InsnArg.reg(resReg, arrType)); for (InsnArg arg : regs) { node.addArg(arg); } return node; } private InsnNode cmp(InsnData insn, InsnType itype, ArgType argType) { InsnNode inode = new InsnNode(itype, 2); inode.setResult(InsnArg.reg(insn, 0, ArgType.INT)); inode.addArg(InsnArg.reg(insn, 1, argType)); inode.addArg(InsnArg.reg(insn, 2, argType)); return inode; } private InsnNode cast(InsnData insn, ArgType from, ArgType to) { InsnNode inode = new IndexInsnNode(InsnType.CAST, to, 1); inode.setResult(InsnArg.reg(insn, 0, to)); inode.addArg(InsnArg.reg(insn, 1, from)); return inode; } private InsnNode invokeCustom(InsnData insn, boolean isRange) { return InvokeCustomBuilder.build(method, insn, isRange); } private InsnNode invokePolymorphic(InsnData insn, boolean isRange) { IMethodRef mthRef = InsnDataUtils.getMethodRef(insn); if (mthRef == null) { throw new JadxRuntimeException("Failed to load method reference for insn: " + insn); } MethodInfo callMth = MethodInfo.fromRef(root, mthRef); IMethodProto proto = insn.getIndexAsProto(insn.getTarget()); // expand call args List<ArgType> args = Utils.collectionMap(proto.getArgTypes(), ArgType::parse); ArgType returnType = ArgType.parse(proto.getReturnType()); MethodInfo effectiveCallMth = MethodInfo.fromDetails(root, callMth.getDeclClass(), callMth.getName(), args, returnType); return new InvokePolymorphicNode(effectiveCallMth, insn, proto, callMth, isRange); } private InsnNode invokeSpecial(InsnData insn) { IMethodRef mthRef = InsnDataUtils.getMethodRef(insn); if (mthRef == null) { throw new JadxRuntimeException("Failed to load method reference for insn: " + insn); } MethodInfo mthInfo = MethodInfo.fromRef(root, mthRef); // convert 'special' to 'direct/super' same as dx InvokeType type; if (mthInfo.isConstructor() || Objects.equals(mthInfo.getDeclClass(), method.getParentClass().getClassInfo())) { type = InvokeType.DIRECT; } else { type = InvokeType.SUPER; } return new InvokeNode(mthInfo, insn, type, false); } private InsnNode invoke(InsnData insn, InvokeType type, boolean isRange) { IMethodRef mthRef = InsnDataUtils.getMethodRef(insn); if (mthRef == null) { throw new JadxRuntimeException("Failed to load method reference for insn: " + insn); } MethodInfo mthInfo = MethodInfo.fromRef(root, mthRef); return new InvokeNode(mthInfo, insn, type, isRange); } private InsnNode arrayGet(InsnData insn, ArgType argType) { return arrayGet(insn, argType, argType); } private InsnNode arrayGet(InsnData insn, ArgType arrElemType, ArgType resType) { InsnNode inode = new InsnNode(InsnType.AGET, 2); inode.setResult(InsnArg.typeImmutableIfKnownReg(insn, 0, resType)); inode.addArg(InsnArg.typeImmutableIfKnownReg(insn, 1, ArgType.array(arrElemType))); inode.addArg(InsnArg.reg(insn, 2, ArgType.NARROW_INTEGRAL)); return inode; } private InsnNode arrayPut(InsnData insn, ArgType argType) { return arrayPut(insn, argType, argType); } private InsnNode arrayPut(InsnData insn, ArgType arrElemType, ArgType argType) { InsnNode inode = new InsnNode(InsnType.APUT, 3); inode.addArg(InsnArg.typeImmutableIfKnownReg(insn, 1, ArgType.array(arrElemType))); inode.addArg(InsnArg.reg(insn, 2, ArgType.NARROW_INTEGRAL)); inode.addArg(InsnArg.typeImmutableIfKnownReg(insn, 0, argType)); return inode; } private InsnNode arith(InsnData insn, ArithOp op, ArgType type) { return ArithNode.build(insn, op, type); } private InsnNode arithLit(InsnData insn, ArithOp op, ArgType type) { return ArithNode.buildLit(insn, op, type); } private InsnNode neg(InsnData insn, ArgType type) { InsnNode inode = new InsnNode(InsnType.NEG, 1); inode.setResult(InsnArg.reg(insn, 0, type)); inode.addArg(InsnArg.reg(insn, 1, type)); return inode; } private InsnNode not(InsnData insn, ArgType type) { InsnNode inode = new InsnNode(InsnType.NOT, 1); inode.setResult(InsnArg.reg(insn, 0, type)); inode.addArg(InsnArg.reg(insn, 1, type)); return inode; } private InsnNode insn(InsnType type, RegisterArg res) { InsnNode node = new InsnNode(type, 0); node.setResult(res); return node; } private InsnNode insn(InsnType type, RegisterArg res, InsnArg arg) { InsnNode node = new InsnNode(type, 1); node.setResult(res); node.addArg(arg); return node; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/InvokePolymorphicNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/InvokePolymorphicNode.java
package jadx.core.dex.instructions; import jadx.api.plugins.input.data.IMethodProto; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; public class InvokePolymorphicNode extends InvokeNode { private final IMethodProto proto; private final MethodInfo baseCallRef; public InvokePolymorphicNode(MethodInfo callMth, InsnData insn, IMethodProto proto, MethodInfo baseRef, boolean isRange) { super(callMth, insn, InvokeType.POLYMORPHIC, true, isRange); this.proto = proto; this.baseCallRef = baseRef; } public InvokePolymorphicNode(MethodInfo callMth, int argsCount, IMethodProto proto, MethodInfo baseRef) { super(callMth, InvokeType.POLYMORPHIC, argsCount); this.proto = proto; this.baseCallRef = baseRef; } public IMethodProto getProto() { return proto; } public MethodInfo getBaseCallRef() { return baseCallRef; } @Override public InsnNode copy() { InvokePolymorphicNode copy = new InvokePolymorphicNode(getCallMth(), getArgsCount(), proto, baseCallRef); copyCommonParams(copy); return copy; } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof InvokePolymorphicNode) || !super.isSame(obj)) { return false; } InvokePolymorphicNode other = (InvokePolymorphicNode) obj; return proto.equals(other.proto); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(InsnUtils.formatOffset(offset)).append(": INVOKE_POLYMORPHIC "); if (getResult() != null) { sb.append(getResult()).append(" = "); } if (!appendArgs(sb)) { sb.append('\n'); } appendAttributes(sb); sb.append(" base: ").append(baseCallRef).append('\n'); sb.append(" proto: ").append(proto).append('\n'); return sb.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/InvokeCustomNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/InvokeCustomNode.java
package jadx.core.dex.instructions; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.MethodHandleType; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; public class InvokeCustomNode extends InvokeNode { private MethodInfo implMthInfo; private MethodHandleType handleType; private InsnNode callInsn; private boolean inlineInsn; private boolean useRef; public InvokeCustomNode(MethodInfo lambdaInfo, InsnData insn, boolean instanceCall, boolean isRange) { super(lambdaInfo, insn, InvokeType.CUSTOM, instanceCall, isRange); } private InvokeCustomNode(MethodInfo mth, InvokeType invokeType, int argsCount) { super(mth, invokeType, argsCount); } @Override public InsnNode copy() { InvokeCustomNode copy = new InvokeCustomNode(getCallMth(), getInvokeType(), getArgsCount()); copyCommonParams(copy); copy.setImplMthInfo(implMthInfo); copy.setHandleType(handleType); copy.setCallInsn(callInsn); copy.setInlineInsn(inlineInsn); copy.setUseRef(useRef); return copy; } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof InvokeCustomNode) || !super.isSame(obj)) { return false; } InvokeCustomNode other = (InvokeCustomNode) obj; return handleType == other.handleType && implMthInfo.equals(other.implMthInfo) && callInsn.isSame(other.callInsn) && inlineInsn == other.inlineInsn && useRef == other.useRef; } public MethodInfo getImplMthInfo() { return implMthInfo; } public void setImplMthInfo(MethodInfo implMthInfo) { this.implMthInfo = implMthInfo; } public MethodHandleType getHandleType() { return handleType; } public void setHandleType(MethodHandleType handleType) { this.handleType = handleType; } public InsnNode getCallInsn() { return callInsn; } public void setCallInsn(InsnNode callInsn) { this.callInsn = callInsn; } public boolean isInlineInsn() { return inlineInsn; } public void setInlineInsn(boolean inlineInsn) { this.inlineInsn = inlineInsn; } public boolean isUseRef() { return useRef; } public void setUseRef(boolean useRef) { this.useRef = useRef; } @Nullable public BaseInvokeNode getInvokeCall() { if (callInsn.getType() == InsnType.INVOKE) { return (BaseInvokeNode) callInsn; } return null; } @Override public @Nullable InsnArg getInstanceArg() { return null; } @Override public boolean isStaticCall() { return true; } @Override public int getFirstArgOffset() { return 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(InsnUtils.formatOffset(offset)).append(": INVOKE_CUSTOM "); if (getResult() != null) { sb.append(getResult()).append(" = "); } appendArgs(sb); appendAttributes(sb); sb.append("\n handle type: ").append(handleType); sb.append("\n lambda: ").append(implMthInfo); sb.append("\n call insn: ").append(callInsn); return sb.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/FillArrayData.java
jadx-core/src/main/java/jadx/core/dex/instructions/FillArrayData.java
package jadx.core.dex.instructions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import jadx.api.plugins.input.insns.custom.IArrayPayload; 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.utils.exceptions.JadxRuntimeException; public final class FillArrayData extends InsnNode { private static final ArgType ONE_BYTE_TYPE = ArgType.unknown(PrimitiveType.BYTE, PrimitiveType.BOOLEAN); private static final ArgType TWO_BYTES_TYPE = ArgType.unknown(PrimitiveType.SHORT, PrimitiveType.CHAR); private static final ArgType FOUR_BYTES_TYPE = ArgType.unknown(PrimitiveType.INT, PrimitiveType.FLOAT); private static final ArgType EIGHT_BYTES_TYPE = ArgType.unknown(PrimitiveType.LONG, PrimitiveType.DOUBLE); private final Object data; private final int size; private final int elemSize; private ArgType elemType; public FillArrayData(IArrayPayload payload) { this(payload.getData(), payload.getSize(), payload.getElementSize()); } private FillArrayData(Object data, int size, int elemSize) { super(InsnType.FILL_ARRAY_DATA, 0); this.data = data; this.size = size; this.elemSize = elemSize; this.elemType = getElementType(elemSize); } private static ArgType getElementType(int elementWidthUnit) { switch (elementWidthUnit) { case 1: case 0: return ONE_BYTE_TYPE; case 2: return TWO_BYTES_TYPE; case 4: return FOUR_BYTES_TYPE; case 8: return EIGHT_BYTES_TYPE; default: throw new JadxRuntimeException("Unknown array element width: " + elementWidthUnit); } } public Object getData() { return data; } public int getSize() { return size; } public ArgType getElementType() { return elemType; } public List<LiteralArg> getLiteralArgs(ArgType type) { List<LiteralArg> list = new ArrayList<>(size); Object array = data; switch (elemSize) { case 1: for (byte b : (byte[]) array) { list.add(InsnArg.lit(b, type)); } break; case 2: for (short b : (short[]) array) { list.add(InsnArg.lit(b, type)); } break; case 4: for (int b : (int[]) array) { list.add(InsnArg.lit(b, type)); } break; case 8: for (long b : (long[]) array) { list.add(InsnArg.lit(b, type)); } break; default: throw new JadxRuntimeException("Unknown type: " + data.getClass() + ", expected: " + type); } return list; } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof FillArrayData) || !super.isSame(obj)) { return false; } FillArrayData other = (FillArrayData) obj; return elemType.equals(other.elemType) && data == other.data; } @Override public InsnNode copy() { FillArrayData copy = new FillArrayData(data, size, elemSize); copy.elemType = this.elemType; return copyCommonParams(copy); } public String dataToString() { switch (elemSize) { case 1: return Arrays.toString((byte[]) data); case 2: return Arrays.toString((short[]) data); case 4: return Arrays.toString((int[]) data); case 8: return Arrays.toString((long[]) data); default: return "?"; } } @Override public String toString() { return super.toString() + ", data: " + dataToString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/IfOp.java
jadx-core/src/main/java/jadx/core/dex/instructions/IfOp.java
package jadx.core.dex.instructions; import jadx.core.utils.exceptions.JadxRuntimeException; public enum IfOp { EQ("=="), NE("!="), LT("<"), LE("<="), GT(">"), GE(">="); private final String symbol; IfOp(String symbol) { this.symbol = symbol; } public String getSymbol() { return symbol; } public IfOp invert() { switch (this) { case EQ: return NE; case NE: return EQ; case LT: return GE; case LE: return GT; case GT: return LE; case GE: return LT; default: throw new JadxRuntimeException("Unknown if operations type: " + this); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/InvokeCustomBuilder.java
jadx-core/src/main/java/jadx/core/dex/instructions/InvokeCustomBuilder.java
package jadx.core.dex.instructions; import java.util.List; import jadx.api.plugins.input.data.ICallSite; import jadx.api.plugins.input.data.annotations.EncodedValue; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.JadxError; import jadx.core.dex.instructions.invokedynamic.CustomLambdaCall; import jadx.core.dex.instructions.invokedynamic.CustomRawCall; import jadx.core.dex.instructions.invokedynamic.CustomStringConcat; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.input.InsnDataUtils; public class InvokeCustomBuilder { public static InsnNode build(MethodNode mth, InsnData insn, boolean isRange) { try { ICallSite callSite = InsnDataUtils.getCallSite(insn); if (callSite == null) { throw new JadxRuntimeException("Failed to get call site for insn: " + insn); } callSite.load(); List<EncodedValue> values = callSite.getValues(); if (CustomLambdaCall.isLambdaInvoke(values)) { return CustomLambdaCall.buildLambdaMethodCall(mth, insn, isRange, values); } if (CustomStringConcat.isStringConcat(values)) { return CustomStringConcat.buildStringConcat(insn, isRange, values); } try { return CustomRawCall.build(mth, insn, isRange, values); } catch (Exception e) { mth.addWarn("Failed to decode invoke-custom: \n" + Utils.listToString(values, "\n") + ",\n exception: " + Utils.getStackTrace(e)); InsnNode nop = new InsnNode(InsnType.NOP, 0); nop.add(AFlag.SYNTHETIC); nop.addAttr(AType.JADX_ERROR, new JadxError("Failed to decode invoke-custom: " + values, e)); return nop; } } catch (Exception e) { throw new JadxRuntimeException("'invoke-custom' instruction processing error: " + e.getMessage(), e); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/IfNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/IfNode.java
package jadx.core.dex.instructions; import java.util.List; import jadx.api.plugins.input.insns.InsnData; 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.BlockNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; import static jadx.core.utils.BlockUtils.getBlockByOffset; import static jadx.core.utils.BlockUtils.selectOther; public class IfNode extends GotoNode { protected IfOp op; private BlockNode thenBlock; private BlockNode elseBlock; public IfNode(InsnData insn, IfOp op) { super(InsnType.IF, insn.getTarget(), 2); this.op = op; ArgType argType = narrowTypeByOp(op); addArg(InsnArg.reg(insn, 0, argType)); if (insn.getRegsCount() == 1) { addArg(InsnArg.lit(0, argType)); } else { addArg(InsnArg.reg(insn, 1, argType)); } } public IfNode(IfOp op, int targetOffset, InsnArg arg1, InsnArg arg2) { this(op, targetOffset); addArg(arg1); addArg(arg2); } private IfNode(IfOp op, int targetOffset) { super(InsnType.IF, targetOffset, 2); this.op = op; } // change default types priority private static final ArgType WIDE_TYPE = ArgType.unknown( PrimitiveType.INT, PrimitiveType.BOOLEAN, PrimitiveType.OBJECT, PrimitiveType.ARRAY, PrimitiveType.BYTE, PrimitiveType.SHORT, PrimitiveType.CHAR); private static final ArgType NUMBERS_TYPE = ArgType.unknown( PrimitiveType.INT, PrimitiveType.BYTE, PrimitiveType.SHORT, PrimitiveType.CHAR); private static ArgType narrowTypeByOp(IfOp op) { if (op == IfOp.EQ || op == IfOp.NE) { return WIDE_TYPE; } return NUMBERS_TYPE; } public IfOp getOp() { return op; } public void invertCondition() { op = op.invert(); BlockNode tmp = thenBlock; thenBlock = elseBlock; elseBlock = tmp; } /** * Change 'a != false' to 'a == true' */ public void normalize() { if (getOp() == IfOp.NE && getArg(1).isFalse()) { changeCondition(IfOp.EQ, getArg(0), LiteralArg.litTrue()); } } public void changeCondition(IfOp op, InsnArg arg1, InsnArg arg2) { this.op = op; setArg(0, arg1); setArg(1, arg2); } @Override public void initBlocks(BlockNode curBlock) { List<BlockNode> successors = curBlock.getSuccessors(); thenBlock = getBlockByOffset(target, successors); if (successors.size() == 1) { elseBlock = thenBlock; } else { elseBlock = selectOther(thenBlock, successors); } } @Override public boolean replaceTargetBlock(BlockNode origin, BlockNode replace) { boolean replaced = false; if (thenBlock == origin) { thenBlock = replace; replaced = true; } if (elseBlock == origin) { elseBlock = replace; replaced = true; } return replaced; } public BlockNode getThenBlock() { return thenBlock; } public BlockNode getElseBlock() { return elseBlock; } @Override public int getTarget() { return thenBlock == null ? target : thenBlock.getStartOffset(); } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof IfNode) || !super.isSame(obj)) { return false; } IfNode other = (IfNode) obj; return op == other.op; } @Override public InsnNode copy() { IfNode copy = new IfNode(op, target); copy.thenBlock = thenBlock; copy.elseBlock = elseBlock; return copyCommonParams(copy); } @Override public String toString() { return InsnUtils.formatOffset(offset) + ": " + InsnUtils.insnTypeToString(insnType) + getArg(0) + ' ' + op.getSymbol() + ' ' + getArg(1) + " -> " + (thenBlock != null ? thenBlock : InsnUtils.formatOffset(target)) + attributesString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/InvokeCustomRawNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/InvokeCustomRawNode.java
package jadx.core.dex.instructions; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.annotations.EncodedValue; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.instructions.invokedynamic.CustomRawCall; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; import jadx.core.utils.Utils; /** * Information for raw invoke-custom instruction.<br> * Output will be formatted as polymorphic call with equivalent semantic * Contains two parts: * - resolve: treated as additional invoke insn (uses only constant args) * - invoke: call of resolved method (base for this invoke) * <br> * See {@link CustomRawCall} class for build details */ public class InvokeCustomRawNode extends InvokeNode { private final InvokeNode resolve; private List<EncodedValue> callSiteValues; public InvokeCustomRawNode(InvokeNode resolve, MethodInfo mthInfo, InsnData insn, boolean isRange) { super(mthInfo, insn, InvokeType.CUSTOM_RAW, false, isRange); this.resolve = resolve; } public InvokeCustomRawNode(InvokeNode resolve, MethodInfo mthInfo, InvokeType invokeType, int argsCount) { super(mthInfo, invokeType, argsCount); this.resolve = resolve; } public InvokeNode getResolveInvoke() { return resolve; } public void setCallSiteValues(List<EncodedValue> callSiteValues) { this.callSiteValues = callSiteValues; } public List<EncodedValue> getCallSiteValues() { return callSiteValues; } @Override public InsnNode copy() { InvokeCustomRawNode copy = new InvokeCustomRawNode(resolve, getCallMth(), getInvokeType(), getArgsCount()); copyCommonParams(copy); copy.setCallSiteValues(callSiteValues); return copy; } @Override public boolean isStaticCall() { return true; } @Override public int getFirstArgOffset() { return 0; } @Override public @Nullable InsnArg getInstanceArg() { return null; } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (obj instanceof InvokeCustomRawNode) { return super.isSame(obj) && resolve.isSame(((InvokeCustomRawNode) obj).resolve); } return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(InsnUtils.formatOffset(offset)).append(": INVOKE_CUSTOM "); if (getResult() != null) { sb.append(getResult()).append(" = "); } if (!appendArgs(sb)) { sb.append('\n'); } appendAttributes(sb); sb.append(" call-site: \n ").append(Utils.listToString(callSiteValues, "\n ")).append('\n'); return sb.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/FillArrayInsn.java
jadx-core/src/main/java/jadx/core/dex/instructions/FillArrayInsn.java
package jadx.core.dex.instructions; import java.util.List; import java.util.Objects; 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.nodes.InsnNode; public final class FillArrayInsn extends InsnNode { private final int target; private FillArrayData arrayData; public FillArrayInsn(InsnArg arg, int target) { super(InsnType.FILL_ARRAY, 1); this.target = target; addArg(arg); } public int getTarget() { return target; } public void setArrayData(FillArrayData arrayData) { this.arrayData = arrayData; } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof FillArrayInsn) || !super.isSame(obj)) { return false; } FillArrayInsn other = (FillArrayInsn) obj; return Objects.equals(arrayData, other.arrayData); } @Override public InsnNode copy() { FillArrayInsn copy = new FillArrayInsn(getArg(0), target); return copyCommonParams(copy); } @Override public String toString() { return super.toString() + ", data: " + arrayData; } public int getSize() { return arrayData.getSize(); } public ArgType getElementType() { return arrayData.getElementType(); } public List<LiteralArg> getLiteralArgs(ArgType elType) { return arrayData.getLiteralArgs(elType); } public String dataToString() { return Objects.toString(arrayData); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/SwitchData.java
jadx-core/src/main/java/jadx/core/dex/instructions/SwitchData.java
package jadx.core.dex.instructions; import jadx.api.plugins.input.insns.custom.ISwitchPayload; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; public class SwitchData extends InsnNode { private final int size; private final int[] keys; private final int[] targets; public SwitchData(ISwitchPayload payload) { super(InsnType.SWITCH_DATA, 0); this.size = payload.getSize(); this.keys = payload.getKeys(); this.targets = payload.getTargets(); } public void fixTargets(int switchOffset) { int size = this.size; int[] targets = this.targets; for (int i = 0; i < size; i++) { targets[i] += switchOffset; } } public int getSize() { return size; } public int[] getKeys() { return keys; } public int[] getTargets() { return targets; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("switch-data {"); for (int i = 0; i < size; i++) { sb.append(keys[i]).append("->").append(InsnUtils.formatOffset(targets[i])).append(", "); } sb.append('}'); appendAttributes(sb); return sb.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/SwitchInsn.java
jadx-core/src/main/java/jadx/core/dex/instructions/SwitchInsn.java
package jadx.core.dex.instructions; import java.util.List; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.utils.BlockUtils.getBlockByOffset; public class SwitchInsn extends TargetInsnNode { private final int dataTarget; private final boolean packed; // type of switch insn, if true can contain filler keys @Nullable private SwitchData switchData; private int def; // next instruction private Object[] modifiedKeys; private BlockNode[] targetBlocks; private BlockNode defTargetBlock; public SwitchInsn(InsnArg arg, int dataTarget, boolean packed) { super(InsnType.SWITCH, 1); addArg(arg); this.dataTarget = dataTarget; this.packed = packed; } public boolean needData() { return this.switchData == null; } public void attachSwitchData(SwitchData data, int def) { this.switchData = data; this.def = def; } @Override public void initBlocks(BlockNode curBlock) { if (switchData == null) { throw new JadxRuntimeException("Switch data not yet attached"); } List<BlockNode> successors = curBlock.getSuccessors(); int[] targets = switchData.getTargets(); int len = targets.length; targetBlocks = new BlockNode[len]; for (int i = 0; i < len; i++) { targetBlocks[i] = getBlockByOffset(targets[i], successors); } defTargetBlock = getBlockByOffset(def, successors); } @Override public boolean replaceTargetBlock(BlockNode origin, BlockNode replace) { if (targetBlocks == null) { return false; } int count = 0; int len = targetBlocks.length; for (int i = 0; i < len; i++) { if (targetBlocks[i] == origin) { targetBlocks[i] = replace; count++; } } if (defTargetBlock == origin) { defTargetBlock = replace; count++; } return count > 0; } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof SwitchInsn) || !super.isSame(obj)) { return false; } SwitchInsn other = (SwitchInsn) obj; return dataTarget == other.dataTarget && packed == other.packed; } @Override public InsnNode copy() { SwitchInsn copy = new SwitchInsn(getArg(0), dataTarget, packed); copy.switchData = switchData; copy.def = def; copy.targetBlocks = targetBlocks; copy.defTargetBlock = defTargetBlock; return copyCommonParams(copy); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(baseString()); if (switchData == null) { sb.append("no payload"); } else { int size = switchData.getSize(); int[] keys = switchData.getKeys(); if (targetBlocks != null) { for (int i = 0; i < size; i++) { sb.append('\n'); sb.append(" case ").append(keys[i]).append(": goto ").append(targetBlocks[i]); } if (def != -1) { sb.append('\n').append(" default: goto ").append(defTargetBlock); } } else { int[] targets = switchData.getTargets(); for (int i = 0; i < size; i++) { sb.append('\n'); sb.append(" case ").append(keys[i]).append(": goto ").append(InsnUtils.formatOffset(targets[i])); } if (def != -1) { sb.append('\n'); sb.append(" default: goto ").append(InsnUtils.formatOffset(def)); } } } appendAttributes(sb); return sb.toString(); } public int getDataTarget() { return dataTarget; } public boolean isPacked() { return packed; } public int getDefaultCaseOffset() { return def; } @NotNull private SwitchData getSwitchData() { if (switchData == null) { throw new JadxRuntimeException("Switch data not yet attached"); } return switchData; } public int[] getTargets() { return getSwitchData().getTargets(); } public int[] getKeys() { return getSwitchData().getKeys(); } public Object getKey(int i) { if (modifiedKeys != null) { return modifiedKeys[i]; } return getSwitchData().getKeys()[i]; } public void modifyKey(int i, Object newKey) { if (modifiedKeys == null) { int[] keys = getKeys(); int caseCount = keys.length; Object[] newKeys = new Object[caseCount]; for (int j = 0; j < caseCount; j++) { newKeys[j] = keys[j]; } modifiedKeys = newKeys; } modifiedKeys[i] = newKey; } public BlockNode[] getTargetBlocks() { return targetBlocks; } public BlockNode getDefTargetBlock() { return defTargetBlock; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/PhiInsn.java
jadx-core/src/main/java/jadx/core/dex/instructions/PhiInsn.java
package jadx.core.dex.instructions; import java.util.ArrayList; import java.util.List; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.instructions.args.SSAVar; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnRemover; import jadx.core.utils.exceptions.JadxRuntimeException; public final class PhiInsn extends InsnNode { // map arguments to blocks (in same order as in arguments list) private final List<BlockNode> blockBinds; public PhiInsn(int regNum, int predecessors) { this(predecessors); setResult(InsnArg.reg(regNum, ArgType.UNKNOWN)); add(AFlag.DONT_INLINE); add(AFlag.DONT_GENERATE); } private PhiInsn(int argsCount) { super(InsnType.PHI, argsCount); this.blockBinds = new ArrayList<>(argsCount); } public RegisterArg bindArg(BlockNode pred) { RegisterArg arg = InsnArg.reg(getResult().getRegNum(), getResult().getInitType()); bindArg(arg, pred); return arg; } public void bindArg(RegisterArg arg, BlockNode pred) { if (blockBinds.contains(pred)) { throw new JadxRuntimeException("Duplicate predecessors in PHI insn: " + pred + ", " + this); } if (pred == null) { throw new JadxRuntimeException("Null bind block in PHI insn: " + this); } super.addArg(arg); blockBinds.add(pred); } @Nullable public BlockNode getBlockByArg(RegisterArg arg) { int index = getArgIndex(arg); if (index == -1) { return null; } return blockBinds.get(index); } public BlockNode getBlockByArgIndex(int argIndex) { return blockBinds.get(argIndex); } @Override @NotNull public RegisterArg getArg(int n) { return (RegisterArg) super.getArg(n); } @Override public boolean removeArg(InsnArg arg) { int index = getArgIndex(arg); if (index == -1) { return false; } removeArg(index); return true; } @Override public RegisterArg removeArg(int index) { RegisterArg reg = (RegisterArg) super.removeArg(index); blockBinds.remove(index); reg.getSVar().updateUsedInPhiList(); return reg; } @Nullable public RegisterArg getArgBySsaVar(SSAVar ssaVar) { if (getArgsCount() == 0) { return null; } for (InsnArg insnArg : getArguments()) { RegisterArg reg = (RegisterArg) insnArg; if (reg.getSVar() == ssaVar) { return reg; } } return null; } @Override public boolean replaceArg(InsnArg from, InsnArg to) { if (!(from instanceof RegisterArg) || !(to instanceof RegisterArg)) { return false; } int argIndex = getArgIndex(from); if (argIndex == -1) { return false; } ((RegisterArg) to).getSVar().addUsedInPhi(this); super.setArg(argIndex, to); InsnRemover.unbindArgUsage(null, from); ((RegisterArg) from).getSVar().updateUsedInPhiList(); return true; } @Override public void addArg(InsnArg arg) { throw new JadxRuntimeException("Direct addArg is forbidden for PHI insn, bindArg must be used"); } @Override public void setArg(int n, InsnArg arg) { throw new JadxRuntimeException("Direct setArg is forbidden for PHI insn, bindArg must be used"); } @Override public InsnNode copy() { return copyCommonParams(new PhiInsn(getArgsCount())); } @Override public String toString() { return baseString() + " binds: " + blockBinds + attributesString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/ArithNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/ArithNode.java
package jadx.core.dex.instructions; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.instructions.args.LiteralArg; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; import jadx.core.utils.exceptions.JadxRuntimeException; public class ArithNode extends InsnNode { public static ArithNode build(InsnData insn, ArithOp op, ArgType type) { RegisterArg resArg = InsnArg.reg(insn, 0, fixResultType(op, type)); ArgType argType = fixArgType(op, type); switch (insn.getRegsCount()) { case 2: return new ArithNode(op, resArg, InsnArg.reg(insn, 0, argType), InsnArg.reg(insn, 1, argType)); case 3: return new ArithNode(op, resArg, InsnArg.reg(insn, 1, argType), InsnArg.reg(insn, 2, argType)); default: throw new JadxRuntimeException("Unexpected registers count in " + insn); } } public static ArithNode buildLit(InsnData insn, ArithOp op, ArgType type) { RegisterArg resArg = InsnArg.reg(insn, 0, fixResultType(op, type)); ArgType argType = fixArgType(op, type); LiteralArg litArg = InsnArg.lit(insn, argType); switch (insn.getRegsCount()) { case 1: return new ArithNode(op, resArg, InsnArg.reg(insn, 0, argType), litArg); case 2: return new ArithNode(op, resArg, InsnArg.reg(insn, 1, argType), litArg); default: throw new JadxRuntimeException("Unexpected registers count in " + insn); } } private static ArgType fixResultType(ArithOp op, ArgType type) { if (type == ArgType.INT && op.isBitOp()) { return ArgType.INT_BOOLEAN; } return type; } private static ArgType fixArgType(ArithOp op, ArgType type) { if (type == ArgType.INT && op.isBitOp()) { return ArgType.NARROW_NUMBERS_NO_FLOAT; } return type; } private final ArithOp op; public ArithNode(ArithOp op, @Nullable RegisterArg res, InsnArg a, InsnArg b) { super(InsnType.ARITH, 2); this.op = op; setResult(res); addArg(a); addArg(b); } /** * Create one argument arithmetic instructions (a+=2). * Result is not set (null). * * @param res argument to change */ public static ArithNode oneArgOp(ArithOp op, InsnArg res, InsnArg a) { ArithNode insn = new ArithNode(op, null, res, a); insn.add(AFlag.ARITH_ONEARG); return insn; } public ArithOp getOp() { return op; } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof ArithNode) || !super.isSame(obj)) { return false; } ArithNode other = (ArithNode) obj; return op == other.op && isSameLiteral(other); } private boolean isSameLiteral(ArithNode other) { InsnArg thisSecond = getArg(1); InsnArg otherSecond = other.getArg(1); if (thisSecond.isLiteral() != otherSecond.isLiteral()) { return false; } if (!thisSecond.isLiteral()) { // both not literals return true; } // both literals long thisLit = ((LiteralArg) thisSecond).getLiteral(); long otherLit = ((LiteralArg) otherSecond).getLiteral(); return thisLit == otherLit; } @Override public InsnNode copy() { ArithNode copy = new ArithNode(op, null, getArg(0).duplicate(), getArg(1).duplicate()); return copyCommonParams(copy); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(InsnUtils.formatOffset(offset)); sb.append(": ARITH "); if (contains(AFlag.ARITH_ONEARG)) { sb.append(getArg(0)).append(' ').append(op.getSymbol()).append("= ").append(getArg(1)); } else { RegisterArg result = getResult(); if (result != null) { sb.append(result).append(" = "); } sb.append(getArg(0)).append(' ').append(op.getSymbol()).append(' ').append(getArg(1)); } appendAttributes(sb); return sb.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/IndexInsnNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/IndexInsnNode.java
package jadx.core.dex.instructions; import java.util.Objects; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; import jadx.core.utils.Utils; public class IndexInsnNode extends InsnNode { private Object index; public IndexInsnNode(InsnType type, Object index, int argCount) { super(type, argCount); this.index = index; } public Object getIndex() { return index; } public void updateIndex(Object index) { this.index = index; } public ArgType getIndexAsType() { return (ArgType) index; } @Override public IndexInsnNode copy() { return copyCommonParams(new IndexInsnNode(insnType, index, getArgsCount())); } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof IndexInsnNode) || !super.isSame(obj)) { return false; } IndexInsnNode other = (IndexInsnNode) obj; return Objects.equals(index, other.index); } @Override public String toString() { switch (insnType) { case CAST: case CHECK_CAST: StringBuilder sb = new StringBuilder(); sb.append(InsnUtils.formatOffset(offset)).append(": "); sb.append(insnType).append(' '); if (getResult() != null) { sb.append(getResult()).append(" = "); } sb.append('(').append(InsnUtils.indexToString(index)).append(") "); sb.append(Utils.listToString(getArguments())); return sb.toString(); default: return super.toString() + ' ' + InsnUtils.indexToString(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/dex/instructions/FilledNewArrayNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/FilledNewArrayNode.java
package jadx.core.dex.instructions; import org.jetbrains.annotations.NotNull; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.InsnNode; public class FilledNewArrayNode extends InsnNode { private final ArgType elemType; public FilledNewArrayNode(@NotNull ArgType elemType, int size) { super(InsnType.FILLED_NEW_ARRAY, size); this.elemType = elemType; } public ArgType getElemType() { return elemType; } public ArgType getArrayType() { return ArgType.array(elemType); } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof FilledNewArrayNode) || !super.isSame(obj)) { return false; } FilledNewArrayNode other = (FilledNewArrayNode) obj; return elemType == other.elemType; } @Override public InsnNode copy() { return copyCommonParams(new FilledNewArrayNode(elemType, getArgsCount())); } @Override public String toString() { return super.toString() + " elemType: " + elemType; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/invokedynamic/CustomStringConcat.java
jadx-core/src/main/java/jadx/core/dex/instructions/invokedynamic/CustomStringConcat.java
package jadx.core.dex.instructions.invokedynamic; import java.util.List; import java.util.Objects; import jadx.api.plugins.input.data.IMethodHandle; import jadx.api.plugins.input.data.IMethodRef; import jadx.api.plugins.input.data.MethodHandleType; 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.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.JadxError; import jadx.core.dex.instructions.ConstClassNode; import jadx.core.dex.instructions.ConstStringNode; 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.LiteralArg; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.EncodedValueUtils; import jadx.core.utils.exceptions.JadxRuntimeException; public class CustomStringConcat { public static boolean isStringConcat(List<EncodedValue> values) { if (values.size() < 4) { return false; } IMethodHandle methodHandle = (IMethodHandle) values.get(0).getValue(); if (methodHandle.getType() != MethodHandleType.INVOKE_STATIC) { return false; } IMethodRef methodRef = methodHandle.getMethodRef(); if (!methodRef.getName().equals("makeConcatWithConstants")) { return false; } if (!methodRef.getParentClassType().equals("Ljava/lang/invoke/StringConcatFactory;")) { return false; } if (!Objects.equals(values.get(1).getValue(), "makeConcatWithConstants")) { return false; } if (values.get(3).getType() != EncodedType.ENCODED_STRING) { return false; } return true; } public static InsnNode buildStringConcat(InsnData insn, boolean isRange, List<EncodedValue> values) { try { int argsCount = values.size() - 3 + insn.getRegsCount(); InsnNode concat = new InsnNode(InsnType.STR_CONCAT, argsCount); String recipe = (String) values.get(3).getValue(); processRecipe(recipe, concat, values, insn); int resReg = insn.getResultReg(); if (resReg != -1) { concat.setResult(InsnArg.reg(resReg, ArgType.STRING)); } return concat; } catch (Exception e) { InsnNode nop = new InsnNode(InsnType.NOP, 0); nop.add(AFlag.SYNTHETIC); nop.addAttr(AType.JADX_ERROR, new JadxError("Failed to process dynamic string concat: " + e.getMessage(), e)); return nop; } } private static void processRecipe(String recipe, InsnNode concat, List<EncodedValue> values, InsnData insn) { int len = recipe.length(); int offset = 0; int argNum = 0; int constNum = 4; StringBuilder sb = new StringBuilder(len); while (offset < len) { int cp = recipe.codePointAt(offset); offset += Character.charCount(cp); boolean argTag = cp == 1; boolean constTag = cp == 2; if (argTag || constTag) { if (sb.length() != 0) { concat.addArg(InsnArg.wrapArg(new ConstStringNode(sb.toString()))); sb.setLength(0); } if (argTag) { concat.addArg(InsnArg.reg(insn, argNum++, ArgType.UNKNOWN)); } else { InsnArg constArg = buildInsnArgFromEncodedValue(values.get(constNum++)); concat.addArg(constArg); } } else { sb.appendCodePoint(cp); } } if (sb.length() != 0) { concat.addArg(InsnArg.wrapArg(new ConstStringNode(sb.toString()))); } } private static InsnArg buildInsnArgFromEncodedValue(EncodedValue encodedValue) { Object value = EncodedValueUtils.convertToConstValue(encodedValue); if (value == null) { return InsnArg.lit(0, ArgType.UNKNOWN); } if (value instanceof LiteralArg) { return ((LiteralArg) value); } if (value instanceof ArgType) { return InsnArg.wrapArg(new ConstClassNode((ArgType) value)); } if (value instanceof String) { return InsnArg.wrapArg(new ConstStringNode(((String) value))); } throw new JadxRuntimeException("Can't build insn arg from encoded value: " + encodedValue); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/invokedynamic/InvokeCustomUtils.java
jadx-core/src/main/java/jadx/core/dex/instructions/invokedynamic/InvokeCustomUtils.java
package jadx.core.dex.instructions.invokedynamic; import jadx.api.plugins.input.data.MethodHandleType; import jadx.core.dex.instructions.InvokeType; import jadx.core.utils.exceptions.JadxRuntimeException; public class InvokeCustomUtils { public static InvokeType convertInvokeType(MethodHandleType type) { switch (type) { case INVOKE_STATIC: return InvokeType.STATIC; case INVOKE_INSTANCE: return InvokeType.VIRTUAL; case INVOKE_DIRECT: case INVOKE_CONSTRUCTOR: return InvokeType.DIRECT; case INVOKE_INTERFACE: return InvokeType.INTERFACE; default: throw new JadxRuntimeException("Unsupported method handle type: " + type); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/invokedynamic/CustomLambdaCall.java
jadx-core/src/main/java/jadx/core/dex/instructions/invokedynamic/CustomLambdaCall.java
package jadx.core.dex.instructions.invokedynamic; import java.util.List; import org.jetbrains.annotations.NotNull; 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.EncodedType; import jadx.api.plugins.input.data.annotations.EncodedValue; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.InvokeCustomNode; 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.NamedArg; import jadx.core.dex.instructions.mods.ConstructorInsn; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; public class CustomLambdaCall { /** * Expect LambdaMetafactory.metafactory method */ public static boolean isLambdaInvoke(List<EncodedValue> values) { if (values.size() < 6) { return false; } EncodedValue mthRef = values.get(0); if (mthRef.getType() != EncodedType.ENCODED_METHOD_HANDLE) { return false; } IMethodHandle methodHandle = (IMethodHandle) mthRef.getValue(); if (methodHandle.getType() != MethodHandleType.INVOKE_STATIC) { return false; } IMethodRef methodRef = methodHandle.getMethodRef(); if (!methodRef.getParentClassType().equals("Ljava/lang/invoke/LambdaMetafactory;")) { return false; } String mthName = methodRef.getName(); return mthName.equals("metafactory") || mthName.equals("altMetafactory"); } public static InvokeCustomNode buildLambdaMethodCall(MethodNode mth, InsnData insn, boolean isRange, List<EncodedValue> values) { IMethodHandle callMthHandle = (IMethodHandle) values.get(4).getValue(); if (callMthHandle.getType().isField()) { throw new JadxRuntimeException("Not yet supported"); } InvokeCustomNode resNode = buildMethodCall(mth, insn, isRange, values, callMthHandle); int resReg = insn.getResultReg(); if (resReg != -1) { resNode.setResult(InsnArg.reg(resReg, mth.getReturnType())); } return resNode; } @NotNull private static InvokeCustomNode buildMethodCall(MethodNode mth, InsnData insn, boolean isRange, List<EncodedValue> values, IMethodHandle callMthHandle) { RootNode root = mth.root(); IMethodProto lambdaProto = (IMethodProto) values.get(2).getValue(); MethodInfo lambdaInfo = MethodInfo.fromMethodProto(root, mth.getParentClass().getClassInfo(), "", lambdaProto); MethodHandleType methodHandleType = callMthHandle.getType(); InvokeCustomNode invokeCustomNode = new InvokeCustomNode(lambdaInfo, insn, false, isRange); invokeCustomNode.setHandleType(methodHandleType); ClassInfo implCls = ClassInfo.fromType(root, lambdaInfo.getReturnType()); String implName = (String) values.get(1).getValue(); IMethodProto implProto = (IMethodProto) values.get(3).getValue(); MethodInfo implMthInfo = MethodInfo.fromMethodProto(root, implCls, implName, implProto); invokeCustomNode.setImplMthInfo(implMthInfo); MethodInfo callMthInfo = MethodInfo.fromRef(root, callMthHandle.getMethodRef()); InvokeNode invokeNode = buildInvokeNode(methodHandleType, invokeCustomNode, callMthInfo); if (methodHandleType == MethodHandleType.INVOKE_CONSTRUCTOR) { ConstructorInsn ctrInsn = new ConstructorInsn(mth, invokeNode); invokeCustomNode.setCallInsn(ctrInsn); } else { invokeCustomNode.setCallInsn(invokeNode); } MethodNode callMth = root.resolveMethod(callMthInfo); if (callMth != null) { invokeCustomNode.getCallInsn().addAttr(callMth); if (callMth.getAccessFlags().isSynthetic() && callMth.getParentClass().equals(mth.getParentClass())) { // inline only synthetic methods from same class callMth.add(AFlag.DONT_GENERATE); invokeCustomNode.setInlineInsn(true); } } if (!invokeCustomNode.isInlineInsn()) { IMethodProto effectiveMthProto = (IMethodProto) values.get(5).getValue(); List<ArgType> args = Utils.collectionMap(effectiveMthProto.getArgTypes(), ArgType::parse); boolean sameArgs = args.equals(callMthInfo.getArgumentsTypes()); invokeCustomNode.setUseRef(sameArgs); } // prevent args inlining into not generated invoke custom node for (InsnArg arg : invokeCustomNode.getArguments()) { arg.add(AFlag.DONT_INLINE); } return invokeCustomNode; } @NotNull private static InvokeNode buildInvokeNode(MethodHandleType methodHandleType, InvokeCustomNode invokeCustomNode, MethodInfo callMthInfo) { InvokeType invokeType = InvokeCustomUtils.convertInvokeType(methodHandleType); int callArgsCount = callMthInfo.getArgsCount(); boolean instanceCall = invokeType != InvokeType.STATIC; if (instanceCall) { callArgsCount++; } InvokeNode invokeNode = new InvokeNode(callMthInfo, invokeType, callArgsCount); // copy insn args int argsCount = invokeCustomNode.getArgsCount(); for (int i = 0; i < argsCount; i++) { InsnArg arg = invokeCustomNode.getArg(i); invokeNode.addArg(arg.duplicate()); } if (callArgsCount > argsCount) { // fill remaining args with NamedArg int callArgNum = argsCount; if (instanceCall) { callArgNum--; // start from instance type } List<ArgType> callArgTypes = callMthInfo.getArgumentsTypes(); for (int i = argsCount; i < callArgsCount; i++) { ArgType argType; if (callArgNum < 0) { // instance arg type argType = callMthInfo.getDeclClass().getType(); } else { argType = callArgTypes.get(callArgNum++); } invokeNode.addArg(new NamedArg("v" + i, argType)); } } return invokeNode; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/invokedynamic/CustomRawCall.java
jadx-core/src/main/java/jadx/core/dex/instructions/invokedynamic/CustomRawCall.java
package jadx.core.dex.instructions.invokedynamic; import java.util.ArrayList; import java.util.List; import jadx.api.plugins.input.data.IMethodHandle; import jadx.api.plugins.input.data.IMethodProto; import jadx.api.plugins.input.data.annotations.EncodedValue; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.ConstStringNode; import jadx.core.dex.instructions.InvokeCustomRawNode; 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.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.utils.EncodedValueUtils.buildLookupArg; import static jadx.core.utils.EncodedValueUtils.convertToInsnArg; /** * Show `invoke-custom` similar to polymorphic call */ public class CustomRawCall { public static InsnNode build(MethodNode mth, InsnData insn, boolean isRange, List<EncodedValue> values) { IMethodHandle resolveHandle = (IMethodHandle) values.get(0).getValue(); String invokeName = (String) values.get(1).getValue(); IMethodProto invokeProto = (IMethodProto) values.get(2).getValue(); List<InsnArg> resolveArgs = buildArgs(mth, values); if (resolveHandle.getType().isField()) { throw new JadxRuntimeException("Field handle not yet supported"); } RootNode root = mth.root(); MethodInfo resolveMth = MethodInfo.fromRef(root, resolveHandle.getMethodRef()); InvokeType resolveInvokeType = InvokeCustomUtils.convertInvokeType(resolveHandle.getType()); InvokeNode resolve = new InvokeNode(resolveMth, resolveInvokeType, resolveArgs.size()); resolveArgs.forEach(resolve::addArg); ClassInfo invokeCls = ClassInfo.fromType(root, ArgType.OBJECT); // type will be known at runtime MethodInfo invokeMth = MethodInfo.fromMethodProto(root, invokeCls, invokeName, invokeProto); InvokeCustomRawNode customRawNode = new InvokeCustomRawNode(resolve, invokeMth, insn, isRange); customRawNode.setCallSiteValues(values); return customRawNode; } private static List<InsnArg> buildArgs(MethodNode mth, List<EncodedValue> values) { int valuesCount = values.size(); List<InsnArg> list = new ArrayList<>(valuesCount); RootNode root = mth.root(); list.add(buildLookupArg(root)); // use `java.lang.invoke.MethodHandles.lookup()` as first arg for (int i = 1; i < valuesCount; i++) { EncodedValue value = values.get(i); try { list.add(convertToInsnArg(root, value)); } catch (Exception e) { mth.addWarnComment("Failed to build arg in invoke-custom insn: " + value, e); list.add(InsnArg.wrapArg(new ConstStringNode(value.toString()))); } } return list; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/java/JsrNode.java
jadx-core/src/main/java/jadx/core/dex/instructions/java/JsrNode.java
package jadx.core.dex.instructions.java; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.TargetInsnNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; public class JsrNode extends TargetInsnNode { protected final int target; public JsrNode(int target) { this(InsnType.JAVA_JSR, target, 0); } protected JsrNode(InsnType type, int target, int argsCount) { super(type, argsCount); this.target = target; } public int getTarget() { return target; } @Override public InsnNode copy() { return copyCommonParams(new JsrNode(target)); } @Override public String toString() { return baseString() + " -> " + InsnUtils.formatOffset(target) + attributesString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/mods/ConstructorInsn.java
jadx-core/src/main/java/jadx/core/dex/instructions/mods/ConstructorInsn.java
package jadx.core.dex.instructions.mods; import org.jetbrains.annotations.Nullable; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.BaseInvokeNode; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.InvokeNode; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; public final class ConstructorInsn extends BaseInvokeNode { private final MethodInfo callMth; private final CallType callType; public enum CallType { CONSTRUCTOR, // just new instance SUPER, // super call THIS, // call constructor from other constructor SELF // call itself } public ConstructorInsn(MethodNode mth, InvokeNode invoke) { this(mth, invoke, invoke.getCallMth()); } public ConstructorInsn(MethodNode mth, InvokeNode invoke, MethodInfo callMth) { super(InsnType.CONSTRUCTOR, invoke.getArgsCount() - 1); this.callMth = callMth; this.callType = getCallType(mth, callMth.getDeclClass(), invoke.getArg(0)); int argsCount = invoke.getArgsCount(); for (int i = 1; i < argsCount; i++) { addArg(invoke.getArg(i)); } } private CallType getCallType(MethodNode mth, ClassInfo classType, InsnArg instanceArg) { if (!instanceArg.isThis()) { return CallType.CONSTRUCTOR; } if (!classType.equals(mth.getParentClass().getClassInfo())) { return CallType.SUPER; } if (callMth.getShortId().equals(mth.getMethodInfo().getShortId())) { // self constructor return CallType.SELF; } return CallType.THIS; } public ConstructorInsn(MethodInfo callMth, CallType callType) { super(InsnType.CONSTRUCTOR, callMth.getArgsCount()); this.callMth = callMth; this.callType = callType; } @Override public MethodInfo getCallMth() { return callMth; } @Override @Nullable public RegisterArg getInstanceArg() { return null; } public ClassInfo getClassType() { return callMth.getDeclClass(); } public CallType getCallType() { return callType; } public boolean isNewInstance() { return callType == CallType.CONSTRUCTOR; } public boolean isSuper() { return callType == CallType.SUPER; } public boolean isThis() { return callType == CallType.THIS; } public boolean isSelf() { return callType == CallType.SELF; } @Override public boolean isStaticCall() { return false; } @Override public int getFirstArgOffset() { return 0; } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof ConstructorInsn) || !super.isSame(obj)) { return false; } ConstructorInsn other = (ConstructorInsn) obj; return callMth.equals(other.callMth) && callType == other.callType; } @Override public InsnNode copy() { return copyCommonParams(new ConstructorInsn(callMth, callType)); } @Override public String toString() { return super.toString() + " call: " + callMth + " type: " + callType; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/mods/TernaryInsn.java
jadx-core/src/main/java/jadx/core/dex/instructions/mods/TernaryInsn.java
package jadx.core.dex.instructions.mods; import java.util.Collection; import java.util.function.Consumer; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.regions.conditions.IfCondition; import jadx.core.utils.InsnUtils; public final class TernaryInsn extends InsnNode { private IfCondition condition; public TernaryInsn(IfCondition condition, RegisterArg result, InsnArg th, InsnArg els) { this(); setResult(result); if (th.isFalse() && els.isTrue()) { // inverted this.condition = IfCondition.invert(condition); addArg(els); addArg(th); } else { this.condition = condition; addArg(th); addArg(els); } visitInsns(this::inheritMetadata); } private TernaryInsn() { super(InsnType.TERNARY, 2); } public IfCondition getCondition() { return condition; } public void simplifyCondition() { condition = IfCondition.simplify(condition); if (condition.getMode() == IfCondition.Mode.NOT) { invert(); } } private void invert() { condition = IfCondition.invert(condition); InsnArg tmp = getArg(0); setArg(0, getArg(1)); setArg(1, tmp); } @Override public void getRegisterArgs(Collection<RegisterArg> list) { super.getRegisterArgs(list); list.addAll(condition.getRegisterArgs()); } @Override public boolean replaceArg(InsnArg from, InsnArg to) { if (super.replaceArg(from, to)) { return true; } return condition.replaceArg(from, to); } public void visitInsns(Consumer<InsnNode> visitor) { super.visitInsns(visitor); condition.visitInsns(visitor); } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof TernaryInsn) || !super.isSame(obj)) { return false; } TernaryInsn that = (TernaryInsn) obj; return condition.equals(that.condition); } @Override public InsnNode copy() { TernaryInsn copy = new TernaryInsn(); copy.condition = condition; return copyCommonParams(copy); } @Override public void rebindArgs() { super.rebindArgs(); for (RegisterArg reg : condition.getRegisterArgs()) { InsnNode parentInsn = reg.getParentInsn(); if (parentInsn != null) { parentInsn.rebindArgs(); } } } @Override public String toString() { return InsnUtils.formatOffset(offset) + ": TERNARY " + getResult() + " = (" + condition + ") ? " + getArg(0) + " : " + getArg(1); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/VarName.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/VarName.java
package jadx.core.dex.instructions.args; public class VarName { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return name; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/SSAVar.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/SSAVar.java
package jadx.core.dex.instructions.args; 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.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.Consts; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.nodes.RegDebugInfoAttr; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.PhiInsn; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.visitors.typeinference.TypeInfo; import jadx.core.utils.StringUtils; import jadx.core.utils.exceptions.JadxRuntimeException; public class SSAVar implements Comparable<SSAVar> { private static final Logger LOG = LoggerFactory.getLogger(SSAVar.class); private static final Comparator<SSAVar> SSA_VAR_COMPARATOR = Comparator.comparingInt(SSAVar::getRegNum).thenComparingInt(SSAVar::getVersion); private final int regNum; private final int version; private RegisterArg assign; private final List<RegisterArg> useList = new ArrayList<>(2); private List<PhiInsn> usedInPhi = null; private final TypeInfo typeInfo = new TypeInfo(); @Nullable("Set in InitCodeVariables pass") private CodeVar codeVar; public SSAVar(int regNum, int v, @NotNull RegisterArg assign) { this.regNum = regNum; this.version = v; this.assign = assign; assign.setSVar(this); } public int getRegNum() { return regNum; } public int getVersion() { return version; } public @NotNull RegisterArg getAssign() { return assign; } public @Nullable InsnNode getAssignInsn() { return assign.getParentInsn(); } public void setAssign(@NotNull RegisterArg assign) { RegisterArg oldAssign = this.assign; if (oldAssign == null) { this.assign = assign; } else if (oldAssign != assign) { oldAssign.resetSSAVar(); this.assign = assign; } } public List<RegisterArg> getUseList() { return useList; } public int getUseCount() { return useList.size(); } @Nullable public ArgType getImmutableType() { if (isTypeImmutable()) { return assign.getInitType(); } return null; } public boolean isTypeImmutable() { return assign.contains(AFlag.IMMUTABLE_TYPE); } public void markAsImmutable(ArgType type) { assign.add(AFlag.IMMUTABLE_TYPE); ArgType initType = assign.getInitType(); if (!initType.equals(type)) { assign.forceSetInitType(type); if (Consts.DEBUG_TYPE_INFERENCE) { LOG.debug("Update immutable type at var {} assign with type: {} previous type: {}", this.toShortString(), type, initType); } } } public void setType(ArgType type) { ArgType imType = getImmutableType(); if (imType != null && !imType.equals(type)) { throw new JadxRuntimeException("Can't change immutable type " + imType + " to " + type + " for " + this); } updateType(type); } public void forceSetType(ArgType type) { updateType(type); } private void updateType(ArgType type) { typeInfo.setType(type); if (codeVar != null) { codeVar.setType(type); } } public void use(RegisterArg arg) { if (arg.getSVar() != null) { arg.getSVar().removeUse(arg); } arg.setSVar(this); useList.add(arg); } public void removeUse(RegisterArg arg) { useList.removeIf(registerArg -> registerArg == arg); } public void addUsedInPhi(PhiInsn phiInsn) { if (usedInPhi == null) { usedInPhi = new ArrayList<>(1); } usedInPhi.add(phiInsn); } public void removeUsedInPhi(PhiInsn phiInsn) { if (usedInPhi != null) { usedInPhi.removeIf(insn -> insn == phiInsn); if (usedInPhi.isEmpty()) { usedInPhi = null; } } } public void updateUsedInPhiList() { this.usedInPhi = null; for (RegisterArg reg : useList) { InsnNode parentInsn = reg.getParentInsn(); if (parentInsn != null && parentInsn.getType() == InsnType.PHI) { addUsedInPhi((PhiInsn) parentInsn); } } } @Nullable public PhiInsn getOnlyOneUseInPhi() { if (usedInPhi != null && usedInPhi.size() == 1) { return usedInPhi.get(0); } return null; } public List<PhiInsn> getUsedInPhi() { if (usedInPhi == null) { return Collections.emptyList(); } return usedInPhi; } /** * Concat assign PHI insn and usedInPhi */ public List<PhiInsn> getPhiList() { InsnNode assignInsn = getAssign().getParentInsn(); if (assignInsn != null && assignInsn.getType() == InsnType.PHI) { PhiInsn assignPhi = (PhiInsn) assignInsn; if (usedInPhi == null) { return Collections.singletonList(assignPhi); } List<PhiInsn> list = new ArrayList<>(1 + usedInPhi.size()); list.add(assignPhi); list.addAll(usedInPhi); return list; } if (usedInPhi == null) { return Collections.emptyList(); } return usedInPhi; } public boolean isAssignInPhi() { InsnNode assignInsn = getAssignInsn(); return assignInsn != null && assignInsn.getType() == InsnType.PHI; } public boolean isUsedInPhi() { return usedInPhi != null && !usedInPhi.isEmpty(); } public void setName(String name) { if (name != null) { if (codeVar == null) { throw new JadxRuntimeException("CodeVar not initialized for name set in SSAVar: " + this); } codeVar.setName(name); } } public String getName() { if (codeVar == null) { return null; } return codeVar.getName(); } public TypeInfo getTypeInfo() { return typeInfo; } @NotNull public CodeVar getCodeVar() { if (codeVar == null) { throw new JadxRuntimeException("Code variable not set in " + this); } return codeVar; } public void setCodeVar(@NotNull CodeVar codeVar) { this.codeVar = codeVar; codeVar.addSsaVar(this); ArgType imType = getImmutableType(); if (imType != null) { codeVar.setType(imType); } } public void resetTypeAndCodeVar() { if (!isTypeImmutable()) { updateType(ArgType.UNKNOWN); } this.typeInfo.getBounds().clear(); this.codeVar = null; } public boolean isCodeVarSet() { return codeVar != null; } public String getDetailedVarInfo(MethodNode mth) { Set<ArgType> types = new HashSet<>(); Set<String> names = Collections.emptySet(); List<RegisterArg> useArgs = new ArrayList<>(1 + useList.size()); useArgs.add(assign); useArgs.addAll(useList); if (mth.contains(AType.LOCAL_VARS_DEBUG_INFO)) { names = new HashSet<>(); for (RegisterArg arg : useArgs) { RegDebugInfoAttr debugInfoAttr = arg.get(AType.REG_DEBUG_INFO); if (debugInfoAttr != null) { names.add(debugInfoAttr.getName()); types.add(debugInfoAttr.getRegType()); } } } for (RegisterArg arg : useArgs) { ArgType initType = arg.getInitType(); if (initType.isTypeKnown()) { types.add(initType); } ArgType type = arg.getType(); if (type.isTypeKnown()) { types.add(type); } } StringBuilder sb = new StringBuilder(); sb.append('r').append(regNum).append('v').append(version); if (!names.isEmpty()) { String orderedNames = names.stream() .sorted() .collect(Collectors.joining(", ", "[", "]")); sb.append(", names: ").append(orderedNames); } if (!types.isEmpty()) { String orderedTypes = types.stream() .map(String::valueOf) .sorted() .collect(Collectors.joining(", ", "[", "]")); sb.append(", types: ").append(orderedTypes); } return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof SSAVar)) { return false; } SSAVar ssaVar = (SSAVar) o; return regNum == ssaVar.regNum && version == ssaVar.version; } @Override public int hashCode() { return 31 * regNum + version; } @Override public int compareTo(@NotNull SSAVar o) { return SSA_VAR_COMPARATOR.compare(this, o); } public String toShortString() { return "r" + regNum + 'v' + version; } @Override public String toString() { return toShortString() + (StringUtils.notEmpty(getName()) ? " '" + getName() + "' " : "") + ' ' + typeInfo.getType(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/InsnArg.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/InsnArg.java
package jadx.core.dex.instructions.args; import java.util.Objects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.plugins.input.insns.InsnData; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.InsnRemover; import jadx.core.utils.InsnUtils; import jadx.core.utils.exceptions.JadxRuntimeException; /** * Instruction argument. * Can be: register, literal, instruction or name */ public abstract class InsnArg extends Typed { private static final Logger LOG = LoggerFactory.getLogger(InsnArg.class); @Nullable("Null for method arguments") protected InsnNode parentInsn; public static RegisterArg reg(int regNum, ArgType type) { return new RegisterArg(regNum, type); } public static RegisterArg reg(InsnData insn, int argNum, ArgType type) { return reg(insn.getReg(argNum), type); } public static RegisterArg typeImmutableIfKnownReg(InsnData insn, int argNum, ArgType type) { if (type.isTypeKnown()) { return typeImmutableReg(insn.getReg(argNum), type); } return reg(insn.getReg(argNum), type); } public static RegisterArg typeImmutableReg(InsnData insn, int argNum, ArgType type) { return typeImmutableReg(insn.getReg(argNum), type); } public static RegisterArg typeImmutableReg(int regNum, ArgType type) { return reg(regNum, type, true); } public static RegisterArg reg(int regNum, ArgType type, boolean typeImmutable) { RegisterArg reg = new RegisterArg(regNum, type); if (typeImmutable) { reg.add(AFlag.IMMUTABLE_TYPE); } return reg; } public static LiteralArg lit(long literal, ArgType type) { return LiteralArg.makeWithFixedType(literal, type); } public static LiteralArg lit(InsnData insn, ArgType type) { return lit(insn.getLiteral(), type); } private static InsnWrapArg wrap(InsnNode insn) { insn.add(AFlag.WRAPPED); return new InsnWrapArg(insn); } public boolean isRegister() { return false; } public boolean isLiteral() { return false; } public boolean isInsnWrap() { return false; } public boolean isNamed() { return false; } @Nullable public InsnNode getParentInsn() { return parentInsn; } public void setParentInsn(@Nullable InsnNode parentInsn) { this.parentInsn = parentInsn; } @Nullable("if wrap failed") public InsnArg wrapInstruction(MethodNode mth, InsnNode insn) { return wrapInstruction(mth, insn, true); } @Nullable("if wrap failed") public InsnArg wrapInstruction(MethodNode mth, InsnNode insn, boolean unbind) { InsnNode parent = parentInsn; if (parent == null) { return null; } if (parent == insn) { LOG.debug("Can't wrap instruction info itself: {}", insn); return null; } int i = getArgIndex(parent, this); if (i == -1) { return null; } if (insn.getType() == InsnType.MOVE && this.isRegister()) { // preserve variable name for move insn (needed in `for-each` loop for iteration variable) String name = ((RegisterArg) this).getName(); if (name != null) { InsnArg arg = insn.getArg(0); if (arg.isRegister()) { ((RegisterArg) arg).setNameIfUnknown(name); } else if (arg.isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) arg).getWrapInsn(); RegisterArg registerArg = wrapInsn.getResult(); if (registerArg != null) { registerArg.setNameIfUnknown(name); } } } } InsnArg arg = wrapInsnIntoArg(insn); InsnArg oldArg = parent.getArg(i); if (arg.getType() == ArgType.UNKNOWN) { // restore arg type if wrapped insn missing result arg.setType(oldArg.getType()); } parent.setArg(i, arg); InsnRemover.unbindArgUsage(mth, oldArg); if (unbind) { InsnRemover.unbindArgUsage(mth, this); // result not needed in wrapped insn InsnRemover.unbindResult(mth, insn); insn.setResult(null); } return arg; } private static int getArgIndex(InsnNode parent, InsnArg arg) { int count = parent.getArgsCount(); for (int i = 0; i < count; i++) { if (parent.getArg(i) == arg) { return i; } } return -1; } @NotNull public static InsnArg wrapInsnIntoArg(InsnNode insn) { InsnType type = insn.getType(); if (type == InsnType.CONST || type == InsnType.MOVE) { if (insn.contains(AFlag.FORCE_ASSIGN_INLINE)) { RegisterArg resArg = insn.getResult(); InsnArg arg = wrap(insn); if (resArg != null) { arg.setType(resArg.getType()); } return arg; } else { InsnArg arg = insn.getArg(0); insn.add(AFlag.DONT_GENERATE); return arg; } } return wrapArg(insn); } /** * Prefer {@link InsnArg#wrapInsnIntoArg(InsnNode)}. * <p> * This method don't support MOVE and CONST insns! */ public static InsnArg wrapArg(InsnNode insn) { RegisterArg resArg = insn.getResult(); InsnArg arg = wrap(insn); switch (insn.getType()) { case CONST: case MOVE: throw new JadxRuntimeException("Don't wrap MOVE or CONST insns: " + insn); case CONST_STR: arg.setType(ArgType.STRING); if (resArg != null) { resArg.setType(ArgType.STRING); } break; case CONST_CLASS: arg.setType(ArgType.CLASS); if (resArg != null) { resArg.setType(ArgType.CLASS); } break; default: if (resArg != null) { arg.setType(resArg.getType()); } break; } return arg; } public boolean isZeroLiteral() { return false; } public boolean isZeroConst() { if (isZeroLiteral()) { return true; } if (isInsnWrap()) { InsnNode wrapInsn = ((InsnWrapArg) this).getWrapInsn(); if (wrapInsn.getType() == InsnType.CONST) { return wrapInsn.getArg(0).isZeroLiteral(); } } return false; } public boolean isFalse() { if (isLiteral()) { LiteralArg litArg = (LiteralArg) this; return litArg.getLiteral() == 0 && Objects.equals(litArg.getType(), ArgType.BOOLEAN); } return false; } public boolean isTrue() { if (isLiteral()) { LiteralArg litArg = (LiteralArg) this; return litArg.getLiteral() == 1 && Objects.equals(litArg.getType(), ArgType.BOOLEAN); } return false; } public boolean isThis() { return contains(AFlag.THIS); } /** * Return true for 'this' from other classes (often occur in anonymous classes) */ public boolean isAnyThis() { if (contains(AFlag.THIS)) { return true; } InsnNode wrappedInsn = unwrap(); if (wrappedInsn != null && wrappedInsn.getType() == InsnType.IGET) { return wrappedInsn.getArg(0).isAnyThis(); } return false; } public InsnNode unwrap() { if (isInsnWrap()) { return ((InsnWrapArg) this).getWrapInsn(); } return null; } public boolean isConst() { return isLiteral() || (isInsnWrap() && ((InsnWrapArg) this).getWrapInsn().isConstInsn()); } public boolean isSameConst(InsnArg other) { if (isConst() && other.isConst()) { return this.equals(other); } return false; } public boolean isSameVar(RegisterArg arg) { if (arg == null) { return false; } if (isRegister()) { return ((RegisterArg) this).sameRegAndSVar(arg); } return false; } public boolean isSameCodeVar(RegisterArg arg) { if (arg == null) { return false; } if (isRegister()) { return ((RegisterArg) this).sameCodeVar(arg); } return false; } public boolean isUseVar(RegisterArg arg) { return InsnUtils.containsVar(this, arg); } protected final <T extends InsnArg> T copyCommonParams(T copy) { copy.copyAttributesFrom(this); copy.setParentInsn(parentInsn); return copy; } public InsnArg duplicate() { return this; } public String toShortString() { return this.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/Typed.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/Typed.java
package jadx.core.dex.instructions.args; import jadx.core.dex.attributes.AttrNode; public abstract class Typed extends AttrNode { protected ArgType type; public ArgType getType() { return type; } public void setType(ArgType type) { this.type = type; } public boolean isTypeImmutable() { return false; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/CodeVar.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/CodeVar.java
package jadx.core.dex.instructions.args; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jadx.api.metadata.annotations.VarNode; public class CodeVar { private String name; private ArgType type; // before type inference can be null and set only for immutable types private List<SSAVar> ssaVars = Collections.emptyList(); private boolean isFinal; private boolean isThis; private boolean isDeclared; private VarNode cachedVarNode; // set and used at codegen stage public static CodeVar fromMthArg(RegisterArg mthArg, boolean linkRegister) { CodeVar var = new CodeVar(); var.setType(mthArg.getInitType()); var.setName(mthArg.getName()); var.setThis(mthArg.isThis()); var.setDeclared(true); var.setThis(mthArg.isThis()); if (linkRegister) { var.setSsaVars(Collections.singletonList(new SSAVar(mthArg.getRegNum(), 0, mthArg))); } return var; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ArgType getType() { return type; } public void setType(ArgType type) { this.type = type; } public List<SSAVar> getSsaVars() { return ssaVars; } public void addSsaVar(SSAVar ssaVar) { if (ssaVars.isEmpty()) { ssaVars = new ArrayList<>(3); } if (!ssaVars.contains(ssaVar)) { ssaVars.add(ssaVar); } } public void setSsaVars(List<SSAVar> ssaVars) { this.ssaVars = ssaVars; } public SSAVar getAnySsaVar() { if (ssaVars.isEmpty()) { throw new IllegalStateException("CodeVar without SSA variables attached: " + this); } return ssaVars.get(0); } public boolean isFinal() { return isFinal; } public void setFinal(boolean aFinal) { isFinal = aFinal; } public boolean isThis() { return isThis; } public void setThis(boolean aThis) { isThis = aThis; } public boolean isDeclared() { return isDeclared; } public void setDeclared(boolean declared) { isDeclared = declared; } public VarNode getCachedVarNode() { return cachedVarNode; } public void setCachedVarNode(VarNode varNode) { this.cachedVarNode = varNode; } /** * Merge flags with OR operator */ public void mergeFlagsFrom(CodeVar other) { if (other.isDeclared()) { setDeclared(true); } if (other.isThis()) { setThis(true); } if (other.isFinal()) { setFinal(true); } } @Override public String toString() { return (isFinal ? "final " : "") + type + ' ' + name; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/RegisterArg.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/RegisterArg.java
package jadx.core.dex.instructions.args; import java.util.Objects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.exceptions.JadxRuntimeException; public class RegisterArg extends InsnArg implements Named { public static final String THIS_ARG_NAME = "this"; public static final String SUPER_ARG_NAME = "super"; protected final int regNum; // not null after SSATransform pass private SSAVar sVar; public RegisterArg(int rn, ArgType type) { this.type = type; // initial type, not changing, can be unknown this.regNum = rn; } public int getRegNum() { return regNum; } @Override public boolean isRegister() { return true; } public ArgType getInitType() { return type; } @Override public ArgType getType() { if (sVar != null) { return sVar.getTypeInfo().getType(); } return ArgType.UNKNOWN; } @Override public void setType(ArgType newType) { if (sVar == null) { throw new JadxRuntimeException("Can't change type for register without SSA variable: " + this); } sVar.setType(newType); } public void forceSetInitType(ArgType type) { this.type = type; } @Nullable public ArgType getImmutableType() { if (sVar != null) { return sVar.getImmutableType(); } if (contains(AFlag.IMMUTABLE_TYPE)) { return type; } return null; } @Override public boolean isTypeImmutable() { if (sVar != null) { return sVar.isTypeImmutable(); } return contains(AFlag.IMMUTABLE_TYPE); } public SSAVar getSVar() { return sVar; } void setSVar(@NotNull SSAVar sVar) { this.sVar = sVar; } public void resetSSAVar() { this.sVar = null; } @Override public String getName() { if (isSuper()) { return SUPER_ARG_NAME; } if (isThis()) { return THIS_ARG_NAME; } if (sVar == null) { return null; } return sVar.getName(); } private boolean isSuper() { return contains(AFlag.SUPER); } @Override public void setName(String name) { if (sVar != null && name != null) { sVar.setName(name); } } public void setNameIfUnknown(String name) { if (getName() == null) { setName(name); } } public boolean isNameEquals(InsnArg arg) { String n = getName(); if (n == null || !(arg instanceof Named)) { return false; } return n.equals(((Named) arg).getName()); } @Override public RegisterArg duplicate() { return duplicate(getRegNum(), getInitType(), sVar); } public RegisterArg duplicate(ArgType initType) { return duplicate(getRegNum(), initType, sVar); } public RegisterArg duplicateWithNewSSAVar(MethodNode mth) { RegisterArg duplicate = duplicate(regNum, getInitType(), null); mth.makeNewSVar(duplicate); return duplicate; } public RegisterArg duplicate(int regNum, @Nullable SSAVar sVar) { return duplicate(regNum, getInitType(), sVar); } public RegisterArg duplicate(int regNum, ArgType initType, @Nullable SSAVar sVar) { RegisterArg dup = new RegisterArg(regNum, initType); if (sVar != null) { // only 'set' here, 'assign' or 'use' will binds later dup.setSVar(sVar); } return copyCommonParams(dup); } @Nullable public InsnNode getAssignInsn() { if (sVar == null) { return null; } return sVar.getAssign().getParentInsn(); } public boolean equalRegisterAndType(RegisterArg arg) { return regNum == arg.regNum && type.equals(arg.type); } public boolean sameRegAndSVar(InsnArg arg) { if (this == arg) { return true; } if (!arg.isRegister()) { return false; } RegisterArg reg = (RegisterArg) arg; return regNum == reg.getRegNum() && Objects.equals(sVar, reg.getSVar()); } public boolean sameReg(InsnArg arg) { if (!arg.isRegister()) { return false; } return regNum == ((RegisterArg) arg).getRegNum(); } public boolean sameType(InsnArg arg) { return this.getType().equals(arg.getType()); } public boolean sameCodeVar(RegisterArg arg) { return this.getSVar().getCodeVar() == arg.getSVar().getCodeVar(); } public boolean isLinkedToOtherSsaVars() { return getSVar().getCodeVar().getSsaVars().size() > 1; } @Override public int hashCode() { return regNum; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof RegisterArg)) { return false; } RegisterArg other = (RegisterArg) obj; return regNum == other.regNum && Objects.equals(sVar, other.getSVar()); } @Override public String toShortString() { StringBuilder sb = new StringBuilder(); sb.append("r").append(regNum); if (sVar != null) { sb.append('v').append(sVar.getVersion()); } return sb.toString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("(r").append(regNum); if (sVar != null) { sb.append('v').append(sVar.getVersion()); } if (getName() != null) { sb.append(" '").append(getName()).append('\''); } ArgType type = sVar != null ? getType() : null; if (type != null) { sb.append(' ').append(type); } ArgType initType = getInitType(); if (type == null || (!type.equals(initType) && !type.isTypeKnown())) { sb.append(" I:").append(initType); } if (!isAttrStorageEmpty()) { sb.append(' ').append(getAttributesString()); } sb.append(')'); return sb.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/LiteralArg.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/LiteralArg.java
package jadx.core.dex.instructions.args; import org.jetbrains.annotations.Nullable; import jadx.core.codegen.TypeGen; import jadx.core.utils.StringUtils; import jadx.core.utils.exceptions.JadxRuntimeException; public final class LiteralArg extends InsnArg { public static LiteralArg make(long value, ArgType type) { return new LiteralArg(value, type); } public static LiteralArg makeWithFixedType(long value, ArgType type) { return new LiteralArg(value, fixLiteralType(value, type)); } private static ArgType fixLiteralType(long value, ArgType type) { if (value == 0 || type.isTypeKnown() || type.contains(PrimitiveType.LONG) || type.contains(PrimitiveType.DOUBLE)) { return type; } if (value == 1) { return ArgType.NARROW_NUMBERS; } return ArgType.NARROW_NUMBERS_NO_BOOL; } public static LiteralArg litFalse() { return new LiteralArg(0, ArgType.BOOLEAN); } public static LiteralArg litTrue() { return new LiteralArg(1, ArgType.BOOLEAN); } private final long literal; private LiteralArg(long value, ArgType type) { if (value != 0 && type.isObject()) { throw new JadxRuntimeException("Wrong literal type: " + type + " for value: " + value); } this.literal = value; this.type = type; } public long getLiteral() { return literal; } @Override public void setType(ArgType type) { super.setType(type); } @Override public boolean isLiteral() { return true; } @Override public boolean isZeroLiteral() { return literal == 0; } public boolean isInteger() { switch (type.getPrimitiveType()) { case INT: case BYTE: case CHAR: case SHORT: case LONG: return true; default: return false; } } public boolean isNegative() { if (isInteger()) { return literal < 0; } if (type == ArgType.FLOAT) { float val = Float.intBitsToFloat(((int) literal)); return val < 0 && Float.isFinite(val); } if (type == ArgType.DOUBLE) { double val = Double.longBitsToDouble(literal); return val < 0 && Double.isFinite(val); } return false; } @Nullable public LiteralArg negate() { long neg; if (isInteger()) { neg = -literal; } else if (type == ArgType.FLOAT) { float val = Float.intBitsToFloat(((int) literal)); neg = Float.floatToIntBits(-val); } else if (type == ArgType.DOUBLE) { double val = Double.longBitsToDouble(literal); neg = Double.doubleToLongBits(-val); } else { return null; } return new LiteralArg(neg, type); } @Override public InsnArg duplicate() { return copyCommonParams(new LiteralArg(literal, type)); } @Override public int hashCode() { return (int) (literal ^ literal >>> 32) + 31 * getType().hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LiteralArg that = (LiteralArg) o; return literal == that.literal && getType().equals(that.getType()); } @Override public String toShortString() { return Long.toString(literal); } @Override public String toString() { try { String value = TypeGen.literalToString(literal, getType(), StringUtils.getInstance(), true, false); if (getType().equals(ArgType.BOOLEAN) && (value.equals("true") || value.equals("false"))) { return value; } return '(' + value + ' ' + type + ')'; } catch (JadxRuntimeException ex) { // can't convert literal to string return "(" + literal + ' ' + type + ')'; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/Named.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/Named.java
package jadx.core.dex.instructions.args; public interface Named { String getName(); void setName(String name); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/ArgType.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/ArgType.java
package jadx.core.dex.instructions.args; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Function; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import jadx.core.Consts; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.nodes.RootNode; import jadx.core.dex.visitors.typeinference.TypeCompareEnum; import jadx.core.utils.ListUtils; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; public abstract class ArgType { public static final ArgType INT = primitive(PrimitiveType.INT); public static final ArgType BOOLEAN = primitive(PrimitiveType.BOOLEAN); public static final ArgType BYTE = primitive(PrimitiveType.BYTE); public static final ArgType SHORT = primitive(PrimitiveType.SHORT); public static final ArgType CHAR = primitive(PrimitiveType.CHAR); public static final ArgType FLOAT = primitive(PrimitiveType.FLOAT); public static final ArgType DOUBLE = primitive(PrimitiveType.DOUBLE); public static final ArgType LONG = primitive(PrimitiveType.LONG); public static final ArgType VOID = primitive(PrimitiveType.VOID); public static final ArgType OBJECT = objectNoCache(Consts.CLASS_OBJECT); public static final ArgType CLASS = objectNoCache(Consts.CLASS_CLASS); public static final ArgType STRING = objectNoCache(Consts.CLASS_STRING); public static final ArgType ENUM = objectNoCache(Consts.CLASS_ENUM); public static final ArgType THROWABLE = objectNoCache(Consts.CLASS_THROWABLE); public static final ArgType ERROR = objectNoCache(Consts.CLASS_ERROR); public static final ArgType EXCEPTION = objectNoCache(Consts.CLASS_EXCEPTION); public static final ArgType RUNTIME_EXCEPTION = objectNoCache(Consts.CLASS_RUNTIME_EXCEPTION); public static final ArgType OBJECT_ARRAY = array(OBJECT); public static final ArgType WILDCARD = wildcard(); public static final ArgType UNKNOWN = unknown(PrimitiveType.values()); public static final ArgType UNKNOWN_OBJECT = unknown(PrimitiveType.OBJECT, PrimitiveType.ARRAY); public static final ArgType UNKNOWN_OBJECT_NO_ARRAY = unknown(PrimitiveType.OBJECT); public static final ArgType UNKNOWN_ARRAY = array(UNKNOWN); public static final ArgType NARROW = unknown( PrimitiveType.INT, PrimitiveType.FLOAT, PrimitiveType.BOOLEAN, PrimitiveType.SHORT, PrimitiveType.BYTE, PrimitiveType.CHAR, PrimitiveType.OBJECT, PrimitiveType.ARRAY); public static final ArgType NARROW_NUMBERS = unknown( PrimitiveType.BOOLEAN, PrimitiveType.INT, PrimitiveType.FLOAT, PrimitiveType.SHORT, PrimitiveType.BYTE, PrimitiveType.CHAR); public static final ArgType NARROW_INTEGRAL = unknown( PrimitiveType.INT, PrimitiveType.SHORT, PrimitiveType.BYTE, PrimitiveType.CHAR); public static final ArgType NARROW_NUMBERS_NO_BOOL = unknown( PrimitiveType.INT, PrimitiveType.FLOAT, PrimitiveType.SHORT, PrimitiveType.BYTE, PrimitiveType.CHAR); public static final ArgType NARROW_NUMBERS_NO_FLOAT = unknown( PrimitiveType.INT, PrimitiveType.BOOLEAN, PrimitiveType.SHORT, PrimitiveType.BYTE, PrimitiveType.CHAR); public static final ArgType WIDE = unknown(PrimitiveType.LONG, PrimitiveType.DOUBLE); public static final ArgType INT_FLOAT = unknown(PrimitiveType.INT, PrimitiveType.FLOAT); public static final ArgType INT_BOOLEAN = unknown(PrimitiveType.INT, PrimitiveType.BOOLEAN); public static final ArgType BYTE_BOOLEAN = unknown(PrimitiveType.BYTE, PrimitiveType.BOOLEAN); public static final ArgType UNKNOWN_INT = unknown(PrimitiveType.INT); protected int hash; private static ArgType primitive(PrimitiveType stype) { return new PrimitiveArg(stype); } private static ArgType objectNoCache(String obj) { return new ObjectType(obj); } public static ArgType object(String obj) { // TODO: add caching String cleanObjectName = Utils.cleanObjectName(obj); switch (cleanObjectName) { case Consts.CLASS_OBJECT: return OBJECT; case Consts.CLASS_STRING: return STRING; case Consts.CLASS_CLASS: return CLASS; case Consts.CLASS_THROWABLE: return THROWABLE; case Consts.CLASS_EXCEPTION: return EXCEPTION; default: return new ObjectType(cleanObjectName); } } public static ArgType genericType(String type) { return new GenericType(type); } public static ArgType genericType(String type, ArgType extendType) { return new GenericType(type, extendType); } public static ArgType genericType(String type, List<ArgType> extendTypes) { return new GenericType(type, extendTypes); } public static ArgType wildcard() { return new WildcardType(OBJECT, WildcardBound.UNBOUND); } public static ArgType wildcard(ArgType obj, WildcardBound bound) { return new WildcardType(obj, bound); } public static ArgType generic(ArgType obj, List<ArgType> generics) { if (!obj.isObject()) { throw new IllegalArgumentException("Expected Object as ArgType, got: " + obj); } return new GenericObject(obj.getObject(), generics); } public static ArgType generic(ArgType obj, ArgType... generics) { return generic(obj, Arrays.asList(generics)); } public static ArgType generic(String obj, List<ArgType> generics) { return new GenericObject(Utils.cleanObjectName(obj), generics); } public static ArgType generic(String obj, ArgType generic) { return generic(obj, Collections.singletonList(generic)); } @TestOnly public static ArgType generic(String obj, ArgType... generics) { return generic(obj, Arrays.asList(generics)); } public static ArgType outerGeneric(ArgType genericOuterType, ArgType innerType) { return new OuterGenericObject((ObjectType) genericOuterType, (ObjectType) innerType); } public static ArgType array(@NotNull ArgType vtype) { return new ArrayArg(vtype); } public static ArgType array(@NotNull ArgType type, int dimension) { if (dimension == 1) { return new ArrayArg(type); } ArgType arrType = type; for (int i = 0; i < dimension; i++) { arrType = new ArrayArg(arrType); } return arrType; } public static ArgType unknown(PrimitiveType... types) { return new UnknownArg(types); } private abstract static class KnownType extends ArgType { private static final PrimitiveType[] EMPTY_POSSIBLES = new PrimitiveType[0]; @Override public boolean isTypeKnown() { return true; } @Override public boolean contains(PrimitiveType type) { return getPrimitiveType() == type; } @Override public ArgType selectFirst() { return null; } @Override public PrimitiveType[] getPossibleTypes() { return EMPTY_POSSIBLES; } } private static final class PrimitiveArg extends KnownType { private final PrimitiveType type; public PrimitiveArg(PrimitiveType type) { this.type = type; this.hash = type.hashCode(); } @Override public PrimitiveType getPrimitiveType() { return type; } @Override public boolean isPrimitive() { return true; } @Override boolean internalEquals(Object obj) { return type == ((PrimitiveArg) obj).type; } @Override public String toString() { return type.toString(); } } private static class ObjectType extends KnownType { protected final String objName; public ObjectType(String obj) { this.objName = obj; this.hash = objName.hashCode(); } @Override public String getObject() { return objName; } @Override public boolean isObject() { return true; } @Override public PrimitiveType getPrimitiveType() { return PrimitiveType.OBJECT; } @Override boolean internalEquals(Object obj) { return objName.equals(((ObjectType) obj).objName); } @Override public String toString() { return objName; } } private static final class GenericType extends ObjectType { private List<ArgType> extendTypes; public GenericType(String obj) { this(obj, Collections.emptyList()); } public GenericType(String obj, ArgType extendType) { this(obj, Collections.singletonList(extendType)); } public GenericType(String obj, List<ArgType> extendTypes) { super(obj); this.extendTypes = extendTypes; } @Override public boolean isGenericType() { return true; } @Override public List<ArgType> getExtendTypes() { return extendTypes; } @Override public void setExtendTypes(List<ArgType> extendTypes) { this.extendTypes = extendTypes; } @Override boolean internalEquals(Object obj) { return super.internalEquals(obj) && extendTypes.equals(((GenericType) obj).extendTypes); } @Override public String toString() { List<ArgType> extTypes = this.extendTypes; if (extTypes.isEmpty()) { return objName; } return objName + " extends " + Utils.listToString(extTypes, " & "); } } public enum WildcardBound { EXTENDS(1, "? extends "), // upper bound (? extends A) UNBOUND(0, "?"), // no bounds (?) SUPER(-1, "? super "); // lower bound (? super A) private final int num; private final String str; WildcardBound(int val, String str) { this.num = val; this.str = str; } public int getNum() { return num; } public String getStr() { return str; } public static WildcardBound getByNum(int num) { return num == 0 ? UNBOUND : (num == 1 ? EXTENDS : SUPER); } } private static final class WildcardType extends ObjectType { private final ArgType type; private final WildcardBound bound; public WildcardType(ArgType obj, WildcardBound bound) { super(OBJECT.getObject()); this.type = Objects.requireNonNull(obj); this.bound = Objects.requireNonNull(bound); } @Override public boolean isWildcard() { return true; } @Override public boolean isGeneric() { return true; } @Override public ArgType getWildcardType() { return type; } @Override public WildcardBound getWildcardBound() { return bound; } @Override boolean internalEquals(Object obj) { return super.internalEquals(obj) && bound == ((WildcardType) obj).bound && type.equals(((WildcardType) obj).type); } @Override public String toString() { if (bound == WildcardBound.UNBOUND) { return bound.getStr(); } return bound.getStr() + type; } } private static class GenericObject extends ObjectType { private final List<ArgType> generics; public GenericObject(String obj, List<ArgType> generics) { super(obj); this.generics = Objects.requireNonNull(generics); this.hash = calcHash(); } private int calcHash() { return objName.hashCode() + 31 * generics.hashCode(); } @Override public boolean isGeneric() { return true; } @Override public List<ArgType> getGenericTypes() { return generics; } @Override boolean internalEquals(Object obj) { return super.internalEquals(obj) && Objects.equals(generics, ((GenericObject) obj).generics); } @Override public String toString() { return super.toString() + '<' + Utils.listToString(generics) + '>'; } } private static class OuterGenericObject extends ObjectType { private final ObjectType outerType; private final ObjectType innerType; public OuterGenericObject(ObjectType outerType, ObjectType innerType) { super(outerType.getObject() + '$' + innerType.getObject()); this.outerType = outerType; this.innerType = innerType; this.hash = calcHash(); } private int calcHash() { return objName.hashCode() + 31 * (outerType.hashCode() + 31 * innerType.hashCode()); } @Override public boolean isGeneric() { return true; } @Override public List<ArgType> getGenericTypes() { return innerType.getGenericTypes(); } @Override public ArgType getOuterType() { return outerType; } @Override public ArgType getInnerType() { return innerType; } @Override boolean internalEquals(Object obj) { return super.internalEquals(obj) && Objects.equals(outerType, ((OuterGenericObject) obj).outerType) && Objects.equals(innerType, ((OuterGenericObject) obj).innerType); } @Override public String toString() { return outerType.toString() + '$' + innerType.toString(); } } private static final class ArrayArg extends KnownType { private static final PrimitiveType[] ARRAY_POSSIBLES = new PrimitiveType[] { PrimitiveType.ARRAY }; private final ArgType arrayElement; public ArrayArg(ArgType arrayElement) { this.arrayElement = arrayElement; this.hash = arrayElement.hashCode(); } @Override public ArgType getArrayElement() { return arrayElement; } @Override public boolean isArray() { return true; } @Override public PrimitiveType getPrimitiveType() { return PrimitiveType.ARRAY; } @Override public boolean isTypeKnown() { return arrayElement.isTypeKnown(); } @Override public ArgType selectFirst() { return array(arrayElement.selectFirst()); } @Override public PrimitiveType[] getPossibleTypes() { return ARRAY_POSSIBLES; } @Override public int getArrayDimension() { return 1 + arrayElement.getArrayDimension(); } @Override public ArgType getArrayRootElement() { return arrayElement.getArrayRootElement(); } @Override boolean internalEquals(Object other) { ArrayArg otherArr = (ArrayArg) other; return this.arrayElement.equals(otherArr.getArrayElement()); } @Override public String toString() { return arrayElement + "[]"; } } private static final class UnknownArg extends ArgType { private final PrimitiveType[] possibleTypes; public UnknownArg(PrimitiveType[] types) { this.possibleTypes = types; this.hash = Arrays.hashCode(possibleTypes); } @Override public PrimitiveType[] getPossibleTypes() { return possibleTypes; } @Override public boolean isTypeKnown() { return false; } @Override public boolean contains(PrimitiveType type) { for (PrimitiveType t : possibleTypes) { if (t == type) { return true; } } return false; } @Override public ArgType selectFirst() { if (contains(PrimitiveType.OBJECT)) { return OBJECT; } if (contains(PrimitiveType.ARRAY)) { return array(OBJECT); } return primitive(possibleTypes[0]); } @Override boolean internalEquals(Object obj) { return Arrays.equals(possibleTypes, ((UnknownArg) obj).possibleTypes); } @Override public String toString() { if (possibleTypes.length == PrimitiveType.values().length) { return "??"; } else { return "??[" + Utils.arrayToStr(possibleTypes) + ']'; } } } public boolean isTypeKnown() { return false; } public PrimitiveType getPrimitiveType() { return null; } public boolean isPrimitive() { return false; } public String getObject() { throw new UnsupportedOperationException("ArgType.getObject(), call class: " + this.getClass()); } public boolean isObject() { return false; } public boolean isGeneric() { return false; } public boolean isGenericType() { return false; } public List<ArgType> getGenericTypes() { return null; } public List<ArgType> getExtendTypes() { return Collections.emptyList(); } public void setExtendTypes(List<ArgType> extendTypes) { } public ArgType getWildcardType() { return null; } public WildcardBound getWildcardBound() { return null; } public boolean isWildcard() { return false; } public ArgType getOuterType() { return null; } public ArgType getInnerType() { return null; } public boolean isArray() { return false; } public int getArrayDimension() { return 0; } public ArgType getArrayElement() { return null; } public ArgType getArrayRootElement() { return this; } public abstract boolean contains(PrimitiveType type); public abstract ArgType selectFirst(); public abstract PrimitiveType[] getPossibleTypes(); public static boolean isCastNeeded(RootNode root, ArgType from, ArgType to) { if (from.equals(to)) { return false; } TypeCompareEnum result = root.getTypeCompare().compareTypes(from, to); return !result.isNarrow(); } public static boolean isInstanceOf(RootNode root, ArgType type, ArgType of) { if (type.equals(of)) { return true; } if (!type.isObject() || !of.isObject()) { return false; } return root.getClsp().isImplements(type.getObject(), of.getObject()); } public static boolean isClsKnown(RootNode root, ArgType cls) { if (cls.isObject()) { return root.getClsp().isClsKnown(cls.getObject()); } return false; } public boolean canBeObject() { return isObject() || (!isTypeKnown() && contains(PrimitiveType.OBJECT)); } public boolean canBeArray() { return isArray() || (!isTypeKnown() && contains(PrimitiveType.ARRAY)); } public boolean canBePrimitive(PrimitiveType primitiveType) { return (isPrimitive() && getPrimitiveType() == primitiveType) || (!isTypeKnown() && contains(primitiveType)); } public boolean canBeAnyNumber() { if (isPrimitive()) { return !getPrimitiveType().isObjectOrArray(); } for (PrimitiveType primitiveType : getPossibleTypes()) { if (!primitiveType.isObjectOrArray()) { return true; } } return false; } public static ArgType convertFromPrimitiveType(PrimitiveType primitiveType) { switch (primitiveType) { case BOOLEAN: return BOOLEAN; case CHAR: return CHAR; case BYTE: return BYTE; case SHORT: return SHORT; case INT: return INT; case FLOAT: return FLOAT; case LONG: return LONG; case DOUBLE: return DOUBLE; case OBJECT: return OBJECT; case ARRAY: return OBJECT_ARRAY; case VOID: return ArgType.VOID; } return OBJECT; } public static ArgType parse(String type) { if (type == null || type.isEmpty()) { throw new JadxRuntimeException("Failed to parse type string: " + type); } char f = type.charAt(0); switch (f) { case 'L': return object(type); case 'T': return genericType(type.substring(1, type.length() - 1)); case '[': return array(parse(type.substring(1))); default: if (type.length() != 1) { throw new JadxRuntimeException("Unknown type string: \"" + type + '"'); } return parse(f); } } public static ArgType parse(char f) { switch (f) { case 'Z': return BOOLEAN; case 'B': return BYTE; case 'C': return CHAR; case 'S': return SHORT; case 'I': return INT; case 'J': return LONG; case 'F': return FLOAT; case 'D': return DOUBLE; case 'V': return VOID; default: throw new JadxRuntimeException("Unknown type char: '" + f + "' (0x" + Integer.toHexString(f) + ')'); } } public int getRegCount() { if (isPrimitive()) { PrimitiveType type = getPrimitiveType(); if (type == PrimitiveType.LONG || type == PrimitiveType.DOUBLE) { return 2; } else { return 1; } } if (!isTypeKnown()) { return 0; } return 1; } public boolean containsGeneric() { if (isGeneric() || isGenericType()) { return true; } if (isArray()) { ArgType arrayElement = getArrayElement(); if (arrayElement != null) { return arrayElement.containsGeneric(); } } return false; } public boolean containsTypeVariable() { if (isGenericType()) { return true; } ArgType wildcardType = getWildcardType(); if (wildcardType != null) { return wildcardType.containsTypeVariable(); } if (isGeneric()) { List<ArgType> genericTypes = getGenericTypes(); if (genericTypes != null) { for (ArgType genericType : genericTypes) { if (genericType.containsTypeVariable()) { return true; } } } ArgType outerType = getOuterType(); if (outerType != null) { return outerType.containsTypeVariable(); } return false; } if (isArray()) { ArgType arrayElement = getArrayElement(); if (arrayElement != null) { return arrayElement.containsTypeVariable(); } } return false; } public boolean isVoid() { return isPrimitive() && getPrimitiveType() == PrimitiveType.VOID; } /** * Recursively visit all subtypes of this type. * To exit return non-null value. */ @Nullable public <R> R visitTypes(Function<ArgType, R> visitor) { R r = visitor.apply(this); if (r != null) { return r; } if (isArray()) { ArgType arrayElement = getArrayElement(); if (arrayElement != null) { return arrayElement.visitTypes(visitor); } } ArgType wildcardType = getWildcardType(); if (wildcardType != null) { R res = wildcardType.visitTypes(visitor); if (res != null) { return res; } } if (isGeneric()) { List<ArgType> genericTypes = getGenericTypes(); if (genericTypes != null) { for (ArgType genericType : genericTypes) { R res = genericType.visitTypes(visitor); if (res != null) { return res; } } } } return null; } public static ArgType tryToResolveClassAlias(RootNode root, ArgType type) { if (type.isGenericType()) { return type; } if (type.isArray()) { ArgType rootType = type.getArrayRootElement(); ArgType aliasType = tryToResolveClassAlias(root, rootType); if (aliasType == rootType) { return type; } return ArgType.array(aliasType, type.getArrayDimension()); } if (type.isObject()) { ArgType wildcardType = type.getWildcardType(); if (wildcardType != null) { return new WildcardType(tryToResolveClassAlias(root, wildcardType), type.getWildcardBound()); } ClassInfo clsInfo = ClassInfo.fromName(root, type.getObject()); ArgType baseType = clsInfo.hasAlias() ? ArgType.object(clsInfo.getAliasFullName()) : type; if (!type.isGeneric()) { return baseType; } List<ArgType> genericTypes = type.getGenericTypes(); if (genericTypes != null) { return new GenericObject(baseType.getObject(), tryToResolveClassAlias(root, genericTypes)); } } return type; } public static List<ArgType> tryToResolveClassAlias(RootNode root, List<ArgType> types) { return ListUtils.map(types, t -> tryToResolveClassAlias(root, t)); } @Override public String toString() { return "ARG_TYPE"; } @Override public int hashCode() { return hash; } abstract boolean internalEquals(Object obj); @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (hash != obj.hashCode()) { return false; } if (getClass() != obj.getClass()) { return false; } return internalEquals(obj); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/InsnWrapArg.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/InsnWrapArg.java
package jadx.core.dex.instructions.args; import org.jetbrains.annotations.NotNull; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.instructions.ConstStringNode; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.exceptions.JadxRuntimeException; public final class InsnWrapArg extends InsnArg { private final InsnNode wrappedInsn; /** * Use {@link InsnArg#wrapInsnIntoArg(InsnNode)} instead this constructor */ InsnWrapArg(@NotNull InsnNode insn) { RegisterArg result = insn.getResult(); this.type = result != null ? result.getType() : ArgType.UNKNOWN; this.wrappedInsn = insn; } public InsnNode getWrapInsn() { return wrappedInsn; } public InsnNode unWrapWithCopy() { InsnNode copy = wrappedInsn.copyWithoutResult(); copy.remove(AFlag.WRAPPED); return copy; } @Override public void setParentInsn(InsnNode parentInsn) { if (parentInsn == wrappedInsn) { throw new JadxRuntimeException("Can't wrap instruction info itself: " + parentInsn); } this.parentInsn = parentInsn; } @Override public InsnArg duplicate() { InsnWrapArg copy = new InsnWrapArg(wrappedInsn.copyWithoutResult()); copy.setType(type); return copyCommonParams(copy); } @Override public boolean isInsnWrap() { return true; } @Override public int hashCode() { return wrappedInsn.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof InsnWrapArg)) { return false; } InsnWrapArg that = (InsnWrapArg) o; InsnNode thisInsn = wrappedInsn; InsnNode thatInsn = that.wrappedInsn; if (!thisInsn.isSame(thatInsn)) { return false; } int count = thisInsn.getArgsCount(); for (int i = 0; i < count; i++) { if (!thisInsn.getArg(i).equals(thatInsn.getArg(i))) { return false; } } return true; } @Override public String toShortString() { if (wrappedInsn.getType() == InsnType.CONST_STR) { return "(\"" + ((ConstStringNode) wrappedInsn).getString() + "\")"; } return "(wrap:" + type + ":" + wrappedInsn.getType() + ')'; } @Override public String toString() { if (wrappedInsn.getType() == InsnType.CONST_STR) { return "(\"" + ((ConstStringNode) wrappedInsn).getString() + "\")"; } return "(wrap:" + type + ":" + wrappedInsn + ')'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/NamedArg.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/NamedArg.java
package jadx.core.dex.instructions.args; import org.jetbrains.annotations.NotNull; public final class NamedArg extends InsnArg implements Named { @NotNull private String name; public NamedArg(@NotNull String name, @NotNull ArgType type) { this.name = name; this.type = type; } @NotNull public String getName() { return name; } @Override public boolean isNamed() { return true; } @Override public void setName(@NotNull String name) { this.name = name; } @Override public InsnArg duplicate() { return copyCommonParams(new NamedArg(name, type)); } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof NamedArg)) { return false; } return name.equals(((NamedArg) o).name); } @Override public String toShortString() { return name; } @Override public String toString() { return '(' + name + ' ' + type + ')'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/instructions/args/PrimitiveType.java
jadx-core/src/main/java/jadx/core/dex/instructions/args/PrimitiveType.java
package jadx.core.dex.instructions.args; public enum PrimitiveType { BOOLEAN("Z", "boolean", ArgType.object("java.lang.Boolean")), CHAR("C", "char", ArgType.object("java.lang.Character")), BYTE("B", "byte", ArgType.object("java.lang.Byte")), SHORT("S", "short", ArgType.object("java.lang.Short")), INT("I", "int", ArgType.object("java.lang.Integer")), FLOAT("F", "float", ArgType.object("java.lang.Float")), LONG("J", "long", ArgType.object("java.lang.Long")), DOUBLE("D", "double", ArgType.object("java.lang.Double")), OBJECT("L", "OBJECT", ArgType.OBJECT), ARRAY("[", "ARRAY", ArgType.OBJECT_ARRAY), VOID("V", "void", ArgType.object("java.lang.Void")); private final String shortName; private final String longName; private final ArgType boxType; PrimitiveType(String shortName, String longName, ArgType boxType) { this.shortName = shortName; this.longName = longName; this.boxType = boxType; } public String getShortName() { return shortName; } public String getLongName() { return longName; } public ArgType getBoxType() { return boxType; } @Override public String toString() { return longName; } public boolean isObjectOrArray() { return this == OBJECT || this == ARRAY; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/PackageNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/PackageNode.java
package jadx.core.dex.nodes; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jadx.api.JavaPackage; import jadx.api.metadata.ICodeNodeRef; import jadx.core.dex.attributes.nodes.LineAttrNode; import jadx.core.dex.info.PackageInfo; import static jadx.core.utils.StringUtils.containsChar; public class PackageNode extends LineAttrNode implements IPackageUpdate, IDexNode, ICodeNodeRef, Comparable<PackageNode> { private final RootNode root; private final PackageInfo pkgInfo; private final @Nullable PackageNode parentPkg; private final List<PackageNode> subPackages = new ArrayList<>(); private final List<ClassNode> classes = new ArrayList<>(); private PackageInfo aliasPkgInfo; private JavaPackage javaNode; public static PackageNode getForClass(RootNode root, String fullPkg, ClassNode cls) { PackageNode pkg = getOrBuild(root, fullPkg); pkg.getClasses().add(cls); return pkg; } public static PackageNode getOrBuild(RootNode root, String fullPkg) { PackageNode existPkg = root.resolvePackage(fullPkg); if (existPkg != null) { return existPkg; } PackageInfo pgkInfo = PackageInfo.fromFullPkg(root, fullPkg); PackageNode parentPkg = getParentPkg(root, pgkInfo); PackageNode pkgNode = new PackageNode(root, parentPkg, pgkInfo); if (parentPkg != null) { parentPkg.getSubPackages().add(pkgNode); } root.addPackage(pkgNode); return pkgNode; } private static @Nullable PackageNode getParentPkg(RootNode root, PackageInfo pgkInfo) { PackageInfo parentPkg = pgkInfo.getParentPkg(); if (parentPkg == null) { return null; } return getOrBuild(root, parentPkg.getFullName()); } private PackageNode(RootNode root, @Nullable PackageNode parentPkg, PackageInfo pkgInfo) { this.root = root; this.parentPkg = parentPkg; this.pkgInfo = pkgInfo; this.aliasPkgInfo = pkgInfo; } @Override public void rename(String newName) { rename(newName, true); } public void rename(String newName, boolean runUpdates) { String alias; boolean isFullAlias; if (containsChar(newName, '/')) { alias = newName.replace('/', '.'); isFullAlias = true; } else if (newName.startsWith(".")) { // treat as full pkg, remove start dot alias = newName.substring(1); isFullAlias = true; } else { alias = newName; isFullAlias = containsChar(newName, '.'); } if (isFullAlias) { setFullAlias(alias, runUpdates); } else { setLeafAlias(alias, runUpdates); } } public void setLeafAlias(String alias, boolean runUpdates) { if (pkgInfo.getName().equals(alias)) { aliasPkgInfo = pkgInfo; } else { aliasPkgInfo = PackageInfo.fromShortName(root, getParentAliasPkgInfo(), alias); } if (runUpdates) { updatePackages(this); } } public void setFullAlias(String fullAlias, boolean runUpdates) { if (pkgInfo.getFullName().equals(fullAlias)) { aliasPkgInfo = pkgInfo; } else { aliasPkgInfo = PackageInfo.fromFullPkg(root, fullAlias); } if (runUpdates) { updatePackages(this); } } @Override public void onParentPackageUpdate(PackageNode updatedPkg) { aliasPkgInfo = PackageInfo.fromShortName(root, getParentAliasPkgInfo(), aliasPkgInfo.getName()); updatePackages(updatedPkg); } public void updatePackages() { updatePackages(this); } private void updatePackages(PackageNode updatedPkg) { for (PackageNode subPackage : subPackages) { subPackage.onParentPackageUpdate(updatedPkg); } for (ClassNode cls : classes) { cls.onParentPackageUpdate(updatedPkg); } } public String getName() { return pkgInfo.getName(); } public String getFullName() { return pkgInfo.getFullName(); } public PackageInfo getPkgInfo() { return pkgInfo; } public PackageInfo getAliasPkgInfo() { return aliasPkgInfo; } public boolean hasAlias() { if (pkgInfo == aliasPkgInfo) { return false; } return !pkgInfo.getName().equals(aliasPkgInfo.getName()); } public boolean hasParentAlias() { if (pkgInfo == aliasPkgInfo) { return false; } return !Objects.equals(pkgInfo.getParentPkg(), aliasPkgInfo.getParentPkg()); } public void removeAlias() { aliasPkgInfo = pkgInfo; } public @Nullable PackageNode getParentPkg() { return parentPkg; } public @Nullable PackageInfo getParentAliasPkgInfo() { return parentPkg == null ? null : parentPkg.aliasPkgInfo; } public boolean isRoot() { return parentPkg == null; } public boolean isLeaf() { return subPackages.isEmpty(); } public List<PackageNode> getSubPackages() { return subPackages; } public List<ClassNode> getClasses() { return classes; } public List<ClassNode> getClassesNoDup() { return classes.stream() .map(ClassNode::getClassInfo) .collect(Collectors.toSet()) .stream() .map(e -> root.resolveClass(e)).collect(Collectors.toList()); } public JavaPackage getJavaNode() { return javaNode; } public void setJavaNode(JavaPackage javaNode) { this.javaNode = javaNode; } public boolean isEmpty() { return classes.isEmpty() && subPackages.isEmpty(); } @Override public String typeName() { return "package"; } @Override public AnnType getAnnType() { return AnnType.PKG; } @Override public RootNode root() { return root; } @Override public String getInputFileName() { return ""; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PackageNode)) { return false; } return pkgInfo.equals(((PackageNode) o).pkgInfo); } @Override public int hashCode() { return pkgInfo.hashCode(); } @Override public int compareTo(@NotNull PackageNode other) { return getPkgInfo().getFullName().compareTo(other.getPkgInfo().getFullName()); } @Override public String toString() { return getPkgInfo().getFullName(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/InsnContainer.java
jadx-core/src/main/java/jadx/core/dex/nodes/InsnContainer.java
package jadx.core.dex.nodes; import java.util.ArrayList; import java.util.List; import jadx.core.dex.attributes.AttrNode; /** * Lightweight replacement for BlockNode in regions. * Use with caution! Some passes still expect BlockNode in method blocks list (mth.getBlockNodes()) */ public final class InsnContainer extends AttrNode implements IBlock { private final List<InsnNode> insns; public InsnContainer(InsnNode insn) { List<InsnNode> list = new ArrayList<>(1); list.add(insn); this.insns = list; } public InsnContainer(List<InsnNode> insns) { this.insns = insns; } @Override public List<InsnNode> getInstructions() { return insns; } @Override public String baseString() { return "IC"; } @Override public String toString() { return "InsnContainer"; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/BlockNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/BlockNode.java
package jadx.core.dex.nodes; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import org.jetbrains.annotations.NotNull; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.AttrNode; import jadx.core.dex.attributes.nodes.LoopInfo; import jadx.core.utils.BlockUtils; import jadx.core.utils.EmptyBitSet; import jadx.core.utils.InsnUtils; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.core.utils.Utils.lockList; public final class BlockNode extends AttrNode implements IBlock, Comparable<BlockNode> { /** * Const ID */ private final int cid; /** * Position in blocks list (easier to use BitSet) */ private int pos; /** * Offset in methods bytecode */ private final int startOffset; private final List<InsnNode> instructions = new ArrayList<>(2); private List<BlockNode> predecessors = new ArrayList<>(1); private List<BlockNode> successors = new ArrayList<>(1); private List<BlockNode> cleanSuccessors; /** * All dominators, excluding self */ private BitSet doms = EmptyBitSet.EMPTY; /** * Post dominators, excluding self */ private BitSet postDoms = EmptyBitSet.EMPTY; /** * Dominance frontier */ private BitSet domFrontier; /** * Immediate dominator */ private BlockNode idom; /** * Immediate post dominator */ private BlockNode iPostDom; /** * Blocks on which dominates this block */ private List<BlockNode> dominatesOn = new ArrayList<>(3); public BlockNode(int cid, int pos, int offset) { this.cid = cid; this.pos = pos; this.startOffset = offset; } public int getCId() { return cid; } void setPos(int id) { this.pos = id; } /** * Deprecated. Use {@link #getPos()}. */ @Deprecated public int getId() { return pos; } public int getPos() { return pos; } public List<BlockNode> getPredecessors() { return predecessors; } public List<BlockNode> getSuccessors() { return successors; } public List<BlockNode> getCleanSuccessors() { return this.cleanSuccessors; } public void updateCleanSuccessors() { cleanSuccessors = cleanSuccessors(this); } public static void updateBlockPositions(List<BlockNode> blocks) { int count = blocks.size(); for (int i = 0; i < count; i++) { blocks.get(i).setPos(i); } } public void lock() { try { List<BlockNode> successorsList = successors; successors = lockList(successorsList); cleanSuccessors = successorsList == cleanSuccessors ? this.successors : lockList(cleanSuccessors); predecessors = lockList(predecessors); dominatesOn = lockList(dominatesOn); if (domFrontier == null) { throw new JadxRuntimeException("Dominance frontier not set for block: " + this); } } catch (Exception e) { throw new JadxRuntimeException("Failed to lock block: " + this, e); } } /** * Return all successor which are not exception handler or followed by loop back edge */ private static List<BlockNode> cleanSuccessors(BlockNode block) { List<BlockNode> sucList = block.getSuccessors(); if (sucList.isEmpty()) { return sucList; } List<BlockNode> toRemove = new ArrayList<>(sucList.size()); for (BlockNode b : sucList) { if (BlockUtils.isExceptionHandlerPath(b)) { toRemove.add(b); } } if (block.contains(AFlag.LOOP_END)) { List<LoopInfo> loops = block.getAll(AType.LOOP); for (LoopInfo loop : loops) { toRemove.add(loop.getStart()); } } if (toRemove.isEmpty()) { return sucList; } List<BlockNode> result = new ArrayList<>(sucList); result.removeAll(toRemove); return result; } @Override public List<InsnNode> getInstructions() { return instructions; } public int getStartOffset() { return startOffset; } /** * Check if 'block' dominated on this node */ public boolean isDominator(BlockNode block) { return doms.get(block.getPos()); } /** * Dominators of this node (exclude itself) */ public BitSet getDoms() { return doms; } public void setDoms(BitSet doms) { this.doms = doms; } public BitSet getPostDoms() { return postDoms; } public void setPostDoms(BitSet postDoms) { this.postDoms = postDoms; } public BitSet getDomFrontier() { return domFrontier; } public void setDomFrontier(BitSet domFrontier) { this.domFrontier = domFrontier; } /** * Immediate dominator */ public BlockNode getIDom() { return idom; } public void setIDom(BlockNode idom) { this.idom = idom; } public BlockNode getIPostDom() { return iPostDom; } public void setIPostDom(BlockNode iPostDom) { this.iPostDom = iPostDom; } public List<BlockNode> getDominatesOn() { return dominatesOn; } public void addDominatesOn(BlockNode block) { dominatesOn.add(block); } public boolean isSynthetic() { return contains(AFlag.SYNTHETIC); } public boolean isReturnBlock() { return contains(AFlag.RETURN); } public boolean isMthExitBlock() { return contains(AFlag.MTH_EXIT_BLOCK); } public boolean isEmpty() { return instructions.isEmpty(); } @Override public int hashCode() { return cid; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BlockNode)) { return false; } BlockNode other = (BlockNode) obj; return cid == other.cid; } @Override public int compareTo(@NotNull BlockNode o) { return Integer.compare(cid, o.cid); } @Override public String baseString() { return Integer.toString(cid); } @Override public String toString() { return "B:" + cid + ':' + InsnUtils.formatOffset(startOffset); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/ILoadable.java
jadx-core/src/main/java/jadx/core/dex/nodes/ILoadable.java
package jadx.core.dex.nodes; import jadx.core.utils.exceptions.DecodeException; public interface ILoadable { /** * On demand loading */ void load() throws DecodeException; /** * Free resources */ void unload(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/ICodeDataUpdateListener.java
jadx-core/src/main/java/jadx/core/dex/nodes/ICodeDataUpdateListener.java
package jadx.core.dex.nodes; import jadx.api.data.ICodeData; public interface ICodeDataUpdateListener { void updated(ICodeData codeData); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/IBlock.java
jadx-core/src/main/java/jadx/core/dex/nodes/IBlock.java
package jadx.core.dex.nodes; import java.util.List; import jadx.api.ICodeWriter; import jadx.core.codegen.RegionGen; import jadx.core.utils.exceptions.CodegenException; public interface IBlock extends IContainer { List<InsnNode> getInstructions(); @Override default void generate(RegionGen regionGen, ICodeWriter code) throws CodegenException { regionGen.makeSimpleBlock(this, code); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/IBranchRegion.java
jadx-core/src/main/java/jadx/core/dex/nodes/IBranchRegion.java
package jadx.core.dex.nodes; import java.util.List; public interface IBranchRegion extends IRegion { /** * Return list of branches in this region. * NOTE: Contains 'null' elements for indicate empty branches. */ List<IContainer> getBranches(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/IMethodDetails.java
jadx-core/src/main/java/jadx/core/dex/nodes/IMethodDetails.java
package jadx.core.dex.nodes; import java.util.List; import jadx.api.plugins.input.data.attributes.IJadxAttribute; import jadx.core.dex.attributes.AType; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.utils.Utils; public interface IMethodDetails extends IJadxAttribute { MethodInfo getMethodInfo(); ArgType getReturnType(); List<ArgType> getArgTypes(); List<ArgType> getTypeParameters(); List<ArgType> getThrows(); boolean isVarArg(); int getRawAccessFlags(); @Override default AType<IMethodDetails> getAttrType() { return AType.METHOD_DETAILS; } @Override default String toAttrString() { StringBuilder sb = new StringBuilder(); sb.append("MD:"); if (Utils.notEmpty(getTypeParameters())) { sb.append('<'); sb.append(Utils.listToString(getTypeParameters())); sb.append(">:"); } sb.append('('); sb.append(Utils.listToString(getArgTypes())); sb.append("):"); sb.append(getReturnType()); if (isVarArg()) { sb.append(" VARARG"); } List<ArgType> throwsList = getThrows(); if (Utils.notEmpty(throwsList)) { sb.append(" throws ").append(Utils.listToString(throwsList)); } return sb.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/LoadStage.java
jadx-core/src/main/java/jadx/core/dex/nodes/LoadStage.java
package jadx.core.dex.nodes; public enum LoadStage { NONE, PROCESS_STAGE, // dependencies not yet loaded CODEGEN_STAGE, // all dependencies loaded }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/IConditionRegion.java
jadx-core/src/main/java/jadx/core/dex/nodes/IConditionRegion.java
package jadx.core.dex.nodes; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.core.dex.regions.conditions.IfCondition; public interface IConditionRegion extends IRegion { @Nullable IfCondition getCondition(); /** * Blocks merged into condition * Needed for backtracking * TODO: merge into condition object ??? */ List<BlockNode> getConditionBlocks(); void invertCondition(); boolean simplifyCondition(); int getConditionSourceLine(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/main/java/jadx/core/dex/nodes/IDexNode.java
jadx-core/src/main/java/jadx/core/dex/nodes/IDexNode.java
package jadx.core.dex.nodes; import jadx.api.data.IRenameNode; public interface IDexNode extends IRenameNode { String typeName(); RootNode root(); String getInputFileName(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false